From 72ebb3dfe4125db14768bb529d396959fe75c3bb Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Wed, 22 Jun 2022 14:22:03 +0200 Subject: [PATCH 01/11] Reworking compiler issues caused by interface simplification --- .../AutoUpdateRequestExecutorProxy.cs | 4 +- .../Batching/BatchExecutor.Enumerable.cs | 22 +-- .../Batching/CollectVariablesVisitationMap.cs | 2 +- .../Batching/CollectVariablesVisitor.cs | 18 +-- .../DefaultRequestExecutorOptionsMonitor.cs | 16 +- .../DefaultRequestContextAccessor.cs | 2 +- ...ecutorBuilderExtensions.Instrumentation.cs | 4 +- ...equestExecutorServiceProviderExtensions.cs | 14 +- ...questExecutorBuilderExtensions.Document.cs | 4 +- ...estExecutorBuilderExtensions.Middleware.cs | 4 +- .../Execution/Errors/DefaultErrorHandler.cs | 6 +- .../Core/src/Execution/IRequestContext.cs | 2 +- .../ApolloTracingDiagnosticEventListener.cs | 14 +- .../ApolloTracingResultBuilder.cs | 2 +- .../Options/ComplexityAnalyzerSettings.cs | 2 +- .../src/Execution/Path/PathSegmentBuffer.cs | 2 +- .../src/Execution/Path/PathSegmentFactory.cs | 2 +- .../ComplexityAnalyzerCompilerVisitor.cs | 10 +- .../Pipeline/Complexity/ComplexityContext.cs | 4 +- .../Pipeline/DocumentCacheMiddleware.cs | 4 +- .../Pipeline/DocumentParserMiddleware.cs | 4 +- .../Pipeline/DocumentValidationMiddleware.cs | 2 +- .../Execution/Pipeline/ExceptionMiddleware.cs | 2 +- .../Pipeline/OperationCacheMiddleware.cs | 2 +- .../Pipeline/OperationComplexityMiddleware.cs | 12 +- .../Pipeline/OperationExecutionMiddleware.cs | 44 ----- .../Pipeline/OperationResolverMiddleware.cs | 6 +- .../Pipeline/ReadPersistedQueryMiddleware.cs | 2 +- .../Pipeline/RequestClassMiddlewareFactory.cs | 10 +- .../Execution/Pipeline/TimeoutMiddleware.cs | 2 +- .../Processing/ArgumentCoercionHelper.cs | 8 +- .../Processing/ArgumentNonNullValidator.cs | 16 +- .../Execution/Processing/DefaultActivator.cs | 4 +- .../Execution/Processing/DeferredFragment.cs | 2 - .../Execution/Processing/DeferredStream.cs | 3 +- .../Processing/DeferredTaskExecutor.cs | 4 +- .../DirectiveCollectionExtensions.cs | 16 +- .../Execution/Processing/DirectiveContext.cs | 151 ++++++------------ .../Processing/Internal/SuspendedWorkQueue.cs | 4 +- .../Processing/MiddlewareContext.Arguments.cs | 14 +- .../Processing/MiddlewareContext.Pure.cs | 16 +- .../Execution/Processing/OperationCompiler.cs | 2 +- .../OperationContext.IExecutionTaskContext.cs | 4 +- .../Processing/OperationContext.Pooling.cs | 2 +- .../Processing/OperationResolverHelper.cs | 4 +- .../src/Execution/Processing/ResultHelper.cs | 14 +- .../src/Execution/Processing/ResultMap.cs | 12 +- .../Processing/ResultObjectBuffer.cs | 2 +- .../src/Execution/Processing/ResultPool.cs | 6 +- .../SubscriptionExecutor.Subscription.cs | 26 +-- .../Processing/ValueCompletion.Leaf.cs | 2 +- .../Processing/ValueCompletion.List.cs | 10 +- .../Processing/ValueCompletion.Tools.cs | 8 +- .../Execution/Processing/ValueCompletion.cs | 2 +- .../Processing/VariableCoercionHelper.cs | 16 +- .../Execution/Processing/VariableRewriter.cs | 24 +-- .../Processing/VariableValueCollection.cs | 10 +- .../Processing/WorkScheduler.ExecuteAsync.cs | 8 +- .../WorkScheduler.IQueryPlanState.cs | 4 +- .../src/Execution/Processing/WorkScheduler.cs | 18 +-- .../Core/src/Execution/RequestContext.cs | 6 +- .../Core/src/Execution/RequestExecutor.cs | 6 +- .../src/Execution/RequestExecutorProxy.cs | 12 +- .../src/Execution/RequestExecutorResolver.cs | 54 +++---- .../JsonArrayResponseStreamFormatter.cs | 2 +- .../Serialization/JsonQueryResultFormatter.cs | 6 +- .../MultiPartResponseStreamFormatter.cs | 2 +- .../Core/src/Execution/ThrowHelper.cs | 2 +- .../Execution/Processing/IArgumentMap.cs | 2 + .../Types/Execution/Processing/IFragment.cs | 2 + .../Types/Execution/Processing/IOperation.cs | 1 - .../Processing/IOptionalSelection.cs | 1 + .../Execution/Processing/ISelectionSet.cs | 2 + .../Processing/ISelectionVariants.cs | 2 + .../Processing/SelectionExecutionStrategy.cs | 2 + 75 files changed, 328 insertions(+), 410 deletions(-) diff --git a/src/HotChocolate/Core/src/Execution/AutoUpdateRequestExecutorProxy.cs b/src/HotChocolate/Core/src/Execution/AutoUpdateRequestExecutorProxy.cs index 950b21ebbe3..f03dbea60d7 100644 --- a/src/HotChocolate/Core/src/Execution/AutoUpdateRequestExecutorProxy.cs +++ b/src/HotChocolate/Core/src/Execution/AutoUpdateRequestExecutorProxy.cs @@ -55,7 +55,7 @@ public static async ValueTask CreateAsync( throw new ArgumentNullException(nameof(requestExecutorProxy)); } - IRequestExecutor executor = await requestExecutorProxy + var executor = await requestExecutorProxy .GetRequestExecutorAsync(cancellationToken) .ConfigureAwait(false); @@ -159,7 +159,7 @@ private async ValueTask UpdateExecutorAsync() try { - IRequestExecutor executor = await _executorProxy + var executor = await _executorProxy .GetRequestExecutorAsync(default) .ConfigureAwait(false); _executor = executor; diff --git a/src/HotChocolate/Core/src/Execution/Batching/BatchExecutor.Enumerable.cs b/src/HotChocolate/Core/src/Execution/Batching/BatchExecutor.Enumerable.cs index dc60daa1375..8d93d82a169 100644 --- a/src/HotChocolate/Core/src/Execution/Batching/BatchExecutor.Enumerable.cs +++ b/src/HotChocolate/Core/src/Execution/Batching/BatchExecutor.Enumerable.cs @@ -53,9 +53,9 @@ public async IAsyncEnumerator GetAsyncEnumerator( { for (var i = 0; i < _requestBatch.Count; i++) { - IQueryRequest queryRequest = _requestBatch[i]; + var queryRequest = _requestBatch[i]; var request = (IReadOnlyQueryRequest)queryRequest; - IQueryResult result = await ExecuteNextAsync( + var result = await ExecuteNextAsync( request, cancellationToken).ConfigureAwait(false); yield return result; @@ -72,11 +72,11 @@ private async Task ExecuteNextAsync( { try { - DocumentNode document = request.Query is QueryDocument d + var document = request.Query is QueryDocument d ? d.Document : Utf8GraphQLParser.Parse(request.Query!.AsSpan()); - OperationDefinitionNode operation = + var operation = document.GetOperation(request.OperationName); if (document != _previous) @@ -93,7 +93,7 @@ private async Task ExecuteNextAsync( _previous = document; document = RewriteDocument(operation); operation = (OperationDefinitionNode)document.Definitions[0]; - IReadOnlyDictionary? variableValues = + var variableValues = MergeVariables(request.VariableValues, operation); request = QueryRequestBuilder.From(request) @@ -147,10 +147,10 @@ private DocumentNode RewriteDocument( return variables; } - ILookup exported = _exportedVariables.ToLookup(t => t.Name); + var exported = _exportedVariables.ToLookup(t => t.Name); var merged = new Dictionary(); - foreach (VariableDefinitionNode variableDefinition in operation.VariableDefinitions) + foreach (var variableDefinition in operation.VariableDefinitions) { var variableName = variableDefinition.Variable.Name.Value; @@ -177,7 +177,7 @@ private DocumentNode RewriteDocument( } } - foreach (ExportedVariable variable in exported[variableName]) + foreach (var variable in exported[variableName]) { SerializeListValue(variable, variableDefinition.Type, list); } @@ -207,7 +207,7 @@ private object Serialize(ExportedVariable exported, ITypeNode type) { if (_requestExecutor.Schema.TryGetType( type.NamedType().Name.Value, - out INamedInputType? inputType) + out var inputType) && _typeConverter.TryConvert( inputType!.RuntimeType, exported.Value, @@ -226,7 +226,7 @@ private void SerializeListValue( { if (_requestExecutor.Schema.TryGetType( type.NamedType().Name.Value, - out INamedInputType? inputType)) + out var inputType)) { SerializeListValue(exported, inputType, list); } @@ -241,7 +241,7 @@ private void SerializeListValue( INamedInputType inputType, ICollection list) { - Type runtimeType = inputType.RuntimeType; + var runtimeType = inputType.RuntimeType; if (exported.Type.IsListType() && exported.Value is IEnumerable l) diff --git a/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitationMap.cs b/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitationMap.cs index 9249f2c982c..aa13cea59c4 100644 --- a/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitationMap.cs +++ b/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitationMap.cs @@ -68,7 +68,7 @@ protected override void ResolveChildren( IList children) { if (_fragments is not null && - _fragments.TryGetValue(node.Name.Value, out FragmentDefinitionNode? d)) + _fragments.TryGetValue(node.Name.Value, out var d)) { ResolveChildren( d.Name.Value, diff --git a/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitor.cs b/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitor.cs index 1399f9c1bea..6c98fba79eb 100644 --- a/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitor.cs +++ b/src/HotChocolate/Core/src/Execution/Batching/CollectVariablesVisitor.cs @@ -52,7 +52,7 @@ public VisitorAction Enter( _action.Clear(); _touchedFragments.Clear(); - ObjectType type = _schema.GetOperationType(node.Operation)!; + var type = _schema.GetOperationType(node.Operation)!; _type.Push(type); for (var i = 0; i < node.VariableDefinitions.Count; i++) @@ -82,7 +82,7 @@ public VisitorAction Enter( { if (_type.Peek().NamedType() is IComplexOutputType complexType && complexType.Fields.TryGetField( - node.Name.Value, out IOutputField? field)) + node.Name.Value, out var field)) { _field.Push(field); _type.Push(field.Type); @@ -116,7 +116,7 @@ public VisitorAction Enter( { if (_field.Peek().Arguments.TryGetField( node.Name.Value, - out IInputField? field)) + out var field)) { _type.Push(field.Type); _action.Push(VisitorAction.Continue); @@ -181,11 +181,11 @@ public VisitorAction Enter( { if (!_declared.Contains(node.Name.Value)) { - IType type = _type.Peek(); + var type = _type.Peek(); if (_variables.TryGetValue( node.Name.Value, - out VariableDefinitionNode? d)) + out var d)) { if (type.IsNonNullType() && d.Type is INullableTypeNode nullable) @@ -198,8 +198,8 @@ public VisitorAction Enter( { if (type.NamedType() is IComplexOutputType complexType) { - Type clrType = complexType.ToRuntimeType(); - InputObjectType inputType = + var clrType = complexType.ToRuntimeType(); + var inputType = _schema.Types.OfType() .First(t => t.RuntimeType == clrType); @@ -252,7 +252,7 @@ public VisitorAction Enter( IReadOnlyList ancestors) { if (node.TypeCondition is not null && - _schema.TryGetType(node.TypeCondition.Name.Value, out INamedType? type)) + _schema.TryGetType(node.TypeCondition.Name.Value, out var type)) { _type.Push(type); _action.Push(VisitorAction.Continue); @@ -282,7 +282,7 @@ public VisitorAction Enter( IReadOnlyList path, IReadOnlyList ancestors) { - if (_schema.TryGetType(node.TypeCondition.Name.Value, out INamedType? type)) + if (_schema.TryGetType(node.TypeCondition.Name.Value, out var type)) { _touchedFragments.Add(node.Name.Value); _type.Push(type); diff --git a/src/HotChocolate/Core/src/Execution/Configuration/DefaultRequestExecutorOptionsMonitor.cs b/src/HotChocolate/Core/src/Execution/Configuration/DefaultRequestExecutorOptionsMonitor.cs index 14e36204bad..937f3e999d6 100644 --- a/src/HotChocolate/Core/src/Execution/Configuration/DefaultRequestExecutorOptionsMonitor.cs +++ b/src/HotChocolate/Core/src/Execution/Configuration/DefaultRequestExecutorOptionsMonitor.cs @@ -40,9 +40,9 @@ public async ValueTask GetAsync( if (_configs.TryGetValue( schemaName, - out List? configurations)) + out var configurations)) { - foreach (IConfigureRequestExecutorSetup configuration in configurations) + foreach (var configuration in configurations) { configuration.Configure(options); } @@ -61,19 +61,19 @@ private async ValueTask InitializeAsync(CancellationToken cancellationToken) { _configs.Clear(); - foreach (IRequestExecutorOptionsProvider provider in _optionsProviders) + foreach (var provider in _optionsProviders) { _disposables.Add(provider.OnChange(OnChange)); - IEnumerable allConfigurations = + var allConfigurations = await provider.GetOptionsAsync(cancellationToken) .ConfigureAwait(false); - foreach (IConfigureRequestExecutorSetup configuration in allConfigurations) + foreach (var configuration in allConfigurations) { if (!_configs.TryGetValue( configuration.SchemaName, - out List? configurations)) + out var configurations)) { configurations = new List(); _configs.Add(configuration.SchemaName, configurations); @@ -99,7 +99,7 @@ private void OnChange(IConfigureRequestExecutorSetup changes) lock (_listeners) { - foreach (Action listener in _listeners) + foreach (var listener in _listeners) { listener.Invoke(changes.SchemaName); } @@ -112,7 +112,7 @@ public void Dispose() { _semaphore.Dispose(); - foreach (IDisposable disposable in _disposables) + foreach (var disposable in _disposables) { disposable.Dispose(); } diff --git a/src/HotChocolate/Core/src/Execution/DefaultRequestContextAccessor.cs b/src/HotChocolate/Core/src/Execution/DefaultRequestContextAccessor.cs index 7cb9d458706..1bb1dc0a627 100644 --- a/src/HotChocolate/Core/src/Execution/DefaultRequestContextAccessor.cs +++ b/src/HotChocolate/Core/src/Execution/DefaultRequestContextAccessor.cs @@ -16,7 +16,7 @@ public IRequestContext RequestContext } set { - RequestContextHolder? holder = _requestContextCurrent.Value; + var holder = _requestContextCurrent.Value; if (holder is null) { diff --git a/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorBuilderExtensions.Instrumentation.cs b/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorBuilderExtensions.Instrumentation.cs index 305ca1648f1..c83adeaa71b 100644 --- a/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorBuilderExtensions.Instrumentation.cs +++ b/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorBuilderExtensions.Instrumentation.cs @@ -59,7 +59,7 @@ public static IRequestExecutorBuilder AddDiagnosticEventListener( foreach (var attribute in typeof(T).GetCustomAttributes(typeof(DiagnosticEventSourceAttribute), true)) { - Type listener = ((DiagnosticEventSourceAttribute)attribute).Listener; + var listener = ((DiagnosticEventSourceAttribute)attribute).Listener; builder.Services.AddSingleton(listener, s => s.GetService()); } } @@ -103,7 +103,7 @@ public static IRequestExecutorBuilder AddDiagnosticEventListener( foreach (var attribute in typeof(T).GetCustomAttributes(typeof(DiagnosticEventSourceAttribute), true)) { - Type listener = ((DiagnosticEventSourceAttribute)attribute).Listener; + var listener = ((DiagnosticEventSourceAttribute)attribute).Listener; builder.Services.AddSingleton(listener, diagnosticEventListener); } } diff --git a/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorServiceProviderExtensions.cs b/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorServiceProviderExtensions.cs index 347e4efe514..98a1b617bbc 100644 --- a/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorServiceProviderExtensions.cs +++ b/src/HotChocolate/Core/src/Execution/DependencyInjection/RequestExecutorServiceProviderExtensions.cs @@ -33,7 +33,7 @@ public static async ValueTask GetSchemaAsync( NameString schemaName = default, CancellationToken cancellationToken = default) { - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(services, schemaName, cancellationToken) .ConfigureAwait(false); @@ -61,7 +61,7 @@ public static async ValueTask BuildSchemaAsync( CancellationToken cancellationToken = default) { IServiceProvider services = builder.Services.BuildServiceProvider(); - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(services, schemaName, cancellationToken) .ConfigureAwait(false); @@ -153,7 +153,7 @@ public static async Task ExecuteRequestAsync( NameString schemaName = default, CancellationToken cancellationToken = default) { - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(services, schemaName, cancellationToken) .ConfigureAwait(false); @@ -198,7 +198,7 @@ public static async Task ExecuteRequestAsync( NameString schemaName = default, CancellationToken cancellationToken = default) { - IRequestExecutor executor = + var executor = await BuildRequestExecutorAsync(builder, schemaName, cancellationToken) .ConfigureAwait(false); @@ -244,7 +244,7 @@ public static async Task ExecuteRequestAsync( NameString schemaName = default, CancellationToken cancellationToken = default) { - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(services, schemaName, cancellationToken) .ConfigureAwait(false); @@ -293,7 +293,7 @@ public static async Task ExecuteRequestAsync( NameString schemaName = default, CancellationToken cancellationToken = default) { - IRequestExecutor executor = + var executor = await BuildRequestExecutorAsync(builder, schemaName, cancellationToken) .ConfigureAwait(false); @@ -329,7 +329,7 @@ public static async Task ExecuteBatchRequestAsync( NameString schemaName = default, CancellationToken cancellationToken = default) { - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(services, schemaName, cancellationToken) .ConfigureAwait(false); diff --git a/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Document.cs b/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Document.cs index 85d406830ef..0119ceaa1a3 100644 --- a/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Document.cs +++ b/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Document.cs @@ -25,7 +25,7 @@ public static IRequestExecutorBuilder AddDocument( return builder.ConfigureSchemaAsync(async (sp, b, ct) => { - DocumentNode document = await loadDocumentAsync(sp, ct).ConfigureAwait(false); + var document = await loadDocumentAsync(sp, ct).ConfigureAwait(false); b.AddDocument(document); }); } @@ -80,7 +80,7 @@ public static IRequestExecutorBuilder AddDocumentFromFile( return builder.AddDocument(async (sp, ct) => { - byte[] buffer = await Task + var buffer = await Task .Run(() => File.ReadAllBytes(filePath), ct) .ConfigureAwait(false); return Utf8GraphQLParser.Parse(buffer); diff --git a/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Middleware.cs b/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Middleware.cs index 869d9acc5cf..d3dfcdb9342 100644 --- a/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Middleware.cs +++ b/src/HotChocolate/Core/src/Execution/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Middleware.cs @@ -45,7 +45,7 @@ public static IRequestExecutorBuilder MapField( FieldClassMiddlewareFactory.Create( (s, n) => { - FieldMiddleware classMiddleware = + var classMiddleware = FieldClassMiddlewareFactory.Create(); return new MapMiddleware( n, fieldReference, classMiddleware(n)); @@ -62,7 +62,7 @@ public static IRequestExecutorBuilder MapField( FieldClassMiddlewareFactory.Create( (s, n) => { - FieldMiddleware classMiddleware = + var classMiddleware = FieldClassMiddlewareFactory .Create(factory); return new MapMiddleware( diff --git a/src/HotChocolate/Core/src/Execution/Errors/DefaultErrorHandler.cs b/src/HotChocolate/Core/src/Execution/Errors/DefaultErrorHandler.cs index dc30ff721b8..70478ff0911 100644 --- a/src/HotChocolate/Core/src/Execution/Errors/DefaultErrorHandler.cs +++ b/src/HotChocolate/Core/src/Execution/Errors/DefaultErrorHandler.cs @@ -44,9 +44,9 @@ public IError Handle(IError error) throw new ArgumentNullException(nameof(error)); } - IError current = error; + var current = error; - foreach (IErrorFilter filter in _filters) + foreach (var filter in _filters) { current = filter.OnError(current); @@ -72,7 +72,7 @@ public IErrorBuilder CreateUnexpectedError(Exception exception) private IErrorBuilder CreateErrorFromException(Exception exception) { - IErrorBuilder builder = ErrorBuilder.New() + var builder = ErrorBuilder.New() .SetMessage("Unexpected Execution Error") .SetException(exception); diff --git a/src/HotChocolate/Core/src/Execution/IRequestContext.cs b/src/HotChocolate/Core/src/Execution/IRequestContext.cs index e973db58a11..39e369f0bd6 100644 --- a/src/HotChocolate/Core/src/Execution/IRequestContext.cs +++ b/src/HotChocolate/Core/src/Execution/IRequestContext.cs @@ -107,7 +107,7 @@ public interface IRequestContext : IHasContextData /// /// Gets or sets the prepared operation. /// - IPreparedOperation? Operation { get; set; } + IOperation? Operation { get; set; } /// /// Gets or sets the coerced variable values. diff --git a/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingDiagnosticEventListener.cs b/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingDiagnosticEventListener.cs index 9d62e02dd41..2f2a5f69dd9 100644 --- a/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingDiagnosticEventListener.cs +++ b/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingDiagnosticEventListener.cs @@ -26,9 +26,9 @@ public override IDisposable ExecuteRequest(IRequestContext context) { if (IsEnabled(context.ContextData)) { - DateTime startTime = _timestampProvider.UtcNow(); + var startTime = _timestampProvider.UtcNow(); - ApolloTracingResultBuilder builder = CreateBuilder(context.ContextData); + var builder = CreateBuilder(context.ContextData); builder.SetRequestStartTime( startTime, @@ -41,21 +41,21 @@ public override IDisposable ExecuteRequest(IRequestContext context) public override IDisposable ParseDocument(IRequestContext context) { - return TryGetBuilder(context.ContextData, out ApolloTracingResultBuilder? builder) + return TryGetBuilder(context.ContextData, out var builder) ? new ParseDocumentScope(builder, _timestampProvider) : EmptyScope; } public override IDisposable ValidateDocument(IRequestContext context) { - return TryGetBuilder(context.ContextData, out ApolloTracingResultBuilder? builder) + return TryGetBuilder(context.ContextData, out var builder) ? new ValidateDocumentScope(builder, _timestampProvider) : EmptyScope; } public override IDisposable ResolveFieldValue(IMiddlewareContext context) { - return TryGetBuilder(context.ContextData, out ApolloTracingResultBuilder? builder) + return TryGetBuilder(context.ContextData, out var builder) ? new ResolveFieldValueScope(context, builder, _timestampProvider) : EmptyScope; } @@ -72,7 +72,7 @@ private static bool TryGetBuilder( IDictionary contextData, [NotNullWhen(true)] out ApolloTracingResultBuilder? builder) { - if (contextData.TryGetValue(nameof(ApolloTracingResultBuilder), out object? value) && + if (contextData.TryGetValue(nameof(ApolloTracingResultBuilder), out var value) && value is ApolloTracingResultBuilder b) { builder = b; @@ -114,7 +114,7 @@ public void Dispose() { if (!_disposed) { - DateTime endTime = _timestampProvider.UtcNow(); + var endTime = _timestampProvider.UtcNow(); _builder.SetRequestDuration(endTime - _startTime); if (_context.Result is IQueryResult queryResult) diff --git a/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingResultBuilder.cs b/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingResultBuilder.cs index 7c70a1776db..9e60e44bcc4 100644 --- a/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingResultBuilder.cs +++ b/src/HotChocolate/Core/src/Execution/Instrumentation/ApolloTracingResultBuilder.cs @@ -88,7 +88,7 @@ private ResultMap[] BuildResolverResults() var i = 0; var results = new ResultMap[_resolverRecords.Count]; - foreach (ApolloTracingResolverRecord record in _resolverRecords) + foreach (var record in _resolverRecords) { var result = new ResultMap(); result.EnsureCapacity(6); diff --git a/src/HotChocolate/Core/src/Execution/Options/ComplexityAnalyzerSettings.cs b/src/HotChocolate/Core/src/Execution/Options/ComplexityAnalyzerSettings.cs index 803a4d3c7ab..923f0b0c34d 100644 --- a/src/HotChocolate/Core/src/Execution/Options/ComplexityAnalyzerSettings.cs +++ b/src/HotChocolate/Core/src/Execution/Options/ComplexityAnalyzerSettings.cs @@ -65,7 +65,7 @@ public static int DefaultCalculation(ComplexityContext context) var cost = context.Complexity + context.ChildComplexity; var needsDefaultMultiplier = true; - foreach (MultiplierPathString multiplier in context.Multipliers) + foreach (var multiplier in context.Multipliers) { if (context.TryGetArgumentValue(multiplier, out int value)) { diff --git a/src/HotChocolate/Core/src/Execution/Path/PathSegmentBuffer.cs b/src/HotChocolate/Core/src/Execution/Path/PathSegmentBuffer.cs index 8c54059a700..e5a69c6fa5b 100644 --- a/src/HotChocolate/Core/src/Execution/Path/PathSegmentBuffer.cs +++ b/src/HotChocolate/Core/src/Execution/Path/PathSegmentBuffer.cs @@ -23,7 +23,7 @@ public PathSegmentBuffer(int capacity, IPooledObjectPolicy policy) public T Pop() { - if (TryPop(out T? obj)) + if (TryPop(out var obj)) { return obj; } diff --git a/src/HotChocolate/Core/src/Execution/Path/PathSegmentFactory.cs b/src/HotChocolate/Core/src/Execution/Path/PathSegmentFactory.cs index 32ff21bd39c..ad8b1a10365 100644 --- a/src/HotChocolate/Core/src/Execution/Path/PathSegmentFactory.cs +++ b/src/HotChocolate/Core/src/Execution/Path/PathSegmentFactory.cs @@ -39,7 +39,7 @@ public T Get() { while (true) { - if (_current is null || !_current.TryPop(out T? segment)) + if (_current is null || !_current.TryPop(out var segment)) { Resize(); continue; diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityAnalyzerCompilerVisitor.cs b/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityAnalyzerCompilerVisitor.cs index 1587717fdbe..34a81ac8afc 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityAnalyzerCompilerVisitor.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityAnalyzerCompilerVisitor.cs @@ -65,9 +65,9 @@ protected override ISyntaxVisitorAction Enter( FieldNode node, IDocumentValidatorContext context) { - if (context.Types.TryPeek(out IType? type) && + if (context.Types.TryPeek(out var type) && type.NamedType() is IComplexOutputType ot && - ot.Fields.TryGetField(node.Name.Value, out IOutputField? of)) + ot.Fields.TryGetField(node.Name.Value, out var of)) { context.List.Push(new List()); context.OutputFields.Push(of); @@ -83,7 +83,7 @@ protected override ISyntaxVisitorAction Leave( FieldNode node, IDocumentValidatorContext context) { - IOutputField field = context.OutputFields.Pop(); + var field = context.OutputFields.Pop(); var children = (List)context.List.Pop()!; context.Types.Pop(); @@ -113,7 +113,7 @@ private Expression CreateCalculateExpression( FieldNode selection, Expression childComplexity) { - CostDirective? costDirective = + var costDirective = field.Directives["cost"] .FirstOrDefault()? .ToObject(); @@ -138,7 +138,7 @@ private Expression GetInputParser() private Expression Combine(IReadOnlyList expressions) { - Expression combinedComplexity = expressions[0]; + var combinedComplexity = expressions[0]; for (var i = 1; i < expressions.Count; i++) { diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityContext.cs b/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityContext.cs index be0c6669416..634483de0a4 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityContext.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/Complexity/ComplexityContext.cs @@ -89,9 +89,9 @@ public ComplexityContext( /// public bool TryGetArgumentValue(string name, out T? value) { - if (Field.Arguments.TryGetField(name, out IInputField? argument)) + if (Field.Arguments.TryGetField(name, out var argument)) { - IValueNode? argumentValue = Selection.Arguments + var argumentValue = Selection.Arguments .FirstOrDefault(t => t.Name.Value.EqualsOrdinal(name))? .Value; diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/DocumentCacheMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/DocumentCacheMiddleware.cs index e45d6db6a9a..56c89421663 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/DocumentCacheMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/DocumentCacheMiddleware.cs @@ -31,13 +31,13 @@ public DocumentCacheMiddleware( public async ValueTask InvokeAsync(IRequestContext context) { - IQueryRequest request = context.Request; + var request = context.Request; var addToCache = true; if (context.Document is null) { if (request.QueryId != null && - _documentCache.TryGetDocument(request.QueryId, out DocumentNode document)) + _documentCache.TryGetDocument(request.QueryId, out var document)) { context.DocumentId = request.QueryId; context.Document = document; diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/DocumentParserMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/DocumentParserMiddleware.cs index 890527710a8..7e5746b41ea 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/DocumentParserMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/DocumentParserMiddleware.cs @@ -29,7 +29,7 @@ public async ValueTask InvokeAsync(IRequestContext context) if (context.Document is null && context.Request.Query is not null) { var success = false; - IQuery query = context.Request.Query; + var query = context.Request.Query; // a parsed document was passed into the request. if (query is QueryDocument parsed) @@ -58,7 +58,7 @@ public async ValueTask InvokeAsync(IRequestContext context) { // if we have syntax errors we will report them within the // parse document diagnostic span. - IError error = context.ErrorHandler.Handle( + var error = context.ErrorHandler.Handle( ErrorBuilder.New() .SetMessage(ex.Message) .SetCode(ErrorCodes.Execution.SyntaxError) diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/DocumentValidationMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/DocumentValidationMiddleware.cs index 0aee3635e2f..1037c9152a3 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/DocumentValidationMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/DocumentValidationMiddleware.cs @@ -50,7 +50,7 @@ public async ValueTask InvokeAsync(IRequestContext context) // if the validation failed we will report errors within the validation // span and we will complete the pipeline since we do not have a valid // GraphQL request. - DocumentValidatorResult validationResult = context.ValidationResult; + var validationResult = context.ValidationResult; context.Result = QueryResultBuilder.CreateError( validationResult.Errors, diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/ExceptionMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/ExceptionMiddleware.cs index 85b7d7f56af..8c163a95556 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/ExceptionMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/ExceptionMiddleware.cs @@ -33,7 +33,7 @@ public async ValueTask InvokeAsync(IRequestContext context) catch (Exception ex) { context.Exception = ex; - IError error = _errorHandler.CreateUnexpectedError(ex).Build(); + var error = _errorHandler.CreateUnexpectedError(ex).Build(); context.Result = QueryResultBuilder.CreateError(_errorHandler.Handle(error)); } } diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/OperationCacheMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/OperationCacheMiddleware.cs index 2f53fedddc3..ccdac8f5f11 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/OperationCacheMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/OperationCacheMiddleware.cs @@ -47,7 +47,7 @@ public async ValueTask InvokeAsync(IRequestContext context) var cacheId = context.CreateCacheId(operationId); - if (_operationCache.TryGetOperation(cacheId, out IOperation? operation)) + if (_operationCache.TryGetOperation(cacheId, out var operation)) { context.Operation = operation; addToCache = false; diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/OperationComplexityMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/OperationComplexityMiddleware.cs index 9877fd04221..c7ba94adb22 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/OperationComplexityMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/OperationComplexityMiddleware.cs @@ -56,17 +56,17 @@ public async ValueTask InvokeAsync(IRequestContext context) context.OperationId is not null && context.Document is not null) { - IExecutionDiagnosticEvents diagnostic = context.DiagnosticEvents; + var diagnostic = context.DiagnosticEvents; using (diagnostic.AnalyzeOperationComplexity(context)) { var cacheId = context.CreateCacheId(context.OperationId); - DocumentNode document = context.Document; - OperationDefinitionNode operationDefinition = + var document = context.Document; + var operationDefinition = context.Operation?.Definition ?? document.GetOperation(context.Request.OperationName); - if (!_cache.TryGetAnalyzer(cacheId, out ComplexityAnalyzerDelegate? analyzer)) + if (!_cache.TryGetAnalyzer(cacheId, out var analyzer)) { analyzer = CompileAnalyzer(context, document, operationDefinition); diagnostic.OperationComplexityAnalyzerCompiled(context); @@ -104,7 +104,7 @@ private ComplexityAnalyzerDelegate CompileAnalyzer( DocumentNode document, OperationDefinitionNode operationDefinition) { - DocumentValidatorContext validatorContext = _contextPool.Get(); + var validatorContext = _contextPool.Get(); ComplexityAnalyzerDelegate? operationAnalyzer = null; try @@ -114,7 +114,7 @@ private ComplexityAnalyzerDelegate CompileAnalyzer( _compiler.Visit(document, validatorContext); var analyzers = (List)validatorContext.List.Peek()!; - foreach (OperationComplexityAnalyzer? analyzer in analyzers) + foreach (var analyzer in analyzers) { if (analyzer.OperationDefinitionNode == operationDefinition) { diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/OperationExecutionMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/OperationExecutionMiddleware.cs index cc30cc29cc2..a6b79f491dc 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/OperationExecutionMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/OperationExecutionMiddleware.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; -using HotChocolate.Execution.Caching; using HotChocolate.Execution.Processing; -using HotChocolate.Execution.Processing.Plan; using HotChocolate.Fetching; using HotChocolate.Language; using Microsoft.Extensions.DependencyInjection; @@ -18,7 +15,6 @@ internal sealed class OperationExecutionMiddleware private readonly ObjectPool _operationContextPool; private readonly QueryExecutor _queryExecutor; private readonly SubscriptionExecutor _subscriptionExecutor; - private readonly IQueryPlanCache _queryPlanCache; private readonly ITransactionScopeHandler _transactionScopeHandler; private object? _cachedQuery; private object? _cachedMutation; @@ -28,7 +24,6 @@ public OperationExecutionMiddleware( ObjectPool operationContextPool, QueryExecutor queryExecutor, SubscriptionExecutor subscriptionExecutor, - IQueryPlanCache queryPlanCache, [SchemaService] ITransactionScopeHandler transactionScopeHandler) { _next = next ?? @@ -39,8 +34,6 @@ public OperationExecutionMiddleware( throw new ArgumentNullException(nameof(queryExecutor)); _subscriptionExecutor = subscriptionExecutor ?? throw new ArgumentNullException(nameof(subscriptionExecutor)); - _queryPlanCache = queryPlanCache ?? - throw new ArgumentNullException(nameof(queryPlanCache)); _transactionScopeHandler = transactionScopeHandler ?? throw new ArgumentNullException(nameof(transactionScopeHandler)); } @@ -58,8 +51,6 @@ public async ValueTask InvokeAsync( { if (IsOperationAllowed(context)) { - var queryPlan = GetQueryPlan(context); - using (context.DiagnosticEvents.ExecuteOperation(context)) { await ExecuteOperationAsync(context, batchDispatcher, context.Operation) @@ -178,7 +169,6 @@ private async Task ExecuteQueryOrMutationAsync( context.Services, batchDispatcher, operation, - queryPlan, context.Variables!, mutation, () => GetQueryRootValue(context)); @@ -191,17 +181,6 @@ private async Task ExecuteQueryOrMutationAsync( } } - private QueryPlan GetQueryPlan(IRequestContext context) - { - if (!_queryPlanCache.TryGetQueryPlan(context.OperationId!, out var queryPlan)) - { - queryPlan = QueryPlanBuilder.Build(context.Operation!); - _queryPlanCache.TryAddQueryPlan(context.OperationId!, queryPlan); - } - - return queryPlan; - } - private object? GetQueryRootValue(IRequestContext context) => RootValueResolver.Resolve( context, @@ -242,27 +221,4 @@ private bool IsOperationAllowed(IRequestContext context) return false; } - - private sealed class StreamSession : IDisposable - { - private readonly IDisposable[] _disposables; - private bool _disposed; - - public StreamSession(IDisposable[] disposables) - { - _disposables = disposables; - } - - public void Dispose() - { - if (!_disposed) - { - foreach (var disposable in _disposables) - { - disposable.Dispose(); - } - _disposed = true; - } - } - } } diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/OperationResolverMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/OperationResolverMiddleware.cs index 0e3d31b5d7c..32d4b220287 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/OperationResolverMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/OperationResolverMiddleware.cs @@ -13,12 +13,12 @@ internal sealed class OperationResolverMiddleware { private readonly RequestDelegate _next; private readonly ObjectPool _operationCompilerPool; - private readonly IReadOnlyList? _optimizers; + private readonly IReadOnlyList? _optimizers; public OperationResolverMiddleware( RequestDelegate next, ObjectPool operationCompilerPool, - IEnumerable optimizers) + IEnumerable optimizers) { if (optimizers is null) { @@ -65,7 +65,7 @@ public async ValueTask InvokeAsync(IRequestContext context) } } - private IPreparedOperation CompileOperation( + private IOperation CompileOperation( IRequestContext context, string operationId, OperationDefinitionNode operationDefinition, diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/ReadPersistedQueryMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/ReadPersistedQueryMiddleware.cs index 75ea03c39f2..2fc0056723b 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/ReadPersistedQueryMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/ReadPersistedQueryMiddleware.cs @@ -45,7 +45,7 @@ private async ValueTask TryLoadQueryAsync(IRequestContext context) if (queryId is not null) { - QueryDocument? queryDocument = + var queryDocument = await _persistedQueryStore.TryReadQueryAsync( queryId, context.RequestAborted) .ConfigureAwait(false); diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/RequestClassMiddlewareFactory.cs b/src/HotChocolate/Core/src/Execution/Pipeline/RequestClassMiddlewareFactory.cs index 570d73813fa..86fb6605033 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/RequestClassMiddlewareFactory.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/RequestClassMiddlewareFactory.cs @@ -45,14 +45,14 @@ internal static RequestCoreMiddleware Create() { return (context, next) => { - TMiddleware middleware = + var middleware = MiddlewareCompiler .CompileFactory( (c, _) => CreateFactoryParameterHandlers( c, context.Options, typeof(TMiddleware))) .Invoke(context, next); - ClassQueryDelegate compiled = + var compiled = MiddlewareCompiler.CompileDelegate( (c, _) => CreateDelegateParameterHandlers(c, context.Options)); @@ -97,12 +97,12 @@ private static List CreateFactoryParameterHandlers( new TypeParameterHandler(typeof(IRequestContextAccessor), requestOptions) }; - ConstructorInfo? constructor = + var constructor = middleware.GetConstructors().SingleOrDefault(t => t.IsPublic); if (constructor is not null) { - foreach (ParameterInfo parameter in constructor.GetParameters() + foreach (var parameter in constructor.GetParameters() .Where(p => p.IsDefined(typeof(SchemaServiceAttribute)))) { AddService(list, schemaServices, parameter.ParameterType); @@ -115,7 +115,7 @@ private static List CreateFactoryParameterHandlers( AddService(list, schemaServices); AddService(list, schemaServices); AddService(list, schemaServices); - AddService>(list, schemaServices); + AddService>(list, schemaServices); AddService(list, schemaServices); AddOptions(list, options); list.Add(new SchemaNameParameterHandler(schemaName)); diff --git a/src/HotChocolate/Core/src/Execution/Pipeline/TimeoutMiddleware.cs b/src/HotChocolate/Core/src/Execution/Pipeline/TimeoutMiddleware.cs index c693859edfc..41d4c9f81a5 100644 --- a/src/HotChocolate/Core/src/Execution/Pipeline/TimeoutMiddleware.cs +++ b/src/HotChocolate/Core/src/Execution/Pipeline/TimeoutMiddleware.cs @@ -38,7 +38,7 @@ public async ValueTask InvokeAsync(IRequestContext context) // We do not dispose the combined token in this middleware at all times. // The dispose is handled in the finally block. - CancellationTokenSource combined = CreateLinkedTokenSource( + var combined = CreateLinkedTokenSource( context.RequestAborted, timeout.Token); try diff --git a/src/HotChocolate/Core/src/Execution/Processing/ArgumentCoercionHelper.cs b/src/HotChocolate/Core/src/Execution/Processing/ArgumentCoercionHelper.cs index 4c8e9614902..19afa00bbde 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ArgumentCoercionHelper.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ArgumentCoercionHelper.cs @@ -23,7 +23,7 @@ public static bool TryCoerceArguments( // signal that this resolver task has errors and shall end. if (arguments.HasErrors) { - foreach (ArgumentValue argument in arguments.Values) + foreach (var argument in arguments.Values) { if (argument.HasError) { @@ -39,7 +39,7 @@ public static bool TryCoerceArguments( // rewrite the arguments that need variable replacement. var args = new Dictionary(); - foreach (ArgumentValue argument in arguments.Values) + foreach (var argument in arguments.Values) { if (argument.IsFullyCoerced) { @@ -47,7 +47,7 @@ public static bool TryCoerceArguments( } else { - IValueNode literal = VariableRewriter.Rewrite( + var literal = VariableRewriter.Rewrite( argument.ValueLiteral!, argument.Type, argument.DefaultValue, @@ -55,7 +55,7 @@ public static bool TryCoerceArguments( args.Add(argument.Name, new ArgumentValue( argument, - literal.TryGetValueKind(out ValueKind kind) + literal.TryGetValueKind(out var kind) ? kind : ValueKind.Unknown, argument.IsFullyCoerced, diff --git a/src/HotChocolate/Core/src/Execution/Processing/ArgumentNonNullValidator.cs b/src/HotChocolate/Core/src/Execution/Processing/ArgumentNonNullValidator.cs index 56a393ff9f5..bca9cfc3525 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ArgumentNonNullValidator.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ArgumentNonNullValidator.cs @@ -53,7 +53,7 @@ private static ValidationResult Validate(IType type, IValueNode? value, Path pat private static ValidationResult ValidateInnerType(IType type, IValueNode? value, Path path) { - IType innerType = type.IsNonNullType() ? type.InnerType() : type; + var innerType = type.IsNonNullType() ? type.InnerType() : type; if (innerType is ListType listType) { @@ -82,15 +82,15 @@ private static ValidationResult ValidateObject( for (var i = 0; i < value.Fields.Count; i++) { - ObjectFieldNode field = value.Fields[i]; + var field = value.Fields[i]; fields[field.Name.Value] = field.Value; } - foreach (InputField field in type.Fields) + foreach (var field in type.Fields) { - fields.TryGetValue(field.Name, out IValueNode? fieldValue); + fields.TryGetValue(field.Name, out var fieldValue); - ValidationResult report = Validate( + var report = Validate( field, fieldValue, PathFactory.Instance.Append(path, field.Name)); @@ -106,12 +106,12 @@ private static ValidationResult ValidateObject( private static ValidationResult ValidateList(ListType type, ListValueNode list, Path path) { - IType elementType = type.ElementType(); + var elementType = type.ElementType(); var i = 0; - foreach (IValueNode element in list.Items) + foreach (var element in list.Items) { - ValidationResult error = + var error = Validate(elementType, element, PathFactory.Instance.Append(path, i++)); if (error.HasErrors) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/DefaultActivator.cs b/src/HotChocolate/Core/src/Execution/Processing/DefaultActivator.cs index e05470edac5..527101fd90d 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DefaultActivator.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DefaultActivator.cs @@ -24,7 +24,7 @@ public void Dispose() { if (_instances.Count > 0) { - foreach (Service service in _instances.Values) + foreach (var service in _instances.Values) { service.Dispose(); } @@ -59,7 +59,7 @@ public Service(DefaultActivator activator, Type type) if (_type != typeof(object)) { - services.TryGetService(_type, out object? value); + services.TryGetService(_type, out var value); if (value is null && !_type.IsAbstract && !_type.IsInterface) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/DeferredFragment.cs b/src/HotChocolate/Core/src/Execution/Processing/DeferredFragment.cs index eaaa19edba2..cb76ef202ea 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DeferredFragment.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DeferredFragment.cs @@ -64,8 +64,6 @@ public DeferredFragment( /// public async Task ExecuteAsync(IOperationContext operationContext) { - operationContext.QueryPlan = operationContext.QueryPlan.GetDeferredPlan(Fragment.Id); - var resultMap = EnqueueResolverTasks( operationContext, Fragment.SelectionSet, diff --git a/src/HotChocolate/Core/src/Execution/Processing/DeferredStream.cs b/src/HotChocolate/Core/src/Execution/Processing/DeferredStream.cs index e8f9518a3dc..fd271b9156d 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DeferredStream.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DeferredStream.cs @@ -84,7 +84,6 @@ public DeferredStream( _task ??= new StreamExecutionTask(operationContext, this); _task.Reset(); - operationContext.QueryPlan = operationContext.QueryPlan.GetStreamPlan(Selection.Id); operationContext.Scheduler.Register(_task); await operationContext.Scheduler.ExecuteAsync().ConfigureAwait(false); @@ -95,7 +94,7 @@ public DeferredStream( operationContext.Scheduler.DeferredWork.Register(this); - IQueryResult result = operationContext + var result = operationContext .TrySetNext(true) .SetLabel(Label) .SetPath(operationContext.PathFactory.Append(Path, Index)) diff --git a/src/HotChocolate/Core/src/Execution/Processing/DeferredTaskExecutor.cs b/src/HotChocolate/Core/src/Execution/Processing/DeferredTaskExecutor.cs index b7d0dcf3deb..03799517d25 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DeferredTaskExecutor.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DeferredTaskExecutor.cs @@ -25,10 +25,10 @@ public async IAsyncEnumerator GetAsyncEnumerator( { yield return _initialResult; - IOperationContext context = _operationContextOwner.OperationContext; + var context = _operationContextOwner.OperationContext; while (context.Scheduler.DeferredWork.TryTake( - out IDeferredExecutionTask? deferredTask)) + out var deferredTask)) { if (cancellationToken.IsCancellationRequested) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/DirectiveCollectionExtensions.cs b/src/HotChocolate/Core/src/Execution/Processing/DirectiveCollectionExtensions.cs index 50ac9f501e1..c93fbebf76a 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DirectiveCollectionExtensions.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DirectiveCollectionExtensions.cs @@ -10,13 +10,13 @@ internal static class DirectiveCollectionExtensions { public static IValueNode? SkipValue(this IReadOnlyList directives) { - DirectiveNode? directive = directives.GetSkipDirective(); + var directive = directives.GetSkipDirective(); return directive is null ? null : GetIfArgumentValue(directive); } public static IValueNode? IncludeValue(this IReadOnlyList directives) { - DirectiveNode? directive = directives.GetIncludeDirective(); + var directive = directives.GetIncludeDirective(); return directive is null ? null : GetIfArgumentValue(directive); } @@ -36,7 +36,7 @@ private static IValueNode GetIfArgumentValue(DirectiveNode directive) { if (directive.Arguments.Count == 1) { - ArgumentNode argument = directive.Arguments[0]; + var argument = directive.Arguments[0]; if (string.Equals( argument.Name.Value, WellKnownDirectives.IfArgument, @@ -61,7 +61,7 @@ private static IValueNode GetIfArgumentValue(DirectiveNode directive) this IReadOnlyList directives, IVariableValueCollection variables) { - DirectiveNode? directiveNode = + var directiveNode = GetDirective(directives, WellKnownDirectives.Defer); if (directiveNode is not null) @@ -69,7 +69,7 @@ private static IValueNode GetIfArgumentValue(DirectiveNode directive) var @if = true; string? label = null; - foreach (ArgumentNode argument in directiveNode.Arguments) + foreach (var argument in directiveNode.Arguments) { switch (argument.Name.Value) { @@ -105,7 +105,7 @@ VariableNode variable this IReadOnlyList directives, IVariableValueCollection variables) { - DirectiveNode? directiveNode = + var directiveNode = GetDirective(directives, WellKnownDirectives.Stream); if (directiveNode is not null) @@ -114,7 +114,7 @@ VariableNode variable string? label = null; var initialCount = 0; - foreach (ArgumentNode argument in directiveNode.Arguments) + foreach (var argument in directiveNode.Arguments) { switch (argument.Name.Value) { @@ -175,7 +175,7 @@ VariableNode variable for (var i = 0; i < directives.Count; i++) { - DirectiveNode directive = directives[i]; + var directive = directives[i]; if (directive.Name.Value.EqualsOrdinal(name)) { return directive; diff --git a/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs b/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs index 97b07ff498a..cb978ee960f 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using HotChocolate.Language; @@ -22,62 +21,45 @@ public DirectiveContext(IMiddlewareContext middlewareContext, IDirective directi public IDirective Directive { get; } - public object? Result - { - get => _middlewareContext.Result; - set => _middlewareContext.Result = value; - } + public ISchema Schema => _middlewareContext.Schema; - public bool IsResultModified => - _middlewareContext.IsResultModified; + public IObjectType ObjectType => _middlewareContext.ObjectType; - public IServiceProvider Services - { - get => _middlewareContext.Services; - set => _middlewareContext.Services = value; - } + public IOperation Operation => _middlewareContext.Operation; - public ISchema Schema => - _middlewareContext.Schema; + public ISelection Selection => _middlewareContext.Selection; - public IObjectType RootType => - _middlewareContext.RootType; + public IVariableValueCollection Variables => _middlewareContext.Variables; - public IObjectType ObjectType => - _middlewareContext.ObjectType; + public Path Path => _middlewareContext.Path; - [Obsolete("Use Selection.Field or Selection.Type.")] - public IObjectField Field => - _middlewareContext.Field; + public T Parent() => _middlewareContext.Parent(); - public DocumentNode Document => _middlewareContext.Document; + public T ArgumentValue(NameString name) => _middlewareContext.ArgumentValue(name); - public DocumentNode QueryDocument => Document; + public TValueNode ArgumentLiteral(NameString name) where TValueNode : IValueNode + => _middlewareContext.ArgumentLiteral(name); - public OperationDefinitionNode Operation => - _middlewareContext.Operation; + public Optional ArgumentOptional(NameString name) + => _middlewareContext.ArgumentOptional(name); - [Obsolete("Use Selection.SyntaxNode")] - public FieldNode FieldSelection => - _middlewareContext.FieldSelection; + public ValueKind ArgumentKind(NameString name) => _middlewareContext.ArgumentKind(name); - public ISelection Selection => - _middlewareContext.Selection; + public T Service() => _middlewareContext.Service(); - public Path Path => - _middlewareContext.Path; + public T Resolver() => _middlewareContext.Resolver(); - public bool HasErrors => - _middlewareContext.HasErrors; + public IServiceProvider Services + { + get => _middlewareContext.Services; + set => _middlewareContext.Services = value; + } - public CancellationToken CancellationToken => - RequestAborted; + public NameString ResponseName => _middlewareContext.ResponseName; - public CancellationToken RequestAborted => - _middlewareContext.RequestAborted; + public bool HasErrors => _middlewareContext.HasErrors; - public IDictionary ContextData => - _middlewareContext.ContextData; + public IDictionary ContextData => _middlewareContext.ContextData; public IImmutableDictionary ScopedContextData { @@ -85,79 +67,52 @@ public IServiceProvider Services set => _middlewareContext.ScopedContextData = value; } - public NameString ResponseName => - _middlewareContext.ResponseName; - - public IVariableValueCollection Variables => - _middlewareContext.Variables; - public IImmutableDictionary LocalContextData { get => _middlewareContext.LocalContextData; set => _middlewareContext.LocalContextData = value; } - public IType? ValueType - { - get => _middlewareContext.ValueType; - set => _middlewareContext.ValueType = value; - } - - [Obsolete( - "Use ArgumentValue(name) or " + - "ArgumentLiteral(name) or " + - "ArgumentOptional(name).")] - [return: MaybeNull] - public T Argument(NameString name) => - _middlewareContext.Argument(name); + public CancellationToken RequestAborted => _middlewareContext.RequestAborted; - public T Parent() => _middlewareContext.Parent(); + public object Service(Type service) => _middlewareContext.Service(service); - public void ReportError(string errorMessage) => - _middlewareContext.ReportError(errorMessage); + public void ReportError(string errorMessage) => _middlewareContext.ReportError(errorMessage); - public void ReportError(IError error) => - _middlewareContext.ReportError(error); + public void ReportError(IError error) => _middlewareContext.ReportError(error); - public void ReportError(Exception exception, Action? configure = null) => - _middlewareContext.ReportError(exception, configure); + public void ReportError(Exception exception, Action? configure = null) + => _middlewareContext.ReportError(exception, configure); - public T Resolver() => - _middlewareContext.Resolver(); - - public T Service() => - _middlewareContext.Service(); - - public object Service(Type service) => - _middlewareContext.Service(service); - - public ValueTask ResolveAsync() => - _middlewareContext.ResolveAsync(); - - public void RegisterForCleanup(Action action) => - _middlewareContext.RegisterForCleanup(action); + public IReadOnlyList GetSelections( + ObjectType typeContext, + ISelection? fieldSelection = null, + bool allowInternals = false) + => _middlewareContext.GetSelections(typeContext, fieldSelection, allowInternals); - public IReadOnlyDictionary ReplaceArguments( - IReadOnlyDictionary argumentValues) => - _middlewareContext.ReplaceArguments(argumentValues); + public T GetQueryRoot() => _middlewareContext.GetQueryRoot(); - public ValueKind ArgumentKind(NameString name) => - _middlewareContext.ArgumentKind(name); + public IType? ValueType + { + get => _middlewareContext.ValueType; + set => _middlewareContext.ValueType = value; + } - public T ArgumentValue(NameString name) => - _middlewareContext.ArgumentValue(name); + public object? Result + { + get => _middlewareContext.Result; + set => _middlewareContext.Result = value; + } - public T ArgumentLiteral(NameString name) where T : IValueNode => - _middlewareContext.ArgumentLiteral(name); + public bool IsResultModified => _middlewareContext.IsResultModified; - public Optional ArgumentOptional(NameString name) => - _middlewareContext.ArgumentOptional(name); + public ValueTask ResolveAsync() + => _middlewareContext.ResolveAsync(); - public IReadOnlyList GetSelections( - ObjectType typeContext, - ISelection? fieldSelection = null, - bool allowInternals = false) => - _middlewareContext.GetSelections(typeContext, fieldSelection, allowInternals); + public void RegisterForCleanup(Action action) + => _middlewareContext.RegisterForCleanup(action); - public T GetQueryRoot() => _middlewareContext.GetQueryRoot(); + public IReadOnlyDictionary ReplaceArguments( + IReadOnlyDictionary argumentValues) + => _middlewareContext.ReplaceArguments(argumentValues); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs b/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs index 70a45ae89c6..41c3e9f5924 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs @@ -16,12 +16,12 @@ internal sealed class SuspendedWorkQueue public void CopyTo(WorkQueue work, WorkQueue serial, QueryPlanStateMachine stateMachine) { - IExecutionTask? head = _head; + var head = _head; _head = null; while (head is not null) { - IExecutionTask current = head; + var current = head; head = head.Next; current.Next = null; diff --git a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs index 7074554ad13..c585c856c3d 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs @@ -17,7 +17,7 @@ public T Argument(NameString name) { if (typeof(IValueNode).IsAssignableFrom(typeof(T))) { - IValueNode literal = ArgumentLiteral(name); + var literal = ArgumentLiteral(name); if (literal is T casted) { @@ -33,7 +33,7 @@ public T Argument(NameString name) public T ArgumentValue(NameString name) { - if (!Arguments.TryGetValue(name, out ArgumentValue? argument)) + if (!Arguments.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, Path, name); } @@ -43,7 +43,7 @@ public T ArgumentValue(NameString name) public Optional ArgumentOptional(NameString name) { - if (!Arguments.TryGetValue(name, out ArgumentValue? argument)) + if (!Arguments.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, Path, name); } @@ -55,12 +55,12 @@ public Optional ArgumentOptional(NameString name) public TValueNode ArgumentLiteral(NameString name) where TValueNode : IValueNode { - if (!Arguments.TryGetValue(name, out ArgumentValue? argument)) + if (!Arguments.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, Path, name); } - IValueNode literal = argument.ValueLiteral!; + var literal = argument.ValueLiteral!; if (literal is TValueNode castedLiteral) { @@ -73,7 +73,7 @@ public TValueNode ArgumentLiteral(NameString name) where TValueNode public ValueKind ArgumentKind(NameString name) { - if (!Arguments.TryGetValue(name, out ArgumentValue? argument)) + if (!Arguments.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, Path, name); } @@ -132,7 +132,7 @@ public IReadOnlyDictionary ReplaceArguments( throw new ArgumentNullException(nameof(argumentValues)); } - IReadOnlyDictionary original = Arguments; + var original = Arguments; Arguments = argumentValues; return original; } diff --git a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs index 0d7d58e54e2..63d3f6a06db 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs @@ -42,7 +42,7 @@ public bool Initialize( if (selection.Arguments.TryCoerceArguments( _parentContext, - out IReadOnlyDictionary? coercedArgs)) + out var coercedArgs)) { _argumentValues = coercedArgs; return true; @@ -91,7 +91,7 @@ public T Parent() public T ArgumentValue(NameString name) { - if (!_argumentValues.TryGetValue(name, out ArgumentValue? argument)) + if (!_argumentValues.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, _path, name); } @@ -102,12 +102,12 @@ public T ArgumentValue(NameString name) public TValueNode ArgumentLiteral(NameString name) where TValueNode : IValueNode { - if (!_argumentValues.TryGetValue(name, out ArgumentValue? argument)) + if (!_argumentValues.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, _path, name); } - IValueNode literal = argument.ValueLiteral!; + var literal = argument.ValueLiteral!; if (literal is TValueNode castedLiteral) { @@ -120,7 +120,7 @@ public TValueNode ArgumentLiteral(NameString name) public Optional ArgumentOptional(NameString name) { - if (!_argumentValues.TryGetValue(name, out ArgumentValue? argument)) + if (!_argumentValues.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, _path, name); } @@ -132,7 +132,7 @@ public Optional ArgumentOptional(NameString name) public ValueKind ArgumentKind(NameString name) { - if (!_argumentValues.TryGetValue(name, out ArgumentValue? argument)) + if (!_argumentValues.TryGetValue(name, out var argument)) { throw ResolverContext_ArgumentDoesNotExist(_selection.SyntaxNode, _path, name); } @@ -166,7 +166,7 @@ private T CoerceArgumentValue(ArgumentValue argument) return default!; } - ITypeConverter converter = _parentContext.GetTypeConverter(); + var converter = _parentContext.GetTypeConverter(); if (value is T castedValue || converter.TryConvert(value, out castedValue)) @@ -191,7 +191,7 @@ private T CoerceArgumentValue(ArgumentValue argument) if (typeof(T).IsInterface) { - object o = dictToObjConverter.Convert(value, argument.Type.RuntimeType); + var o = dictToObjConverter.Convert(value, argument.Type.RuntimeType); if (o is T c) { return c; diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs index 28938e454f3..925d40ab3a9 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs @@ -32,7 +32,7 @@ internal OperationCompiler(InputParser parser) _parser = parser ?? throw new ArgumentNullException(nameof(parser)); } - public IPreparedOperation Compile( + public IOperation Compile( string operationId, OperationDefinitionNode operationDefinition, ObjectType operationType, diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationContext.IExecutionTaskContext.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationContext.IExecutionTaskContext.cs index 4deb60d9ebd..5c3b009220f 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationContext.IExecutionTaskContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationContext.IExecutionTaskContext.cs @@ -35,7 +35,7 @@ private void ReportError(IExecutionTask task, IError error) if (error is AggregateError aggregateError) { - foreach (IError? innerError in aggregateError.Errors) + foreach (var innerError in aggregateError.Errors) { ReportSingle(innerError); } @@ -54,7 +54,7 @@ void AddProcessedError(IError processed) { if (processed is AggregateError ar) { - foreach (IError? ie in ar.Errors) + foreach (var ie in ar.Errors) { Result.AddError(ie); DiagnosticEvents.TaskError(task, ie); diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationContext.Pooling.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationContext.Pooling.cs index e465e22cf61..bc342c1d245 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationContext.Pooling.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationContext.Pooling.cs @@ -63,7 +63,7 @@ public void Clean() { if (!_cleanupActions.IsEmpty) { - while (_cleanupActions.TryTake(out Action? clean)) + while (_cleanupActions.TryTake(out var clean)) { clean(); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationResolverHelper.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationResolverHelper.cs index c92eae9ed17..caa5f826829 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationResolverHelper.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationResolverHelper.cs @@ -16,7 +16,7 @@ public static OperationDefinitionNode GetOperation( { OperationDefinitionNode? operation = null; - for (int i = 0; i < document.Definitions.Count; i++) + for (var i = 0; i < document.Definitions.Count; i++) { if (document.Definitions[i] is OperationDefinitionNode op) { @@ -40,7 +40,7 @@ public static OperationDefinitionNode GetOperation( } else { - for (int i = 0; i < document.Definitions.Count; i++) + for (var i = 0; i < document.Definitions.Count; i++) { if (document.Definitions[i] is OperationDefinitionNode { Name: { } } op && op.Name!.Value.EqualsOrdinal(operationName)) diff --git a/src/HotChocolate/Core/src/Execution/Processing/ResultHelper.cs b/src/HotChocolate/Core/src/Execution/Processing/ResultHelper.cs index 1947ef0c97c..72dc3157af1 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ResultHelper.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ResultHelper.cs @@ -40,7 +40,7 @@ public ResultMap RentResultMap(int capacity) lock (_syncMap) { - if (!_resultOwner.ResultMaps.TryPeek(out ResultObjectBuffer? buffer) || + if (!_resultOwner.ResultMaps.TryPeek(out var buffer) || !buffer.TryPop(out map)) { buffer = _resultPool.GetResultMap(); @@ -60,7 +60,7 @@ public ResultMapList RentResultMapList() lock (_syncMapList) { if (!_resultOwner.ResultMapLists.TryPeek( - out ResultObjectBuffer? buffer) || + out var buffer) || !buffer.TryPop(out mapList)) { buffer = _resultPool.GetResultMapList(); @@ -78,7 +78,7 @@ public ResultList RentResultList() lock (_syncList) { - if (!_resultOwner.ResultLists.TryPeek(out ResultObjectBuffer? buffer) || + if (!_resultOwner.ResultLists.TryPeek(out var buffer) || !buffer.TryPop(out list)) { buffer = _resultPool.GetResultList(); @@ -158,9 +158,9 @@ public void AddNonNullViolation(FieldNode selection, Path path, IResultMap paren public IQueryResult BuildResult() { - while (_data != null && _nonNullViolations.TryPop(out NonNullViolation violation)) + while (_data != null && _nonNullViolations.TryPop(out var violation)) { - Path? path = violation.Path; + var path = violation.Path; IResultData? parent = violation.Parent; if (!_fieldErrors.Contains(violation.Selection)) @@ -172,7 +172,7 @@ public IQueryResult BuildResult() { if (parent is ResultMap map && path is NamePathSegment nameSegment) { - ResultValue value = map.GetValue(nameSegment.Name.Value, out var index); + var value = map.GetValue(nameSegment.Name.Value, out var index); if (value.IsNullable) { @@ -261,7 +261,7 @@ public IQueryResult BuildResult() if (data.Count == 1) { - KeyValuePair value = data.Single(); + var value = data.Single(); return new SingleValueExtensionData(value.Key, value.Value); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/ResultMap.cs b/src/HotChocolate/Core/src/Execution/Processing/ResultMap.cs index b7c56c0d23c..cc16d794fbe 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ResultMap.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ResultMap.cs @@ -32,7 +32,7 @@ public ResultMap() { get { - ResultValue value = GetValue(key, out var index); + var value = GetValue(key, out var index); if (index == -1) { @@ -49,7 +49,7 @@ public ResultMap() { for (var i = 0; i < _capacity; i++) { - ResultValue value = _buffer[i]; + var value = _buffer[i]; if (value.IsInitialized) { @@ -65,7 +65,7 @@ public ResultMap() { for (var i = 0; i < _capacity; i++) { - ResultValue value = _buffer[i]; + var value = _buffer[i]; if (value.IsInitialized) { @@ -99,7 +99,7 @@ public ResultValue GetValue(string name, out int index) var i = (IntPtr)0; var length = _capacity; - ref ResultValue searchSpace = ref MemoryMarshal.GetReference(_buffer.AsSpan()); + ref var searchSpace = ref MemoryMarshal.GetReference(_buffer.AsSpan()); while (length > 0) { @@ -155,7 +155,7 @@ public IEnumerator GetEnumerator() { for (var i = 0; i < _capacity; i++) { - ResultValue value = _buffer[i]; + var value = _buffer[i]; if (value.IsInitialized) { @@ -171,7 +171,7 @@ public IEnumerator GetEnumerator() { for (var i = 0; i < _capacity; i++) { - ResultValue value = _buffer[i]; + var value = _buffer[i]; if (value.IsInitialized) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/ResultObjectBuffer.cs b/src/HotChocolate/Core/src/Execution/Processing/ResultObjectBuffer.cs index 47224dfbb69..333e02b6e4a 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ResultObjectBuffer.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ResultObjectBuffer.cs @@ -20,7 +20,7 @@ public ResultObjectBuffer(int capacity, IPooledObjectPolicy policy) public T Pop() { - if (TryPop(out T? obj)) + if (TryPop(out var obj)) { return obj; } diff --git a/src/HotChocolate/Core/src/Execution/Processing/ResultPool.cs b/src/HotChocolate/Core/src/Execution/Processing/ResultPool.cs index b4a8cf85a1a..9e8d4239756 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ResultPool.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ResultPool.cs @@ -36,7 +36,7 @@ public ResultObjectBuffer GetResultList() public void Return(IList> buffers) { - for (int i = 0; i < buffers.Count; i++) + for (var i = 0; i < buffers.Count; i++) { _resultMapPool.Return(buffers[i]); } @@ -44,7 +44,7 @@ public void Return(IList> buffers) public void Return(IList> buffers) { - for (int i = 0; i < buffers.Count; i++) + for (var i = 0; i < buffers.Count; i++) { _resultMapListPool.Return(buffers[i]); } @@ -52,7 +52,7 @@ public void Return(IList> buffers) public void Return(IList> buffers) { - for (int i = 0; i < buffers.Count; i++) + for (var i = 0; i < buffers.Count; i++) { _resultListPool.Return(buffers[i]); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs b/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs index e36d61de39c..6cc574062a4 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs @@ -153,19 +153,19 @@ public async ValueTask DisposeAsync() /// private async Task OnEvent(object payload) { - using IDisposable es = _diagnosticEvents.OnSubscriptionEvent(new(this, payload)); - using IServiceScope serviceScope = _requestContext.Services.CreateScope(); + using var es = _diagnosticEvents.OnSubscriptionEvent(new(this, payload)); + using var serviceScope = _requestContext.Services.CreateScope(); - OperationContext operationContext = _operationContextPool.Get(); + var operationContext = _operationContextPool.Get(); try { - IServiceProvider? eventServices = serviceScope.ServiceProvider; - IBatchDispatcher? dispatcher = eventServices.GetRequiredService(); + var eventServices = serviceScope.ServiceProvider; + var dispatcher = eventServices.GetRequiredService(); // we store the event payload on the scoped context so that it is accessible // in the resolvers. - IImmutableDictionary scopedContext = + var scopedContext = _scopedContextData.SetItem(WellKnownContextData.EventMessage, payload); // next we resolve the subscription instance. @@ -191,7 +191,7 @@ private async Task OnEvent(object payload) WellKnownContextData.EventMessage, payload); - IQueryResult result = await _queryExecutor + var result = await _queryExecutor .ExecuteAsync(operationContext, scopedContext) .ConfigureAwait(false); @@ -216,7 +216,7 @@ private async Task OnEvent(object payload) // the event messages from the underlying pub/sub-system. private async ValueTask SubscribeAsync() { - OperationContext operationContext = _operationContextPool.Get(); + var operationContext = _operationContextPool.Get(); try { @@ -244,8 +244,8 @@ private async ValueTask SubscribeAsync() // next we need a result map so that we can store the subscribe temporarily // while executing the subscribe pipeline. - ResultMap resultMap = operationContext.Result.RentResultMap(1); - ISelection rootSelection = _rootSelections.Selections[0]; + var resultMap = operationContext.Result.RentResultMap(1); + var rootSelection = _rootSelections.Selections[0]; // we create a temporary middleware context so that we can use the standard // resolver pipeline. @@ -263,7 +263,7 @@ private async ValueTask SubscribeAsync() // invoking subscribe. if (!rootSelection.Arguments.TryCoerceArguments( middlewareContext, - out IReadOnlyDictionary? coercedArgs)) + out var coercedArgs)) { // the middleware context reports errors to the operation context, // this means if we failed, we need to grab the coercion errors from there @@ -276,7 +276,7 @@ private async ValueTask SubscribeAsync() // last but not least we can invoke the subscribe resolver which will subscribe // to the underlying pub/sub-system yielding the source stream. - ISourceStream sourceStream = + var sourceStream = await rootSelection.Field.SubscribeResolver!.Invoke(middlewareContext) .ConfigureAwait(false); _scopedContextData = middlewareContext.ScopedContextData; @@ -330,7 +330,7 @@ public IAsyncEnumerator GetAsyncEnumerator( { try { - IAsyncEnumerator eventStreamEnumerator = + var eventStreamEnumerator = _sourceStream.ReadEventsAsync() .GetAsyncEnumerator(cancellationToken); diff --git a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Leaf.cs b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Leaf.cs index 684525b46a2..b7f2e807077 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Leaf.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Leaf.cs @@ -19,7 +19,7 @@ private static bool TryCompleteLeafValue( try { var leafType = (ILeafType)fieldType; - Type runtimeType = leafType.RuntimeType; + var runtimeType = leafType.RuntimeType; if (!runtimeType.IsInstanceOfType(result) && operationContext.Converter.TryConvert(runtimeType, result, out var c)) diff --git a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.List.cs b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.List.cs index 9ea7af1f090..f67fe0cc396 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.List.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.List.cs @@ -21,7 +21,7 @@ private static bool TryCompleteListValue( List bufferedTasks, out object? completedValue) { - IType elementType = fieldType.InnerType(); + var elementType = fieldType.InnerType(); if (elementType.Kind is TypeKind.NonNull) { @@ -68,8 +68,8 @@ private static bool TryCompleteCompositeListValue( List bufferedTasks, out object? completedResult) { - ResultMapList resultList = operationContext.Result.RentResultMapList(); - IType elementType = fieldType.InnerType(); + var resultList = operationContext.Result.RentResultMapList(); + var elementType = fieldType.InnerType(); resultList.IsNullable = elementType.Kind is not TypeKind.NonNull; if (result is Array array) @@ -174,8 +174,8 @@ private static bool TryCompleteOtherListValue( List bufferedTasks, out object? completedResult) { - ResultList resultList = operationContext.Result.RentResultList(); - IType elementType = fieldType.InnerType(); + var resultList = operationContext.Result.RentResultList(); + var elementType = fieldType.InnerType(); resultList.IsNullable = elementType.Kind is not TypeKind.NonNull; var isElementList = elementType.IsListType(); diff --git a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Tools.cs b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Tools.cs index d8d65f417b4..0e7dec1f683 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Tools.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.Tools.cs @@ -12,7 +12,7 @@ public static void ReportError( { if (error is AggregateError aggregateError) { - foreach (IError? innerError in aggregateError.Errors) + foreach (var innerError in aggregateError.Errors) { ReportSingle(innerError); } @@ -31,7 +31,7 @@ void AddProcessedError(IError processed) { if (processed is AggregateError ar) { - foreach (IError? ie in ar.Errors) + foreach (var ie in ar.Errors) { operationContext.Result.AddError(ie, selection.SyntaxNode); operationContext.DiagnosticEvents.ResolverError(resolverContext, ie); @@ -59,14 +59,14 @@ public static void ReportError( if (exception is GraphQLException graphQLException) { - foreach (IError error in graphQLException.Errors) + foreach (var error in graphQLException.Errors) { ReportError(operationContext, resolverContext, selection, error); } } else { - IError error = operationContext.ErrorHandler + var error = operationContext.ErrorHandler .CreateUnexpectedError(exception) .SetPath(path) .AddLocation(selection.SyntaxNode) diff --git a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.cs b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.cs index 39d4d4a3fff..e2299092afc 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ValueCompletion.cs @@ -19,7 +19,7 @@ public static bool TryComplete( List bufferedTasks, out object? completedResult) { - TypeKind typeKind = fieldType.Kind; + var typeKind = fieldType.Kind; if (typeKind is TypeKind.NonNull) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/VariableCoercionHelper.cs b/src/HotChocolate/Core/src/Execution/Processing/VariableCoercionHelper.cs index 23c4a5b3f9b..30059455462 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/VariableCoercionHelper.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/VariableCoercionHelper.cs @@ -47,9 +47,9 @@ public void CoerceVariableValues( for (var i = 0; i < variableDefinitions.Count; i++) { - VariableDefinitionNode variableDefinition = variableDefinitions[i]; + var variableDefinition = variableDefinitions[i]; var variableName = variableDefinition.Variable.Name.Value; - IInputType variableType = AssertInputType(schema, variableDefinition); + var variableType = AssertInputType(schema, variableDefinition); VariableValueOrLiteral coercedVariable; var hasValue = values.TryGetValue(variableName, out var value); @@ -115,7 +115,7 @@ private VariableValueOrLiteral CoerceVariableValue( } var runtimeValue = _inputParser.ParseResult(value, variableType, root); - IValueNode literal = _inputFormatter.FormatResult(value, variableType, root); + var literal = _inputFormatter.FormatResult(value, variableType, root); return new VariableValueOrLiteral(variableType, runtimeValue, literal); } @@ -169,7 +169,7 @@ private static ObjectValueNode Rewrite( for (var i = 0; i < node.Fields.Count; i++) { - ObjectFieldNode current = node.Fields[i]; + var current = node.Fields[i]; if (!inputObjectType.Fields.TryGetField(current.Name.Value, out IInputField? field)) { @@ -178,7 +178,7 @@ private static ObjectValueNode Rewrite( continue; } - IValueNode rewritten = Rewrite(field.Type, current.Value); + var rewritten = Rewrite(field.Type, current.Value); // we try initially just to traverse the input graph, only if we detect a change // will we create a new input object. In this case if the fields list is initialized @@ -218,13 +218,13 @@ private static ListValueNode Rewrite(IType inputType, ListValueNode node) return node; } - IType elementType = inputType.ListType().ElementType; + var elementType = inputType.ListType().ElementType; List? values = null; for (var i = 0; i < node.Items.Count; i++) { - IValueNode current = node.Items[i]; - IValueNode value = Rewrite(elementType, current); + var current = node.Items[i]; + var value = Rewrite(elementType, current); // we try initially just to traverse the list graph, only if we detect a change // will we create a new list object. In this case if values list is initialized diff --git a/src/HotChocolate/Core/src/Execution/Processing/VariableRewriter.cs b/src/HotChocolate/Core/src/Execution/Processing/VariableRewriter.cs index cb179004bfd..9060f49895f 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/VariableRewriter.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/VariableRewriter.cs @@ -52,7 +52,7 @@ public static IValueNode Rewrite( type, defaultValue ?? NullValueNode.Default, variableValues, - out IValueNode? rewritten) + out var rewritten) ? rewritten : node; } @@ -69,11 +69,11 @@ private static ObjectValueNode Rewrite( if (node.Fields.Count == 1) { - bool oneOf = type.Directives.Contains(WellKnownDirectives.OneOf); - ObjectFieldNode value = node.Fields[0]; + var oneOf = type.Directives.Contains(WellKnownDirectives.OneOf); + var value = node.Fields[0]; - if (type.Fields.TryGetField(value.Name.Value, out InputField? field) && - TryRewriteField(value, field, variableValues, out ObjectFieldNode? rewritten)) + if (type.Fields.TryGetField(value.Name.Value, out var field) && + TryRewriteField(value, field, variableValues, out var rewritten)) { if (oneOf && rewritten.Value.Kind is SyntaxKind.NullValue) { @@ -92,10 +92,10 @@ private static ObjectValueNode Rewrite( for (var i = 0; i < node.Fields.Count; i++) { - ObjectFieldNode value = node.Fields[i]; + var value = node.Fields[i]; - if (type.Fields.TryGetField(value.Name.Value, out InputField? field) && - TryRewriteField(value, field, variableValues, out ObjectFieldNode? rewritten)) + if (type.Fields.TryGetField(value.Name.Value, out var field) && + TryRewriteField(value, field, variableValues, out var rewritten)) { if (rewrittenItems is null) { @@ -132,7 +132,7 @@ private static bool TryRewriteField( field.Type, field.DefaultValue ?? NullValueNode.Default, variableValues, - out IValueNode? rewrittenValue)) + out var rewrittenValue)) { rewritten = original.WithValue(rewrittenValue); return true; @@ -152,7 +152,7 @@ private static ObjectValueNode Rewrite( type.ElementType, NullValueNode.Default, variableValues, - out IValueNode? rewritten) && + out var rewritten) && rewritten is ObjectValueNode rewrittenObj ? rewrittenObj : node; @@ -175,7 +175,7 @@ private static ListValueNode Rewrite( type.ElementType, NullValueNode.Default, variableValues, - out IValueNode? rewritten) + out var rewritten) ? node.WithItems(new[] { rewritten }) : node; } @@ -189,7 +189,7 @@ private static ListValueNode Rewrite( type.ElementType, NullValueNode.Default, variableValues, - out IValueNode? rewritten)) + out var rewritten)) { if (rewrittenItems is null) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/VariableValueCollection.cs b/src/HotChocolate/Core/src/Execution/Processing/VariableValueCollection.cs index 76bceef76af..36349159a8f 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/VariableValueCollection.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/VariableValueCollection.cs @@ -35,9 +35,9 @@ public VariableValueCollection(Dictionary coerce public bool TryGetVariable(NameString name, out T? value) { - if (_coercedValues.TryGetValue(name.Value, out VariableValueOrLiteral variableValue)) + if (_coercedValues.TryGetValue(name.Value, out var variableValue)) { - Type requestedType = typeof(T); + var requestedType = typeof(T); if (requestedType == typeof(IValueNode)) { @@ -82,10 +82,10 @@ public bool TryGetVariable(NameString name, out T? value) public IEnumerator GetEnumerator() { - foreach (KeyValuePair item in _coercedValues) + foreach (var item in _coercedValues) { - IInputType type = item.Value.Type; - IValueNode value = item.Value.ValueLiteral; + var type = item.Value.Type; + var value = item.Value.ValueLiteral; yield return new VariableValue(item.Key, type, value); } } diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs index 8ba78b87d6f..90a4646d596 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs @@ -16,7 +16,7 @@ public async Task ExecuteAsync() _suspended.CopyTo(_work, _serial, _stateMachine); } - IExecutionTask?[] buffer = _buffer; + var buffer = _buffer; RESTART: lock (_sync) @@ -50,7 +50,7 @@ public async Task ExecuteAsync() for (var i = 0; i < work; i++) { - IExecutionTask task = buffer[i]!; + var task = buffer[i]!; task.BeginExecute(_requestAborted); await task.WaitForCompletionAsync(_requestAborted) .ConfigureAwait(false); @@ -91,7 +91,7 @@ await task.WaitForCompletionAsync(_requestAborted) private void HandleError(Exception exception) { - IError error = + var error = _errorHandler .CreateUnexpectedError(exception) .SetCode(ErrorCodes.Execution.TaskProcessingError) @@ -101,7 +101,7 @@ private void HandleError(Exception exception) if (error is AggregateError aggregateError) { - foreach (IError? innerError in aggregateError.Errors) + foreach (var innerError in aggregateError.Errors) { _result.AddError(innerError); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs index f6af1f78539..de49acc6e18 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs @@ -14,13 +14,13 @@ void IQueryPlanState.RegisterUnsafe(IReadOnlyList tasks) { for (var i = 0; i < tasks.Count; i++) { - IExecutionTask task = tasks[i]; + var task = tasks[i]; _stateMachine.TryInitializeTask(task); task.IsRegistered = true; if (_stateMachine.RegisterTask(task)) { - WorkQueue work = task.IsSerial ? _serial : _work; + var work = task.IsSerial ? _serial : _work; work.Push(task); } else diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs index e5f5e3a08d7..3abde433d3e 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs @@ -50,7 +50,7 @@ public void Register(IExecutionTask task) { if (_stateMachine.RegisterTask(task)) { - WorkQueue work = task.IsSerial ? _serial : _work; + var work = task.IsSerial ? _serial : _work; work.Push(task); start = ShouldStartProcessing(); } @@ -87,7 +87,7 @@ public void Register(IReadOnlyList tasks) // interact with the task object itself. for (var i = 0; i < tasks.Count; i++) { - IExecutionTask task = tasks[i]; + var task = tasks[i]; _stateMachine.TryInitializeTask(task); task.IsRegistered = true; } @@ -96,11 +96,11 @@ public void Register(IReadOnlyList tasks) { for (var i = 0; i < tasks.Count; i++) { - IExecutionTask task = tasks[i]; + var task = tasks[i]; if (_stateMachine.RegisterTask(task)) { - WorkQueue work = task.IsSerial ? _serial : _work; + var work = task.IsSerial ? _serial : _work; work.Push(task); start = true; } @@ -148,7 +148,7 @@ public void Complete(IExecutionTask task) if (task.IsRegistered) { // determine the work queue. - WorkQueue work = task.IsSerial ? _serial : _work; + var work = task.IsSerial ? _serial : _work; // now we complete the work queue which will signal to the execution context // that work has been completed if it has no more tasks enqueued or marked @@ -204,11 +204,11 @@ private int TryTake(IExecutionTask?[] buffer) lock (_sync) { - WorkQueue work = _stateMachine.IsSerial ? _serial : _work; + var work = _stateMachine.IsSerial ? _serial : _work; for (var i = 0; i < buffer.Length; i++) { - if (!work.TryTake(out IExecutionTask? task)) + if (!work.TryTake(out var task)) { break; } @@ -327,7 +327,7 @@ private void EnsureContextIsClean() void CancelTasks(WorkQueue queue) { - while (queue.TryTake(out IExecutionTask? task)) + while (queue.TryTake(out var task)) { if (task is ResolverTask resolverTask) { @@ -338,7 +338,7 @@ void CancelTasks(WorkQueue queue) void CancelSuspendedTasks(SuspendedWorkQueue queue) { - while (queue.TryDequeue(out IExecutionTask? task)) + while (queue.TryDequeue(out var task)) { if (task is ResolverTask resolverTask) { diff --git a/src/HotChocolate/Core/src/Execution/RequestContext.cs b/src/HotChocolate/Core/src/Execution/RequestContext.cs index d06baab0180..5a618e658fa 100644 --- a/src/HotChocolate/Core/src/Execution/RequestContext.cs +++ b/src/HotChocolate/Core/src/Execution/RequestContext.cs @@ -75,7 +75,7 @@ public DocumentValidatorResult? ValidationResult public string? OperationId { get; set; } - public IPreparedOperation? Operation { get; set; } + public IOperation? Operation { get; set; } public IVariableValueCollection? Variables { get; set; } @@ -110,7 +110,7 @@ public IRequestContext Clone() if (_contextData is not null) { - foreach (KeyValuePair item in ContextData) + foreach (var item in ContextData) { cloned._contextData.TryAdd(item.Key, item.Value); } @@ -126,7 +126,7 @@ public void Initialize(IQueryRequest request, IServiceProvider services) if (request.ContextData is not null) { - foreach (KeyValuePair item in request.ContextData) + foreach (var item in request.ContextData) { _contextData.TryAdd(item.Key, item.Value); } diff --git a/src/HotChocolate/Core/src/Execution/RequestExecutor.cs b/src/HotChocolate/Core/src/Execution/RequestExecutor.cs index 3e5dc0f4eb9..ae50f33a0a2 100644 --- a/src/HotChocolate/Core/src/Execution/RequestExecutor.cs +++ b/src/HotChocolate/Core/src/Execution/RequestExecutor.cs @@ -59,15 +59,15 @@ public async Task ExecuteAsync( throw new ArgumentNullException(nameof(request)); } - IServiceScope? scope = request.Services is null + var scope = request.Services is null ? _applicationServices.CreateScope() : null; - IServiceProvider services = scope is null + var services = scope is null ? request.Services! : scope.ServiceProvider; - RequestContext context = _contextPool.Get(); + var context = _contextPool.Get(); try { diff --git a/src/HotChocolate/Core/src/Execution/RequestExecutorProxy.cs b/src/HotChocolate/Core/src/Execution/RequestExecutorProxy.cs index 0c5edb5a20d..07e6405e3ad 100644 --- a/src/HotChocolate/Core/src/Execution/RequestExecutorProxy.cs +++ b/src/HotChocolate/Core/src/Execution/RequestExecutorProxy.cs @@ -64,11 +64,11 @@ public async Task ExecuteAsync( throw new ArgumentNullException(nameof(request)); } - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(cancellationToken) .ConfigureAwait(false); - IExecutionResult result = + var result = await executor .ExecuteAsync(request, cancellationToken) .ConfigureAwait(false); @@ -97,11 +97,11 @@ public async Task ExecuteBatchAsync( throw new ArgumentNullException(nameof(requestBatch)); } - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(cancellationToken) .ConfigureAwait(false); - IResponseStream result = + var result = await executor .ExecuteBatchAsync(requestBatch, cancellationToken) .ConfigureAwait(false); @@ -121,7 +121,7 @@ await executor public async ValueTask GetSchemaAsync( CancellationToken cancellationToken) { - IRequestExecutor executor = + var executor = await GetRequestExecutorAsync(cancellationToken) .ConfigureAwait(false); return executor.Schema; @@ -139,7 +139,7 @@ await GetRequestExecutorAsync(cancellationToken) public async ValueTask GetRequestExecutorAsync( CancellationToken cancellationToken) { - IRequestExecutor? executor = _executor; + var executor = _executor; if (executor is null) { diff --git a/src/HotChocolate/Core/src/Execution/RequestExecutorResolver.cs b/src/HotChocolate/Core/src/Execution/RequestExecutorResolver.cs index 7f9a7c49dd4..bfbaa8929c5 100644 --- a/src/HotChocolate/Core/src/Execution/RequestExecutorResolver.cs +++ b/src/HotChocolate/Core/src/Execution/RequestExecutorResolver.cs @@ -53,7 +53,7 @@ public async ValueTask GetRequestExecutorAsync( { schemaName = schemaName.HasValue ? schemaName : Schema.DefaultName; - if (!_executors.TryGetValue(schemaName, out RegisteredExecutor? re)) + if (!_executors.TryGetValue(schemaName, out var re)) { await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -77,13 +77,13 @@ public async ValueTask GetRequestExecutorNoLockAsync( { schemaName = schemaName.HasValue ? schemaName : Schema.DefaultName; - if (!_executors.TryGetValue(schemaName, out RegisteredExecutor? re)) + if (!_executors.TryGetValue(schemaName, out var re)) { - RequestExecutorSetup options = + var options = await _optionsMonitor.GetAsync(schemaName, cancellationToken) .ConfigureAwait(false); - IServiceProvider schemaServices = + var schemaServices = await CreateSchemaServicesAsync(schemaName, options, cancellationToken) .ConfigureAwait(false); @@ -94,7 +94,7 @@ await CreateSchemaServicesAsync(schemaName, options, cancellationToken) options, schemaServices.GetRequiredService()); - foreach (OnRequestExecutorCreatedAction action in options.OnRequestExecutorCreated) + foreach (var action in options.OnRequestExecutorCreated) { action.Action?.Invoke(re.Executor); @@ -116,7 +116,7 @@ public void EvictRequestExecutor(NameString schemaName = default) { schemaName = schemaName.HasValue ? schemaName : Schema.DefaultName; - if (_executors.TryRemove(schemaName, out RegisteredExecutor? re)) + if (_executors.TryRemove(schemaName, out var re)) { re.DiagnosticEvents.ExecutorEvicted(schemaName, re.Executor); @@ -140,7 +140,7 @@ private static void BeginRunEvictionEvents(RegisteredExecutor registeredExecutor { try { - foreach (OnRequestExecutorEvictedAction action in + foreach (var action in registeredExecutor.Setup.OnRequestExecutorEvicted) { action.Action?.Invoke(registeredExecutor.Executor); @@ -180,7 +180,7 @@ private async Task CreateSchemaServicesAsync( var typeModuleChangeMonitor = new TypeModuleChangeMonitor(this, schemaName); var lazy = new SchemaBuilder.LazySchema(); - RequestExecutorOptions executorOptions = + var executorOptions = await CreateExecutorOptionsAsync(options, cancellationToken) .ConfigureAwait(false); @@ -188,7 +188,7 @@ await CreateExecutorOptionsAsync(options, cancellationToken) // type module change monitor. // The module will track if type modules signal changes to the schema and // start a schema eviction. - foreach (ITypeModule? typeModule in options.TypeModules) + foreach (var typeModule in options.TypeModules) { typeModuleChangeMonitor.Register(typeModule); } @@ -217,13 +217,13 @@ await CreateExecutorOptionsAsync(options, cancellationToken) serviceCollection.TryAddTimespanProvider(); // register global error filters - foreach (IErrorFilter errorFilter in _applicationServices.GetServices()) + foreach (var errorFilter in _applicationServices.GetServices()) { serviceCollection.AddSingleton(errorFilter); } // register global diagnostic listener - foreach (IExecutionDiagnosticEventListener diagnosticEventListener in + foreach (var diagnosticEventListener in _applicationServices.GetServices()) { serviceCollection.AddSingleton(diagnosticEventListener); @@ -248,7 +248,7 @@ await CreateExecutorOptionsAsync(options, cancellationToken) serviceCollection.TryAddSingleton>(sp => { - ObjectPoolProvider provider = sp.GetRequiredService(); + var provider = sp.GetRequiredService(); var policy = new RequestContextPooledObjectPolicy( sp.GetRequiredService(), sp.GetRequiredService(), @@ -270,13 +270,13 @@ await CreateExecutorOptionsAsync(options, cancellationToken) sp.GetRequiredService>(), version)); - foreach (Action configureServices in options.SchemaServices) + foreach (var configureServices in options.SchemaServices) { configureServices(serviceCollection); } - ServiceProvider schemaServices = serviceCollection.BuildServiceProvider(); - IServiceProvider combinedServices = schemaServices.Include(_applicationServices); + var schemaServices = serviceCollection.BuildServiceProvider(); + var combinedServices = schemaServices.Include(_applicationServices); lazy.Schema = await CreateSchemaAsync( @@ -305,17 +305,17 @@ private async ValueTask CreateSchemaAsync( return options.Schema; } - ISchemaBuilder schemaBuilder = options.SchemaBuilder ?? new SchemaBuilder(); - ComplexityAnalyzerSettings complexitySettings = executorOptions.Complexity; + var schemaBuilder = options.SchemaBuilder ?? new SchemaBuilder(); + var complexitySettings = executorOptions.Complexity; schemaBuilder .AddServices(serviceProvider) .SetContextData(typeof(RequestExecutorOptions).FullName!, executorOptions) .SetContextData(typeof(ComplexityAnalyzerSettings).FullName!, complexitySettings); - IDescriptorContext context = schemaBuilder.CreateContext(); + var context = schemaBuilder.CreateContext(); - await foreach (ITypeSystemMember member in + await foreach (var member in typeModuleChangeMonitor.CreateTypesAsync(context) .WithCancellation(cancellationToken) .ConfigureAwait(false)) @@ -332,7 +332,7 @@ private async ValueTask CreateSchemaAsync( } } - foreach (SchemaBuilderAction action in options.SchemaBuilderActions) + foreach (var action in options.SchemaBuilderActions) { if (action.Action is { } configure) { @@ -348,7 +348,7 @@ await configureAsync(serviceProvider, schemaBuilder, cancellationToken) schemaBuilder.TryAddTypeInterceptor(new SetSchemaNameInterceptor(schemaName)); - ISchema schema = schemaBuilder.Create(context); + var schema = schemaBuilder.Create(context); AssertSchemaNameValid(schema, schemaName); return schema; } @@ -367,11 +367,11 @@ private static async ValueTask CreateExecutorOptionsAsyn RequestExecutorSetup options, CancellationToken cancellationToken) { - RequestExecutorOptions executorOptions = + var executorOptions = options.RequestExecutorOptions ?? new RequestExecutorOptions(); - foreach (RequestExecutorOptionsAction action in options.RequestExecutorOptionsActions) + foreach (var action in options.RequestExecutorOptionsActions) { if (action.Action is { } configure) { @@ -518,7 +518,7 @@ public void Dispose() { if (!_disposed) { - foreach (ITypeModule? typeModule in _typeModules) + foreach (var typeModule in _typeModules) { typeModule.TypesChanged -= EvictRequestExecutor; } @@ -544,13 +544,13 @@ public TypeModuleEnumerable( public async IAsyncEnumerator GetAsyncEnumerator( CancellationToken cancellationToken = default) { - foreach (ITypeModule? typeModule in _typeModules) + foreach (var typeModule in _typeModules) { - IReadOnlyCollection types = + var types = await typeModule.CreateTypesAsync(_context, cancellationToken) .ConfigureAwait(false); - foreach (ITypeSystemMember type in types) + foreach (var type in types) { yield return type; } diff --git a/src/HotChocolate/Core/src/Execution/Serialization/JsonArrayResponseStreamFormatter.cs b/src/HotChocolate/Core/src/Execution/Serialization/JsonArrayResponseStreamFormatter.cs index 12fa7e2aee3..62d737bba7f 100644 --- a/src/HotChocolate/Core/src/Execution/Serialization/JsonArrayResponseStreamFormatter.cs +++ b/src/HotChocolate/Core/src/Execution/Serialization/JsonArrayResponseStreamFormatter.cs @@ -78,7 +78,7 @@ private async Task WriteStreamAsync( await outputStream.WriteAsync(new[] { _leftBracket }, 0, 1, ct).ConfigureAwait(false); - await foreach (IQueryResult result in + await foreach (var result in responseStream.ReadResultsAsync().WithCancellation(ct).ConfigureAwait(false)) { try diff --git a/src/HotChocolate/Core/src/Execution/Serialization/JsonQueryResultFormatter.cs b/src/HotChocolate/Core/src/Execution/Serialization/JsonQueryResultFormatter.cs index 47023811c17..e5fba8c4191 100644 --- a/src/HotChocolate/Core/src/Execution/Serialization/JsonQueryResultFormatter.cs +++ b/src/HotChocolate/Core/src/Execution/Serialization/JsonQueryResultFormatter.cs @@ -277,7 +277,7 @@ private static void WritePathValue(Utf8JsonWriter writer, Path path) writer.WriteStartArray(); - IReadOnlyList list = path.ToList(); + var list = path.ToList(); for (var i = 0; i < list.Count; i++) { @@ -329,7 +329,7 @@ private void WriteDictionary( { writer.WriteStartObject(); - foreach (KeyValuePair item in dict) + foreach (var item in dict) { writer.WritePropertyName(item.Key); WriteFieldValue(writer, item.Value); @@ -346,7 +346,7 @@ private void WriteResultMap( for (var i = 0; i < resultMap.Count; i++) { - ResultValue value = resultMap[i]; + var value = resultMap[i]; if (value.IsInitialized) { writer.WritePropertyName(value.Name); diff --git a/src/HotChocolate/Core/src/Execution/Serialization/MultiPartResponseStreamFormatter.cs b/src/HotChocolate/Core/src/Execution/Serialization/MultiPartResponseStreamFormatter.cs index d130b7cda84..727eb222609 100644 --- a/src/HotChocolate/Core/src/Execution/Serialization/MultiPartResponseStreamFormatter.cs +++ b/src/HotChocolate/Core/src/Execution/Serialization/MultiPartResponseStreamFormatter.cs @@ -74,7 +74,7 @@ private async Task WriteResponseStreamAsync( { await WriteNextAsync(outputStream, ct).ConfigureAwait(false); - await foreach (IQueryResult result in + await foreach (var result in responseStream.ReadResultsAsync().WithCancellation(ct).ConfigureAwait(false)) { try diff --git a/src/HotChocolate/Core/src/Execution/ThrowHelper.cs b/src/HotChocolate/Core/src/Execution/ThrowHelper.cs index 4ccd42ad21e..f4be84f2494 100644 --- a/src/HotChocolate/Core/src/Execution/ThrowHelper.cs +++ b/src/HotChocolate/Core/src/Execution/ThrowHelper.cs @@ -45,7 +45,7 @@ public static GraphQLException VariableValueInvalidType( ? serializationException.Message : null; - IErrorBuilder errorBuilder = ErrorBuilder.New() + var errorBuilder = ErrorBuilder.New() .SetMessage( ThrowHelper_VariableValueInvalidType_Message, variableDefinition.Variable.Name.Value) diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/IArgumentMap.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/IArgumentMap.cs index 1cda51c04a5..00f6137e543 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/IArgumentMap.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/IArgumentMap.cs @@ -1,3 +1,5 @@ +#nullable enable + using System.Collections.Generic; using HotChocolate.Resolvers; diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/IFragment.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/IFragment.cs index 0f9eb8089e5..688e9c233f5 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/IFragment.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/IFragment.cs @@ -1,3 +1,5 @@ +#nullable enable + using System.Collections.Generic; using HotChocolate.Language; using HotChocolate.Types; diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/IOperation.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/IOperation.cs index 15272941424..524381d31e4 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/IOperation.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/IOperation.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using HotChocolate.Language; -using HotChocolate.Resolvers; using HotChocolate.Types; namespace HotChocolate.Execution.Processing; diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/IOptionalSelection.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/IOptionalSelection.cs index 02a10b4c149..27be66070ba 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/IOptionalSelection.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/IOptionalSelection.cs @@ -1,3 +1,4 @@ +#nullable enable namespace HotChocolate.Execution.Processing; diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionSet.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionSet.cs index 509213ecea3..94976f8ba94 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionSet.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionSet.cs @@ -1,3 +1,5 @@ +#nullable enable + using System.Collections.Generic; namespace HotChocolate.Execution.Processing; diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionVariants.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionVariants.cs index 0f011b7c71d..fe6bb62437e 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionVariants.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/ISelectionVariants.cs @@ -1,3 +1,5 @@ +#nullable enable + using System.Collections.Generic; using HotChocolate.Types; diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/SelectionExecutionStrategy.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/SelectionExecutionStrategy.cs index 8ff5cfc74df..972ca481bc0 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/SelectionExecutionStrategy.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/SelectionExecutionStrategy.cs @@ -1,3 +1,5 @@ +#nullable enable + namespace HotChocolate.Execution.Processing; /// From b86b580ff5d2f4b92468006a0279092efb10701b Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Wed, 22 Jun 2022 22:36:49 +0200 Subject: [PATCH 02/11] started work on the work scheduler --- .../Execution/HotChocolate.Execution.csproj | 18 +++++ .../Execution/Processing/DirectiveContext.cs | 4 +- .../Execution/Processing/IOperationContext.cs | 2 +- .../src/Execution/Processing/ISubscription.cs | 2 +- .../Processing/MiddlewareContext.Arguments.cs | 2 +- .../Processing/MiddlewareContext.Global.cs | 28 ++------ .../Processing/MiddlewareContext.Pure.cs | 4 +- .../src/Execution/Processing/Operation.cs | 10 ++- .../OperationCompiler.Optimizers.cs | 6 +- .../Execution/Processing/OperationCompiler.cs | 18 +++-- .../SelectionSetOptimizerContext.cs | 3 +- .../SubscriptionExecutor.Subscription.cs | 11 +-- .../Processing/SubscriptionExecutor.cs | 7 -- .../Processing/Tasks/ResolverTask.cs | 2 +- .../Properties/Resources.Designer.cs | 6 ++ .../src/Execution/Properties/Resources.resx | 3 + .../AggregateSchemaInterceptor.cs | 6 +- .../Configuration/AggregateTypeInterceptor.cs | 58 +++++++-------- .../DependantFactoryTypeReferenceHandler.cs | 2 +- .../ExtendedTypeReferenceHandler.cs | 10 +-- .../FactoryTypeReferenceHandler.cs | 2 +- .../RegisteredType.CompletionContext.cs | 2 +- .../RegisteredType.DiscoveryContext.cs | 4 +- .../SchemaTypeReferenceHandler.cs | 2 +- .../Types/Configuration/SchemaTypeResolver.cs | 6 +- .../SyntaxTypeReferenceHandler.cs | 4 +- .../src/Types/Configuration/TypeDiscoverer.cs | 20 +++--- .../Types/Configuration/TypeInitializer.cs | 52 +++++++------- .../src/Types/Configuration/TypeLookup.cs | 8 +-- .../Configuration/TypeReferenceResolver.cs | 18 ++--- .../src/Types/Configuration/TypeRegistrar.cs | 16 ++--- .../src/Types/Configuration/TypeRegistry.cs | 12 ++-- .../src/Types/Configuration/TypeTrimmer.cs | 26 +++---- .../Validation/DirectiveValidationRule.cs | 2 +- .../InputObjectTypeValidationRule.cs | 4 +- ...nterfaceHasAtLeastOneImplementationRule.cs | 8 +-- .../Validation/InterfaceTypeValidationRule.cs | 2 +- .../Validation/ObjectTypeValidationRule.cs | 2 +- .../Validation/SchemaValidator.cs | 2 +- .../Validation/TypeValidationHelper.cs | 28 ++++---- .../Extensions/ResolverContextExtensions.cs | 6 +- .../SchemaBuilderExtensions.Conventions.cs | 2 +- .../SchemaBuilderExtensions.Middleware.cs | 4 +- .../SchemaBuilderExtensions.Resolvers.cs | 2 +- .../SchemaBuilderExtensions.Types.cs | 4 +- .../Types/Internal/ExtendedType.BaseTypes.cs | 2 +- .../src/Types/Internal/ExtendedType.Helper.cs | 32 ++++----- .../Types/Internal/ExtendedType.Members.cs | 36 +++++----- .../Types/Internal/ExtendedType.SchemaType.cs | 6 +- .../Types/Internal/ExtendedType.SystemType.cs | 10 +-- .../src/Types/Internal/ExtendedType.Tools.cs | 10 +-- .../Core/src/Types/Internal/ExtendedType.cs | 2 +- .../src/Types/Internal/FieldInitHelper.cs | 6 +- .../Core/src/Types/Internal/TypeCache.cs | 8 +-- .../Types/Internal/TypeDependencyHelper.cs | 34 ++++----- .../src/Types/Internal/TypeExtensionHelper.cs | 22 +++--- .../Types/Internal/TypeInfo.RuntimeType.cs | 12 ++-- .../src/Types/Internal/TypeInfo.SchemaType.cs | 6 +- .../Core/src/Types/Internal/TypeInfo.cs | 4 +- .../Resolvers/DefaultResolverCompiler.cs | 70 +++++++++---------- .../DirectiveClassMiddlewareFactory.cs | 6 +- .../FieldParameterExpressionBuilder.cs | 2 +- .../GlobalStateParameterExpressionBuilder.cs | 10 +-- .../ObjectTypeParameterExpressionBuilder.cs | 2 +- .../ParentParameterExpressionBuilder.cs | 4 +- ...ScopedServiceParameterExpressionBuilder.cs | 6 +- .../ScopedStateParameterExpressionBuilder.cs | 8 +-- .../Parameters/ServiceExpressionHelper.cs | 10 +-- .../Expressions/Parameters/ServiceHelper.cs | 12 ++-- .../ServiceParameterExpressionBuilder.cs | 2 +- .../Expressions/SubscribeExpressionHelper.cs | 14 ++-- .../Expressions/TypeInfoExtensions.cs | 4 +- .../Resolvers/FieldClassMiddlewareFactory.cs | 6 +- .../src/Types/Resolvers/IResolverContext.cs | 8 +-- .../Types/Resolvers/ResolveResultHelper.cs | 6 +- .../Types/Resolvers/SubscribeResultHelper.cs | 40 +++++------ .../Core/src/Types/Schema.Initialization.cs | 2 +- src/HotChocolate/Core/src/Types/Schema.cs | 4 +- .../Core/src/Types/SchemaBuilder.Setup.cs | 38 +++++----- .../Core/src/Types/SchemaBuilder.cs | 6 +- .../src/Types/SchemaErrorBuilder.Error.cs | 4 +- .../Core/src/Types/SchemaException.cs | 4 +- .../Core/src/Types/SchemaSerializer.cs | 14 ++-- .../Core/src/Types/SchemaTypes.cs | 20 +++--- .../Types/AggregateInputValueFormatter.cs | 2 +- .../Core/src/Types/Types/Argument.cs | 2 +- .../SubscribeAndResolveAttribute.cs | 6 +- .../Types/Attributes/SubscribeAttribute.cs | 14 ++-- .../Types/Descriptors/ArgumentDescriptor.cs | 2 +- .../Descriptors/ArgumentDescriptorBase~1.cs | 4 +- .../Conventions/DefaultNamingConventions.cs | 20 +++--- .../Conventions/DefaultTypeInspector.cs | 24 +++---- .../Conventions/DescriptorContext.cs | 16 ++--- .../XmlDocumentationFileResolver.cs | 4 +- .../Conventions/XmlDocumentationProvider.cs | 48 ++++++------- .../Descriptors/Definitions/DefinitionBase.cs | 6 +- .../Definitions/DirectiveTypeDefinition.cs | 2 +- .../Definitions/EnumTypeDefinition.cs | 2 +- .../Definitions/InputObjectTypeDefinition.cs | 8 +-- .../Definitions/InterfaceTypeDefinition.cs | 4 +- .../Definitions/ObjectFieldDefinition.cs | 2 +- .../Definitions/ObjectTypeDefinition.cs | 12 ++-- .../Definitions/OutputFieldDefinitionBase.cs | 6 +- .../Descriptors/DependencyDescriptorBase~1.cs | 4 +- .../Types/Descriptors/DescriptorBase~1.cs | 4 +- .../DirectiveArgumentDescriptor.cs | 4 +- .../Descriptors/DirectiveTypeDescriptor.cs | 6 +- .../Descriptors/DirectiveTypeDescriptor~1.cs | 2 +- .../Types/Descriptors/EnumTypeDescriptor.cs | 8 +-- .../Descriptors/InputObjectTypeDescriptor.cs | 6 +- .../InputObjectTypeDescriptor~1.cs | 2 +- .../Descriptors/InterfaceTypeDescriptor.cs | 6 +- .../Descriptors/InterfaceTypeDescriptor~1.cs | 4 +- .../Descriptors/ObjectFieldDescriptor.cs | 8 +-- .../Types/Descriptors/ObjectTypeDescriptor.cs | 12 ++-- .../Descriptors/ObjectTypeDescriptorBase~1.cs | 4 +- .../Descriptors/OutputFieldDescriptorBase.cs | 8 +-- .../TypeReferences/SchemaTypeReference.cs | 4 +- .../Types/Descriptors/UnionTypeDescriptor.cs | 2 +- .../Core/src/Types/Types/Directive.cs | 38 +++++----- .../src/Types/Types/DirectiveCollection.cs | 14 ++-- .../Types/Types/Directives/CostDirective.cs | 6 +- .../Types/Directives/CostTypeInterceptor.cs | 8 +-- .../Types/Directives/DeprecatedDirective.cs | 2 +- .../src/Types/Types/Directives/Directives.cs | 2 +- .../Types/Types/EnumType.Initialization.cs | 4 +- .../Core/src/Types/Types/EnumType.cs | 14 ++-- .../Core/src/Types/Types/EnumTypeExtension.cs | 4 +- .../Extensions/DirectiveLocationExtensions.cs | 2 +- .../ObjectFieldDescriptorExtensions.cs | 4 +- .../ResolveObjectFieldDescriptorExtensions.cs | 8 +-- ...olveWithObjectFieldDescriptorExtensions.cs | 8 +-- ...ResolverObjectFieldDescriptorExtensions.cs | 8 +-- ...dServiceObjectFieldDescriptorExtensions.cs | 6 +- ...ResolverObjectFieldDescriptorExtensions.cs | 10 +-- .../Types/Types/Extensions/TypeExtensions.cs | 8 +-- .../Types/Factories/BindDirectiveHelper.cs | 4 +- .../Types/Factories/DirectiveTypeFactory.cs | 8 +-- .../Types/Types/Factories/EnumTypeFactory.cs | 6 +- .../Types/Factories/InputObjectTypeFactory.cs | 6 +- .../Types/Factories/InterfaceTypeFactory.cs | 12 ++-- .../Types/Factories/ObjectTypeFactory.cs | 12 ++-- .../Types/Factories/SchemaSyntaxVisitor.cs | 2 +- .../Types/Factories/SdlToTypeSystemHelper.cs | 4 +- .../Types/Types/Factories/UnionTypeFactory.cs | 8 +-- .../Core/src/Types/Types/FieldCollection.cs | 4 +- .../Types/Helpers/CompleteInterfacesHelper.cs | 2 +- .../Types/Helpers/FieldDescriptorUtilities.cs | 14 ++-- .../Types/Helpers/ResolverContextProxy.cs | 6 +- .../src/Types/Types/Helpers/TypeNameHelper.cs | 2 +- .../Core/src/Types/Types/InputField.cs | 2 +- .../Core/src/Types/Types/InputFormatter.cs | 12 ++-- .../Types/InputObjectType.Initialization.cs | 4 +- .../Core/src/Types/Types/InputParser.cs | 32 ++++----- .../InterfaceCompletionTypeInterceptor.cs | 28 ++++---- .../MiddlewareValidationTypeInterceptor.cs | 6 +- .../Interceptors/ResolverTypeInterceptor.cs | 66 ++++++++--------- .../TypeValidationTypeInterceptor.cs | 2 +- .../Types/InterfaceType.Initialization.cs | 2 +- .../Introspection/IntrospectionFields.cs | 4 +- .../IntrospectionTypeInterceptor.cs | 2 +- .../Types/Introspection/__AppliedDirective.cs | 4 +- .../Types/Types/Introspection/__Directive.cs | 20 +++--- .../Introspection/__DirectiveArgument.cs | 2 +- .../Types/Types/Introspection/__EnumValue.cs | 8 +-- .../src/Types/Types/Introspection/__Field.cs | 16 ++--- .../Types/Types/Introspection/__InputValue.cs | 12 ++-- .../src/Types/Types/Introspection/__Schema.cs | 12 ++-- .../src/Types/Types/Introspection/__Type.cs | 20 +++--- .../Types/Types/ObjectType.Initialization.cs | 6 +- .../src/Types/Types/ObjectTypeExtension.cs | 6 +- .../src/Types/Types/ObjectTypeExtension~1.cs | 2 +- .../Types/Types/Pagination/PagingHelper.cs | 22 +++--- .../Types/Relay/Attributes/NodeAttribute.cs | 10 +-- .../Types/Relay/Descriptors/NodeDescriptor.cs | 8 +-- .../Relay/Descriptors/NodeDescriptorBase.cs | 8 +-- .../Relay/Descriptors/NodeDescriptor~1.cs | 6 +- .../Relay/Descriptors/NodeDescriptor~2.cs | 6 +- .../Relay/Extensions/RelayIdFieldHelpers.cs | 16 ++--- .../Relay/GlobalIdInputValueFormatter.cs | 16 ++--- .../src/Types/Types/Relay/IdSerializer.cs | 12 ++-- .../Types/Relay/NodeFieldTypeInterceptor.cs | 36 +++++----- .../src/Types/Types/Relay/NodeResolver~2.cs | 2 +- .../Types/Relay/QueryFieldTypeInterceptor.cs | 4 +- .../Core/src/Types/Types/Scalars/AnyType.cs | 14 ++-- .../src/Types/Types/Scalars/DateTimeType.cs | 8 +-- .../Core/src/Types/Types/Scalars/DateType.cs | 6 +- .../Types/Types/Scalars/Iso8601Duration.cs | 4 +- .../Scalars/ScalarType.Initialization.cs | 2 +- .../src/Types/Types/Scalars/ScalarType.cs | 2 +- .../Core/src/Types/Types/Scalars/Scalars.cs | 2 +- .../src/Types/Types/Scalars/TimeSpanType.cs | 8 +-- .../Core/src/Types/Types/Scalars/UrlType.cs | 4 +- .../Core/src/Types/Types/Scalars/UuidType.cs | 8 +-- .../src/Types/Types/TypeSystemObjectBase~1.cs | 10 +-- .../Core/src/Types/Types/UnionType.cs | 8 +-- .../src/Types/Types/UnionTypeExtension.cs | 2 +- .../Core/src/Types/Types/UnionType~1.cs | 4 +- .../Core/src/Types/Utilities/AstUtilities.cs | 2 +- .../Types/Utilities/DefaultTypeConverter.cs | 8 +-- .../Utilities/DictionaryToObjectConverter.cs | 10 +-- .../src/Types/Utilities/DictionaryVisitor.cs | 2 +- .../src/Types/Utilities/ITypeConverter.cs | 1 + .../InputObjectToDictionaryConverter.cs | 4 +- .../src/Types/Utilities/ListTypeConverter.cs | 14 ++-- .../src/Types/Utilities/NullableHelper.cs | 12 ++-- .../Types/Utilities/NullableTypeConverter.cs | 4 +- .../Utilities/ObjectToDictionaryConverter.cs | 18 ++--- .../ObjectValueToDictionaryConverter.cs | 8 +-- .../src/Types/Utilities/ReflectionUtils.cs | 18 ++--- .../Serialization/InputObjectCompiler.cs | 28 ++++---- .../InputObjectConstructorResolver.cs | 16 ++--- .../ObservableSourceStreamAdapter.cs | 2 +- .../Core/src/Types/Utilities/ThrowHelper.cs | 8 +-- .../Utilities/TypeConverterExtensions.cs | 2 +- 215 files changed, 1049 insertions(+), 1040 deletions(-) diff --git a/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj b/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj index 7cc27456c1f..b67566d6515 100644 --- a/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj +++ b/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj @@ -60,6 +60,24 @@ OperationCompiler.cs + + MiddlewareContext.Global.cs + + + MiddlewareContext.Global.cs + + + MiddlewareContext.Global.cs + + + MiddlewareContext.Global.cs + + + MiddlewareContext.Global.cs + + + ResolverTask.cs + diff --git a/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs b/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs index cb978ee960f..f6b93f059bd 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs @@ -86,9 +86,9 @@ public void ReportError(Exception exception, Action? configure = public IReadOnlyList GetSelections( ObjectType typeContext, - ISelection? fieldSelection = null, + ISelection? selection = null, bool allowInternals = false) - => _middlewareContext.GetSelections(typeContext, fieldSelection, allowInternals); + => _middlewareContext.GetSelections(typeContext, selection, allowInternals); public T GetQueryRoot() => _middlewareContext.GetQueryRoot(); diff --git a/src/HotChocolate/Core/src/Execution/Processing/IOperationContext.cs b/src/HotChocolate/Core/src/Execution/Processing/IOperationContext.cs index 8a7ed47c997..24973e18aa0 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/IOperationContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/IOperationContext.cs @@ -105,7 +105,7 @@ internal interface IOperationContext : IHasContextData /// ISelectionSet CollectFields( ISelection selection, - ObjectType typeContext); + IObjectType typeContext); /// /// Register cleanup tasks that will be executed after resolver execution is finished. diff --git a/src/HotChocolate/Core/src/Execution/Processing/ISubscription.cs b/src/HotChocolate/Core/src/Execution/Processing/ISubscription.cs index 2d292311f1c..f4a4c168d29 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/ISubscription.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/ISubscription.cs @@ -13,5 +13,5 @@ public interface ISubscription /// /// The compiled subscription operation. /// - IPreparedOperation Operation { get; } + IOperation Operation { get; } } diff --git a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs index c585c856c3d..3d2082ade31 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Arguments.cs @@ -8,7 +8,7 @@ namespace HotChocolate.Execution.Processing; -internal partial class MiddlewareContext : IMiddlewareContext +internal partial class MiddlewareContext { public IReadOnlyDictionary Arguments { get; set; } = default!; diff --git a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Global.cs b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Global.cs index 58786b418ec..8498642b128 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Global.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Global.cs @@ -3,14 +3,13 @@ using System.Threading; using System.Threading.Tasks; using HotChocolate.Execution.Properties; -using HotChocolate.Language; using HotChocolate.Resolvers; using HotChocolate.Types; using Microsoft.Extensions.DependencyInjection; namespace HotChocolate.Execution.Processing; -internal partial class MiddlewareContext +internal partial class MiddlewareContext : IMiddlewareContext { private IOperationContext _operationContext = default!; private IServiceProvider _services = default!; @@ -28,9 +27,7 @@ public IServiceProvider Services public IObjectType RootType => _operationContext.Operation.RootType; - public DocumentNode Document => _operationContext.Operation.Document; - - public OperationDefinitionNode Operation => _operationContext.Operation.Definition; + public IOperation Operation => _operationContext.Operation; public IDictionary ContextData => _operationContext.ContextData; @@ -39,8 +36,8 @@ public IServiceProvider Services public CancellationToken RequestAborted { get; private set; } public IReadOnlyList GetSelections( - ObjectType typeContext, - ISelection? fieldSelection = null, + IObjectType typeContext, + ISelection? selection = null, bool allowInternals = false) { if (typeContext is null) @@ -48,7 +45,7 @@ public IReadOnlyList GetSelections( throw new ArgumentNullException(nameof(typeContext)); } - var selection = GetSelection(fieldSelection); + selection ??= _selection; if (selection.SelectionSet is null) { @@ -76,21 +73,6 @@ public IReadOnlyList GetSelections( return fields.Selections; } - private ISelection GetSelection(ISelection? fieldSelection) - { - if (fieldSelection is null) - { - return _selection; - } - - if (fieldSelection is ISelection selection) - { - return selection; - } - - throw new ArgumentException("Invalid selection type."); - } - public void ReportError(string errorMessage) { if (string.IsNullOrEmpty(errorMessage)) diff --git a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs index 63d3f6a06db..64d6f61f20b 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/MiddlewareContext.Pure.cs @@ -62,10 +62,10 @@ public void Clear() public ISchema Schema => _parentContext.Schema; - public IObjectType RootType => _parentContext.RootType; - public IObjectType ObjectType => _parentType; + public IOperation Operation => _parentContext.Operation; + public ISelection Selection => _selection; public Path Path => _path; diff --git a/src/HotChocolate/Core/src/Execution/Processing/Operation.cs b/src/HotChocolate/Core/src/Execution/Processing/Operation.cs index 142a8e45f92..19c6695ede2 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Operation.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Operation.cs @@ -5,7 +5,7 @@ namespace HotChocolate.Execution.Processing; -internal sealed class Operation : IPreparedOperation +internal sealed class Operation : IOperation { private readonly SelectionVariants[] _selectionVariants; private readonly IncludeCondition[] _includeConditions; @@ -16,12 +16,14 @@ public Operation( OperationDefinitionNode definition, ObjectType rootType, SelectionVariants[] selectionVariants, - IncludeCondition[] includeConditions) + IncludeCondition[] includeConditions, + Dictionary contextData) { Id = id; Document = document; Definition = definition; RootType = rootType; + ContextData = contextData; Type = definition.Operation; if (definition.Name?.Value is { } name) @@ -55,6 +57,8 @@ public IReadOnlyList SelectionVariants public IReadOnlyList IncludeConditions => _includeConditions; + public IReadOnlyDictionary ContextData { get; } + public ISelectionSet GetSelectionSet(ISelection selection, IObjectType typeContext) { if (selection is null) @@ -94,7 +98,7 @@ public IEnumerable GetPossibleTypes(ISelection selection) return _selectionVariants[selectionSetId].GetPossibleTypes(); } - public long CreateIncludeContext(IVariableValueCollection variables) + public long CreateIncludeFlags(IVariableValueCollection variables) { long context = 0; diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.Optimizers.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.Optimizers.cs index 60090c49e39..145de30f4cb 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.Optimizers.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.Optimizers.cs @@ -13,7 +13,11 @@ private void OptimizeSelectionSet(CompilerContext context) return; } - var optimizerContext = new SelectionSetOptimizerContext(this, context, _selectionLookup); + var optimizerContext = new SelectionSetOptimizerContext( + this, + context, + _selectionLookup, + _contextData); if (context.Optimizers.Count == 1) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs index 925d40ab3a9..03d9a1ac864 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs @@ -19,6 +19,7 @@ public sealed partial class OperationCompiler private readonly Dictionary _selectionSetIdLookup = new(BySyntax); private readonly Dictionary _selectionVariants = new(); private readonly Dictionary _fragmentDefinitions = new(Ordinal); + private readonly Dictionary _contextData = new(); private readonly List _operationOptimizers = new(); private readonly List _selectionSetOptimizers = new(); private IncludeCondition[] _includeConditions = Array.Empty(); @@ -93,6 +94,7 @@ public IOperation Compile( _selectionSetIdLookup.Clear(); _selectionVariants.Clear(); _fragmentDefinitions.Clear(); + _contextData.Clear(); _operationOptimizers.Clear(); _selectionSetOptimizers.Clear(); @@ -108,7 +110,6 @@ private Operation CreateOperation( DocumentNode document, ISchema schema) { - var contextData = new Dictionary(); var variants = new SelectionVariants[_selectionVariants.Count]; if (_operationOptimizers.Count == 0) @@ -131,7 +132,7 @@ private Operation CreateOperation( schema, operationType, variants, - contextData); + _contextData); foreach (var item in _selectionVariants) { @@ -155,7 +156,8 @@ private Operation CreateOperation( operationDefinition, operationType, variants, - _includeConditions); + _includeConditions, + new Dictionary(_contextData)); } private void CompileSelectionSet(CompilerContext context) @@ -523,8 +525,7 @@ private long GetSelectionIncludeCondition( if (pos == 64) { - throw new InvalidOperationException( - "The operation compiler only allows for 64 unique include conditions."); + throw new InvalidOperationException(OperationCompiler_ToManyIncludeConditions); } if (_includeConditions.Length == 0) @@ -565,13 +566,18 @@ private CompilerContext RentContext(CompilerContext context) private void ReturnContext(CompilerContext context) => _deferContext ??= context; - private void PrepareOptimizers(IReadOnlyList optimizers) + private void PrepareOptimizers(IReadOnlyList? optimizers) { // we only clear the selectionSetOptimizers since we use this list as a temp // to temporarily store the selectionSetOptimizers before they are copied to // the context. _selectionSetOptimizers.Clear(); + if (optimizers is null) + { + return; + } + if (optimizers.Count > 0) { for (var i = 0; i < optimizers.Count; i++) diff --git a/src/HotChocolate/Core/src/Execution/Processing/SelectionSetOptimizerContext.cs b/src/HotChocolate/Core/src/Execution/Processing/SelectionSetOptimizerContext.cs index d9fbec38ef2..fc4cf9909e2 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/SelectionSetOptimizerContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/SelectionSetOptimizerContext.cs @@ -23,7 +23,8 @@ public readonly ref struct SelectionSetOptimizerContext internal SelectionSetOptimizerContext( OperationCompiler compiler, OperationCompiler.CompilerContext compilerContext, - Dictionary selectionLookup) + Dictionary selectionLookup, + Dictionary contextData) { _compiler = compiler; _compilerContext = compilerContext; diff --git a/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs b/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs index 6cc574062a4..b1207c47269 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.Subscription.cs @@ -4,9 +4,7 @@ using System.Threading; using System.Threading.Tasks; using HotChocolate.Execution.Instrumentation; -using HotChocolate.Execution.Processing.Plan; using HotChocolate.Fetching; -using HotChocolate.Resolvers; using HotChocolate.Types; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.ObjectPool; @@ -23,7 +21,6 @@ private sealed class Subscription : ISubscription, IAsyncDisposable private readonly IExecutionDiagnosticEvents _diagnosticEvents; private IDisposable? _subscriptionScope; private readonly IRequestContext _requestContext; - private readonly QueryPlan _queryPlan; private readonly ObjectType _subscriptionType; private readonly ISelectionSet _rootSelections; private readonly Func _resolveQueryRootValue; @@ -37,7 +34,6 @@ private Subscription( ObjectPool operationContextPool, QueryExecutor queryExecutor, IRequestContext requestContext, - QueryPlan queryPlan, ObjectType subscriptionType, ISelectionSet rootSelections, Func resolveQueryRootValue, @@ -51,7 +47,6 @@ private Subscription( _operationContextPool = operationContextPool; _queryExecutor = queryExecutor; _requestContext = requestContext; - _queryPlan = queryPlan; _subscriptionType = subscriptionType; _rootSelections = rootSelections; _resolveQueryRootValue = resolveQueryRootValue; @@ -93,7 +88,6 @@ public static async ValueTask SubscribeAsync( ObjectPool operationContextPool, QueryExecutor queryExecutor, IRequestContext requestContext, - QueryPlan queryPlan, ObjectType subscriptionType, ISelectionSet rootSelections, Func resolveQueryRootValue, @@ -103,7 +97,6 @@ public static async ValueTask SubscribeAsync( operationContextPool, queryExecutor, requestContext, - queryPlan, subscriptionType, rootSelections, resolveQueryRootValue, @@ -129,7 +122,7 @@ public IAsyncEnumerable ExecuteAsync() public ulong Id => _id; /// - public IPreparedOperation Operation => _requestContext.Operation!; + public IOperation Operation => _requestContext.Operation!; public async ValueTask DisposeAsync() { @@ -182,7 +175,6 @@ private async Task OnEvent(object payload) eventServices, dispatcher, _requestContext.Operation!, - _queryPlan, _requestContext.Variables!, rootValue, _resolveQueryRootValue); @@ -237,7 +229,6 @@ private async ValueTask SubscribeAsync() _requestContext.Services, NoopBatchDispatcher.Default, _requestContext.Operation!, - _queryPlan, _requestContext.Variables!, rootValue, _resolveQueryRootValue); diff --git a/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.cs b/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.cs index b2d473702c0..7e325429eb0 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/SubscriptionExecutor.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading.Tasks; using HotChocolate.Execution.Instrumentation; -using HotChocolate.Execution.Processing.Plan; using Microsoft.Extensions.ObjectPool; using static HotChocolate.Execution.ThrowHelper; @@ -33,11 +32,6 @@ public async Task ExecuteAsync( throw new ArgumentNullException(nameof(requestContext)); } - if (queryPlan is null) - { - throw new ArgumentNullException(nameof(queryPlan)); - } - if (requestContext.Operation is null || requestContext.Variables is null) { throw SubscriptionExecutor_ContextInvalidState(); @@ -63,7 +57,6 @@ public async Task ExecuteAsync( _operationContextPool, _queryExecutor, requestContext, - queryPlan, requestContext.Operation.RootType, selectionSet, resolveQueryValue, diff --git a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs index 7abf9bccd9d..3240b363584 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs @@ -103,7 +103,7 @@ private void CompleteValue(bool success, CancellationToken cancellationToken) if (ValueCompletion.TryComplete( _operationContext, _resolverContext, - (ISelection)_resolverContext.Selection, + _resolverContext.Selection, _resolverContext.Path, _selection.Type, _resolverContext.ResponseName, diff --git a/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs b/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs index 676509f00a0..80a7e0023da 100644 --- a/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs +++ b/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs @@ -386,5 +386,11 @@ internal static string SelectionSetOptimizerContext_InvalidFieldName { return ResourceManager.GetString("SelectionSetOptimizerContext_InvalidFieldName", resourceCulture); } } + + internal static string OperationCompiler_ToManyIncludeConditions { + get { + return ResourceManager.GetString("OperationCompiler_ToManyIncludeConditions", resourceCulture); + } + } } } diff --git a/src/HotChocolate/Core/src/Execution/Properties/Resources.resx b/src/HotChocolate/Core/src/Execution/Properties/Resources.resx index 5b5f147b03a..4bdf20c3189 100644 --- a/src/HotChocolate/Core/src/Execution/Properties/Resources.resx +++ b/src/HotChocolate/Core/src/Execution/Properties/Resources.resx @@ -288,4 +288,7 @@ The `{0}` is not a valid GraphQL field name. + + The operation compiler only allows for 64 unique include conditions. + diff --git a/src/HotChocolate/Core/src/Types/Configuration/AggregateSchemaInterceptor.cs b/src/HotChocolate/Core/src/Types/Configuration/AggregateSchemaInterceptor.cs index 19bf86c88ed..c7084de50b0 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/AggregateSchemaInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/AggregateSchemaInterceptor.cs @@ -27,7 +27,7 @@ public override void OnBeforeCreate( return; } - foreach (ISchemaInterceptor interceptor in _interceptors) + foreach (var interceptor in _interceptors) { interceptor.OnBeforeCreate(context, schemaBuilder); } @@ -40,7 +40,7 @@ public override void OnAfterCreate(IDescriptorContext context, ISchema schema) return; } - foreach (ISchemaInterceptor interceptor in _interceptors) + foreach (var interceptor in _interceptors) { interceptor.OnAfterCreate(context, schema); } @@ -53,7 +53,7 @@ public override void OnError(IDescriptorContext context, Exception exception) return; } - foreach (ISchemaInterceptor interceptor in _interceptors) + foreach (var interceptor in _interceptors) { interceptor.OnError(context, exception); } diff --git a/src/HotChocolate/Core/src/Types/Configuration/AggregateTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Configuration/AggregateTypeInterceptor.cs index 6f74ab0e31f..0c0c65c63a7 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/AggregateTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/AggregateTypeInterceptor.cs @@ -60,7 +60,7 @@ internal override void InitializeContext( TypeLookup typeLookup, TypeReferenceResolver typeReferenceResolver) { - foreach (TypeInterceptor interceptor in _typeInterceptors) + foreach (var interceptor in _typeInterceptors) { interceptor.InitializeContext( context, @@ -73,7 +73,7 @@ internal override void InitializeContext( public override void OnBeforeDiscoverTypes() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnBeforeDiscoverTypes(); } @@ -81,7 +81,7 @@ public override void OnBeforeDiscoverTypes() public override void OnAfterDiscoverTypes() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnAfterDiscoverTypes(); } @@ -90,7 +90,7 @@ public override void OnAfterDiscoverTypes() public override void OnBeforeInitialize( ITypeDiscoveryContext discoveryContext) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(discoveryContext)) { @@ -104,7 +104,7 @@ public override void OnAfterInitialize( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(discoveryContext)) { @@ -115,7 +115,7 @@ public override void OnAfterInitialize( public override void OnTypeRegistered(ITypeDiscoveryContext discoveryContext) { - foreach (ITypeRegistryInterceptor interceptor in _registryInterceptors) + foreach (var interceptor in _registryInterceptors) { interceptor.OnTypeRegistered(discoveryContext); } @@ -128,11 +128,11 @@ public override IEnumerable RegisterMoreTypes( if (_agrInterceptors.Count > 0) { - foreach (ITypeInitializationInterceptor interceptor in _agrInterceptors) + foreach (var interceptor in _agrInterceptors) { _discoveryContexts.Clear(); - foreach (ITypeDiscoveryContext discoveryContext in discoveryContexts) + foreach (var discoveryContext in discoveryContexts) { if (interceptor.CanHandle(discoveryContext)) { @@ -155,11 +155,11 @@ public override void OnTypesInitialized( { if (_agrInterceptors.Count > 0) { - foreach (ITypeInitializationInterceptor interceptor in _agrInterceptors) + foreach (var interceptor in _agrInterceptors) { _discoveryContexts.Clear(); - foreach (ITypeDiscoveryContext discoveryContext in discoveryContexts) + foreach (var discoveryContext in discoveryContexts) { if (interceptor.CanHandle(discoveryContext)) { @@ -179,7 +179,7 @@ public override void OnAfterRegisterDependencies( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(discoveryContext)) { @@ -194,7 +194,7 @@ public override void OnBeforeRegisterDependencies( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(discoveryContext)) { @@ -206,7 +206,7 @@ public override void OnBeforeRegisterDependencies( public override void OnBeforeCompleteTypeNames() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnBeforeCompleteTypeNames(); } @@ -214,7 +214,7 @@ public override void OnBeforeCompleteTypeNames() public override void OnAfterCompleteTypeNames() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnAfterCompleteTypeNames(); } @@ -225,7 +225,7 @@ public override void OnBeforeCompleteName( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(completionContext)) { @@ -239,7 +239,7 @@ public override void OnAfterCompleteName( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(completionContext)) { @@ -254,7 +254,7 @@ internal override void OnAfterResolveRootType( OperationType operationType, IDictionary contextData) { - foreach (TypeInterceptor interceptor in _typeInterceptors) + foreach (var interceptor in _typeInterceptors) { if (interceptor.CanHandle(completionContext)) { @@ -272,11 +272,11 @@ public override void OnTypesCompletedName( { if (_agrInterceptors.Count > 0) { - foreach (ITypeInitializationInterceptor interceptor in _agrInterceptors) + foreach (var interceptor in _agrInterceptors) { _completionContexts.Clear(); - foreach (ITypeCompletionContext completionContext in completionContexts) + foreach (var completionContext in completionContexts) { if (interceptor.CanHandle(completionContext)) { @@ -293,7 +293,7 @@ public override void OnTypesCompletedName( public override void OnBeforeMergeTypeExtensions() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnBeforeMergeTypeExtensions(); } @@ -301,7 +301,7 @@ public override void OnBeforeMergeTypeExtensions() public override void OnAfterMergeTypeExtensions() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnAfterMergeTypeExtensions(); } @@ -309,7 +309,7 @@ public override void OnAfterMergeTypeExtensions() public override void OnBeforeCompleteTypes() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnBeforeCompleteTypes(); } @@ -317,7 +317,7 @@ public override void OnBeforeCompleteTypes() public override void OnAfterCompleteTypes() { - foreach (ITypeInitializationFlowInterceptor interceptor in _flowInterceptors) + foreach (var interceptor in _flowInterceptors) { interceptor.OnAfterCompleteTypes(); } @@ -328,7 +328,7 @@ public override void OnBeforeCompleteType( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(completionContext)) { @@ -342,7 +342,7 @@ public override void OnAfterCompleteType( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(completionContext)) { @@ -356,7 +356,7 @@ public override void OnValidateType( DefinitionBase? definition, IDictionary contextData) { - foreach (ITypeInitializationInterceptor interceptor in _initInterceptors) + foreach (var interceptor in _initInterceptors) { if (interceptor.CanHandle(validationContext)) { @@ -369,7 +369,7 @@ public override bool TryCreateScope( ITypeDiscoveryContext discoveryContext, [NotNullWhen(true)] out IReadOnlyList? typeDependencies) { - foreach (ITypeScopeInterceptor interceptor in _scopeInterceptors) + foreach (var interceptor in _scopeInterceptors) { if (interceptor.TryCreateScope(discoveryContext, out typeDependencies)) { @@ -386,11 +386,11 @@ public override void OnTypesCompleted( { if (_agrInterceptors.Count > 0) { - foreach (ITypeInitializationInterceptor interceptor in _agrInterceptors) + foreach (var interceptor in _agrInterceptors) { _completionContexts.Clear(); - foreach (ITypeCompletionContext completionContext in completionContexts) + foreach (var completionContext in completionContexts) { if (interceptor.CanHandle(completionContext)) { diff --git a/src/HotChocolate/Core/src/Types/Configuration/DependantFactoryTypeReferenceHandler.cs b/src/HotChocolate/Core/src/Types/Configuration/DependantFactoryTypeReferenceHandler.cs index 08a3383d2bd..d3eeb740169 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/DependantFactoryTypeReferenceHandler.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/DependantFactoryTypeReferenceHandler.cs @@ -23,7 +23,7 @@ public void Handle(ITypeRegistrar typeRegistrar, ITypeReference typeReference) if (_handled.Add(typeRef)) { - TypeSystemObjectBase obj = typeRef.Factory(_context); + var obj = typeRef.Factory(_context); typeRegistrar.Register(obj, typeRef.Scope, configure: AddTypeRef); } diff --git a/src/HotChocolate/Core/src/Types/Configuration/ExtendedTypeReferenceHandler.cs b/src/HotChocolate/Core/src/Types/Configuration/ExtendedTypeReferenceHandler.cs index 0d87d278f57..720b9f257dd 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/ExtendedTypeReferenceHandler.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/ExtendedTypeReferenceHandler.cs @@ -24,7 +24,7 @@ public void Handle(ITypeRegistrar typeRegistrar, ITypeReference typeReference) { var typeRef = (ExtendedTypeReference)typeReference; - if (_typeInspector.TryCreateTypeInfo(typeRef.Type, out ITypeInfo? typeInfo) && + if (_typeInspector.TryCreateTypeInfo(typeRef.Type, out var typeInfo) && !ExtendedType.Tools.IsNonGenericBaseType(typeInfo.NamedType)) { if (typeInfo.NamedType == typeof(IExecutable)) @@ -32,11 +32,11 @@ public void Handle(ITypeRegistrar typeRegistrar, ITypeReference typeReference) throw ThrowHelper.NonGenericExecutableNotAllowed(); } - Type namedType = typeInfo.NamedType; + var namedType = typeInfo.NamedType; if (IsTypeSystemObject(namedType)) { - IExtendedType extendedType = _typeInspector.GetType(namedType); - ExtendedTypeReference namedTypeReference = typeRef.With(extendedType); + var extendedType = _typeInspector.GetType(namedType); + var namedTypeReference = typeRef.With(extendedType); if (!typeRegistrar.IsResolved(namedTypeReference)) { @@ -66,7 +66,7 @@ private static void TryMapToExistingRegistration( ExtendedTypeReference? normalizedTypeRef = null; var resolved = false; - foreach (TypeComponent component in typeInfo.Components) + foreach (var component in typeInfo.Components) { normalizedTypeRef = TypeReference.Create( component.Type, diff --git a/src/HotChocolate/Core/src/Types/Configuration/FactoryTypeReferenceHandler.cs b/src/HotChocolate/Core/src/Types/Configuration/FactoryTypeReferenceHandler.cs index bda2f18efaa..5c74d9523fa 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/FactoryTypeReferenceHandler.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/FactoryTypeReferenceHandler.cs @@ -23,7 +23,7 @@ public void Handle(ITypeRegistrar typeRegistrar, ITypeReference typeReference) if (_handled.Add(typeRef.Name)) { - TypeSystemObjectBase obj = typeRef.Factory!(_context); + var obj = typeRef.Factory!(_context); typeRegistrar.Register(obj, typeRef.Scope, configure: AddTypeRef); } diff --git a/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.CompletionContext.cs b/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.CompletionContext.cs index 463738542c9..ec5f299c331 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.CompletionContext.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.CompletionContext.cs @@ -61,7 +61,7 @@ public bool TryGetType( throw new InvalidOperationException(RegisteredType_Completion_NotYetReady); } - if (_typeReferenceResolver.TryGetType(typeRef, out IType? t) && + if (_typeReferenceResolver.TryGetType(typeRef, out var t) && t is T casted) { type = casted; diff --git a/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.DiscoveryContext.cs b/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.DiscoveryContext.cs index 151430c422b..b9bd55eb62d 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.DiscoveryContext.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/RegisteredType.DiscoveryContext.cs @@ -42,8 +42,8 @@ public void ReportError(ISchemaError error) public bool TryPredictTypeKind(ITypeReference typeRef, out TypeKind kind) { - if (_typeLookup.TryNormalizeReference(typeRef, out ITypeReference? namedTypeRef) && - _typeRegistry.TryGetType(namedTypeRef, out RegisteredType? registeredType)) + if (_typeLookup.TryNormalizeReference(typeRef, out var namedTypeRef) && + _typeRegistry.TryGetType(namedTypeRef, out var registeredType)) { switch (registeredType.Type) { diff --git a/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeReferenceHandler.cs b/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeReferenceHandler.cs index 4fd7f07126b..b6c68bed691 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeReferenceHandler.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeReferenceHandler.cs @@ -15,7 +15,7 @@ public void Handle(ITypeRegistrar typeRegistrar, ITypeReference typeReference) if (!typeRegistrar.IsResolved(typeReference)) { - ITypeSystemMember tsm = typeRef.Type; + var tsm = typeRef.Type; // if it is a type object we will make sure it is unwrapped. if (typeRef.Type is IType type) diff --git a/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeResolver.cs b/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeResolver.cs index b1a84ba8762..575fbf93383 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeResolver.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/SchemaTypeResolver.cs @@ -65,7 +65,7 @@ public static bool TryInferSchemaType( typeInspector.GetType( typeof(EnumType<>).MakeGenericType(typeInfo.RuntimeType))); } - else if (Scalars.TryGetScalar(unresolvedType.Type.Type, out Type? scalarType)) + else if (Scalars.TryGetScalar(unresolvedType.Type.Type, out var scalarType)) { schemaType = unresolvedType.With(typeInspector.GetType(scalarType)); } @@ -194,7 +194,7 @@ public TypeInfo(ExtendedTypeReference typeReference) private static ITypeAttribute? GetTypeAttributeInternal( ExtendedTypeReference unresolvedType) { - Type runtimeType = unresolvedType.Type.Type; + var runtimeType = unresolvedType.Type.Type; foreach (var attribute in runtimeType.GetCustomAttributes(typeof(DescriptorAttribute), false)) @@ -228,7 +228,7 @@ private static bool IsComplexTypeInternal( if (!isComplexType && unresolvedType.Type.IsGeneric) { - Type? typeDefinition = unresolvedType.Type.Definition; + var typeDefinition = unresolvedType.Type.Definition; return typeDefinition == _keyValuePair; } diff --git a/src/HotChocolate/Core/src/Types/Configuration/SyntaxTypeReferenceHandler.cs b/src/HotChocolate/Core/src/Types/Configuration/SyntaxTypeReferenceHandler.cs index 0a30e709b93..7b22022e880 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/SyntaxTypeReferenceHandler.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/SyntaxTypeReferenceHandler.cs @@ -25,9 +25,9 @@ public void Handle(ITypeRegistrar typeRegistrar, ITypeReference typeReference) var typeRef = (SyntaxTypeReference)typeReference; if (_handled.Add(typeRef.Name) && - Scalars.TryGetScalar(typeRef.Name, out Type? scalarType)) + Scalars.TryGetScalar(typeRef.Name, out var scalarType)) { - ExtendedTypeReference namedTypeReference = _typeInspector.GetTypeRef(scalarType); + var namedTypeReference = _typeInspector.GetTypeRef(scalarType); if (!typeRegistrar.IsResolved(namedTypeReference)) { diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeDiscoverer.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeDiscoverer.cs index 8cbba653bac..c08ac8cc250 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeDiscoverer.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeDiscoverer.cs @@ -113,7 +113,7 @@ public IReadOnlyList DiscoverTypes() if (_errors.Count == 0 && _unregistered.Count == 0) { - foreach (ITypeReference typeReference in + foreach (var typeReference in _interceptor.RegisterMoreTypes(_typeRegistry.Types)) { if (processed.Add(typeReference)) @@ -142,7 +142,7 @@ private void RegisterTypes() { while (_unregistered.Count > 0) { - foreach (ITypeReference? typeRef in _unregistered) + foreach (var typeRef in _unregistered) { _handlers[(int)typeRef.Kind].Handle(_typeRegistrar, typeRef); } @@ -156,21 +156,21 @@ private bool TryInferTypes() { var inferred = false; - foreach (ITypeReference? typeRef in _typeRegistrar.Unresolved) + foreach (var typeRef in _typeRegistrar.Unresolved) { if (typeRef is ExtendedTypeReference unresolvedType) { - if (Scalars.TryGetScalar(unresolvedType.Type.Type, out Type? scalarType)) + if (Scalars.TryGetScalar(unresolvedType.Type.Type, out var scalarType)) { inferred = true; - ExtendedTypeReference typeReference = _typeInspector.GetTypeRef(scalarType); + var typeReference = _typeInspector.GetTypeRef(scalarType); _unregistered.Add(typeReference); _resolved.Add(unresolvedType); _typeRegistry.TryRegister(unresolvedType, typeReference); } else if (SchemaTypeResolver.TryInferSchemaType( - _typeInspector, unresolvedType, out ExtendedTypeReference? schemaType)) + _typeInspector, unresolvedType, out var schemaType)) { inferred = true; _unregistered.Add(schemaType); @@ -181,7 +181,7 @@ private bool TryInferTypes() if (_resolved.Count > 0) { - foreach (ITypeReference typeRef in _resolved) + foreach (var typeRef in _resolved) { _typeRegistrar.MarkResolved(typeRef); } @@ -192,7 +192,7 @@ private bool TryInferTypes() private void CollectErrors() { - foreach (RegisteredType type in _typeRegistry.Types) + foreach (var type in _typeRegistry.Types) { if (type.Errors.Count == 0) { @@ -204,13 +204,13 @@ private void CollectErrors() if (_errors.Count == 0 && _typeRegistrar.Unresolved.Count > 0) { - foreach (ITypeReference unresolvedReference in _typeRegistrar.Unresolved) + foreach (var unresolvedReference in _typeRegistrar.Unresolved) { var types = _typeRegistry.Types.Where( t => t.Dependencies.Select(d => d.TypeReference) .Any(r => r.Equals(unresolvedReference))).ToList(); - ISchemaErrorBuilder builder = + var builder = SchemaErrorBuilder.New() .SetMessage( TypeResources.TypeRegistrar_TypesInconsistent, diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeInitializer.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeInitializer.cs index a9b8019737b..67f383e86ad 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeInitializer.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeInitializer.cs @@ -55,7 +55,7 @@ public TypeInitializer( _isOfType = isOfType ?? options.DefaultIsOfTypeCheck; _interceptor = descriptorContext.TypeInterceptor; - ITypeInspector typeInspector = descriptorContext.TypeInspector; + var typeInspector = descriptorContext.TypeInspector; _typeLookup = new TypeLookup(typeInspector, _typeRegistry); _typeReferenceResolver = new TypeReferenceResolver( typeInspector, _typeRegistry, _typeLookup); @@ -156,27 +156,27 @@ private void RegisterImplicitInterfaceDependencies() .Distinct() .ToList(); - foreach (RegisteredType objectType in objectTypes) + foreach (var objectType in objectTypes) { - foreach (RegisteredType interfaceType in interfaceTypes) + foreach (var interfaceType in interfaceTypes) { if (interfaceType.RuntimeType.IsAssignableFrom(objectType.RuntimeType)) { - SchemaTypeReference typeReference = TypeReference.Create(interfaceType.Type); + var typeReference = TypeReference.Create(interfaceType.Type); ((ObjectType)objectType.Type).Definition!.Interfaces.Add(typeReference); objectType.Dependencies.Add(new(typeReference, TypeDependencyKind.Completed)); } } } - foreach (RegisteredType implementing in interfaceTypes) + foreach (var implementing in interfaceTypes) { - foreach (RegisteredType interfaceType in interfaceTypes) + foreach (var interfaceType in interfaceTypes) { if (!ReferenceEquals(implementing, interfaceType) && interfaceType.RuntimeType.IsAssignableFrom(implementing.RuntimeType)) { - SchemaTypeReference typeReference = TypeReference.Create(interfaceType.Type); + var typeReference = TypeReference.Create(interfaceType.Type); ((InterfaceType)implementing.Type).Definition!.Interfaces.Add(typeReference); implementing.Dependencies.Add(new(typeReference, TypeDependencyKind.Completed)); } @@ -233,14 +233,14 @@ internal bool CompleteTypeName(RegisteredType registeredType) _typeRegistry.Register(registeredType.Type.Name, registeredType); } - RootTypeKind kind = _getTypeKind(registeredType.Type); + var kind = _getTypeKind(registeredType.Type); registeredType.IsQueryType = kind == RootTypeKind.Query; registeredType.IsMutationType = kind == RootTypeKind.Mutation; registeredType.IsSubscriptionType = kind == RootTypeKind.Subscription; if (kind is not RootTypeKind.None) { - OperationType operationType = kind switch + var operationType = kind switch { RootTypeKind.Query => OperationType.Query, RootTypeKind.Mutation => OperationType.Mutation, @@ -274,14 +274,14 @@ private void MergeTypeExtensions() .Where(t => t.IsNamedType) .ToList(); - foreach (NameString typeName in extensions + foreach (var typeName in extensions .Select(t => t.Type) .OfType() .Where(t => t.ExtendsType is null) .Select(t => t.Name) .Distinct()) { - RegisteredType? type = types.FirstOrDefault(t => t.Type.Name.Equals(typeName)); + var type = types.FirstOrDefault(t => t.Type.Name.Equals(typeName)); if (type?.Type is INamedType namedType) { MergeTypeExtension( @@ -294,7 +294,7 @@ private void MergeTypeExtensions() var extensionArray = new RegisteredType[1]; - foreach (RegisteredType? extension in extensions.Except(processed)) + foreach (var extension in extensions.Except(processed)) { if (extension.Type is INamedTypeExtension { @@ -304,7 +304,7 @@ private void MergeTypeExtensions() var isSchemaType = typeof(INamedType).IsAssignableFrom(extendsType); extensionArray[0] = extension; - foreach (RegisteredType? possibleMatchingType in types + foreach (var possibleMatchingType in types .Where(t => t.Type is INamedType n && n.Kind == namedTypeExtension.Kind)) @@ -343,7 +343,7 @@ private void MergeTypeExtension( INamedType namedType, HashSet processed) { - foreach (RegisteredType extension in extensions) + foreach (var extension in extensions) { processed.Add(extension); @@ -398,7 +398,7 @@ bool CompleteType(RegisteredType registeredType) private void FinalizeTypes() { - foreach (RegisteredType? registeredType in _typeRegistry.Types) + foreach (var registeredType in _typeRegistry.Types) { if (!registeredType.IsExtension) { @@ -419,7 +419,7 @@ private bool ProcessTypes( && processed.Count < _typeRegistry.Count && batch.Count > 0) { - foreach (RegisteredType registeredType in batch) + foreach (var registeredType in batch) { if (!action(registeredType)) { @@ -427,7 +427,7 @@ private bool ProcessTypes( break; } - foreach (ITypeReference reference in registeredType.References) + foreach (var reference in registeredType.References) { processed.Add(reference); } @@ -442,7 +442,7 @@ private bool ProcessTypes( if (!failed && processed.Count < _typeRegistry.Count) { - foreach (RegisteredType type in _typeRegistry.Types + foreach (var type in _typeRegistry.Types .Where(t => !processed.Contains(t.References[0]))) { var name = type.Type.Name.HasValue @@ -451,7 +451,7 @@ private bool ProcessTypes( IReadOnlyList needed = TryNormalizeDependencies(type.Conditionals, - out IReadOnlyList? normalized) + out var normalized) ? normalized.Except(processed).ToArray() : type.Conditionals.Select(t => t.TypeReference).ToArray(); @@ -475,12 +475,12 @@ private IEnumerable GetInitialBatch( { _next.Clear(); - foreach (RegisteredType? registeredType in _typeRegistry.Types) + foreach (var registeredType in _typeRegistry.Types) { var conditional = false; registeredType.ClearConditionals(); - foreach (TypeDependency? dependency in registeredType.Dependencies) + foreach (var dependency in registeredType.Dependencies) { if (dependency.Kind == kind) { @@ -503,7 +503,7 @@ private IEnumerable GetInitialBatch( private IEnumerable GetNextBatch( ISet processed) { - foreach (RegisteredType type in _next) + foreach (var type in _next) { if (TryNormalizeDependencies(type.Conditionals, out var normalized) && processed.IsSupersetOf(GetTypeRefsExceptSelfRefs(type, normalized))) @@ -532,7 +532,7 @@ List GetTypeRefsExceptSelfRefs( _typeRefSet.Clear(); _typeRefSet.UnionWith(type.References); - foreach (ITypeReference? typeRef in normalizedTypeReferences) + foreach (var typeRef in normalizedTypeReferences) { if (_typeRefSet.Add(typeRef)) { @@ -550,11 +550,11 @@ private bool TryNormalizeDependencies( { var n = new List(); - foreach (TypeDependency dependency in dependencies) + foreach (var dependency in dependencies) { if (!_typeLookup.TryNormalizeReference( dependency.TypeReference, - out ITypeReference? nr)) + out var nr)) { normalized = null; return false; @@ -574,7 +574,7 @@ private void EnsureNoErrors() { var errors = new List(_errors); - foreach (RegisteredType type in _typeRegistry.Types) + foreach (var type in _typeRegistry.Types) { if (type.Errors.Count == 0) { diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeLookup.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeLookup.cs index 31c288a2ba7..82560eb1222 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeLookup.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeLookup.cs @@ -88,7 +88,7 @@ public bool TryNormalizeReference( if (directiveRef is ClrTypeDirectiveReference cr) { - ExtendedTypeReference directiveTypeRef = _typeInspector.GetTypeRef(cr.ClrType); + var directiveTypeRef = _typeInspector.GetTypeRef(cr.ClrType); if (!_typeRegistry.TryGetTypeRef(directiveTypeRef, out namedTypeRef)) { namedTypeRef = directiveTypeRef; @@ -120,7 +120,7 @@ private bool TryNormalizeExtendedTypeReference( // if the typeRef refers to a schema type base class we skip since such a type is not // resolvable. if (typeRef.Type.Type.IsNonGenericSchemaType() || - !_typeInspector.TryCreateTypeInfo(typeRef.Type, out ITypeInfo? typeInfo)) + !_typeInspector.TryCreateTypeInfo(typeRef.Type, out var typeInfo)) { namedTypeRef = null; return false; @@ -138,8 +138,8 @@ private bool TryNormalizeExtendedTypeReference( // eg list to ByteArray. for (var i = 0; i < typeInfo.Components.Count; i++) { - IExtendedType componentType = typeInfo.Components[i].Type; - ExtendedTypeReference componentRef = typeRef.WithType(componentType); + var componentType = typeInfo.Components[i].Type; + var componentRef = typeRef.WithType(componentType); if (_typeRegistry.TryGetTypeRef(componentRef, out namedTypeRef) || _typeRegistry.TryGetTypeRef(componentRef.WithContext(), out namedTypeRef)) { diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeReferenceResolver.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeReferenceResolver.cs index 0cbd2ba3724..ae5da20f5f5 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeReferenceResolver.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeReferenceResolver.cs @@ -44,7 +44,7 @@ public ITypeReference GetNamedTypeReference(ITypeReference typeRef) throw new ArgumentNullException(nameof(typeRef)); } - if (_typeLookup.TryNormalizeReference(typeRef, out ITypeReference? namedTypeRef)) + if (_typeLookup.TryNormalizeReference(typeRef, out var namedTypeRef)) { return namedTypeRef; } @@ -65,19 +65,19 @@ public bool TryGetType(ITypeReference typeRef, [NotNullWhen(true)] out IType? ty return true; } - if (!_typeLookup.TryNormalizeReference(typeRef, out ITypeReference? namedTypeRef)) + if (!_typeLookup.TryNormalizeReference(typeRef, out var namedTypeRef)) { type = null; return false; } - TypeId typeId = CreateId(typeRef, namedTypeRef); + var typeId = CreateId(typeRef, namedTypeRef); if (_typeCache.TryGetValue(typeId, out type)) { return true; } - if (!_typeRegistry.TryGetType(namedTypeRef, out RegisteredType? registeredType) || + if (!_typeRegistry.TryGetType(namedTypeRef, out var registeredType) || registeredType.Type is not INamedType) { type = null; @@ -89,7 +89,7 @@ public bool TryGetType(ITypeReference typeRef, [NotNullWhen(true)] out IType? ty switch (typeRef) { case ExtendedTypeReference r: - ITypeFactory typeFactory = _typeInspector.CreateTypeFactory(r.Type); + var typeFactory = _typeInspector.CreateTypeFactory(r.Type); type = typeFactory.CreateType(namedType); _typeCache[typeId] = type; return true; @@ -116,13 +116,13 @@ public bool TryGetDirectiveType( throw new ArgumentNullException(nameof(typeRef)); } - if (!_typeLookup.TryNormalizeReference(typeRef, out ITypeReference? namedTypeRef)) + if (!_typeLookup.TryNormalizeReference(typeRef, out var namedTypeRef)) { directiveType = null; return false; } - if (_typeRegistry.TryGetType(namedTypeRef, out RegisteredType? registeredType) && + if (_typeRegistry.TryGetType(namedTypeRef, out var registeredType) && registeredType.Type is DirectiveType d) { directiveType = d; @@ -155,7 +155,7 @@ private TypeId CreateId(ITypeReference typeRef, ITypeReference namedTypeRef) switch (typeRef) { case ExtendedTypeReference r: - ITypeInfo typeInfo = _typeInspector.CreateTypeInfo(r.Type); + var typeInfo = _typeInspector.CreateTypeInfo(r.Type); return new TypeId(namedTypeRef, CreateFlags(typeInfo)); case SyntaxTypeReference r: @@ -195,7 +195,7 @@ private static int CreateFlags(ITypeInfo typeInfo) private static int CreateFlags(ITypeNode type) { var flags = 1; - ITypeNode current = type; + var current = type; while (current is not NamedTypeNode) { diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeRegistrar.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeRegistrar.cs index da4a4613260..0430ac73cce 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeRegistrar.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeRegistrar.cs @@ -49,7 +49,7 @@ public void Register( throw new ArgumentNullException(nameof(obj)); } - RegisteredType registeredType = InitializeType(obj, scope, inferred); + var registeredType = InitializeType(obj, scope, inferred); configure?.Invoke(registeredType); @@ -60,7 +60,7 @@ public void Register( if (obj is IHasRuntimeType hasRuntimeType && hasRuntimeType.RuntimeType != typeof(object)) { - ExtendedTypeReference runtimeTypeRef = + var runtimeTypeRef = _context.TypeInspector.GetTypeRef( hasRuntimeType.RuntimeType, SchemaTypeReference.InferTypeContext(obj), @@ -81,7 +81,7 @@ private void RegisterTypeAndResolveReferences(RegisteredType registeredType) { _typeRegistry.Register(registeredType); - foreach (ITypeReference typeReference in registeredType.References) + foreach (var typeReference in registeredType.References) { MarkResolved(typeReference); } @@ -137,11 +137,11 @@ public IReadOnlyCollection GetUnhandled() var unhandled = new List(); var registered = new HashSet(); - foreach (RegisteredType type in _typeRegistry.Types) + foreach (var type in _typeRegistry.Types) { if (_handled.Add(type)) { - foreach (TypeDependency typeDep in type.Dependencies) + foreach (var typeDep in type.Dependencies) { if (registered.Add(typeDep.TypeReference)) { @@ -165,7 +165,7 @@ private RegisteredType InitializeType( // not already registered it. TypeReference instanceRef = TypeReference.Create(typeSystemObject, scope); - if (_typeRegistry.TryGetType(instanceRef, out RegisteredType? registeredType)) + if (_typeRegistry.TryGetType(instanceRef, out var registeredType)) { // if we already no this object we will short-circuit here and just return the // already registered instance. @@ -205,7 +205,7 @@ private RegisteredType InitializeType( if (typeSystemObject is IHasTypeIdentity hasTypeIdentity && hasTypeIdentity.TypeIdentity is not null) { - ExtendedTypeReference reference = + var reference = _context.TypeInspector.GetTypeRef( hasTypeIdentity.TypeIdentity, SchemaTypeReference.InferTypeContext(typeSystemObject), @@ -216,7 +216,7 @@ private RegisteredType InitializeType( if (_interceptor.TryCreateScope( registeredType, - out IReadOnlyList? dependencies)) + out var dependencies)) { registeredType.Dependencies.Clear(); registeredType.Dependencies.AddRange(dependencies); diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeRegistry.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeRegistry.cs index c5aecfe5ce2..bfc43f6d0c1 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeRegistry.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeRegistry.cs @@ -64,7 +64,7 @@ public bool TryGetType( } if (typeRef is ExtendedTypeReference clrTypeRef && - _runtimeTypeRefs.TryGetValue(clrTypeRef, out ITypeReference? internalRef)) + _runtimeTypeRefs.TryGetValue(clrTypeRef, out var internalRef)) { typeRef = internalRef; } @@ -128,9 +128,9 @@ public void Register(RegisteredType registeredType) var addToTypes = !_typeRegister.ContainsValue(registeredType); - foreach (ITypeReference typeReference in registeredType.References) + foreach (var typeReference in registeredType.References) { - if (_typeRegister.TryGetValue(typeReference, out RegisteredType? current) && + if (_typeRegister.TryGetValue(typeReference, out var current) && !ReferenceEquals(current, registeredType)) { if (current.IsInferred && !registeredType.IsInferred) @@ -206,8 +206,8 @@ public void Register(NameString typeName, RegisteredType registeredType) return; } - if (TryGetTypeRef(typeName, out ITypeReference? typeRef) && - TryGetType(typeRef, out RegisteredType? type) && + if (TryGetTypeRef(typeName, out var typeRef) && + TryGetType(typeRef, out var type) && !ReferenceEquals(type, registeredType)) { throw TypeInitializer_DuplicateTypeName(registeredType.Type, type.Type); @@ -218,7 +218,7 @@ public void Register(NameString typeName, RegisteredType registeredType) public void CompleteDiscovery() { - foreach (RegisteredType registeredType in _types) + foreach (var registeredType in _types) { ITypeReference reference = TypeReference.Create(registeredType.Type); registeredType.References.TryAdd(reference); diff --git a/src/HotChocolate/Core/src/Types/Configuration/TypeTrimmer.cs b/src/HotChocolate/Core/src/Types/Configuration/TypeTrimmer.cs index 10f3b319dc6..9ac1fae39a2 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/TypeTrimmer.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/TypeTrimmer.cs @@ -33,7 +33,7 @@ public void AddOperationType(ObjectType? operationType) public IReadOnlyCollection Trim() { - foreach (DirectiveType? directiveType in _discoveredTypes.OfType()) + foreach (var directiveType in _discoveredTypes.OfType()) { if (directiveType.IsExecutableDirective || directiveType.Name.Equals(WellKnownDirectives.Deprecated)) @@ -43,7 +43,7 @@ public IReadOnlyCollection Trim() } } - foreach (ObjectType rootType in _rootTypes) + foreach (var rootType in _rootTypes) { VisitRoot(rootType); } @@ -102,7 +102,7 @@ private void VisitEnum(EnumType type) { VisitDirectives(type); - foreach (IEnumValue value in type.Values) + foreach (var value in type.Values) { VisitDirectives(value); } @@ -112,17 +112,17 @@ private void VisitObject(ObjectType type) { VisitDirectives(type); - foreach (InterfaceType interfaceType in type.Implements) + foreach (var interfaceType in type.Implements) { Visit(interfaceType); } - foreach (ObjectField field in type.Fields) + foreach (var field in type.Fields) { VisitDirectives(field); Visit((TypeSystemObjectBase)field.Type.NamedType()); - foreach (Argument argument in field.Arguments) + foreach (var argument in field.Arguments) { VisitDirectives(argument); Visit((TypeSystemObjectBase)argument.Type.NamedType()); @@ -134,7 +134,7 @@ private void VisitUnion(UnionType type) { VisitDirectives(type); - foreach (ObjectType objectType in type.Types.Values) + foreach (var objectType in type.Types.Values) { Visit(objectType); } @@ -144,19 +144,19 @@ private void VisitInterface(InterfaceType type) { VisitDirectives(type); - foreach (InterfaceField field in type.Fields) + foreach (var field in type.Fields) { VisitDirectives(field); Visit((TypeSystemObjectBase)field.Type.NamedType()); - foreach (Argument argument in field.Arguments) + foreach (var argument in field.Arguments) { VisitDirectives(argument); Visit((TypeSystemObjectBase)argument.Type.NamedType()); } } - foreach (IComplexOutputType complexType in + foreach (var complexType in _discoveredTypes.OfType()) { if (complexType.IsImplementing(type)) @@ -170,7 +170,7 @@ private void VisitInput(InputObjectType type) { VisitDirectives(type); - foreach (InputField field in type.Fields) + foreach (var field in type.Fields) { VisitDirectives(field); Visit((TypeSystemObjectBase)field.Type.NamedType()); @@ -179,7 +179,7 @@ private void VisitInput(InputObjectType type) private void VisitDirective(DirectiveType type) { - foreach (Argument argument in type.Arguments) + foreach (var argument in type.Arguments) { VisitDirectives(argument); Visit((TypeSystemObjectBase)argument.Type.NamedType()); @@ -188,7 +188,7 @@ private void VisitDirective(DirectiveType type) private void VisitDirectives(IHasDirectives hasDirectives) { - foreach (DirectiveType type in hasDirectives.Directives.Select(t => t.Type)) + foreach (var type in hasDirectives.Directives.Select(t => t.Type)) { Visit(type); } diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/DirectiveValidationRule.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/DirectiveValidationRule.cs index e916c1dba8d..bf660c56871 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/DirectiveValidationRule.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/DirectiveValidationRule.cs @@ -21,7 +21,7 @@ public void Validate( { if (options.StrictValidation) { - foreach (DirectiveType type in typeSystemObjects.OfType()) + foreach (var type in typeSystemObjects.OfType()) { EnsureDirectiveNameIsValid(type, errors); EnsureArgumentNamesAreValid(type, errors); diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/InputObjectTypeValidationRule.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/InputObjectTypeValidationRule.cs index dc047bc41c1..e5ca1fc3258 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/InputObjectTypeValidationRule.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/InputObjectTypeValidationRule.cs @@ -15,7 +15,7 @@ public void Validate( { if (options.StrictValidation) { - foreach (InputObjectType type in typeSystemObjects.OfType()) + foreach (var type in typeSystemObjects.OfType()) { EnsureTypeHasFields(type, errors); EnsureFieldNamesAreValid(type, errors); @@ -33,7 +33,7 @@ private static void EnsureOneOfFieldsAreValid( { if (type.Fields.Any(t => t.Type.Kind is TypeKind.NonNull || t.DefaultValue is not null)) { - string[] fieldNames = type.Fields + var fieldNames = type.Fields .Where(t => t.Type.Kind is TypeKind.NonNull || t.DefaultValue is not null) .Select(t => t.Name.Value) .ToArray(); diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceHasAtLeastOneImplementationRule.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceHasAtLeastOneImplementationRule.cs index 6984d894134..3aa91fddff5 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceHasAtLeastOneImplementationRule.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceHasAtLeastOneImplementationRule.cs @@ -23,20 +23,20 @@ public void Validate( var fieldTypes = new HashSet(); - foreach (ObjectType objectType in typeSystemObjects.OfType()) + foreach (var objectType in typeSystemObjects.OfType()) { - foreach (InterfaceType interfaceType in objectType.Implements) + foreach (var interfaceType in objectType.Implements) { interfaceTypes.Remove(interfaceType); } - foreach (ObjectField field in objectType.Fields) + foreach (var field in objectType.Fields) { fieldTypes.Add(field.Type.NamedType()); } } - foreach (InterfaceType interfaceType in interfaceTypes.Where(fieldTypes.Contains)) + foreach (var interfaceType in interfaceTypes.Where(fieldTypes.Contains)) { // TODO : resources errors.Add(SchemaErrorBuilder.New() diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceTypeValidationRule.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceTypeValidationRule.cs index cdbfe9242a8..8ac7a9ded26 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceTypeValidationRule.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/InterfaceTypeValidationRule.cs @@ -16,7 +16,7 @@ public void Validate( { if (options.StrictValidation) { - foreach (InterfaceType type in typeSystemObjects.OfType()) + foreach (var type in typeSystemObjects.OfType()) { EnsureTypeHasFields(type, errors); EnsureFieldNamesAreValid(type, errors); diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/ObjectTypeValidationRule.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/ObjectTypeValidationRule.cs index 63399a226db..76db0a31368 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/ObjectTypeValidationRule.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/ObjectTypeValidationRule.cs @@ -20,7 +20,7 @@ public void Validate( { if (options.StrictValidation) { - foreach (ObjectType type in typeSystemObjects.OfType()) + foreach (var type in typeSystemObjects.OfType()) { EnsureTypeHasFields(type, errors); EnsureFieldNamesAreValid(type, errors); diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/SchemaValidator.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/SchemaValidator.cs index 9bba7174454..dd439ff86d9 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/SchemaValidator.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/SchemaValidator.cs @@ -33,7 +33,7 @@ public static IReadOnlyCollection Validate( var types = typeSystemObjects.ToList(); var errors = new List(); - foreach (ISchemaValidationRule rule in _rules) + foreach (var rule in _rules) { rule.Validate(types, options, errors); } diff --git a/src/HotChocolate/Core/src/Types/Configuration/Validation/TypeValidationHelper.cs b/src/HotChocolate/Core/src/Types/Configuration/Validation/TypeValidationHelper.cs index 791e4bc768e..06f6ddeadc4 100644 --- a/src/HotChocolate/Core/src/Types/Configuration/Validation/TypeValidationHelper.cs +++ b/src/HotChocolate/Core/src/Types/Configuration/Validation/TypeValidationHelper.cs @@ -28,7 +28,7 @@ public static void EnsureFieldDeprecationIsValid( { for (var i = 0; i < type.Fields.Count; i++) { - IInputField field = type.Fields[i]; + var field = type.Fields[i]; if (field.IsDeprecated && field.Type.IsNonNullType()) { @@ -43,10 +43,10 @@ public static void EnsureArgumentDeprecationIsValid( { for (var i = 0; i < type.Fields.Count; i++) { - IOutputField field = type.Fields[i]; + var field = type.Fields[i]; for (var j = 0; j < field.Arguments.Count; j++) { - IInputField argument = field.Arguments[j]; + var argument = field.Arguments[j]; if (argument.IsDeprecated && argument.Type.IsNonNullType()) { @@ -62,7 +62,7 @@ public static void EnsureArgumentDeprecationIsValid( { for (var i = 0; i < type.Arguments.Count; i++) { - Argument argument = type.Arguments[i]; + var argument = type.Arguments[i]; if (argument.IsDeprecated && argument.Type.IsNonNullType()) { errors.Add(RequiredArgumentCannotBeDeprecated(type, argument)); @@ -86,7 +86,7 @@ public static void EnsureFieldNamesAreValid( { for (var i = 0; i < type.Fields.Count; i++) { - IOutputField field = type.Fields[i]; + var field = type.Fields[i]; if (!field.IsIntrospectionField) { @@ -97,7 +97,7 @@ public static void EnsureFieldNamesAreValid( for (var j = 0; j < field.Arguments.Count; j++) { - IInputField argument = field.Arguments[j]; + var argument = field.Arguments[j]; if (argument.Name.Value.StartsWith(_twoUnderscores)) { @@ -117,7 +117,7 @@ public static void EnsureFieldNamesAreValid( { for (var i = 0; i < type.Fields.Count; i++) { - InputField field = type.Fields[i]; + var field = type.Fields[i]; if (field.Name.Value.StartsWith(_twoUnderscores)) { @@ -147,7 +147,7 @@ public static void EnsureInterfacesAreCorrectlyImplemented( { if (type.Implements.Count > 0) { - foreach (IInterfaceType implementedType in type.Implements) + foreach (var implementedType in type.Implements) { ValidateImplementation(type, implementedType, errors); } @@ -165,9 +165,9 @@ private static void ValidateImplementation( errors.Add(NotTransitivelyImplemented(type, implementedType)); } - foreach (IOutputField implementedField in implementedType.Fields) + foreach (var implementedField in implementedType.Fields) { - if (type.Fields.TryGetField(implementedField.Name, out IOutputField? field)) + if (type.Fields.TryGetField(implementedField.Name, out var field)) { ValidateArguments(field, implementedField, errors); @@ -190,9 +190,9 @@ private static void ValidateArguments( { var implArgs = implementedField.Arguments.ToDictionary(t => t.Name); - foreach (IInputField? argument in field.Arguments) + foreach (var argument in field.Arguments) { - if (implArgs.TryGetValue(argument.Name, out IInputField? implementedArgument)) + if (implArgs.TryGetValue(argument.Name, out var implementedArgument)) { implArgs.Remove(argument.Name); if (!argument.Type.IsEqualTo(implementedArgument.Type)) @@ -213,7 +213,7 @@ private static void ValidateArguments( } } - foreach (IInputField? missingArgument in implArgs.Values) + foreach (var missingArgument in implArgs.Values) { errors.Add(ArgumentNotImplemented( field, @@ -226,7 +226,7 @@ private static bool IsFullyImplementingInterface( IComplexOutputType type, IInterfaceType implementedType) { - foreach (IInterfaceType? interfaceType in implementedType.Implements) + foreach (var interfaceType in implementedType.Implements) { if (!type.IsImplementing(interfaceType)) { diff --git a/src/HotChocolate/Core/src/Types/Extensions/ResolverContextExtensions.cs b/src/HotChocolate/Core/src/Types/Extensions/ResolverContextExtensions.cs index 8da30aa0c59..9d2182fb987 100644 --- a/src/HotChocolate/Core/src/Types/Extensions/ResolverContextExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Extensions/ResolverContextExtensions.cs @@ -421,7 +421,7 @@ public static T GetOrSetGlobalState( } else { - T newValue = createValue(name); + var newValue = createValue(name); SetGlobalState(context, name, newValue); return newValue; } @@ -477,7 +477,7 @@ public static T GetOrSetScopedState( } else { - T newValue = createValue(name); + var newValue = createValue(name); SetScopedState(context, name, newValue); return newValue; } @@ -533,7 +533,7 @@ public static T GetOrSetLocalState( } else { - T newValue = createValue(name); + var newValue = createValue(name); SetLocalState(context, name, newValue); return newValue; } diff --git a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Conventions.cs b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Conventions.cs index 5086f627dd6..ea2ac2bfaa6 100644 --- a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Conventions.cs +++ b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Conventions.cs @@ -130,7 +130,7 @@ public static ISchemaBuilder AddConvention( { if (s.TryGetOrCreateService( concreteConvention, - out IConvention convention)) + out var convention)) { return convention; } diff --git a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Middleware.cs b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Middleware.cs index 34488801c32..961aec3911d 100644 --- a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Middleware.cs +++ b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Middleware.cs @@ -43,7 +43,7 @@ public static ISchemaBuilder Map( FieldClassMiddlewareFactory.Create( (s, n) => { - FieldMiddleware classMiddleware = + var classMiddleware = FieldClassMiddlewareFactory.Create(); return new MapMiddleware( n, fieldReference, classMiddleware(n)); @@ -60,7 +60,7 @@ public static ISchemaBuilder Map( FieldClassMiddlewareFactory.Create( (s, n) => { - FieldMiddleware classMiddleware = + var classMiddleware = FieldClassMiddlewareFactory .Create(factory); return new MapMiddleware( diff --git a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Resolvers.cs b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Resolvers.cs index ddb9588a7be..2a27776daa6 100644 --- a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Resolvers.cs +++ b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Resolvers.cs @@ -632,7 +632,7 @@ public static ISchemaBuilder AddRootResolver(this ISchemaBuilder builder, Type r if (resolverType is { IsClass: true } or { IsInterface: true }) { - foreach (PropertyInfo? property in resolverType.GetProperties()) + foreach (var property in resolverType.GetProperties()) { AddResolverTypeInternal(builder, property.Name, property.PropertyType); } diff --git a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Types.cs b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Types.cs index c88491a223b..55d8aace987 100644 --- a/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Types.cs +++ b/src/HotChocolate/Core/src/Types/Extensions/SchemaBuilderExtensions.Types.cs @@ -585,7 +585,7 @@ public static ISchemaBuilder AddTypes( throw new ArgumentNullException(nameof(types)); } - foreach (INamedType type in types) + foreach (var type in types) { builder.AddType(type); } @@ -606,7 +606,7 @@ public static ISchemaBuilder AddTypes( throw new ArgumentNullException(nameof(types)); } - foreach (Type type in types) + foreach (var type in types) { builder.AddType(type); } diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.BaseTypes.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.BaseTypes.cs index 731c7123c10..f1799d8d0a7 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.BaseTypes.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.BaseTypes.cs @@ -42,7 +42,7 @@ public static bool IsNamedType(Type type) return true; } - foreach (Type baseType in _baseTypes) + foreach (var baseType in _baseTypes) { if (baseType.IsAssignableFrom(type)) { diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Helper.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Helper.cs index 0772ce26a67..87147366047 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Helper.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Helper.cs @@ -26,7 +26,7 @@ internal static bool IsSchemaType(Type type) if (type.IsGenericType) { - Type definition = type.GetGenericTypeDefinition(); + var definition = type.GetGenericTypeDefinition(); if (typeof(ListType<>) == definition || typeof(NonNullType<>) == definition || typeof(NativeType<>) == definition) @@ -79,7 +79,7 @@ private static bool ImplementsListInterface(Type type) => IExtendedType key = type.TypeArguments[0]; IExtendedType value = type.TypeArguments[1]; - Type itemType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, value.Type); + var itemType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, value.Type); return cache.GetOrCreateType(itemType, () => { @@ -101,11 +101,11 @@ private static bool ImplementsListInterface(Type type) => return type.TypeArguments[0]; } - foreach (Type interfaceType in type.Type.GetInterfaces()) + foreach (var interfaceType in type.Type.GetInterfaces()) { if (IsSupportedCollectionInterface(interfaceType)) { - Type elementType = interfaceType.GetGenericArguments()[0]; + var elementType = interfaceType.GetGenericArguments()[0]; if (type.TypeArguments.Count == 1 && type.TypeArguments[0].Type == elementType) @@ -122,7 +122,7 @@ private static bool ImplementsListInterface(Type type) => internal static Type? GetInnerListType(Type type) { - Type? typeDefinition = type.IsGenericType ? type.GetGenericTypeDefinition() : null; + var typeDefinition = type.IsGenericType ? type.GetGenericTypeDefinition() : null; if (IsSupportedCollectionInterface(type)) { @@ -134,7 +134,7 @@ private static bool ImplementsListInterface(Type type) => return type.GetGenericArguments()[0]; } - foreach (Type interfaceType in type.GetInterfaces()) + foreach (var interfaceType in type.GetInterfaces()) { if (IsSupportedCollectionInterface(interfaceType)) { @@ -156,7 +156,7 @@ public static bool IsSupportedCollectionInterface(Type type) { if (type.IsGenericType) { - Type typeDefinition = type.GetGenericTypeDefinition(); + var typeDefinition = type.GetGenericTypeDefinition(); if (typeDefinition == typeof(IReadOnlyCollection<>) || typeDefinition == typeof(IReadOnlyList<>) || typeDefinition == typeof(ICollection<>) @@ -189,7 +189,7 @@ private static bool IsDictionary(Type type) { if (type.IsGenericType) { - Type typeDefinition = type.GetGenericTypeDefinition(); + var typeDefinition = type.GetGenericTypeDefinition(); if (typeDefinition == typeof(IDictionary<,>) || typeDefinition == typeof(IReadOnlyDictionary<,>) || typeDefinition == typeof(Dictionary<,>) @@ -213,9 +213,9 @@ internal static IExtendedType ChangeNullability( return type; } - ExtendedTypeId id = Tools.CreateId(type, nullable); + var id = Tools.CreateId(type, nullable); - if (cache.TryGetType(id, out ExtendedType? extendedType)) + if (cache.TryGetType(id, out var extendedType)) { return extendedType; } @@ -231,7 +231,7 @@ private static ExtendedType ChangeNullability( ref int position, TypeCache cache) { - if (cache.TryGetType(id, out ExtendedType? cached)) + if (cache.TryGetType(id, out var cached)) { return cached; } @@ -241,7 +241,7 @@ private static ExtendedType ChangeNullability( nullable.Length > pos && nullable[pos].HasValue && nullable[pos]!.Value != type.IsNullable; - IReadOnlyList typeArguments = type.TypeArguments; + var typeArguments = type.TypeArguments; if (type.TypeArguments.Count > 0 && nullable.Length > position) { @@ -249,8 +249,8 @@ private static ExtendedType ChangeNullability( for (var j = 0; j < type.TypeArguments.Count; j++) { - ExtendedType typeArgument = type.TypeArguments[j]; - ExtendedTypeId typeArgumentId = + var typeArgument = type.TypeArguments[j]; + var typeArgumentId = Tools.CreateId(typeArgument, nullable.Slice(position)); args[j] = nullable.Length > position @@ -268,7 +268,7 @@ private static ExtendedType ChangeNullability( if (changeNullability || !ReferenceEquals(typeArguments, type.TypeArguments)) { - ExtendedType? elementType = type.IsArrayOrList + var elementType = type.IsArrayOrList ? type.ElementType : null; @@ -367,7 +367,7 @@ internal static void CollectNullability( nullability[position++] = type.IsNullable; - foreach (IExtendedType typeArgument in type.TypeArguments) + foreach (var typeArgument in type.TypeArguments) { CollectNullability(typeArgument, nullability, ref position); } diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Members.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Members.cs index 10414dd31d6..327b71babf3 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Members.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Members.cs @@ -19,7 +19,7 @@ public static ExtendedType FromMember(MemberInfo member, TypeCache cache) => private static ExtendedType FromMember(MemberInfo member) { var helper = new NullableHelper(member.DeclaringType!); - bool? context = helper.GetContext(member); + var context = helper.GetContext(member); ReadOnlySpan flags = helper.GetFlags(member); return member switch @@ -34,7 +34,7 @@ private static ExtendedType FromMember(MemberInfo member) public static ExtendedMethodInfo FromMethod(MethodInfo method, TypeCache cache) { var helper = new NullableHelper(method.DeclaringType!); - bool? context = helper.GetContext(method); + var context = helper.GetContext(method); IExtendedType returnType = cache.GetOrCreateType( method, @@ -43,10 +43,10 @@ public static ExtendedMethodInfo FromMethod(MethodInfo method, TypeCache cache) method, cache)); - ParameterInfo[] parameters = method.GetParameters(); + var parameters = method.GetParameters(); var parameterTypes = new Dictionary(); - foreach (ParameterInfo parameter in parameters) + foreach (var parameter in parameters) { parameterTypes.Add( parameter, @@ -71,7 +71,7 @@ private static ExtendedType Rewrite( { extendedType = Helper.RemoveNonEssentialTypes(extendedType); - IReadOnlyList arguments = extendedType.TypeArguments; + var arguments = extendedType.TypeArguments; var extendedArguments = new ExtendedType[arguments.Count]; for (var i = 0; i < extendedArguments.Length; i++) @@ -86,11 +86,11 @@ private static ExtendedType Rewrite( if (isList) { - Type itemType = Helper.GetInnerListType(extendedType.Type)!; + var itemType = Helper.GetInnerListType(extendedType.Type)!; if (extendedType.TypeArguments.Count == 1) { - IExtendedType typeArgument = extendedType.TypeArguments[0]; + var typeArgument = extendedType.TypeArguments[0]; if (itemType == typeArgument.Type || itemType == typeArgument.Source) { elementType = extendedArguments[0]; @@ -138,7 +138,7 @@ private static ExtendedType CreateExtendedType( Type type, ref int position) { - bool? state = position == -1 || (type.IsValueType && !type.IsGenericType) + var state = position == -1 || (type.IsValueType && !type.IsGenericType) ? null : GetNextState(flags, ref position); @@ -147,7 +147,7 @@ private static ExtendedType CreateExtendedType( if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { - Type inner = type.GetGenericArguments()[0]; + var inner = type.GetGenericArguments()[0]; return new ExtendedType( inner, @@ -167,7 +167,7 @@ private static ExtendedType CreateExtendedType( if (type.IsArray) { - ExtendedType elementType = + var elementType = CreateExtendedType( context, flags, @@ -192,7 +192,7 @@ private static ExtendedType CreateExtendedType( bool? GetNextState(ReadOnlySpan flags, ref int position) { - bool? state = context; + var state = context; if (!flags.IsEmpty) { if (flags.Length > position) @@ -217,12 +217,12 @@ private static IReadOnlyList GetGenericArguments( { if (type.IsGenericType) { - Type[] arguments = type.GetGenericArguments(); - ExtendedType[] extendedArguments = new ExtendedType[arguments.Length]; - bool skipFlags = SkipFlags(arguments); - int skipPos = -1; + var arguments = type.GetGenericArguments(); + var extendedArguments = new ExtendedType[arguments.Length]; + var skipFlags = SkipFlags(arguments); + var skipPos = -1; - for (int i = 0; i < arguments.Length; i++) + for (var i = 0; i < arguments.Length; i++) { extendedArguments[i] = skipFlags @@ -238,9 +238,9 @@ private static IReadOnlyList GetGenericArguments( private static bool SkipFlags(Type[] arguments) { - bool skipFlags = true; + var skipFlags = true; - foreach (Type argument in arguments) + foreach (var argument in arguments) { if (!argument.IsValueType) { diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SchemaType.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SchemaType.cs index fdb705ec8dd..efdac0f2a38 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SchemaType.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SchemaType.cs @@ -22,7 +22,7 @@ private static ExtendedType FromType( if (type.IsGenericType) { - Type definition = type.GetGenericTypeDefinition(); + var definition = type.GetGenericTypeDefinition(); if (definition == typeof(NonNullType<>)) { @@ -35,7 +35,7 @@ private static ExtendedType FromType( source is not null ? source : type, () => { - ExtendedType elementType = + var elementType = FromType(type.GetGenericArguments()[0], null, true, cache); return new ExtendedType( @@ -55,7 +55,7 @@ private static ExtendedType FromType( source ?? type, () => { - Type? definition = type.IsGenericType + var definition = type.IsGenericType ? type.GetGenericTypeDefinition() : null; diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SystemType.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SystemType.cs index 4217821a2a3..16fcd105893 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SystemType.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.SystemType.cs @@ -19,7 +19,7 @@ private static ExtendedType FromTypeInternal(Type type, TypeCache cache) if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { - Type inner = type.GetGenericArguments()[0]; + var inner = type.GetGenericArguments()[0]; return new ExtendedType( inner, @@ -29,12 +29,12 @@ private static ExtendedType FromTypeInternal(Type type, TypeCache cache) isNullable: true); } - ExtendedType? elementType = + var elementType = Helper.GetInnerListType(type) is { } e ? FromType(e, cache) : null; - IReadOnlyList typeArguments = + var typeArguments = type.IsArray && elementType is not null ? new[] { elementType } : GetGenericArguments(type, cache); @@ -55,8 +55,8 @@ public static IReadOnlyList GetGenericArguments( { if (type.IsGenericType) { - Type[] arguments = type.GetGenericArguments(); - ExtendedType[] extendedArguments = new ExtendedType[arguments.Length]; + var arguments = type.GetGenericArguments(); + var extendedArguments = new ExtendedType[arguments.Length]; for (var i = 0; i < arguments.Length; i++) { diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Tools.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Tools.cs index 9c76274a24c..00f5e49eed2 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Tools.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.Tools.cs @@ -63,7 +63,7 @@ internal static bool IsNonGenericBaseType(Type type) if (type.IsGenericType) { - Type definition = type.GetGenericTypeDefinition(); + var definition = type.GetGenericTypeDefinition(); if (typeof(ListType<>) == definition || typeof(NonNullType<>) == definition || typeof(NativeType<>) == definition) @@ -109,13 +109,13 @@ internal static IExtendedType ChangeNullability( internal static bool?[] CollectNullability(IExtendedType type) { - int length = 0; + var length = 0; Span buffer = stackalloc bool[32]; Helper.CollectNullability(type, buffer, ref length); buffer = buffer.Slice(0, length); var nullability = new bool?[buffer.Length]; - for (int i = 0; i < nullability.Length; i++) + for (var i = 0; i < nullability.Length; i++) { nullability[i] = buffer[i]; } @@ -127,7 +127,7 @@ internal static bool CollectNullability( Span nullability, out int written) { - int length = 0; + var length = 0; Span buffer = stackalloc bool[32]; Helper.CollectNullability(type, buffer, ref length); buffer = buffer.Slice(0, length); @@ -138,7 +138,7 @@ internal static bool CollectNullability( return false; } - for (int i = 0; i < buffer.Length; i++) + for (var i = 0; i < buffer.Length; i++) { nullability[i] = buffer[i]; } diff --git a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.cs b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.cs index df0426c27d8..115dbd20c66 100644 --- a/src/HotChocolate/Core/src/Types/Internal/ExtendedType.cs +++ b/src/HotChocolate/Core/src/Types/Internal/ExtendedType.cs @@ -175,7 +175,7 @@ public static ExtendedType FromType(Type type, TypeCache cache) throw new ArgumentNullException(nameof(cache)); } - if (cache.TryGetType(type, out ExtendedType? extendedType)) + if (cache.TryGetType(type, out var extendedType)) { return extendedType; } diff --git a/src/HotChocolate/Core/src/Types/Internal/FieldInitHelper.cs b/src/HotChocolate/Core/src/Types/Internal/FieldInitHelper.cs index 3cdf68246a6..c19925213ca 100644 --- a/src/HotChocolate/Core/src/Types/Internal/FieldInitHelper.cs +++ b/src/HotChocolate/Core/src/Types/Internal/FieldInitHelper.cs @@ -159,7 +159,7 @@ public static FieldCollection CompleteFieldsInternal fieldDefs = fieldDefinitions.Where(t => !t.Ignore); + var fieldDefs = fieldDefinitions.Where(t => !t.Ignore); if (context.DescriptorContext.Options.SortFieldsByName) { @@ -169,7 +169,7 @@ public static FieldCollection CompleteFieldsInternal CompleteFieldsInternal( return FieldCollection.Empty; } - foreach (TField field in fields) + foreach (var field in fields) { ((IFieldCompletion)field).CompleteField(context, declaringMember); } diff --git a/src/HotChocolate/Core/src/Types/Internal/TypeCache.cs b/src/HotChocolate/Core/src/Types/Internal/TypeCache.cs index 4e8133fb60b..ea6e2931f3a 100644 --- a/src/HotChocolate/Core/src/Types/Internal/TypeCache.cs +++ b/src/HotChocolate/Core/src/Types/Internal/TypeCache.cs @@ -45,9 +45,9 @@ public ExtendedType GetOrCreateType(object member, Func create) { lock (_sync) { - if (!_typeMemberLookup.TryGetValue(member, out ExtendedType? extendedType)) + if (!_typeMemberLookup.TryGetValue(member, out var extendedType)) { - ExtendedType type = create(); + var type = create(); if (_types.TryGetValue(type.Id, out extendedType)) { @@ -85,11 +85,11 @@ public TypeInfo GetOrCreateTypeInfo( IExtendedType extendedType, Func create) { - ExtendedTypeId id = ((ExtendedType)extendedType).Id; + var id = ((ExtendedType)extendedType).Id; lock (_sync) { - if (!_typeInfos.TryGetValue(id, out TypeInfo? typeInfo)) + if (!_typeInfos.TryGetValue(id, out var typeInfo)) { typeInfo = create(); _typeInfos.Add(id, typeInfo); diff --git a/src/HotChocolate/Core/src/Types/Internal/TypeDependencyHelper.cs b/src/HotChocolate/Core/src/Types/Internal/TypeDependencyHelper.cs index 328b36ea860..2ec0d53af90 100644 --- a/src/HotChocolate/Core/src/Types/Internal/TypeDependencyHelper.cs +++ b/src/HotChocolate/Core/src/Types/Internal/TypeDependencyHelper.cs @@ -25,7 +25,7 @@ public static void CollectDependencies( if (definition.HasDependencies) { - foreach (TypeDependency dependency in definition.Dependencies) + foreach (var dependency in definition.Dependencies) { dependencies.Add(dependency); } @@ -33,7 +33,7 @@ public static void CollectDependencies( if (definition.HasInterfaces) { - foreach (ITypeReference typeRef in definition.Interfaces) + foreach (var typeRef in definition.Interfaces) { dependencies.Add(new(typeRef, TypeDependencyKind.Completed)); } @@ -59,7 +59,7 @@ public static void CollectDependencies( if (definition.HasDependencies) { - foreach (TypeDependency dependency in definition.Dependencies) + foreach (var dependency in definition.Dependencies) { dependencies.Add(dependency); } @@ -67,7 +67,7 @@ public static void CollectDependencies( if (definition.HasInterfaces) { - foreach (ITypeReference typeRef in definition.Interfaces) + foreach (var typeRef in definition.Interfaces) { dependencies.Add(new(typeRef, TypeDependencyKind.Completed)); } @@ -93,17 +93,17 @@ public static void CollectDependencies( if (definition.HasDependencies) { - foreach (TypeDependency dependency in definition.Dependencies) + foreach (var dependency in definition.Dependencies) { dependencies.Add(dependency); } } - foreach (InputFieldDefinition field in definition.Fields) + foreach (var field in definition.Fields) { if (field.HasDependencies) { - foreach (TypeDependency dependency in field.Dependencies) + foreach (var dependency in field.Dependencies) { dependencies.Add(dependency); } @@ -136,17 +136,17 @@ public static void CollectDependencies( if (definition.HasDependencies) { - foreach (TypeDependency dependency in definition.Dependencies) + foreach (var dependency in definition.Dependencies) { dependencies.Add(dependency); } } - foreach (EnumValueDefinition value in definition.Values) + foreach (var value in definition.Values) { if (value.HasDependencies) { - foreach (TypeDependency dependency in value.Dependencies) + foreach (var dependency in value.Dependencies) { dependencies.Add(dependency); } @@ -164,7 +164,7 @@ public static void CollectDependencies( { if (definition.HasArguments) { - foreach (DirectiveArgumentDefinition argument in definition.Arguments) + foreach (var argument in definition.Arguments) { if (argument.Type is not null) { @@ -183,7 +183,7 @@ internal static void CollectDirectiveDependencies( { if (definition.HasDirectives) { - foreach (DirectiveDefinition directive in definition.Directives) + foreach (var directive in definition.Directives) { dependencies.Add(new(directive.TypeReference, TypeDependencyKind.Completed)); } @@ -196,7 +196,7 @@ private static void CollectDirectiveDependencies( { if (definition.HasDirectives) { - foreach (DirectiveDefinition directive in definition.Directives) + foreach (var directive in definition.Directives) { dependencies.Add(new(directive.TypeReference, TypeDependencyKind.Completed)); } @@ -207,11 +207,11 @@ private static void CollectFieldDependencies( IReadOnlyList fields, ICollection dependencies) { - foreach (OutputFieldDefinitionBase field in fields) + foreach (var field in fields) { if (field.HasDependencies) { - foreach (TypeDependency dependency in field.Dependencies) + foreach (var dependency in field.Dependencies) { dependencies.Add(dependency); } @@ -235,11 +235,11 @@ private static void CollectArgumentDependencies( IReadOnlyList fields, ICollection dependencies) { - foreach (ArgumentDefinition field in fields) + foreach (var field in fields) { if (field.HasDependencies) { - foreach (TypeDependency dependency in field.Dependencies) + foreach (var dependency in field.Dependencies) { dependencies.Add(dependency); } diff --git a/src/HotChocolate/Core/src/Types/Internal/TypeExtensionHelper.cs b/src/HotChocolate/Core/src/Types/Internal/TypeExtensionHelper.cs index f161d43e67e..59c9e84268c 100644 --- a/src/HotChocolate/Core/src/Types/Internal/TypeExtensionHelper.cs +++ b/src/HotChocolate/Core/src/Types/Internal/TypeExtensionHelper.cs @@ -72,9 +72,9 @@ private static void MergeFields( Action? onBeforeAdd = null) where T : FieldDefinitionBase { - foreach (T extensionField in extensionFields) + foreach (var extensionField in extensionFields) { - T? typeField = typeFields.FirstOrDefault(t => t.Name.Equals(extensionField.Name)); + var typeField = typeFields.FirstOrDefault(t => t.Name.Equals(extensionField.Name)); if (typeField is null) { @@ -102,24 +102,24 @@ public static void MergeDirectives( { var directives = new List<(DirectiveType type, DirectiveDefinition def)>(); - foreach (DirectiveDefinition directive in type) + foreach (var directive in type) { if (context.TryGetDirectiveType( directive.Reference, - out DirectiveType? directiveType)) + out var directiveType)) { directives.Add((directiveType, directive)); } } - foreach (DirectiveDefinition directive in extension) + foreach (var directive in extension) { MergeDirective(context, directives, directive); } type.Clear(); - foreach (DirectiveDefinition directive in directives.Select(t => t.def)) + foreach (var directive in directives.Select(t => t.def)) { type.Add(directive); } @@ -130,7 +130,7 @@ private static void MergeDirective( IList<(DirectiveType type, DirectiveDefinition def)> directives, DirectiveDefinition directive) { - if (context.TryGetDirectiveType(directive.Reference, out DirectiveType? directiveType)) + if (context.TryGetDirectiveType(directive.Reference, out var directiveType)) { if (directiveType.IsRepeatable) { @@ -138,7 +138,7 @@ private static void MergeDirective( } else { - (DirectiveType type, DirectiveDefinition def) entry = directives.FirstOrDefault(t => t.type == directiveType); + var entry = directives.FirstOrDefault(t => t.type == directiveType); if (entry == default) { directives.Add((directiveType, directive)); @@ -168,7 +168,7 @@ public static void MergeInterfaces( { if (extension.GetInterfaces().Count > 0) { - foreach (ITypeReference interfaceReference in extension.GetInterfaces()) + foreach (var interfaceReference in extension.GetInterfaces()) { type.Interfaces.Add(interfaceReference); } @@ -187,7 +187,7 @@ public static void MergeTypes( { var set = new HashSet(typeTypes); - foreach (ITypeReference reference in extensionTypes) + foreach (var reference in extensionTypes) { if (set.Add(reference)) { @@ -200,7 +200,7 @@ public static void MergeConfigurations( ICollection extensionConfigurations, ICollection typeConfigurations) { - foreach (ITypeSystemMemberConfiguration configuration in extensionConfigurations) + foreach (var configuration in extensionConfigurations) { typeConfigurations.Add(configuration); } diff --git a/src/HotChocolate/Core/src/Types/Internal/TypeInfo.RuntimeType.cs b/src/HotChocolate/Core/src/Types/Internal/TypeInfo.RuntimeType.cs index 0a34b799455..14970c59290 100644 --- a/src/HotChocolate/Core/src/Types/Internal/TypeInfo.RuntimeType.cs +++ b/src/HotChocolate/Core/src/Types/Internal/TypeInfo.RuntimeType.cs @@ -26,8 +26,8 @@ internal static bool TryCreateTypeInfo( { if (type.Kind != ExtendedTypeKind.Schema) { - IReadOnlyList components = - Decompose(type, cache, out IExtendedType namedType); + var components = + Decompose(type, cache, out var namedType); typeInfo = new TypeInfo( namedType.Type, @@ -49,7 +49,7 @@ private static IReadOnlyList Decompose( out IExtendedType namedType) { var list = new List(); - IExtendedType? current = type; + var current = type; while (current is not null) { @@ -62,7 +62,7 @@ private static IReadOnlyList Decompose( if (current.IsArrayOrList) { - IExtendedType rewritten = current.IsNullable + var rewritten = current.IsNullable ? current : ExtendedType.Tools.ChangeNullability( current, new bool?[] { true }, cache); @@ -72,7 +72,7 @@ private static IReadOnlyList Decompose( } else { - IExtendedType rewritten = current.IsNullable + var rewritten = current.IsNullable ? current : ExtendedType.Tools.ChangeNullability( current, new bool?[] { true }, cache); @@ -89,7 +89,7 @@ private static IReadOnlyList Decompose( private static IExtendedType RemoveNonEssentialParts(IExtendedType type) { short i = 0; - IExtendedType current = type; + var current = type; while (IsWrapperType(current) || IsTaskType(current) || IsOptional(current)) { diff --git a/src/HotChocolate/Core/src/Types/Internal/TypeInfo.SchemaType.cs b/src/HotChocolate/Core/src/Types/Internal/TypeInfo.SchemaType.cs index 188d0828549..4b4f7ea0782 100644 --- a/src/HotChocolate/Core/src/Types/Internal/TypeInfo.SchemaType.cs +++ b/src/HotChocolate/Core/src/Types/Internal/TypeInfo.SchemaType.cs @@ -17,8 +17,8 @@ internal static bool TryCreateTypeInfo( { if (type.Kind == ExtendedTypeKind.Schema) { - IReadOnlyList components = - Decompose(type, out IExtendedType namedType); + var components = + Decompose(type, out var namedType); typeInfo = new TypeInfo( namedType.Type, @@ -39,7 +39,7 @@ private static IReadOnlyList Decompose( out IExtendedType namedType) { var list = new List(); - IExtendedType? current = type; + var current = type; while (current is not null) { diff --git a/src/HotChocolate/Core/src/Types/Internal/TypeInfo.cs b/src/HotChocolate/Core/src/Types/Internal/TypeInfo.cs index 8c32d76c1fe..ca29b6a2dd4 100644 --- a/src/HotChocolate/Core/src/Types/Internal/TypeInfo.cs +++ b/src/HotChocolate/Core/src/Types/Internal/TypeInfo.cs @@ -118,7 +118,7 @@ public IType CreateType(INamedType namedType) public static TypeInfo Create(IExtendedType type, TypeCache cache) { - if (TryCreate(type, cache, out TypeInfo? typeInfo)) + if (TryCreate(type, cache, out var typeInfo)) { return typeInfo; } @@ -153,7 +153,7 @@ private static TypeInfo CreateInternal( if (SchemaType.TryCreateTypeInfo( type, originalType, - out TypeInfo? typeInfo)) + out var typeInfo)) { return typeInfo; } diff --git a/src/HotChocolate/Core/src/Types/Resolvers/DefaultResolverCompiler.cs b/src/HotChocolate/Core/src/Types/Resolvers/DefaultResolverCompiler.cs index 29d9cd49c65..c7cc1a237d3 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/DefaultResolverCompiler.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/DefaultResolverCompiler.cs @@ -64,7 +64,7 @@ public DefaultResolverCompiler( { // then we will add custom parameter expression builder and // give the user a chance to override our implicit expression builder. - foreach (IParameterExpressionBuilder builder in custom) + foreach (var builder in custom) { if (!builder.IsDefaultHandler) { @@ -94,7 +94,7 @@ public DefaultResolverCompiler( // last we will add all custom default handlers. This will give these handlers a chance // to apply logic only on arguments. - foreach (IParameterExpressionBuilder builder in custom) + foreach (var builder in custom) { if (builder.IsDefaultHandler) { @@ -114,7 +114,7 @@ public DefaultResolverCompiler( var parameterFieldConfigurations = new List(); - foreach (IParameterExpressionBuilder builder in _parameterExpressionBuilders) + foreach (var builder in _parameterExpressionBuilders) { if (builder is IParameterFieldConfiguration configuration) { @@ -122,7 +122,7 @@ public DefaultResolverCompiler( } } - foreach (IParameterExpressionBuilder builder in _defaultParameterExpressionBuilders) + foreach (var builder in _defaultParameterExpressionBuilders) { if (builder is IParameterFieldConfiguration configuration) { @@ -144,12 +144,12 @@ public FieldResolverDelegates CompileResolve( throw new ArgumentNullException(nameof(propertyOrMethod)); } - MemberInfo? member = propertyOrMethod.TryExtractMember(); + var member = propertyOrMethod.TryExtractMember(); if (member is PropertyInfo or MethodInfo) { - Type source = sourceType ?? typeof(TResolver); - Type? resolver = sourceType is null ? typeof(TResolver) : null; + var source = sourceType ?? typeof(TResolver); + var resolver = sourceType is null ? typeof(TResolver) : null; return CompileResolve(member, source, resolver, parameterExpressionBuilders); } @@ -171,7 +171,7 @@ public FieldResolverDelegates CompileResolve( resolverType ??= sourceType ?? throw new ArgumentNullException(nameof(sourceType)); - Expression owner = CreateResolverOwner(_context, sourceType, resolverType); + var owner = CreateResolverOwner(_context, sourceType, resolverType); Expression resolver = Invoke(lambda, owner); resolver = EnsureResolveResult(resolver, lambda.ReturnType); return new(Lambda(resolver, _context).Compile()); @@ -233,9 +233,9 @@ public SubscribeResolverDelegate CompileSubscribe( if (member is MethodInfo method) { - ParameterInfo[] parameters = method.GetParameters(); - Expression owner = CreateResolverOwner(_context, sourceType, resolverType); - Expression[] parameterExpr = CreateParameters(_context, parameters, _empty); + var parameters = method.GetParameters(); + var owner = CreateResolverOwner(_context, sourceType, resolverType); + var parameterExpr = CreateParameters(_context, parameters, _empty); Expression subscribeResolver = Call(owner, method, parameterExpr); subscribeResolver = EnsureSubscribeResult(subscribeResolver, method.ReturnType); return Lambda(subscribeResolver, _context).Compile(); @@ -256,9 +256,9 @@ public IEnumerable GetArgumentParameters( throw new ArgumentNullException(nameof(parameters)); } - foreach (ParameterInfo parameter in parameters) + foreach (var parameter in parameters) { - IParameterExpressionBuilder builder = + var builder = GetParameterExpressionBuilder( parameter, parameterExpressionBuilders ?? _empty); @@ -280,9 +280,9 @@ public void ApplyConfiguration( throw new ArgumentNullException(nameof(parameters)); } - foreach (ParameterInfo parameter in parameters) + foreach (var parameter in parameters) { - foreach (IParameterFieldConfiguration configuration in _parameterFieldConfigurations) + foreach (var configuration in _parameterFieldConfigurations) { if (configuration.CanHandle(parameter)) { @@ -297,7 +297,7 @@ private FieldResolverDelegate CompileStaticResolver( MethodInfo method, IParameterExpressionBuilder[] fieldParameterExpressionBuilders) { - Expression[] parameters = CreateParameters( + var parameters = CreateParameters( _context, method.GetParameters(), fieldParameterExpressionBuilders); @@ -314,7 +314,7 @@ private FieldResolverDelegate CreateResolver( { if (member is PropertyInfo property) { - Expression owner = CreateResolverOwner(_context, source, resolverType); + var owner = CreateResolverOwner(_context, source, resolverType); Expression propResolver = Property(owner, property); propResolver = EnsureResolveResult(propResolver, property.PropertyType); return Lambda(propResolver, _context).Compile(); @@ -322,9 +322,9 @@ private FieldResolverDelegate CreateResolver( if (member is MethodInfo method) { - ParameterInfo[] parameters = method.GetParameters(); - Expression owner = CreateResolverOwner(_context, source, resolverType); - Expression[] parameterExpr = CreateParameters( + var parameters = method.GetParameters(); + var owner = CreateResolverOwner(_context, source, resolverType); + var parameterExpr = CreateParameters( _context, parameters, fieldParameterExpressionBuilders); @@ -345,7 +345,7 @@ private FieldResolverDelegate CreateResolver( { if (member is PropertyInfo property && IsPureResolverResult(property.PropertyType)) { - Expression owner = CreateResolverOwner(_pureContext, source, resolver); + var owner = CreateResolverOwner(_pureContext, source, resolver); Expression propertyResolver = Property(owner, property); if (property.PropertyType != typeof(object)) @@ -358,12 +358,12 @@ private FieldResolverDelegate CreateResolver( if (member is MethodInfo method) { - ParameterInfo[] parameters = method.GetParameters(); + var parameters = method.GetParameters(); if (IsPureResolver(method, parameters, fieldParameterExpressionBuilders)) { - Expression owner = CreateResolverOwner(_pureContext, source, resolver); - Expression[] parameterExpr = CreateParameters( + var owner = CreateResolverOwner(_pureContext, source, resolver); + var parameterExpr = CreateParameters( _pureContext, parameters, fieldParameterExpressionBuilders); @@ -391,9 +391,9 @@ private bool IsPureResolver( return false; } - foreach (ParameterInfo parameter in parameters) + foreach (var parameter in parameters) { - IParameterExpressionBuilder builder = + var builder = GetParameterExpressionBuilder(parameter, fieldParameterExpressionBuilders); if (!builder.IsPure) @@ -421,7 +421,7 @@ private static bool IsPureResolverResult(Type resultType) if (resultType.IsGenericType) { - Type type = resultType.GetGenericTypeDefinition(); + var type = resultType.GetGenericTypeDefinition(); if (type == typeof(ValueTask<>) || type == typeof(IAsyncEnumerable<>)) { @@ -438,7 +438,7 @@ private static Expression CreateResolverOwner( Type source, Type resolver) { - MethodInfo resolverMethod = source == resolver + var resolverMethod = source == resolver ? _parent.MakeGenericMethod(source) : _resolver.MakeGenericMethod(resolver); return Call(context, resolverMethod); @@ -453,9 +453,9 @@ private Expression[] CreateParameters( for (var i = 0; i < parameters.Length; i++) { - ParameterInfo parameter = parameters[i]; + var parameter = parameters[i]; - IParameterExpressionBuilder builder = + var builder = GetParameterExpressionBuilder(parameter, fieldParameterExpressionBuilders); parameterResolvers[i] = builder.Build(parameter, context); @@ -469,14 +469,14 @@ private IParameterExpressionBuilder GetParameterExpressionBuilder( IParameterExpressionBuilder[] fieldParameterExpressionBuilders) { if (fieldParameterExpressionBuilders.Length == 0 && - _cache.TryGetValue(parameter, out IParameterExpressionBuilder? cached)) + _cache.TryGetValue(parameter, out var cached)) { return cached; } if (fieldParameterExpressionBuilders.Length > 0) { - foreach (IParameterExpressionBuilder builder in fieldParameterExpressionBuilders) + foreach (var builder in fieldParameterExpressionBuilders) { if (!builder.IsDefaultHandler && builder.CanHandle(parameter)) { @@ -490,7 +490,7 @@ private IParameterExpressionBuilder GetParameterExpressionBuilder( } } - foreach (IParameterExpressionBuilder builder in _parameterExpressionBuilders) + foreach (var builder in _parameterExpressionBuilders) { if (builder.CanHandle(parameter)) { @@ -505,7 +505,7 @@ private IParameterExpressionBuilder GetParameterExpressionBuilder( if (fieldParameterExpressionBuilders.Length > 0) { - foreach (IParameterExpressionBuilder builder in fieldParameterExpressionBuilders) + foreach (var builder in fieldParameterExpressionBuilders) { if (builder.IsDefaultHandler && builder.CanHandle(parameter)) { @@ -521,7 +521,7 @@ private IParameterExpressionBuilder GetParameterExpressionBuilder( if (_defaultParameterExpressionBuilders.Count > 0) { - foreach (IParameterExpressionBuilder builder in _defaultParameterExpressionBuilders) + foreach (var builder in _defaultParameterExpressionBuilders) { if (builder.CanHandle(parameter)) { diff --git a/src/HotChocolate/Core/src/Types/Resolvers/DirectiveClassMiddlewareFactory.cs b/src/HotChocolate/Core/src/Types/Resolvers/DirectiveClassMiddlewareFactory.cs index 37f2da281fd..8e9eeb87ce7 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/DirectiveClassMiddlewareFactory.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/DirectiveClassMiddlewareFactory.cs @@ -30,7 +30,7 @@ internal static DirectiveMiddleware Create() { return next => { - MiddlewareFactory factory = + var factory = MiddlewareCompiler .CompileFactory( (services, next) => @@ -61,10 +61,10 @@ internal static DirectiveDelegate CreateDelegate( FieldDelegate next) where TMiddleware : class { - object sync = new object(); + var sync = new object(); TMiddleware middleware = null; - ClassQueryDelegate compiled = + var compiled = MiddlewareCompiler.CompileDelegate( (context, middleware) => new List { diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/FieldParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/FieldParameterExpressionBuilder.cs index b7ff61d5dd7..632b1af8a99 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/FieldParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/FieldParameterExpressionBuilder.cs @@ -22,7 +22,7 @@ public override bool CanHandle(ParameterInfo parameter) public override Expression Build(ParameterInfo parameter, Expression context) { - Expression expression = base.Build(parameter, context); + var expression = base.Build(parameter, context); return parameter.ParameterType != typeof(IOutputField) ? Expression.Convert(expression, parameter.ParameterType) diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/GlobalStateParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/GlobalStateParameterExpressionBuilder.cs index 32ec75c38ee..429fa8c4e00 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/GlobalStateParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/GlobalStateParameterExpressionBuilder.cs @@ -38,14 +38,14 @@ public bool CanHandle(ParameterInfo parameter) public Expression Build(ParameterInfo parameter, Expression context) { - GlobalStateAttribute attribute = parameter.GetCustomAttribute()!; + var attribute = parameter.GetCustomAttribute()!; - ConstantExpression key = + var key = attribute.Key is null ? Expression.Constant(parameter.Name, typeof(string)) : Expression.Constant(attribute.Key, typeof(string)); - MemberExpression contextData = Expression.Property(context, _contextData); + var contextData = Expression.Property(context, _contextData); return IsStateSetter(parameter.ParameterType) ? BuildSetter(parameter, key, contextData) @@ -57,7 +57,7 @@ private Expression BuildSetter( ConstantExpression key, MemberExpression contextData) { - MethodInfo setGlobalState = + var setGlobalState = parameter.ParameterType.IsGenericType ? _setGlobalStateGeneric.MakeGenericMethod( parameter.ParameterType.GetGenericArguments()[0]) @@ -74,7 +74,7 @@ private Expression BuildGetter( ConstantExpression key, MemberExpression contextData) { - MethodInfo getGlobalState = + var getGlobalState = parameter.HasDefaultValue ? _getGlobalStateWithDefault.MakeGenericMethod(parameter.ParameterType) : _getGlobalState.MakeGenericMethod(parameter.ParameterType); diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ObjectTypeParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ObjectTypeParameterExpressionBuilder.cs index 022bc0f0c2a..014aa9da90d 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ObjectTypeParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ObjectTypeParameterExpressionBuilder.cs @@ -23,7 +23,7 @@ public override bool CanHandle(ParameterInfo parameter) public override Expression Build(ParameterInfo parameter, Expression context) { - Expression expression = base.Build(parameter, context); + var expression = base.Build(parameter, context); return parameter.ParameterType == typeof(ObjectType) ? Expression.Convert(expression, typeof(ObjectType)) diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ParentParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ParentParameterExpressionBuilder.cs index 4b57bbf97c6..63ec495958f 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ParentParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ParentParameterExpressionBuilder.cs @@ -36,8 +36,8 @@ public bool CanHandle(ParameterInfo parameter) public Expression Build(ParameterInfo parameter, Expression context) { - Type parameterType = parameter.ParameterType; - MethodInfo argumentMethod = _getParentMethod.MakeGenericMethod(parameterType); + var parameterType = parameter.ParameterType; + var argumentMethod = _getParentMethod.MakeGenericMethod(parameterType); return Expression.Call(context, argumentMethod); } } diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedServiceParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedServiceParameterExpressionBuilder.cs index 228461cb246..a0d53fe29dd 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedServiceParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedServiceParameterExpressionBuilder.cs @@ -19,18 +19,18 @@ internal class ScopedServiceParameterExpressionBuilder public bool IsDefaultHandler => false; public bool CanHandle(ParameterInfo parameter) - => ServiceExpressionHelper.TryGetServiceKind(parameter, out ServiceKind kind) && + => ServiceExpressionHelper.TryGetServiceKind(parameter, out var kind) && kind is not ServiceKind.Default; public void ApplyConfiguration(ParameterInfo parameter, ObjectFieldDescriptor descriptor) { - ServiceExpressionHelper.TryGetServiceKind(parameter, out ServiceKind kind); + ServiceExpressionHelper.TryGetServiceKind(parameter, out var kind); ServiceExpressionHelper.ApplyConfiguration(parameter, descriptor, kind); } public Expression Build(ParameterInfo parameter, Expression context) { - ServiceExpressionHelper.TryGetServiceKind(parameter, out ServiceKind kind); + ServiceExpressionHelper.TryGetServiceKind(parameter, out var kind); return ServiceExpressionHelper.Build(parameter, context, kind); } } diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedStateParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedStateParameterExpressionBuilder.cs index 5ac620d645e..cbaad061405 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedStateParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ScopedStateParameterExpressionBuilder.cs @@ -43,7 +43,7 @@ public virtual Expression Build(ParameterInfo parameter, Expression context) { var key = GetKey(parameter); - ConstantExpression keyExpression = + var keyExpression = key is null ? Expression.Constant(parameter.Name, typeof(string)) : Expression.Constant(key, typeof(string)); @@ -61,7 +61,7 @@ protected Expression BuildSetter( ConstantExpression key, Expression context) { - MethodInfo setGlobalState = + var setGlobalState = parameter.ParameterType.IsGenericType ? SetStateGenericMethod.MakeGenericMethod( parameter.ParameterType.GetGenericArguments()[0]) @@ -81,9 +81,9 @@ protected Expression BuildGetter( { targetType ??= parameter.ParameterType; - MemberExpression contextData = Expression.Property(context, ContextDataProperty); + var contextData = Expression.Property(context, ContextDataProperty); - MethodInfo getScopedState = + var getScopedState = parameter.HasDefaultValue ? _getScopedStateWithDefault.MakeGenericMethod(targetType) : _getScopedState.MakeGenericMethod(targetType); diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceExpressionHelper.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceExpressionHelper.cs index e97a1526dfe..11e3d09372a 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceExpressionHelper.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceExpressionHelper.cs @@ -98,21 +98,21 @@ public static Expression Build( private static Expression BuildDefaultService(ParameterInfo parameter, Expression context) { - Type parameterType = parameter.ParameterType; - MethodInfo argumentMethod = _getServiceMethod.MakeGenericMethod(parameterType); + var parameterType = parameter.ParameterType; + var argumentMethod = _getServiceMethod.MakeGenericMethod(parameterType); return Expression.Call(context, argumentMethod); } private static Expression BuildLocalService(ParameterInfo parameter, Expression context) { - ConstantExpression key = Expression.Constant( + var key = Expression.Constant( parameter.ParameterType.FullName ?? parameter.ParameterType.Name, typeof(string)); - MemberExpression contextData = Expression.Property(context, _contextData); + var contextData = Expression.Property(context, _contextData); - MethodInfo getScopedState = + var getScopedState = parameter.HasDefaultValue ? _getScopedStateWithDefault.MakeGenericMethod(parameter.ParameterType) : _getScopedState.MakeGenericMethod(parameter.ParameterType); diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceHelper.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceHelper.cs index 5e72e406f64..305078d31c3 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceHelper.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceHelper.cs @@ -43,9 +43,9 @@ private static void UsePooledServiceInternal( FieldMiddlewareDefinition serviceMiddleware = new(next => async context => { - IServiceProvider services = context.Services; + var services = context.Services; var objectPool = services.GetRequiredService>(); - TService service = objectPool.Get(); + var service = objectPool.Get(); try { @@ -76,7 +76,7 @@ private static void UseResolverServiceInternal( { var scopedServiceName = typeof(TService).FullName ?? typeof(TService).Name; - FieldMiddlewareDefinition? middleware = + var middleware = definition.MiddlewareDefinitions.FirstOrDefault( t => t.Key == WellKnownMiddleware.ResolverServiceScope); var index = 0; @@ -86,7 +86,7 @@ private static void UseResolverServiceInternal( middleware = new FieldMiddlewareDefinition( next => async context => { - using IServiceScope scope = context.Services.CreateScope(); + using var scope = context.Services.CreateScope(); context.SetLocalState(WellKnownContextData.ResolverServiceScope, scope); await next(context).ConfigureAwait(false); }, @@ -102,7 +102,7 @@ private static void UseResolverServiceInternal( FieldMiddlewareDefinition serviceMiddleware = new(next => async context => { - IServiceScope? scope = context.GetLocalStateOrDefault( + var scope = context.GetLocalStateOrDefault( WellKnownContextData.ResolverServiceScope); if (scope is null) @@ -111,7 +111,7 @@ private static void UseResolverServiceInternal( TypeResources.ServiceHelper_UseResolverServiceInternal_Order); } - TService service = scope.ServiceProvider.GetRequiredService(); + var service = scope.ServiceProvider.GetRequiredService(); context.SetLocalState(scopedServiceName, service); await next(context).ConfigureAwait(false); }, diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceParameterExpressionBuilder.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceParameterExpressionBuilder.cs index 7e149292a4e..702d16a99af 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceParameterExpressionBuilder.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/Parameters/ServiceParameterExpressionBuilder.cs @@ -23,7 +23,7 @@ internal sealed class ServiceParameterExpressionBuilder public bool IsDefaultHandler => false; public bool CanHandle(ParameterInfo parameter) - => ServiceExpressionHelper.TryGetServiceKind(parameter, out ServiceKind kind) && + => ServiceExpressionHelper.TryGetServiceKind(parameter, out var kind) && kind is ServiceKind.Default; public void ApplyConfiguration(ParameterInfo parameter, ObjectFieldDescriptor descriptor) diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/SubscribeExpressionHelper.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/SubscribeExpressionHelper.cs index d2c401bb58f..991fa261329 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/SubscribeExpressionHelper.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/SubscribeExpressionHelper.cs @@ -41,7 +41,7 @@ public static async ValueTask AwaitTaskAsyncEnumerable( return null; } - IAsyncEnumerable enumerable = await task.ConfigureAwait(false); + var enumerable = await task.ConfigureAwait(false); return ConvertEnumerable(enumerable); } @@ -53,7 +53,7 @@ public static async ValueTask AwaitTaskEnumerable( return null; } - IEnumerable enumerable = await task.ConfigureAwait(false); + var enumerable = await task.ConfigureAwait(false); return ConvertEnumerable(enumerable); } @@ -77,7 +77,7 @@ public static async ValueTask AwaitTaskObservable( return null; } - IObservable enumerable = await task.ConfigureAwait(false); + var enumerable = await task.ConfigureAwait(false); return ConvertObservable(enumerable); } @@ -90,14 +90,14 @@ public static async ValueTask AwaitValueTaskSourceStreamGeneric AwaitValueTaskAsyncEnumerable( ValueTask> task) { - IAsyncEnumerable enumerable = await task.ConfigureAwait(false); + var enumerable = await task.ConfigureAwait(false); return ConvertEnumerable(enumerable); } public static async ValueTask AwaitValueTaskEnumerable( ValueTask> task) { - IEnumerable enumerable = await task.ConfigureAwait(false); + var enumerable = await task.ConfigureAwait(false); return ConvertEnumerable(enumerable); } @@ -111,7 +111,7 @@ public static async ValueTask AwaitValueTaskQueryable( public static async ValueTask AwaitValueTaskObservable( ValueTask> task) { - IObservable enumerable = await task.ConfigureAwait(false); + var enumerable = await task.ConfigureAwait(false); return ConvertObservable(enumerable); } @@ -165,7 +165,7 @@ public Enumerate(IAsyncEnumerable enumerable) public async IAsyncEnumerator GetAsyncEnumerator( CancellationToken cancellationToken = default) { - await foreach (T item in + await foreach (var item in _enumerable.WithCancellation(cancellationToken).ConfigureAwait(false)) { yield return item; diff --git a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/TypeInfoExtensions.cs b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/TypeInfoExtensions.cs index df7943f5fa8..c4b685ef334 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/Expressions/TypeInfoExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/Expressions/TypeInfoExtensions.cs @@ -13,13 +13,13 @@ public static MethodInfo GetDeclaredMethod( { return typeInfo.GetDeclaredMethods(name).FirstOrDefault(t => { - ParameterInfo[] parameters = t.GetParameters(); + var parameters = t.GetParameters(); if (types.Length != parameters.Length) { return false; } - for (int i = 0; i < types.Length; i++) + for (var i = 0; i < types.Length; i++) { if (types[i] != parameters[i].ParameterType) { diff --git a/src/HotChocolate/Core/src/Types/Resolvers/FieldClassMiddlewareFactory.cs b/src/HotChocolate/Core/src/Types/Resolvers/FieldClassMiddlewareFactory.cs index 420e3374608..823af1232cc 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/FieldClassMiddlewareFactory.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/FieldClassMiddlewareFactory.cs @@ -31,14 +31,14 @@ public static FieldMiddleware Create( { var parameters = new List(); - foreach ((Type Service, object Instance) service in services) + foreach (var service in services) { parameters.Add(new TypeParameterHandler( service.Service, Expression.Constant(service.Instance))); } - MiddlewareFactory factory = + var factory = MiddlewareCompiler.CompileFactory( (services, next) => { @@ -79,7 +79,7 @@ private static FieldDelegate CreateDelegate( var sync = new object(); TMiddleware middleware = null; - ClassQueryDelegate compiled = + var compiled = MiddlewareCompiler.CompileDelegate( (context, middleware) => new List { diff --git a/src/HotChocolate/Core/src/Types/Resolvers/IResolverContext.cs b/src/HotChocolate/Core/src/Types/Resolvers/IResolverContext.cs index 4f2cf7eca27..0d22619e99e 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/IResolverContext.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/IResolverContext.cs @@ -106,19 +106,19 @@ public interface IResolverContext : IPureResolverContext /// /// The object type context. /// - /// + /// /// The selection for which the pre-compiled child selections shall be returned. /// /// /// Include also internal selections that shall not be included into the result set. /// /// - /// Returns the pre-compiled selections for the + /// Returns the pre-compiled selections for the /// with the specified . /// IReadOnlyList GetSelections( - ObjectType typeContext, - ISelection? fieldSelection = null, + IObjectType typeContext, + ISelection? selection = null, bool allowInternals = false); /// diff --git a/src/HotChocolate/Core/src/Types/Resolvers/ResolveResultHelper.cs b/src/HotChocolate/Core/src/Types/Resolvers/ResolveResultHelper.cs index 820af14f2b1..9fe41943f88 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/ResolveResultHelper.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/ResolveResultHelper.cs @@ -47,21 +47,21 @@ public static Expression EnsureResolveResult(Expression resolver, Type result) private static MethodCallExpression AwaitTaskMethodCall( Expression taskExpression, Type value) { - MethodInfo awaitHelper = _awaitTaskHelper.MakeGenericMethod(value); + var awaitHelper = _awaitTaskHelper.MakeGenericMethod(value); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitValueTaskMethodCall( Expression taskExpression, Type value) { - MethodInfo awaitHelper = _awaitValueTaskHelper.MakeGenericMethod(value); + var awaitHelper = _awaitValueTaskHelper.MakeGenericMethod(value); return Call(awaitHelper, taskExpression); } private static MethodCallExpression WrapResult( Expression taskExpression, Type value) { - MethodInfo wrapResultHelper = _wrapResultHelper.MakeGenericMethod(value); + var wrapResultHelper = _wrapResultHelper.MakeGenericMethod(value); return Call(wrapResultHelper, taskExpression); } } diff --git a/src/HotChocolate/Core/src/Types/Resolvers/SubscribeResultHelper.cs b/src/HotChocolate/Core/src/Types/Resolvers/SubscribeResultHelper.cs index bf9ba5bcc4d..c0eacd3ff7b 100644 --- a/src/HotChocolate/Core/src/Types/Resolvers/SubscribeResultHelper.cs +++ b/src/HotChocolate/Core/src/Types/Resolvers/SubscribeResultHelper.cs @@ -94,7 +94,7 @@ public static Expression EnsureSubscribeResult( if (typeof(Task).IsAssignableFrom(resultType) && resultType.IsGenericType) { - Type subscriptionType = resultType.GetGenericArguments().First(); + var subscriptionType = resultType.GetGenericArguments().First(); if (subscriptionType == typeof(ISourceStream)) { @@ -103,7 +103,7 @@ public static Expression EnsureSubscribeResult( if (subscriptionType.IsGenericType) { - Type typeDefinition = subscriptionType.GetGenericTypeDefinition(); + var typeDefinition = subscriptionType.GetGenericTypeDefinition(); if (typeDefinition == typeof(ISourceStream<>)) { return AwaitTaskSourceStreamGeneric( @@ -144,11 +144,11 @@ public static Expression EnsureSubscribeResult( if (resultType.IsGenericType && resultType.GetGenericTypeDefinition() == typeof(ValueTask<>)) { - Type subscriptionType = resultType.GetGenericArguments().First(); + var subscriptionType = resultType.GetGenericArguments().First(); if (subscriptionType.IsGenericType) { - Type typeDefinition = subscriptionType.GetGenericTypeDefinition(); + var typeDefinition = subscriptionType.GetGenericTypeDefinition(); if (typeDefinition == typeof(ISourceStream<>)) { return AwaitValueTaskSourceStreamGeneric( @@ -193,7 +193,7 @@ public static Expression EnsureSubscribeResult( if (resultType.IsGenericType) { - Type typeDefinition = resultType.GetGenericTypeDefinition(); + var typeDefinition = resultType.GetGenericTypeDefinition(); if (typeDefinition == typeof(ISourceStream<>)) { return WrapSourceStreamGeneric( @@ -244,42 +244,42 @@ private static MethodCallExpression AwaitTaskSourceStream( private static MethodCallExpression AwaitTaskSourceStreamGeneric( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitTaskSourceStreamGeneric.MakeGenericMethod(valueType); + var awaitHelper = _awaitTaskSourceStreamGeneric.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitTaskAsyncEnumerable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitTaskAsyncEnumerable.MakeGenericMethod(valueType); + var awaitHelper = _awaitTaskAsyncEnumerable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitTaskEnumerable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitTaskEnumerable.MakeGenericMethod(valueType); + var awaitHelper = _awaitTaskEnumerable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitTaskQueryable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitTaskQueryable.MakeGenericMethod(valueType); + var awaitHelper = _awaitTaskQueryable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitTaskObservable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitTaskObservable.MakeGenericMethod(valueType); + var awaitHelper = _awaitTaskObservable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitValueTaskSourceStreamGeneric( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = + var awaitHelper = _awaitValueTaskSourceStreamGeneric.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } @@ -287,28 +287,28 @@ private static MethodCallExpression AwaitValueTaskSourceStreamGeneric( private static MethodCallExpression AwaitValueTaskAsyncEnumerable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitValueTaskAsyncEnumerable.MakeGenericMethod(valueType); + var awaitHelper = _awaitValueTaskAsyncEnumerable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitValueTaskEnumerable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitValueTaskEnumerable.MakeGenericMethod(valueType); + var awaitHelper = _awaitValueTaskEnumerable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitValueTaskQueryable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitValueTaskQueryable.MakeGenericMethod(valueType); + var awaitHelper = _awaitValueTaskQueryable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } private static MethodCallExpression AwaitValueTaskObservable( Expression taskExpression, Type valueType) { - MethodInfo awaitHelper = _awaitValueTaskObservable.MakeGenericMethod(valueType); + var awaitHelper = _awaitValueTaskObservable.MakeGenericMethod(valueType); return Call(awaitHelper, taskExpression); } @@ -320,35 +320,35 @@ private static MethodCallExpression WrapSourceStream(Expression taskExpression) private static MethodCallExpression WrapSourceStreamGeneric( Expression taskExpression, Type valueType) { - MethodInfo wrapResultHelper = _wrapSourceStreamGeneric.MakeGenericMethod(valueType); + var wrapResultHelper = _wrapSourceStreamGeneric.MakeGenericMethod(valueType); return Call(wrapResultHelper, taskExpression); } private static MethodCallExpression WrapAsyncEnumerable( Expression taskExpression, Type valueType) { - MethodInfo wrapResultHelper = _wrapAsyncEnumerable.MakeGenericMethod(valueType); + var wrapResultHelper = _wrapAsyncEnumerable.MakeGenericMethod(valueType); return Call(wrapResultHelper, taskExpression); } private static MethodCallExpression WrapEnumerable( Expression taskExpression, Type valueType) { - MethodInfo wrapResultHelper = _wrapEnumerable.MakeGenericMethod(valueType); + var wrapResultHelper = _wrapEnumerable.MakeGenericMethod(valueType); return Call(wrapResultHelper, taskExpression); } private static MethodCallExpression WrapQueryable( Expression taskExpression, Type valueType) { - MethodInfo wrapResultHelper = _wrapQueryable.MakeGenericMethod(valueType); + var wrapResultHelper = _wrapQueryable.MakeGenericMethod(valueType); return Call(wrapResultHelper, taskExpression); } private static MethodCallExpression WrapObservable( Expression taskExpression, Type valueType) { - MethodInfo wrapResultHelper = _wrapObservable.MakeGenericMethod(valueType); + var wrapResultHelper = _wrapObservable.MakeGenericMethod(valueType); return Call(wrapResultHelper, taskExpression); } } diff --git a/src/HotChocolate/Core/src/Types/Schema.Initialization.cs b/src/HotChocolate/Core/src/Types/Schema.Initialization.cs index b208c7c4c17..11bff96654a 100644 --- a/src/HotChocolate/Core/src/Types/Schema.Initialization.cs +++ b/src/HotChocolate/Core/src/Types/Schema.Initialization.cs @@ -47,7 +47,7 @@ protected override void OnRegisterDependencies( if (definition.HasDirectives) { - foreach (DirectiveDefinition directive in definition.Directives) + foreach (var directive in definition.Directives) { context.Dependencies.Add(new( directive.TypeReference, diff --git a/src/HotChocolate/Core/src/Types/Schema.cs b/src/HotChocolate/Core/src/Types/Schema.cs index b78c97b6eec..f710920492c 100644 --- a/src/HotChocolate/Core/src/Types/Schema.cs +++ b/src/HotChocolate/Core/src/Types/Schema.cs @@ -122,7 +122,7 @@ public IReadOnlyList GetPossibleTypes(INamedType abstractType) throw new ArgumentNullException(nameof(abstractType)); } - if (_types.TryGetPossibleTypes(abstractType.Name, out IReadOnlyList? types)) + if (_types.TryGetPossibleTypes(abstractType.Name, out var types)) { return types; } @@ -147,7 +147,7 @@ public DirectiveType GetDirectiveType(NameString directiveName) { if (_directiveTypes.TryGetValue( directiveName.EnsureNotEmpty(nameof(directiveName)), - out DirectiveType? type)) + out var type)) { return type; } diff --git a/src/HotChocolate/Core/src/Types/SchemaBuilder.Setup.cs b/src/HotChocolate/Core/src/Types/SchemaBuilder.Setup.cs index 953deb3bfa7..2b444127b83 100644 --- a/src/HotChocolate/Core/src/Types/SchemaBuilder.Setup.cs +++ b/src/HotChocolate/Core/src/Types/SchemaBuilder.Setup.cs @@ -62,10 +62,10 @@ public static Schema Create( context.SchemaInterceptor.OnBeforeCreate(context, builder); - IReadOnlyList typeReferences = + var typeReferences = CreateTypeReferences(builder, context); - TypeRegistry typeRegistry = InitializeTypes(builder, context, typeReferences); + var typeRegistry = InitializeTypes(builder, context, typeReferences); return CompleteSchema(builder, context, lazySchema, typeRegistry); } @@ -80,7 +80,7 @@ public static DescriptorContext CreateContext( SchemaBuilder builder, LazySchema lazySchema) { - IServiceProvider services = builder._services ?? new EmptyServiceProvider(); + var services = builder._services ?? new EmptyServiceProvider(); var schemaInterceptor = new AggregateSchemaInterceptor(); var typeInterceptor = new AggregateTypeInterceptor(); @@ -103,7 +103,7 @@ private static IReadOnlyList CreateTypeReferences( { var types = new List(); - foreach (CreateRef typeRef in builder._types) + foreach (var typeRef in builder._types) { types.Add(typeRef(context.TypeInspector)); } @@ -128,9 +128,9 @@ private static IEnumerable ParseDocuments( var documents = new List(); context.ContextData[WellKnownContextData.SchemaDocuments] = documents; - foreach (LoadSchemaDocument fetchSchema in builder._documents) + foreach (var fetchSchema in builder._documents) { - DocumentNode schemaDocument = fetchSchema(context.Services); + var schemaDocument = fetchSchema(context.Services); schemaDocument = schemaDocument.RemoveBuiltInTypes(); documents.Add(schemaDocument); @@ -155,7 +155,7 @@ private static IEnumerable ParseDocuments( OperationType.Subscription, visitorContext.SubscriptionTypeName); - IReadOnlyCollection directives = + var directives = visitorContext.Directives ?? Array.Empty(); if (builder._schema is null @@ -165,7 +165,7 @@ private static IEnumerable ParseDocuments( builder.SetSchema(new Schema(d => { d.Description(visitorContext.Description); - foreach (DirectiveNode directive in directives) + foreach (var directive in directives) { d.Directive(directive); } @@ -196,7 +196,7 @@ private static TypeRegistry InitializeTypes( IReadOnlyList types) { var typeRegistry = new TypeRegistry(context.TypeInterceptor); - TypeInitializer initializer = + var initializer = CreateTypeInitializer(builder, context, types, typeRegistry); initializer.Initialize(); return typeRegistry; @@ -221,12 +221,12 @@ private static TypeInitializer CreateTypeInitializer( type => GetOperationKind(type, context.TypeInspector, operations), builder._options); - foreach (FieldMiddleware component in builder._globalComponents) + foreach (var component in builder._globalComponents) { initializer.GlobalComponents.Add(component); } - foreach (KeyValuePair binding in builder._clrTypes) + foreach (var binding in builder._clrTypes) { typeRegistry.TryRegister( (ExtendedTypeReference)binding.Value.Item1(context.TypeInspector), @@ -314,7 +314,7 @@ private static bool IsOperationType( ITypeInspector typeInspector, Dictionary operations) { - if (operations.TryGetValue(operationType, out ITypeReference? typeRef)) + if (operations.TryGetValue(operationType, out var typeRef)) { if (typeRef is SchemaTypeReference sr) { @@ -354,7 +354,7 @@ private static Schema CompleteSchema( LazySchema lazySchema, TypeRegistry typeRegistry) { - SchemaTypesDefinition definition = + var definition = CreateSchemaDefinition(builder, context, typeRegistry); if (definition.QueryType is null && builder._options.StrictValidation) @@ -365,7 +365,7 @@ private static Schema CompleteSchema( .Build()); } - Schema schema = typeRegistry.Types.Select(t => t.Type).OfType().First(); + var schema = typeRegistry.Types.Select(t => t.Type).OfType().First(); schema.CompleteSchema(definition); lazySchema.Schema = schema; context.SchemaInterceptor.OnAfterCreate(context, schema); @@ -400,7 +400,7 @@ private static SchemaTypesDefinition CreateSchemaDefinition( ResolveOperations(definition, operations, typeRegistry); - IReadOnlyCollection types = + var types = RemoveUnreachableTypes(builder, typeRegistry, definition); definition.Types = types.OfType().Distinct().ToArray(); @@ -429,7 +429,7 @@ private static void ResolveOperations( ObjectType? GetObjectType(NameString typeName) { - foreach (RegisteredType registeredType in typeRegistry.Types) + foreach (var registeredType in typeRegistry.Types) { if (registeredType.Type is ObjectType objectType && objectType.Name.Equals(typeName)) @@ -443,7 +443,7 @@ private static void ResolveOperations( ObjectType? GetOperationType(OperationType operation) { - if (operations.TryGetValue(operation, out ITypeReference? reference)) + if (operations.TryGetValue(operation, out var reference)) { if (reference is SchemaTypeReference sr) { @@ -451,14 +451,14 @@ private static void ResolveOperations( } if (reference is ExtendedTypeReference cr && - typeRegistry.TryGetType(cr, out RegisteredType? registeredType)) + typeRegistry.TryGetType(cr, out var registeredType)) { return (ObjectType)registeredType.Type; } if (reference is SyntaxTypeReference str) { - NamedTypeNode namedType = str.Type.NamedType(); + var namedType = str.Type.NamedType(); return typeRegistry.Types .Select(t => t.Type) .OfType() diff --git a/src/HotChocolate/Core/src/Types/SchemaBuilder.cs b/src/HotChocolate/Core/src/Types/SchemaBuilder.cs index ac03a7dfc56..75e9599a1ac 100644 --- a/src/HotChocolate/Core/src/Types/SchemaBuilder.cs +++ b/src/HotChocolate/Core/src/Types/SchemaBuilder.cs @@ -197,7 +197,7 @@ public ISchemaBuilder AddConvention( if (!_conventions.TryGetValue( (convention, scope), - out List? factories)) + out var factories)) { factories = new List(); _conventions[(convention, scope)] = factories; @@ -233,7 +233,7 @@ public ISchemaBuilder BindRuntimeType(Type runtimeType, Type schemaType) nameof(schemaType)); } - TypeContext context = SchemaTypeReference.InferTypeContext(schemaType); + var context = SchemaTypeReference.InferTypeContext(schemaType); _clrTypes[runtimeType] = (ti => ti.GetTypeRef(runtimeType, context), ti => ti.GetTypeRef(schemaType, context)); @@ -342,7 +342,7 @@ public ISchemaBuilder AddRootType( nameof(operation)); } - SchemaTypeReference reference = TypeReference.Create(rootType); + var reference = TypeReference.Create(rootType); _operations.Add(operation, _ => reference); _types.Add(_ => reference); return this; diff --git a/src/HotChocolate/Core/src/Types/SchemaErrorBuilder.Error.cs b/src/HotChocolate/Core/src/Types/SchemaErrorBuilder.Error.cs index aed9a8d175c..5ebfd9d9004 100644 --- a/src/HotChocolate/Core/src/Types/SchemaErrorBuilder.Error.cs +++ b/src/HotChocolate/Core/src/Types/SchemaErrorBuilder.Error.cs @@ -80,7 +80,7 @@ private void Serialize(Utf8JsonWriter writer) writer.WritePropertyName("path"); writer.WriteStartArray(); - foreach (string segment in Path.Select(t => t.ToString()!)) + foreach (var segment in Path.Select(t => t.ToString()!)) { writer.WriteStringValue(segment); } @@ -93,7 +93,7 @@ private void Serialize(Utf8JsonWriter writer) writer.WritePropertyName("extensions"); writer.WriteStartObject(); - foreach (KeyValuePair item in Extensions.OrderBy(t => t.Key)) + foreach (var item in Extensions.OrderBy(t => t.Key)) { writer.WritePropertyName(item.Key); diff --git a/src/HotChocolate/Core/src/Types/SchemaException.cs b/src/HotChocolate/Core/src/Types/SchemaException.cs index 631c0f08a01..f0dd5fb8c20 100644 --- a/src/HotChocolate/Core/src/Types/SchemaException.cs +++ b/src/HotChocolate/Core/src/Types/SchemaException.cs @@ -48,9 +48,9 @@ private static string CreateErrorMessage(IReadOnlyList errors) message.AppendLine("For more details look at the `Errors` property."); message.AppendLine(); - for (int i = 0; i < errors.Count; i++) + for (var i = 0; i < errors.Count; i++) { - ISchemaError error = errors[i]; + var error = errors[i]; message.Append($"{i + 1}. {error.Message}"); diff --git a/src/HotChocolate/Core/src/Types/SchemaSerializer.cs b/src/HotChocolate/Core/src/Types/SchemaSerializer.cs index f0f52a6c224..1b6170e239a 100644 --- a/src/HotChocolate/Core/src/Types/SchemaSerializer.cs +++ b/src/HotChocolate/Core/src/Types/SchemaSerializer.cs @@ -22,7 +22,7 @@ public static string Serialize(ISchema schema) throw new ArgumentNullException(nameof(schema)); } - DocumentNode document = SerializeSchema(schema); + var document = SerializeSchema(schema); return document.Print(); } @@ -38,7 +38,7 @@ public static void Serialize(ISchema schema, TextWriter textWriter) throw new ArgumentNullException(nameof(textWriter)); } - DocumentNode document = SerializeSchema(schema); + var document = SerializeSchema(schema); textWriter.Write(document.Print()); } @@ -58,7 +58,7 @@ public static async ValueTask SerializeAsync( throw new ArgumentNullException(nameof(stream)); } - DocumentNode document = SerializeSchema(schema); + var document = SerializeSchema(schema); await document.PrintToAsync(stream, indented, cancellationToken).ConfigureAwait(false); } @@ -80,9 +80,9 @@ public static async ValueTask SerializeAsync( var list = new List(); - foreach (INamedType namedType in namedTypes) + foreach (var namedType in namedTypes) { - ITypeDefinitionNode typeDefinition = + var typeDefinition = namedType is ScalarType scalarType ? SerializeScalarType(scalarType) : SerializeNonScalarTypeDefinition(namedType, false); @@ -118,7 +118,7 @@ public static DocumentNode SerializeSchema( var builtInDirectives = new HashSet { Skip, Include, Deprecated }; - IEnumerable directiveTypeDefinitions = + var directiveTypeDefinitions = schema.DirectiveTypes .Where(directive => !builtInDirectives.Contains(directive.Name)) .OrderBy(t => t.Name.ToString(), StringComparer.Ordinal) @@ -126,7 +126,7 @@ public static DocumentNode SerializeSchema( typeDefinitions.AddRange(directiveTypeDefinitions); - IEnumerable scalarTypeDefinitions = + var scalarTypeDefinitions = schema.Types .OfType() .Where(t => includeSpecScalars || !BuiltInTypes.IsBuiltInType(t.Name)) diff --git a/src/HotChocolate/Core/src/Types/SchemaTypes.cs b/src/HotChocolate/Core/src/Types/SchemaTypes.cs index cdd89dea636..809593d0830 100644 --- a/src/HotChocolate/Core/src/Types/SchemaTypes.cs +++ b/src/HotChocolate/Core/src/Types/SchemaTypes.cs @@ -43,7 +43,7 @@ public SchemaTypes(SchemaTypesDefinition definition) public T GetType(NameString typeName) where T : IType { - if (_types.TryGetValue(typeName, out INamedType? namedType) + if (_types.TryGetValue(typeName, out var namedType) && namedType is T type) { return type; @@ -57,7 +57,7 @@ public T GetType(NameString typeName) where T : IType public bool TryGetType(NameString typeName, [NotNullWhen(true)] out T? type) where T : IType { - if (_types.TryGetValue(typeName, out INamedType? namedType) + if (_types.TryGetValue(typeName, out var namedType) && namedType is T t) { type = t; @@ -75,7 +75,7 @@ public IReadOnlyCollection GetTypes() public bool TryGetClrType(NameString typeName, [NotNullWhen(true)] out Type? clrType) { - if (_types.TryGetValue(typeName, out INamedType? type) + if (_types.TryGetValue(typeName, out var type) && type is IHasRuntimeType ct && ct.RuntimeType != typeof(object)) { @@ -91,7 +91,7 @@ public bool TryGetPossibleTypes( string abstractTypeName, [NotNullWhen(true)] out IReadOnlyList? types) { - if (_possibleTypes.TryGetValue(abstractTypeName, out List? pt)) + if (_possibleTypes.TryGetValue(abstractTypeName, out var pt)) { types = pt; return true; @@ -106,13 +106,13 @@ private static Dictionary> CreatePossibleTypeLookup { var possibleTypes = new Dictionary>(); - foreach (ObjectType objectType in types.OfType()) + foreach (var objectType in types.OfType()) { possibleTypes[objectType.Name] = new List { objectType }; - foreach (InterfaceType interfaceType in objectType.Implements) + foreach (var interfaceType in objectType.Implements) { - if (!possibleTypes.TryGetValue(interfaceType.Name, out List? pt)) + if (!possibleTypes.TryGetValue(interfaceType.Name, out var pt)) { pt = new List(); possibleTypes[interfaceType.Name] = pt; @@ -122,12 +122,12 @@ private static Dictionary> CreatePossibleTypeLookup } } - foreach (UnionType unionType in types.OfType()) + foreach (var unionType in types.OfType()) { - foreach (ObjectType objectType in unionType.Types.Values) + foreach (var objectType in unionType.Types.Values) { if (!possibleTypes.TryGetValue( - unionType.Name, out List? pt)) + unionType.Name, out var pt)) { pt = new List(); possibleTypes[unionType.Name] = pt; diff --git a/src/HotChocolate/Core/src/Types/Types/AggregateInputValueFormatter.cs b/src/HotChocolate/Core/src/Types/Types/AggregateInputValueFormatter.cs index f9616f9b010..72742fd3dfc 100644 --- a/src/HotChocolate/Core/src/Types/Types/AggregateInputValueFormatter.cs +++ b/src/HotChocolate/Core/src/Types/Types/AggregateInputValueFormatter.cs @@ -31,7 +31,7 @@ public AggregateInputValueFormatter(IEnumerable formatters { var current = runtimeValue; - foreach (IInputValueFormatter formatter in _formatters) + foreach (var formatter in _formatters) { current = formatter.OnAfterDeserialize(current); } diff --git a/src/HotChocolate/Core/src/Types/Types/Argument.cs b/src/HotChocolate/Core/src/Types/Types/Argument.cs index a1465479f9a..523060ec4ef 100644 --- a/src/HotChocolate/Core/src/Types/Types/Argument.cs +++ b/src/HotChocolate/Core/src/Types/Types/Argument.cs @@ -22,7 +22,7 @@ public Argument(ArgumentDefinition definition, int index) { DefaultValue = definition.DefaultValue; - IReadOnlyList formatters = definition.GetFormatters(); + var formatters = definition.GetFormatters(); if (formatters.Count == 0) { diff --git a/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAndResolveAttribute.cs b/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAndResolveAttribute.cs index 6ac79c82bc4..b24007f08ea 100644 --- a/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAndResolveAttribute.cs +++ b/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAndResolveAttribute.cs @@ -23,14 +23,14 @@ public override void OnConfigure( { descriptor.Extend().OnBeforeCreate(d => { - ITypeReference typeReference = + var typeReference = context.TypeInspector.GetReturnTypeRef(member, TypeContext.Output); if (typeReference is ExtendedTypeReference typeRef && - context.TypeInspector.TryCreateTypeInfo(typeRef.Type, out ITypeInfo? typeInfo) && + context.TypeInspector.TryCreateTypeInfo(typeRef.Type, out var typeInfo) && !typeInfo.IsSchemaType) { - IExtendedType? rewritten = typeRef.Type.IsArrayOrList + var rewritten = typeRef.Type.IsArrayOrList ? typeRef.Type.ElementType : null; diff --git a/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAttribute.cs b/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAttribute.cs index 90916f11d6a..82829b94ece 100644 --- a/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAttribute.cs +++ b/src/HotChocolate/Core/src/Types/Types/Attributes/SubscribeAttribute.cs @@ -54,7 +54,7 @@ public override void OnConfigure( if (MessageType is null) { - ParameterInfo? messageParameter = + var messageParameter = method.GetParameters() .FirstOrDefault(t => t.IsDefined(typeof(EventMessageAttribute))); @@ -68,16 +68,16 @@ public override void OnConfigure( if (string.IsNullOrEmpty(With)) { - (string? name, string? value, Type type) topic = ResolveTopic(method); + var topic = ResolveTopic(method); if (topic.value is { }) { - MethodInfo config = _constantTopic.MakeGenericMethod(MessageType); + var config = _constantTopic.MakeGenericMethod(MessageType); config.Invoke(null, new object?[] { descriptor, topic.value }); } else { - MethodInfo config = _argumentTopic.MakeGenericMethod(topic.type, MessageType); + var config = _argumentTopic.MakeGenericMethod(topic.type, MessageType); config.Invoke(null, new object?[] { descriptor, topic.name }); } } @@ -86,7 +86,7 @@ public override void OnConfigure( descriptor.Extend().OnBeforeCreate(d => { - MethodInfo? subscribeResolver = member.DeclaringType?.GetMethod( + var subscribeResolver = member.DeclaringType?.GetMethod( With!, BindingFlags.Public | BindingFlags.Instance); if (subscribeResolver is null) @@ -102,7 +102,7 @@ public override void OnConfigure( private (string? name, string? value, Type type) ResolveTopic(MethodInfo method) { - ParameterInfo? topicParameter = + var topicParameter = method.GetParameters() .FirstOrDefault(t => t.IsDefined(typeof(TopicAttribute))); @@ -110,7 +110,7 @@ public override void OnConfigure( { if (topicParameter is null) { - string name = method.GetCustomAttribute()?.Name ?? method.Name; + var name = method.GetCustomAttribute()?.Name ?? method.Name; return (null, name, typeof(string)); } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptor.cs index d9a1f00ef97..a858e28649a 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptor.cs @@ -54,7 +54,7 @@ protected internal ArgumentDescriptor( Definition.Type = context.TypeInspector.GetArgumentTypeRef(parameter); Definition.Parameter = parameter; - if (context.TypeInspector.TryGetDefaultValue(parameter, out object defaultValue)) + if (context.TypeInspector.TryGetDefaultValue(parameter, out var defaultValue)) { Definition.RuntimeDefaultValue = defaultValue; } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptorBase~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptorBase~1.cs index f5e19f1b152..2f48773e2e7 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptorBase~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/ArgumentDescriptorBase~1.cs @@ -80,7 +80,7 @@ public void Type() where TInputType : IInputType /// public void Type(Type type) { - ITypeInfo typeInfo = Context.TypeInspector.CreateTypeInfo(type); + var typeInfo = Context.TypeInspector.CreateTypeInfo(type); if (typeInfo.IsSchemaType && !typeInfo.IsInputType()) { @@ -169,7 +169,7 @@ public void DefaultValue(object? value) } else { - IExtendedType type = Context.TypeInspector.GetType(value.GetType()); + var type = Context.TypeInspector.GetType(value.GetType()); Definition.SetMoreSpecificType(type, TypeContext.Input); Definition.RuntimeDefaultValue = value; Definition.DefaultValue = null; diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultNamingConventions.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultNamingConventions.cs index 56f80472e89..7d594eaebc8 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultNamingConventions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultNamingConventions.cs @@ -53,7 +53,7 @@ public virtual NameString GetTypeName(Type type, TypeKind kind) throw new ArgumentNullException(nameof(type)); } - string name = type.GetGraphQLName(); + var name = type.GetGraphQLName(); if (kind == TypeKind.InputObject) { @@ -167,11 +167,11 @@ public virtual unsafe NameString GetEnumValueName(object value) throw new ArgumentNullException(nameof(value)); } - Type enumType = value.GetType(); + var enumType = value.GetType(); if (enumType.IsEnum) { - MemberInfo? enumMember = enumType + var enumMember = enumType .GetMember(value.ToString()!) .FirstOrDefault(); @@ -183,7 +183,7 @@ public virtual unsafe NameString GetEnumValueName(object value) } var underscores = 0; - ReadOnlySpan name = value.ToString().AsSpan(); + var name = value.ToString().AsSpan(); if (name.Length == 1) { @@ -225,7 +225,7 @@ public virtual unsafe NameString GetEnumValueName(object value) var size = underscores + name.Length; char[]? rented = null; - Span buffer = size <= 128 + var buffer = size <= 128 ? stackalloc char[size] : rented = ArrayPool.Shared.Rent(size); @@ -234,7 +234,7 @@ public virtual unsafe NameString GetEnumValueName(object value) var p = 0; buffer[p++] = char.ToUpper(name[0]); - bool lastWasUnderline = false; + var lastWasUnderline = false; for (var i = 1; i < name.Length; i++) { if (!lastWasUnderline && @@ -270,10 +270,10 @@ public virtual unsafe NameString GetEnumValueName(object value) throw new ArgumentNullException(nameof(value)); } - Type enumType = value.GetType(); + var enumType = value.GetType(); if (enumType.IsEnum) { - MemberInfo? enumMember = enumType + var enumMember = enumType .GetMember(value.ToString()!) .FirstOrDefault(); @@ -308,11 +308,11 @@ public virtual bool IsDeprecated(object value, out string? reason) throw new ArgumentNullException(nameof(value)); } - Type enumType = value.GetType(); + var enumType = value.GetType(); if (enumType.IsEnum) { - MemberInfo? enumMember = enumType + var enumMember = enumType .GetMember(value.ToString()!) .FirstOrDefault(); diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultTypeInspector.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultTypeInspector.cs index 7936e4d7dd9..4302fdbbf84 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultTypeInspector.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DefaultTypeInspector.cs @@ -68,7 +68,7 @@ public virtual bool IsMemberIgnored(MemberInfo member) private IEnumerable GetMembersInternal(Type type, bool includeIgnored) { - foreach (MemberInfo member in type.GetMembers(Instance | Public)) + foreach (var member in type.GetMembers(Instance | Public)) { if (CanBeHandled(member, includeIgnored)) { @@ -156,7 +156,7 @@ public IExtendedType GetArgumentType( throw new ArgumentNullException(nameof(parameter)); } - IExtendedType argumentType = GetArgumentTypeInternal(parameter); + var argumentType = GetArgumentTypeInternal(parameter); return ignoreAttributes ? argumentType : ApplyTypeAttributes(argumentType, parameter); @@ -166,7 +166,7 @@ private IExtendedType GetArgumentTypeInternal(ParameterInfo parameter) { var method = (MethodInfo)parameter.Member; - if (!_methods.TryGetValue(method, out ExtendedMethodInfo? info)) + if (!_methods.TryGetValue(method, out var info)) { info = ExtendedType.FromMethod(method, _typeCache); _methods[method] = info; @@ -252,7 +252,7 @@ public virtual IEnumerable GetEnumValues(Type enumType) throw new ArgumentNullException(nameof(value)); } - Type enumType = value.GetType(); + var enumType = value.GetType(); if (enumType.IsEnum) { @@ -297,7 +297,7 @@ public virtual IEnumerable GetEnumValues(Type enumType) // if we have a resolver type on the other hand the load method must // include the type name and can be an instance method. // first we will check for static load methods. - MethodInfo? method = resolverType + var method = resolverType .GetMembers(Static | Public | FlattenHierarchy) .OfType() .FirstOrDefault(m => IsPossibleExternalNodeResolver(m, nodeType)); @@ -370,7 +370,7 @@ public void ApplyAttributes( IDescriptor descriptor, ICustomAttributeProvider attributeProvider) { - foreach (DescriptorAttribute attr in + foreach (var attr in GetCustomAttributes(attributeProvider, true) .OrderBy(t => t.Order)) { @@ -542,7 +542,7 @@ public bool TryCreateTypeInfo( IExtendedType type, [NotNullWhen(true)] out ITypeInfo? typeInfo) { - if (TypeInfo.TryCreate(type, _typeCache, out TypeInfo? t)) + if (TypeInfo.TryCreate(type, _typeCache, out var t)) { typeInfo = t; return true; @@ -556,7 +556,7 @@ private IExtendedType ApplyTypeAttributes( IExtendedType type, ICustomAttributeProvider attributeProvider) { - IExtendedType resultType = type; + var resultType = type; var hasGraphQLTypeAttribute = false; @@ -660,7 +660,7 @@ private static bool CanHandleReturnType(MemberInfo member, Type returnType) { if (returnType.IsGenericType) { - Type returnTypeDefinition = returnType.GetGenericTypeDefinition(); + var returnTypeDefinition = returnType.GetGenericTypeDefinition(); if (returnTypeDefinition == typeof(ValueTask<>) || returnTypeDefinition == typeof(Task<>)) @@ -730,7 +730,7 @@ private static bool CanHandleParameter(ParameterInfo parameter) if (parameter.ParameterType.IsGenericType) { - Type parameterTypeDefinition = parameter.ParameterType.GetGenericTypeDefinition(); + var parameterTypeDefinition = parameter.ParameterType.GetGenericTypeDefinition(); if (parameterTypeDefinition == typeof(ValueTask<>) || parameterTypeDefinition == typeof(Task<>)) @@ -798,11 +798,11 @@ private bool TryGetDefaultValueFromConstructor( out object? defaultValue) { defaultValue = null; - ConstructorInfo[] constructors = property.DeclaringType!.GetConstructors(); + var constructors = property.DeclaringType!.GetConstructors(); if (constructors.Length == 1) { - foreach (ParameterInfo parameter in constructors[0].GetParameters()) + foreach (var parameter in constructors[0].GetParameters()) { if (parameter.Name.EqualsOrdinal(property.Name)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DescriptorContext.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DescriptorContext.cs index 11e12b6d684..1d2789131bd 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DescriptorContext.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/DescriptorContext.cs @@ -138,7 +138,7 @@ public bool TryGetSchemaDirective( if (ContextData.TryGetValue(SchemaDirectives, out var value) && value is IReadOnlyList directives) { - foreach (ISchemaDirective sd in directives) + foreach (var sd in directives) { _schemaDirectives[sd.Name.Value] = sd; } @@ -160,7 +160,7 @@ public T GetConventionOrDefault( throw new ArgumentNullException(nameof(defaultConvention)); } - if (_conventions.TryGetValue((typeof(T), scope), out IConvention? conv) && + if (_conventions.TryGetValue((typeof(T), scope), out var conv) && conv is T castedConvention) { return castedConvention; @@ -168,8 +168,8 @@ public T GetConventionOrDefault( CreateConventions( scope, - out IConvention? createdConvention, - out IList? extensions); + out var createdConvention, + out var extensions); createdConvention ??= createdConvention as T; createdConvention ??= _services.GetService(typeof(T)) as T; @@ -177,7 +177,7 @@ public T GetConventionOrDefault( if (createdConvention is Convention init) { - ConventionContext conventionContext = + var conventionContext = ConventionContext.Create(scope, _services, this); init.Initialize(conventionContext); @@ -204,11 +204,11 @@ private void CreateConventions( if (_cFactories.TryGetValue( (typeof(T), scope), - out List? factories)) + out var factories)) { for (var i = 0; i < factories.Count; i++) { - IConvention convention = factories[i](_services); + var convention = factories[i](_services); if (convention is IConventionExtension extension) { extensions.Add(extension); @@ -235,7 +235,7 @@ private static void MergeExtensions( Convention convention, IList extensions) { - foreach (IConventionExtension? extension in extensions) + foreach (var extension in extensions) { if (extension is Convention extensionConvention) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationFileResolver.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationFileResolver.cs index 675bd06eb8d..42f39db6984 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationFileResolver.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationFileResolver.cs @@ -35,7 +35,7 @@ public bool TryGetXmlDocument( { var fullName = assembly.GetName().FullName; - if (!_cache.TryGetValue(fullName, out XDocument? doc)) + if (!_cache.TryGetValue(fullName, out var doc)) { var xmlDocumentFileName = GetXmlDocumentationPath(assembly); @@ -59,7 +59,7 @@ public bool TryGetXmlDocument( return null; } - AssemblyName assemblyName = assembly.GetName(); + var assemblyName = assembly.GetName(); if (string.IsNullOrEmpty(assemblyName.Name)) { return null; diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationProvider.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationProvider.cs index 6cb4ef01e44..b580137de11 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationProvider.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Conventions/XmlDocumentationProvider.cs @@ -45,7 +45,7 @@ public XmlDocumentationProvider( public string? GetDescription(ParameterInfo parameter) { - XElement? element = GetParameterElement(parameter); + var element = GetParameterElement(parameter); if (element is null) { @@ -65,7 +65,7 @@ public XmlDocumentationProvider( private string? GetDescriptionInternal(MemberInfo member) { - XElement? element = GetMemberElement(member); + var element = GetMemberElement(member); if (element is null) { @@ -85,7 +85,7 @@ public XmlDocumentationProvider( XElement? returns, IEnumerable errors) { - StringBuilder description = _stringBuilderPool.Get(); + var description = _stringBuilderPool.Get(); try { @@ -121,9 +121,9 @@ private void AppendErrorDescription( bool needsNewLine) { var errorCount = 0; - foreach (XElement error in errors) + foreach (var error in errors) { - XAttribute? code = error.Attribute(_code); + var code = error.Attribute(_code); if (code is { } && !string.IsNullOrEmpty(error.Value) && !string.IsNullOrEmpty(code.Value)) @@ -155,7 +155,7 @@ private static void AppendText( return; } - foreach (XNode? node in element.Nodes()) + foreach (var node in element.Nodes()) { var currentElement = node as XElement; if (currentElement is null) @@ -170,7 +170,7 @@ private static void AppendText( continue; } - XAttribute? attribute = currentElement.Attribute(_langword); + var attribute = currentElement.Attribute(_langword); if (attribute != null) { description.Append(attribute.Value); @@ -219,10 +219,10 @@ private void AppendNewLineIfNeeded( { if (_fileResolver.TryGetXmlDocument( member.Module.Assembly, - out XDocument? document)) + out var document)) { - MemberName name = GetMemberElementName(member); - XElement? element = document.XPathSelectElements(name.Path) + var name = GetMemberElementName(member); + var element = document.XPathSelectElements(name.Path) .FirstOrDefault(); ReplaceInheritdocElements(member, element); @@ -244,11 +244,11 @@ private void AppendNewLineIfNeeded( { if (_fileResolver.TryGetXmlDocument( parameter.Member.Module.Assembly, - out XDocument? document)) + out var document)) { - MemberName name = GetMemberElementName(parameter.Member); - IEnumerable result = document.XPathSelectElements(name.Path); - XElement? element = result.FirstOrDefault(); + var name = GetMemberElementName(parameter.Member); + var result = document.XPathSelectElements(name.Path); + var element = result.FirstOrDefault(); if (element is null) { @@ -288,24 +288,24 @@ private void ReplaceInheritdocElements( return; } - List children = element.Nodes().ToList(); - foreach (XElement? child in children.OfType()) + var children = element.Nodes().ToList(); + foreach (var child in children.OfType()) { if (string.Equals(child.Name.LocalName, _inheritdoc, StringComparison.OrdinalIgnoreCase)) { - Type? baseType = + var baseType = member.DeclaringType?.GetTypeInfo().BaseType; - MemberInfo? baseMember = + var baseMember = baseType?.GetTypeInfo().DeclaredMembers .SingleOrDefault(m => m.Name == member.Name); if (baseMember != null) { - XElement? baseDoc = GetMemberElement(baseMember); + var baseDoc = GetMemberElement(baseMember); if (baseDoc != null) { - object[] nodes = + var nodes = baseDoc.Nodes().OfType().ToArray(); child.ReplaceWith(nodes); } @@ -328,15 +328,15 @@ private void ProcessInheritdocInterfaceElements( { if (member.DeclaringType is { }) { - foreach (Type baseInterface in member.DeclaringType + foreach (var baseInterface in member.DeclaringType .GetTypeInfo().ImplementedInterfaces) { - MemberInfo? baseMember = baseInterface.GetTypeInfo() + var baseMember = baseInterface.GetTypeInfo() .DeclaredMembers.SingleOrDefault(m => m.Name.EqualsOrdinal(member.Name)); if (baseMember != null) { - XElement? baseDoc = GetMemberElement(baseMember); + var baseDoc = GetMemberElement(baseMember); if (baseDoc != null) { child.ReplaceWith( @@ -357,7 +357,7 @@ private void ProcessInheritdocInterfaceElements( documentation = "\n" + documentation.Replace("\r", string.Empty).Trim('\n'); - string whitespace = + var whitespace = Regex.Match(documentation, "(\\n[ \\t]*)").Value; documentation = documentation.Replace(whitespace, "\n"); diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DefinitionBase.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DefinitionBase.cs index 0e0986ab12d..d652b215d49 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DefinitionBase.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DefinitionBase.cs @@ -116,7 +116,7 @@ protected void CopyTo(DefinitionBase target) { target._configurations = new List(); - foreach (ITypeSystemMemberConfiguration configuration in _configurations) + foreach (var configuration in _configurations) { target._configurations.Add(configuration.Copy(target)); } @@ -145,7 +145,7 @@ protected void MergeInto(DefinitionBase target) { target._configurations ??= new List(); - foreach (ITypeSystemMemberConfiguration configuration in _configurations) + foreach (var configuration in _configurations) { target._configurations.Add(configuration.Copy(target)); } @@ -154,7 +154,7 @@ protected void MergeInto(DefinitionBase target) if (_contextData is not null && _contextData.Count > 0) { target._contextData ??= new ExtensionData(); - foreach (KeyValuePair item in _contextData) + foreach (var item in _contextData) { target._contextData[item.Key] = item.Value; } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DirectiveTypeDefinition.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DirectiveTypeDefinition.cs index 279deb6fd2f..eac242a44a6 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DirectiveTypeDefinition.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/DirectiveTypeDefinition.cs @@ -87,7 +87,7 @@ public override IEnumerable GetConfigurations() configs.AddRange(Configurations); - foreach (DirectiveArgumentDefinition field in GetArguments()) + foreach (var field in GetArguments()) { configs.AddRange(field.Configurations); } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/EnumTypeDefinition.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/EnumTypeDefinition.cs index 9bf98d9338a..07c7254911b 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/EnumTypeDefinition.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/EnumTypeDefinition.cs @@ -46,7 +46,7 @@ public override IEnumerable GetConfigurations() configs.AddRange(Configurations); } - foreach (EnumValueDefinition value in Values) + foreach (var value in Values) { if (value.HasConfigurations) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InputObjectTypeDefinition.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InputObjectTypeDefinition.cs index 26bc50635d5..9de831b869d 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InputObjectTypeDefinition.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InputObjectTypeDefinition.cs @@ -56,7 +56,7 @@ public override IEnumerable GetConfigurations() configs.AddRange(Configurations); } - foreach (InputFieldDefinition field in Fields) + foreach (var field in Fields) { if (field.HasConfigurations) { @@ -76,7 +76,7 @@ protected internal void CopyTo(InputObjectTypeDefinition target) { target.Fields.Clear(); - foreach (InputFieldDefinition? field in Fields) + foreach (var field in Fields) { target.Fields.Add(field); } @@ -90,9 +90,9 @@ protected internal void MergeInto(InputObjectTypeDefinition target) { base.MergeInto(target); - foreach (InputFieldDefinition? field in Fields) + foreach (var field in Fields) { - InputFieldDefinition? targetField = + var targetField = target.Fields.FirstOrDefault(t => field.Name.Equals(t.Name)); if (field.Ignore) diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InterfaceTypeDefinition.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InterfaceTypeDefinition.cs index 86479242ea0..0a0b78e8ce1 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InterfaceTypeDefinition.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/InterfaceTypeDefinition.cs @@ -56,7 +56,7 @@ public override IEnumerable GetConfigurations() configs.AddRange(Configurations); } - foreach (InterfaceFieldDefinition field in Fields) + foreach (var field in Fields) { if (field.HasConfigurations) { @@ -66,7 +66,7 @@ public override IEnumerable GetConfigurations() if (field.HasArguments) { - foreach (ArgumentDefinition argument in field.Arguments) + foreach (var argument in field.Arguments) { if (argument.HasConfigurations) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectFieldDefinition.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectFieldDefinition.cs index 01287c67614..ce78694d5ab 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectFieldDefinition.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectFieldDefinition.cs @@ -336,7 +336,7 @@ private static void CleanMiddlewareDefinitions( { var nonRepeatable = 0; - foreach (T def in definitions) + foreach (var def in definitions) { if (!def.IsRepeatable && def.Key is not null) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectTypeDefinition.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectTypeDefinition.cs index 8feeb0fe82c..db2c9c792cc 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectTypeDefinition.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/ObjectTypeDefinition.cs @@ -105,7 +105,7 @@ public override IEnumerable GetConfigurations() configs.AddRange(Configurations); } - foreach (ObjectFieldDefinition field in Fields) + foreach (var field in Fields) { if (field.HasConfigurations) { @@ -113,7 +113,7 @@ public override IEnumerable GetConfigurations() configs.AddRange(field.Configurations); } - foreach (ArgumentDefinition argument in field.GetArguments()) + foreach (var argument in field.GetArguments()) { if (argument.HasConfigurations) { @@ -179,7 +179,7 @@ protected internal void CopyTo(ObjectTypeDefinition target) { target.Fields.Clear(); - foreach (ObjectFieldDefinition? field in Fields) + foreach (var field in Fields) { target.Fields.Add(field); } @@ -212,9 +212,9 @@ protected internal void MergeInto(ObjectTypeDefinition target) target._fieldIgnores.AddRange(_fieldIgnores); } - foreach (ObjectFieldDefinition? field in Fields) + foreach (var field in Fields) { - ObjectFieldDefinition? targetField = field switch + var targetField = field switch { { BindToField: { Type: ObjectFieldBindingType.Property } bindTo } => target.Fields.FirstOrDefault(t => bindTo.Name.Equals(t.Member?.Name!)), @@ -230,7 +230,7 @@ protected internal void MergeInto(ObjectTypeDefinition target) if (field.Member is MethodInfo p && p.GetParameters() is { Length: > 0 } parameters) { - ParameterInfo? parent = parameters.FirstOrDefault( + var parent = parameters.FirstOrDefault( t => t.IsDefined(typeof(ParentAttribute), true)); if (parent is not null && !parent.ParameterType.IsAssignableFrom(target.RuntimeType) && diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs index f61ff16a9ef..c17ee6a97f0 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/Definitions/OutputFieldDefinitionBase.cs @@ -39,7 +39,7 @@ protected void CopyTo(OutputFieldDefinitionBase target) { target._arguments = new List(); - foreach (ArgumentDefinition argument in _arguments) + foreach (var argument in _arguments) { var newArgument = new ArgumentDefinition(); argument.CopyTo(newArgument); @@ -58,9 +58,9 @@ protected void MergeInto(OutputFieldDefinitionBase target) { target._arguments ??= new List(); - foreach (ArgumentDefinition argument in _arguments) + foreach (var argument in _arguments) { - ArgumentDefinition? targetArgument = + var targetArgument = target._arguments.FirstOrDefault(t => t.Name.Equals(argument.Name)); if (targetArgument is null) diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/DependencyDescriptorBase~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/DependencyDescriptorBase~1.cs index 516b52b9eb4..985850b84da 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/DependencyDescriptorBase~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/DependencyDescriptorBase~1.cs @@ -47,7 +47,7 @@ protected void DependsOn(IExtendedType schemaType, bool mustBeNamedOrCompleted) nameof(schemaType)); } - TypeDependencyKind kind = mustBeNamedOrCompleted + var kind = mustBeNamedOrCompleted ? DependencyKind : TypeDependencyKind.Default; @@ -61,7 +61,7 @@ protected void DependsOn( { typeName.EnsureNotEmpty(nameof(typeName)); - TypeDependencyKind kind = mustBeNamedOrCompleted + var kind = mustBeNamedOrCompleted ? DependencyKind : TypeDependencyKind.Default; diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/DescriptorBase~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/DescriptorBase~1.cs index 334acc1f6e4..937ff0c26f8 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/DescriptorBase~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/DescriptorBase~1.cs @@ -39,8 +39,8 @@ public T CreateDefinition() var i = 0; var buffered = 0; var length = Definition.Configurations.Count; - CreateConfiguration[] rented = ArrayPool.Shared.Rent(length); - IList configurations = Definition.Configurations; + var rented = ArrayPool.Shared.Rent(length); + var configurations = Definition.Configurations; do { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveArgumentDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveArgumentDescriptor.cs index 0ca69560360..9f2948bf62a 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveArgumentDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveArgumentDescriptor.cs @@ -39,12 +39,12 @@ protected internal DirectiveArgumentDescriptor( Definition.Type = context.TypeInspector.GetInputReturnTypeRef(property); Definition.Property = property; - if (context.TypeInspector.TryGetDefaultValue(property, out object? defaultValue)) + if (context.TypeInspector.TryGetDefaultValue(property, out var defaultValue)) { Definition.RuntimeDefaultValue = defaultValue; } - if (context.Naming.IsDeprecated(property, out string? reason)) + if (context.Naming.IsDeprecated(property, out var reason)) { Deprecated(reason); } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor.cs index 85b231832ac..84790b94b71 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor.cs @@ -110,7 +110,7 @@ public IDirectiveTypeDescriptor Description(string value) public IDirectiveArgumentDescriptor Argument(NameString name) { - DirectiveArgumentDescriptor descriptor = + var descriptor = Arguments.FirstOrDefault(t => t.Definition.Name.Equals(name)); if (descriptor is { }) { @@ -126,7 +126,7 @@ public IDirectiveArgumentDescriptor Argument(NameString name) public IDirectiveTypeDescriptor Location(DirectiveLocation value) { - Array values = Enum.GetValues(typeof(DirectiveLocation)); + var values = Enum.GetValues(typeof(DirectiveLocation)); foreach (DirectiveLocation item in values) { if (value.HasFlag(item)) @@ -224,7 +224,7 @@ public static DirectiveTypeDescriptor FromSchemaType( IDescriptorContext context, Type schemaType) { - DirectiveTypeDescriptor descriptor = New(context, schemaType); + var descriptor = New(context, schemaType); descriptor.Definition.RuntimeType = typeof(object); return descriptor; } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor~1.cs index 306fe15ea61..436f1d7bb4a 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/DirectiveTypeDescriptor~1.cs @@ -94,7 +94,7 @@ public IDirectiveArgumentDescriptor Argument( if (property.ExtractMember() is PropertyInfo p) { - DirectiveArgumentDescriptor descriptor = + var descriptor = Arguments.FirstOrDefault(t => t.Definition.Property == p); if (descriptor is { }) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/EnumTypeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/EnumTypeDescriptor.cs index cc4b77e9755..98a531eddd6 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/EnumTypeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/EnumTypeDescriptor.cs @@ -55,7 +55,7 @@ protected override void OnCreateDefinition( definition.Values.Clear(); - foreach (EnumValueDefinition value in values.Values) + foreach (var value in values.Values) { definition.Values.Add(value); } @@ -71,7 +71,7 @@ protected void AddImplicitValues( { foreach (var value in Context.TypeInspector.GetEnumValues(typeDefinition.RuntimeType)) { - EnumValueDefinition valueDefinition = + var valueDefinition = EnumValueDescriptor.New(Context, value) .CreateDefinition(); @@ -126,7 +126,7 @@ public IEnumTypeDescriptor BindValuesImplicitly() => public IEnumValueDescriptor Value(T value) { - EnumValueDescriptor descriptor = Values.FirstOrDefault(t => + var descriptor = Values.FirstOrDefault(t => t.Definition.RuntimeValue is not null && t.Definition.RuntimeValue.Equals(value)); @@ -178,7 +178,7 @@ public static EnumTypeDescriptor FromSchemaType( IDescriptorContext context, Type schemaType) { - EnumTypeDescriptor descriptor = New(context, schemaType); + var descriptor = New(context, schemaType); descriptor.Definition.RuntimeType = typeof(object); return descriptor; } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor.cs index 48e7d48df4b..5b227b98c37 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor.cs @@ -40,7 +40,7 @@ protected InputObjectTypeDescriptor( { Definition = definition ?? throw new ArgumentNullException(nameof(definition)); - foreach (InputFieldDefinition field in definition.Fields) + foreach (var field in definition.Fields) { Fields.Add(InputFieldDescriptor.From(Context, field)); } @@ -106,7 +106,7 @@ public IInputObjectTypeDescriptor Description(string value) public IInputFieldDescriptor Field(NameString name) { - InputFieldDescriptor fieldDescriptor = + var fieldDescriptor = Fields.FirstOrDefault(t => t.Definition.Name.Equals(name)); if (fieldDescriptor is not null) @@ -160,7 +160,7 @@ public static InputObjectTypeDescriptor FromSchemaType( IDescriptorContext context, Type schemaType) { - InputObjectTypeDescriptor descriptor = New(context, schemaType); + var descriptor = New(context, schemaType); descriptor.Definition.RuntimeType = typeof(object); return descriptor; } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor~1.cs index 4c8abcf4c56..9a60f0bfd7b 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/InputObjectTypeDescriptor~1.cs @@ -86,7 +86,7 @@ public IInputFieldDescriptor Field( { if (property.ExtractMember() is PropertyInfo p) { - InputFieldDescriptor fieldDescriptor = + var fieldDescriptor = Fields.FirstOrDefault(t => t.Definition.Property == p); if (fieldDescriptor is { }) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor.cs index b4681cb45b2..ab8f9ed4489 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor.cs @@ -42,7 +42,7 @@ protected InterfaceTypeDescriptor( { Definition = definition ?? throw new ArgumentNullException(nameof(definition)); - foreach (InterfaceFieldDefinition field in definition.Fields) + foreach (var field in definition.Fields) { Fields.Add(InterfaceFieldDescriptor.From(Context, field)); } @@ -161,7 +161,7 @@ public IInterfaceTypeDescriptor Implements(NamedTypeNode type) public IInterfaceFieldDescriptor Field(NameString name) { - InterfaceFieldDescriptor fieldDescriptor = + var fieldDescriptor = Fields.FirstOrDefault(t => t.Definition.Name.Equals(name)); if (fieldDescriptor is not null) @@ -221,7 +221,7 @@ public static InterfaceTypeDescriptor New( public static InterfaceTypeDescriptor FromSchemaType( IDescriptorContext context, Type schemaType) { - InterfaceTypeDescriptor descriptor = New(context, schemaType); + var descriptor = New(context, schemaType); descriptor.Definition.RuntimeType = typeof(object); return descriptor; } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor~1.cs index c4e306ce817..c41c29d3825 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/InterfaceTypeDescriptor~1.cs @@ -123,10 +123,10 @@ public IInterfaceFieldDescriptor Field( throw new ArgumentNullException(nameof(propertyOrMethod)); } - MemberInfo member = propertyOrMethod.ExtractMember(); + var member = propertyOrMethod.ExtractMember(); if (member is PropertyInfo || member is MethodInfo) { - InterfaceFieldDescriptor fieldDescriptor = + var fieldDescriptor = Fields.FirstOrDefault(t => t.Definition.Member == member); if (fieldDescriptor is { }) { diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectFieldDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectFieldDescriptor.cs index ee9d95a6949..2cfb39962f7 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectFieldDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectFieldDescriptor.cs @@ -91,7 +91,7 @@ protected ObjectFieldDescriptor( Definition.IsParallelExecutable = context.Options.DefaultResolverStrategy is ExecutionStrategy.Parallel; - MemberInfo? member = expression.TryExtractCallMember(); + var member = expression.TryExtractCallMember(); if (member is not null) { @@ -140,7 +140,7 @@ protected ObjectFieldDescriptor( /// protected override void OnCreateDefinition(ObjectFieldDefinition definition) { - MemberInfo? member = definition.ResolverMember ?? definition.Member; + var member = definition.ResolverMember ?? definition.Member; if (!Definition.AttributesAreApplied && member is not null) { @@ -298,9 +298,9 @@ public IObjectFieldDescriptor Resolve( if (resultType.IsGenericType) { - Type resultTypeDef = resultType.GetGenericTypeDefinition(); + var resultTypeDef = resultType.GetGenericTypeDefinition(); - Type clrResultType = resultTypeDef == typeof(NativeType<>) + var clrResultType = resultTypeDef == typeof(NativeType<>) ? resultType.GetGenericArguments()[0] : resultType; diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptor.cs index da8ba3232ac..05182ead552 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptor.cs @@ -43,7 +43,7 @@ protected ObjectTypeDescriptor( { Definition = definition ?? throw new ArgumentNullException(nameof(definition)); - foreach (ObjectFieldDefinition field in definition.Fields) + foreach (var field in definition.Fields) { Fields.Add(ObjectFieldDescriptor.From(Context, field)); } @@ -66,7 +66,7 @@ protected override void OnCreateDefinition( Definition.AttributesAreApplied = true; } - foreach (ObjectFieldDescriptor field in Fields) + foreach (var field in Fields) { if (!field.Definition.Ignore) { @@ -185,7 +185,7 @@ public IObjectTypeDescriptor IsOfType(IsOfType? isOfType) public IObjectFieldDescriptor Field(NameString name) { - ObjectFieldDescriptor? fieldDescriptor = Fields.FirstOrDefault( + var fieldDescriptor = Fields.FirstOrDefault( t => t.Definition.Name.Equals(name)); if (fieldDescriptor is { }) @@ -212,7 +212,7 @@ public IObjectFieldDescriptor Field( if (propertyOrMethod is PropertyInfo || propertyOrMethod is MethodInfo) { - ObjectFieldDescriptor? fieldDescriptor = Fields.FirstOrDefault( + var fieldDescriptor = Fields.FirstOrDefault( t => t.Definition.Member == propertyOrMethod); if (fieldDescriptor is not null) @@ -242,11 +242,11 @@ public IObjectFieldDescriptor Field( throw new ArgumentNullException(nameof(propertyOrMethod)); } - MemberInfo? member = propertyOrMethod.TryExtractMember(); + var member = propertyOrMethod.TryExtractMember(); if (member is PropertyInfo or MethodInfo) { - ObjectFieldDescriptor? fieldDescriptor = Fields.FirstOrDefault( + var fieldDescriptor = Fields.FirstOrDefault( t => t.Definition.Member == member); if (fieldDescriptor is not null) diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptorBase~1.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptorBase~1.cs index 3db2d18d545..c16124a9bc9 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptorBase~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/ObjectTypeDescriptorBase~1.cs @@ -74,7 +74,7 @@ protected override void OnCompleteFields( bool IncludeField(IReadOnlyList all, MemberInfo current) { - NameString name = Context.Naming.GetMemberName(current, MemberKind.ObjectField); + var name = Context.Naming.GetMemberName(current, MemberKind.ObjectField); if (Fields.Any(t => t.Definition.Name.Equals(name))) { @@ -85,7 +85,7 @@ bool IncludeField(IReadOnlyList all, MemberInfo current) { subscribeResolver = new HashSet(); - foreach (MemberInfo member in all) + foreach (var member in all) { HandlePossibleSubscribeMember(member); } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/OutputFieldDescriptorBase.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/OutputFieldDescriptorBase.cs index 1be973a2f92..352bab923a6 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/OutputFieldDescriptorBase.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/OutputFieldDescriptorBase.cs @@ -33,7 +33,7 @@ protected override void OnCreateDefinition(TDefinition definition) { base.OnCreateDefinition(definition); - foreach (ArgumentDescriptor argument in Arguments) + foreach (var argument in Arguments) { Definition.Arguments.Add(argument.CreateDefinition()); } @@ -62,7 +62,7 @@ protected void Type() protected void Type(Type type) { - Internal.ITypeInfo? typeInfo = Context.TypeInspector.CreateTypeInfo(type); + var typeInfo = Context.TypeInspector.CreateTypeInfo(type); if (typeInfo.IsSchemaType && !typeInfo.IsOutputType()) { @@ -115,13 +115,13 @@ protected void Argument( ParameterInfo? parameter = null; Parameters?.TryGetValue(name, out parameter); - ArgumentDescriptor? descriptor = parameter is null + var descriptor = parameter is null ? Arguments.FirstOrDefault(t => t.Definition.Name.Equals(name)) : Arguments.FirstOrDefault(t => t.Definition.Parameter == parameter); if (descriptor is null && Definition.Arguments.Count > 0) { - ArgumentDefinition? definition = parameter is null + var definition = parameter is null ? Definition.Arguments.FirstOrDefault(t => t.Name.Equals(name)) : Definition.Arguments.FirstOrDefault(t => t.Parameter == parameter); diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/TypeReferences/SchemaTypeReference.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/TypeReferences/SchemaTypeReference.cs index 76cfd4ae4ad..310238f1ede 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/TypeReferences/SchemaTypeReference.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/TypeReferences/SchemaTypeReference.cs @@ -133,7 +133,7 @@ internal static TypeContext InferTypeContext(object? type) { if (type is IType t) { - INamedType namedType = t.NamedType(); + var namedType = t.NamedType(); if (namedType.IsInputType() && namedType.IsOutputType()) { @@ -176,7 +176,7 @@ internal static TypeContext InferTypeContext(Type type) throw new ArgumentNullException(nameof(type)); } - Type? namedType = ExtendedType.Tools.GetNamedType(type); + var namedType = ExtendedType.Tools.GetNamedType(type); return InferTypeContextInternal(namedType ?? type); } diff --git a/src/HotChocolate/Core/src/Types/Types/Descriptors/UnionTypeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Descriptors/UnionTypeDescriptor.cs index 2de8386bc06..42adc5f46e6 100644 --- a/src/HotChocolate/Core/src/Types/Types/Descriptors/UnionTypeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Descriptors/UnionTypeDescriptor.cs @@ -143,7 +143,7 @@ public static UnionTypeDescriptor FromSchemaType( IDescriptorContext context, Type schemaType) { - UnionTypeDescriptor descriptor = New(context, schemaType); + var descriptor = New(context, schemaType); descriptor.Definition.RuntimeType = typeof(object); return descriptor; } diff --git a/src/HotChocolate/Core/src/Types/Types/Directive.cs b/src/HotChocolate/Core/src/Types/Types/Directive.cs index be40a81af86..7fece362e5f 100644 --- a/src/HotChocolate/Core/src/Types/Types/Directive.cs +++ b/src/HotChocolate/Core/src/Types/Types/Directive.cs @@ -75,7 +75,7 @@ public DirectiveNode ToNode(bool removeNullArguments) { var arguments = new List(); - foreach (ArgumentNode argument in _parsedDirective.Arguments) + foreach (var argument in _parsedDirective.Arguments) { if (!argument.Value.IsNull()) { @@ -96,9 +96,9 @@ public T GetArgument(string argumentName) throw new ArgumentNullException(nameof(argumentName)); } - Dictionary arguments = GetArguments(); - if (arguments.TryGetValue(argumentName, out ArgumentNode? argValue) - && Type.Arguments.TryGetField(argumentName, out Argument? arg)) + var arguments = GetArguments(); + if (arguments.TryGetValue(argumentName, out var argValue) + && Type.Arguments.TryGetField(argumentName, out var arg)) { return Type.DeserializeArgument(arg, argValue.Value); } @@ -118,13 +118,13 @@ private T CreateCustomDirective() directive = (T)Activator.CreateInstance(typeof(T))!; - ILookup properties = + var properties = typeof(T).GetProperties() .ToLookup(t => t.Name, StringComparer.OrdinalIgnoreCase); - foreach (Argument argument in Type.Arguments) + foreach (var argument in Type.Arguments) { - PropertyInfo? property = properties[argument.Name].FirstOrDefault(); + var property = properties[argument.Name].FirstOrDefault(); if (property != null) { @@ -140,8 +140,8 @@ private void SetProperty( object obj, PropertyInfo property) { - Dictionary arguments = GetArguments(); - if (arguments.TryGetValue(argument.Name, out ArgumentNode? argumentValue)) + var arguments = GetArguments(); + if (arguments.TryGetValue(argument.Name, out var argumentValue)) { var parsedValue = Type.DeserializeArgument( argument, argumentValue.Value, property.PropertyType); @@ -157,10 +157,10 @@ private bool TryDeserialize( DirectiveNode directiveNode, out T directive) { - ConstructorInfo? constructor = typeof(T).GetTypeInfo() + var constructor = typeof(T).GetTypeInfo() .DeclaredConstructors.FirstOrDefault(t => { - ParameterInfo[] parameters = t.GetParameters(); + var parameters = t.GetParameters(); return parameters.Length == 2 && parameters[0].ParameterType == typeof(SerializationInfo) @@ -215,7 +215,7 @@ public static Directive FromDescription( source); } - DirectiveNode directiveNode = ParseValue( + var directiveNode = ParseValue( directiveType, definition.CustomDirective); return new Directive( @@ -247,7 +247,7 @@ public static Directive FromAstNode( if (schema.TryGetDirectiveType( directiveNode.Name.Value, - out DirectiveType? type)) + out var type)) { return new Directive( type, @@ -273,7 +273,7 @@ private static DirectiveNode CompleteArguments( var argumentNames = new HashSet( directive.Arguments.Select(t => t.Name.Value)); - foreach (Argument argument in directiveType.Arguments) + foreach (var argument in directiveType.Arguments) { if (argument.DefaultValue is { } && !argumentNames.Contains(argument.Name)) @@ -299,16 +299,16 @@ private static DirectiveNode ParseValue( { var arguments = new List(); - Type type = directive.GetType(); - ILookup properties = + var type = directive.GetType(); + var properties = type.GetProperties().ToLookup(t => t.Name, StringComparer.OrdinalIgnoreCase); - foreach (Argument argument in directiveType.Arguments) + foreach (var argument in directiveType.Arguments) { - PropertyInfo? property = properties[argument.Name].FirstOrDefault(); + var property = properties[argument.Name].FirstOrDefault(); var propertyValue = property?.GetValue(directive); - IValueNode valueNode = directiveType.SerializeArgument(argument, propertyValue); + var valueNode = directiveType.SerializeArgument(argument, propertyValue); arguments.Add(new ArgumentNode(argument.Name, valueNode)); } diff --git a/src/HotChocolate/Core/src/Types/Types/DirectiveCollection.cs b/src/HotChocolate/Core/src/Types/Types/DirectiveCollection.cs index f46e0230ddb..b48bc6fabb5 100644 --- a/src/HotChocolate/Core/src/Types/Types/DirectiveCollection.cs +++ b/src/HotChocolate/Core/src/Types/Types/DirectiveCollection.cs @@ -58,13 +58,13 @@ public void CompleteCollection(ITypeCompletionContext context) var processed = new HashSet(); List? directives = null; - foreach (DirectiveDefinition description in _definitions!) + foreach (var description in _definitions!) { if (TryCompleteDirective( context, description, processed, - out Directive? directive)) + out var directive)) { directives ??= new List(); directives.Add(directive); @@ -93,7 +93,7 @@ private bool TryCompleteDirective( { if (!context.TryGetDirectiveType( definition.Reference, - out DirectiveType? directiveType)) + out var directiveType)) { directive = null; return false; @@ -132,11 +132,11 @@ private void ValidateArguments(ITypeCompletionContext context, Directive directi { var arguments = directive.ToNode().Arguments.ToDictionary(t => t.Name.Value); - foreach (ArgumentNode argument in arguments.Values) + foreach (var argument in arguments.Values) { if (directive.Type.Arguments.TryGetField( argument.Name.Value, - out Argument? arg)) + out var arg)) { if (!arg.Type.IsInstanceOfType(argument.Value)) { @@ -161,10 +161,10 @@ private void ValidateArguments(ITypeCompletionContext context, Directive directi } } - foreach (Argument argument in directive.Type.Arguments + foreach (var argument in directive.Type.Arguments .Where(a => a.Type.IsNonNullType())) { - if (!arguments.TryGetValue(argument.Name, out ArgumentNode? arg) + if (!arguments.TryGetValue(argument.Name, out var arg) || arg.Value is NullValueNode) { context.ReportError( diff --git a/src/HotChocolate/Core/src/Types/Types/Directives/CostDirective.cs b/src/HotChocolate/Core/src/Types/Types/Directives/CostDirective.cs index cd1ed1abbcf..ec8341a69e4 100644 --- a/src/HotChocolate/Core/src/Types/Types/Directives/CostDirective.cs +++ b/src/HotChocolate/Core/src/Types/Types/Directives/CostDirective.cs @@ -113,11 +113,11 @@ private CostDirective( } else { - ArgumentNode complexityArgument = node.Arguments + var complexityArgument = node.Arguments .FirstOrDefault(t => t.Name.Value == "complexity"); - ArgumentNode multipliersArgument = node.Arguments + var multipliersArgument = node.Arguments .FirstOrDefault(t => t.Name.Value == "multipliers"); - ArgumentNode defaultMultiplierArgument = node.Arguments + var defaultMultiplierArgument = node.Arguments .FirstOrDefault(t => t.Name.Value == "defaultMultiplier"); _complexity = complexityArgument is { Value: IntValueNode iv } diff --git a/src/HotChocolate/Core/src/Types/Types/Directives/CostTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Directives/CostTypeInterceptor.cs index b79687d321e..06e6dbc551f 100644 --- a/src/HotChocolate/Core/src/Types/Types/Directives/CostTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Directives/CostTypeInterceptor.cs @@ -47,7 +47,7 @@ public override void OnBeforeRegisterDependencies( definition is ObjectTypeDefinition objectDef && objectDef.Fields.Any(CanApplyDefaultCost)) { - IExtendedType directive = + var directive = discoveryContext.TypeInspector.GetType(typeof(CostDirectiveType)); discoveryContext.Dependencies.Add(new( @@ -69,7 +69,7 @@ public override void OnBeforeCompleteType( if (!completionContext.IsIntrospectionType && definition is ObjectTypeDefinition objectDef) { - foreach (ObjectFieldDefinition field in objectDef.Fields) + foreach (var field in objectDef.Fields) { if (CanApplyDefaultCost(field)) { @@ -119,7 +119,7 @@ private bool CanApplyDefaultCost(ObjectFieldDefinition field) return false; } - IReadOnlyList directives = field.GetDirectives(); + var directives = field.GetDirectives(); return directives is { Count: 0 } || !directives.Any(IsCostDirective); } @@ -154,7 +154,7 @@ private static bool IsDataResolver(ObjectFieldDefinition field) return true; } - MemberInfo? resolver = field.ResolverMember ?? field.Member; + var resolver = field.ResolverMember ?? field.Member; if (resolver is MethodInfo method) { diff --git a/src/HotChocolate/Core/src/Types/Types/Directives/DeprecatedDirective.cs b/src/HotChocolate/Core/src/Types/Types/Directives/DeprecatedDirective.cs index c7bc0e48504..a76fd676c9c 100644 --- a/src/HotChocolate/Core/src/Types/Types/Directives/DeprecatedDirective.cs +++ b/src/HotChocolate/Core/src/Types/Types/Directives/DeprecatedDirective.cs @@ -70,7 +70,7 @@ public static DirectiveNode CreateNode(string? reason = null) reason = null; } - ArgumentNode[] arguments = reason is null + var arguments = reason is null ? Array.Empty() : new[] { new ArgumentNode(DeprecatedDirectiveType.Names.Reason, reason) }; diff --git a/src/HotChocolate/Core/src/Types/Types/Directives/Directives.cs b/src/HotChocolate/Core/src/Types/Types/Directives/Directives.cs index 11a8e033752..df4c1b7654f 100644 --- a/src/HotChocolate/Core/src/Types/Types/Directives/Directives.cs +++ b/src/HotChocolate/Core/src/Types/Types/Directives/Directives.cs @@ -22,7 +22,7 @@ public static class Directives internal static IReadOnlyList CreateReferences( IDescriptorContext descriptorContext) { - ITypeInspector typeInspector = descriptorContext.TypeInspector; + var typeInspector = descriptorContext.TypeInspector; if (descriptorContext.Options.EnableOneOf) { diff --git a/src/HotChocolate/Core/src/Types/Types/EnumType.Initialization.cs b/src/HotChocolate/Core/src/Types/Types/EnumType.Initialization.cs index fd00370085d..bb0ea939fa3 100644 --- a/src/HotChocolate/Core/src/Types/Types/EnumType.Initialization.cs +++ b/src/HotChocolate/Core/src/Types/Types/EnumType.Initialization.cs @@ -100,12 +100,12 @@ protected override void OnCompleteType( _naming = context.DescriptorContext.Naming; SyntaxNode = definition.SyntaxNode; - foreach (EnumValueDefinition enumValueDefinition in definition.Values) + foreach (var enumValueDefinition in definition.Values) { if (enumValueDefinition.Ignore) continue; - if (TryCreateEnumValue(context, enumValueDefinition, out IEnumValue? enumValue)) + if (TryCreateEnumValue(context, enumValueDefinition, out var enumValue)) { _enumValues[enumValue.Name] = enumValue; _valueLookup[enumValue.Value] = enumValue; diff --git a/src/HotChocolate/Core/src/Types/Types/EnumType.cs b/src/HotChocolate/Core/src/Types/Types/EnumType.cs index 0f0d59bfcab..3014a0cb342 100644 --- a/src/HotChocolate/Core/src/Types/Types/EnumType.cs +++ b/src/HotChocolate/Core/src/Types/Types/EnumType.cs @@ -60,7 +60,7 @@ public bool TryGetValue(NameString name, [NotNullWhen(true)] out IEnumValue? val /// public bool TryGetRuntimeValue(NameString name, [NotNullWhen(true)] out object? runtimeValue) { - if (_enumValues.TryGetValue(name, out IEnumValue? value)) + if (_enumValues.TryGetValue(name, out var value)) { runtimeValue = value.Value; return true; @@ -112,7 +112,7 @@ public bool IsInstanceOfType(object? runtimeValue) } if (valueSyntax is EnumValueNode evn && - _enumValues.TryGetValue(evn.Value, out IEnumValue? ev)) + _enumValues.TryGetValue(evn.Value, out var ev)) { return ev.Value; } @@ -141,7 +141,7 @@ public IValueNode ParseValue(object? runtimeValue) return NullValueNode.Default; } - if (_valueLookup.TryGetValue(runtimeValue, out IEnumValue? enumValue)) + if (_valueLookup.TryGetValue(runtimeValue, out var enumValue)) { return new EnumValueNode(enumValue.Name); } @@ -160,7 +160,7 @@ public IValueNode ParseResult(object? resultValue) } if (resultValue is string s && - _enumValues.TryGetValue(s, out IEnumValue? enumValue)) + _enumValues.TryGetValue(s, out var enumValue)) { return new EnumValueNode(enumValue.Name); } @@ -190,7 +190,7 @@ public IValueNode ParseResult(object? resultValue) } if (RuntimeType.IsInstanceOfType(runtimeValue) && - _valueLookup.TryGetValue(runtimeValue, out IEnumValue? enumValue)) + _valueLookup.TryGetValue(runtimeValue, out var enumValue)) { return enumValue.Name; } @@ -213,7 +213,7 @@ public IValueNode ParseResult(object? resultValue) /// public object? Deserialize(object? resultValue) { - if (TryDeserialize(resultValue, out object? runtimeValue)) + if (TryDeserialize(resultValue, out var runtimeValue)) { return runtimeValue; } @@ -233,7 +233,7 @@ public bool TryDeserialize(object? resultValue, out object? runtimeValue) } if (resultValue is string s && - _enumValues.TryGetValue(s, out IEnumValue? enumValue)) + _enumValues.TryGetValue(s, out var enumValue)) { runtimeValue = enumValue.Value; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/EnumTypeExtension.cs b/src/HotChocolate/Core/src/Types/Types/EnumTypeExtension.cs index ce8d2c8a8d7..a43762f7c0f 100644 --- a/src/HotChocolate/Core/src/Types/Types/EnumTypeExtension.cs +++ b/src/HotChocolate/Core/src/Types/Types/EnumTypeExtension.cs @@ -129,12 +129,12 @@ private void MergeValues( EnumTypeDefinition extension, EnumTypeDefinition type) { - foreach (EnumValueDefinition enumValue in + foreach (var enumValue in extension.Values.Where(t => t.RuntimeValue != null)) { if (type.RuntimeType.IsInstanceOfType(enumValue.RuntimeValue)) { - EnumValueDefinition? existingValue = type.Values.FirstOrDefault( + var existingValue = type.Values.FirstOrDefault( t => Equals(enumValue.RuntimeValue, t.RuntimeValue)); if (existingValue is null) diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/DirectiveLocationExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/DirectiveLocationExtensions.cs index 1927fa4ec64..4690b08e3b8 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/DirectiveLocationExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/DirectiveLocationExtensions.cs @@ -87,7 +87,7 @@ public static class DirectiveLocationExtensions public static Language.DirectiveLocation MapDirectiveLocation( this DirectiveLocation location) { - if (!_locs.TryGetValue(location, out Language.DirectiveLocation l)) + if (!_locs.TryGetValue(location, out var l)) { throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/ObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/ObjectFieldDescriptorExtensions.cs index c7da8c7e997..4345b9b453b 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/ObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/ObjectFieldDescriptorExtensions.cs @@ -137,10 +137,10 @@ public static IObjectFieldDescriptor UseServiceScope( { // first we preserve the original services so that we can restore them once // we have executed the inner pipeline. - IServiceProvider services = context.Services; + var services = context.Services; // now we create the service scope that we will wrap around the execution of next. - using IServiceScope scope = services.CreateScope(); + using var scope = services.CreateScope(); context.Services = scope.ServiceProvider; try diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveObjectFieldDescriptorExtensions.cs index 6fd4353abfd..0b7fd0be0fc 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveObjectFieldDescriptorExtensions.cs @@ -44,7 +44,7 @@ public static IObjectFieldDescriptor Resolve( return descriptor.Resolve(async ctx => { - Task resolverTask = resolver(ctx); + var resolverTask = resolver(ctx); if (resolverTask is null) { return default; @@ -91,7 +91,7 @@ public static IObjectFieldDescriptor Resolve( return descriptor.Resolve( async ctx => { - Task? resolverTask = resolver(ctx); + var resolverTask = resolver(ctx); if (resolverTask is null) { return default; @@ -173,7 +173,7 @@ public static IObjectFieldDescriptor Resolve( return descriptor.Resolve( async ctx => { - Task? resolverTask = resolver(); + var resolverTask = resolver(); if (resolverTask is null) { return default; @@ -239,7 +239,7 @@ public static IObjectFieldDescriptor Resolve( return descriptor.Resolve( async ctx => { - Task? resolverTask = resolver(ctx, ctx.RequestAborted); + var resolverTask = resolver(ctx, ctx.RequestAborted); if (resolverTask is null) { return default; diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveWithObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveWithObjectFieldDescriptorExtensions.cs index f524d4189aa..4ea161dc5f7 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveWithObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/ResolveWithObjectFieldDescriptorExtensions.cs @@ -11,7 +11,7 @@ namespace HotChocolate.Types; public static class ResolveWithObjectFieldDescriptorExtensions { /// - /// Resolve a using the + /// Resolve a using the /// member selector on . /// /// @@ -41,7 +41,7 @@ public static IObjectFieldDescriptor ResolveWith( throw new ArgumentNullException(nameof(propertyOrMethod)); } - UnaryExpression? convertedBody = Expression.Convert(propertyOrMethod.Body, typeof(object)); + var convertedBody = Expression.Convert(propertyOrMethod.Body, typeof(object)); var newExpression = Expression.Lambda>(convertedBody, propertyOrMethod.Parameters); @@ -49,7 +49,7 @@ public static IObjectFieldDescriptor ResolveWith( } /// - /// Asynchronously resolve a using the + /// Asynchronously resolve a using the /// member selector on . /// /// @@ -79,7 +79,7 @@ public static IObjectFieldDescriptor ResolveWith( throw new ArgumentNullException(nameof(propertyOrMethod)); } - UnaryExpression? convertedBody = Expression.Convert(propertyOrMethod.Body, typeof(object)); + var convertedBody = Expression.Convert(propertyOrMethod.Body, typeof(object)); var newExpression = Expression.Lambda>(convertedBody, propertyOrMethod.Parameters); diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/ResolverObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/ResolverObjectFieldDescriptorExtensions.cs index 385ca4d88c7..ae112717dbc 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/ResolverObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/ResolverObjectFieldDescriptorExtensions.cs @@ -47,7 +47,7 @@ public static IObjectFieldDescriptor Resolver( return descriptor.Resolve(async ctx => { - Task resolverTask = resolver(ctx); + var resolverTask = resolver(ctx); if (resolverTask is null) { return default; @@ -96,7 +96,7 @@ public static IObjectFieldDescriptor Resolver( return descriptor.Resolve( async ctx => { - Task resolverTask = resolver(ctx); + var resolverTask = resolver(ctx); if (resolverTask is null) { return default; @@ -182,7 +182,7 @@ public static IObjectFieldDescriptor Resolver( return descriptor.Resolve( async _ => { - Task resolverTask = resolver(); + var resolverTask = resolver(); if (resolverTask is null) { return default; @@ -251,7 +251,7 @@ public static IObjectFieldDescriptor Resolver( return descriptor.Resolve( async ctx => { - Task resolverTask = resolver(ctx, ctx.RequestAborted); + var resolverTask = resolver(ctx, ctx.RequestAborted); if (resolverTask is null) { return default; diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/ScopedServiceObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/ScopedServiceObjectFieldDescriptorExtensions.cs index f9e058d4738..d4cf46646e2 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/ScopedServiceObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/ScopedServiceObjectFieldDescriptorExtensions.cs @@ -14,12 +14,12 @@ public static IObjectFieldDescriptor UseScopedService( Action? dispose = null, Func? disposeAsync = null) { - string scopedServiceName = typeof(TService).FullName ?? typeof(TService).Name; + var scopedServiceName = typeof(TService).FullName ?? typeof(TService).Name; return descriptor.Use(next => async context => { - IServiceProvider services = context.Service(); - TService scopedService = create(services); + var services = context.Service(); + var scopedService = create(services); try { diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/SubscribeResolverObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/SubscribeResolverObjectFieldDescriptorExtensions.cs index 4ae20e64793..c973ad7fb69 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/SubscribeResolverObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/SubscribeResolverObjectFieldDescriptorExtensions.cs @@ -16,7 +16,7 @@ public static IObjectFieldDescriptor Subscribe( { return descriptor.Subscribe(async ctx => { - IObservable observable = await subscribe(ctx).ConfigureAwait(false); + var observable = await subscribe(ctx).ConfigureAwait(false); return new SourceStreamWrapper(new ObservableSourceStreamAdapter(observable)); }); } @@ -32,7 +32,7 @@ public static IObjectFieldDescriptor Subscribe( { return descriptor.Subscribe(async ctx => { - IEnumerable enumerable = await subscribe(ctx).ConfigureAwait(false); + var enumerable = await subscribe(ctx).ConfigureAwait(false); return new SourceStreamWrapper(new EnumerableStreamAdapter(enumerable)); }); } @@ -48,7 +48,7 @@ public static IObjectFieldDescriptor Subscribe( { return descriptor.Subscribe(async ctx => { - IAsyncEnumerable enumerable = await subscribe(ctx).ConfigureAwait(false); + var enumerable = await subscribe(ctx).ConfigureAwait(false); return new SourceStreamWrapper(new AsyncEnumerableStreamAdapter(enumerable)); }); } @@ -133,8 +133,8 @@ public static IObjectFieldDescriptor SubscribeToTopic( { return descriptor.Subscribe(async ctx => { - ITopicEventReceiver receiver = ctx.Service(); - TTopic topic = await resolveTopic(ctx).ConfigureAwait(false); + var receiver = ctx.Service(); + var topic = await resolveTopic(ctx).ConfigureAwait(false); return await receiver.SubscribeAsync(topic).ConfigureAwait(false); }); } diff --git a/src/HotChocolate/Core/src/Types/Types/Extensions/TypeExtensions.cs b/src/HotChocolate/Core/src/Types/Types/Extensions/TypeExtensions.cs index 868ce6fdcb5..6a98f9a09e1 100644 --- a/src/HotChocolate/Core/src/Types/Types/Extensions/TypeExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Types/Extensions/TypeExtensions.cs @@ -259,7 +259,7 @@ public static ListType ListType(this IType type) if (type.Kind == TypeKind.NonNull) { - IType innerType = ((NonNullType)type).Type; + var innerType = ((NonNullType)type).Type; if (innerType.Kind == TypeKind.List) { return (ListType)innerType; @@ -276,7 +276,7 @@ public static INamedType NamedType(this IType type) throw new ArgumentNullException(nameof(type)); } - IType current = type; + var current = type; if (IsNamed(current)) { @@ -341,7 +341,7 @@ public static Type ToRuntimeType(this IType type) if (type.IsListType()) { - Type elementType = ToRuntimeType(type.ElementType()); + var elementType = ToRuntimeType(type.ElementType()); return typeof(List<>).MakeGenericType(elementType); } @@ -540,7 +540,7 @@ public static IType RewriteNullability(this IType type, INullabilityNode? nullab // we optimized this case to not allocate memory in the case that the type is // already non-null and the inner type is either a named type or if the // inner nullability modifier is null. - IType innerType = type.InnerType(); + var innerType = type.InnerType(); return nullability.Element is null || innerType.IsNamedType() // if the type is not a list type or if the nullability has no inner part // we do not recursively rewrite. diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/BindDirectiveHelper.cs b/src/HotChocolate/Core/src/Types/Types/Factories/BindDirectiveHelper.cs index 6862567a070..a78c3d69343 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/BindDirectiveHelper.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/BindDirectiveHelper.cs @@ -17,7 +17,7 @@ public static bool IsBindingDirective(this DirectiveNode directiveNode) public static string? GetBindingValue(this Language.IHasDirectives syntaxNode) { - DirectiveNode? directive = syntaxNode.Directives.FirstOrDefault( + var directive = syntaxNode.Directives.FirstOrDefault( t => t.Name.Value == Name); if (directive is null) @@ -27,7 +27,7 @@ public static bool IsBindingDirective(this DirectiveNode directiveNode) if (directive.Arguments.Count == 1) { - ArgumentNode to = directive.Arguments[0]; + var to = directive.Arguments[0]; if (to.Name.Value.EqualsOrdinal(ToArgument) && to.Value is StringValueNode { Value: { Length: > 0 } value }) diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/DirectiveTypeFactory.cs b/src/HotChocolate/Core/src/Types/Types/Factories/DirectiveTypeFactory.cs index 9063f61007b..977b00c4ce8 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/DirectiveTypeFactory.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/DirectiveTypeFactory.cs @@ -119,7 +119,7 @@ private static void DeclareArguments( IReadOnlyCollection arguments, bool preserveSyntaxNodes) { - foreach (InputValueDefinitionNode argument in arguments) + foreach (var argument in arguments) { var argumentDefinition = new DirectiveArgumentDefinition( argument.Name.Value, @@ -145,11 +145,11 @@ private static void DeclareLocations( DirectiveTypeDefinition parent, DirectiveDefinitionNode node) { - foreach (NameNode location in node.Locations) + foreach (var location in node.Locations) { if (Language.DirectiveLocation.TryParse( location.Value, - out Language.DirectiveLocation parsedLocation)) + out var parsedLocation)) { parent.Locations.Add(MapDirectiveLocation(parsedLocation)); } @@ -159,7 +159,7 @@ private static void DeclareLocations( private static DirectiveLocation MapDirectiveLocation( Language.DirectiveLocation location) { - if (!_locs.TryGetValue(location, out DirectiveLocation loc)) + if (!_locs.TryGetValue(location, out var loc)) { throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/EnumTypeFactory.cs b/src/HotChocolate/Core/src/Types/Types/Factories/EnumTypeFactory.cs index 6e14f86aa87..572e83c574b 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/EnumTypeFactory.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/EnumTypeFactory.cs @@ -12,7 +12,7 @@ internal sealed class EnumTypeFactory public EnumType Create(IDescriptorContext context, EnumTypeDefinitionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new EnumTypeDefinition( @@ -35,7 +35,7 @@ public EnumType Create(IDescriptorContext context, EnumTypeDefinitionNode node) public EnumTypeExtension Create(IDescriptorContext context, EnumTypeExtensionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new EnumTypeDefinition(node.Name.Value); @@ -57,7 +57,7 @@ private static void DeclareValues( { path.Push(parent); - foreach (EnumValueDefinitionNode value in values) + foreach (var value in values) { var valueDefinition = new EnumValueDefinition( value.Name.Value, diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/InputObjectTypeFactory.cs b/src/HotChocolate/Core/src/Types/Types/Factories/InputObjectTypeFactory.cs index ade5c9e245a..733bd16e6dc 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/InputObjectTypeFactory.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/InputObjectTypeFactory.cs @@ -14,7 +14,7 @@ public InputObjectType Create( InputObjectTypeDefinitionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new InputObjectTypeDefinition( @@ -37,7 +37,7 @@ public InputObjectType Create( public InputObjectTypeExtension Create(IDescriptorContext context, InputObjectTypeExtensionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new InputObjectTypeDefinition(node.Name.Value); @@ -59,7 +59,7 @@ private static void DeclareFields( { path.Push(parent); - foreach (InputValueDefinitionNode inputField in fields) + foreach (var inputField in fields) { var inputFieldDefinition = new InputFieldDefinition( inputField.Name.Value, diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/InterfaceTypeFactory.cs b/src/HotChocolate/Core/src/Types/Types/Factories/InterfaceTypeFactory.cs index 6ed718efde1..67f3a0d8594 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/InterfaceTypeFactory.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/InterfaceTypeFactory.cs @@ -12,7 +12,7 @@ internal sealed class InterfaceTypeFactory public InterfaceType Create(IDescriptorContext context, InterfaceTypeDefinitionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new InterfaceTypeDefinition( @@ -25,7 +25,7 @@ public InterfaceType Create(IDescriptorContext context, InterfaceTypeDefinitionN typeDefinition.SyntaxNode = node; } - foreach (NamedTypeNode typeNode in node.Interfaces) + foreach (var typeNode in node.Interfaces) { typeDefinition.Interfaces.Add(TypeReference.Create(typeNode)); } @@ -40,13 +40,13 @@ public InterfaceType Create(IDescriptorContext context, InterfaceTypeDefinitionN public InterfaceTypeExtension Create(IDescriptorContext context, InterfaceTypeExtensionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new InterfaceTypeDefinition(node.Name.Value); typeDefinition.BindTo = node.GetBindingValue(); - foreach (NamedTypeNode typeNode in node.Interfaces) + foreach (var typeNode in node.Interfaces) { typeDefinition.Interfaces.Add(TypeReference.Create(typeNode)); } @@ -67,7 +67,7 @@ private static void DeclareFields( { path.Push(parent); - foreach (FieldDefinitionNode field in fields) + foreach (var field in fields) { var fieldDefinition = new InterfaceFieldDefinition( field.Name.Value, @@ -104,7 +104,7 @@ private static void DeclareFieldArguments( { path.Push(parent); - foreach (InputValueDefinitionNode argument in field.Arguments) + foreach (var argument in field.Arguments) { var argumentDefinition = new ArgumentDefinition( argument.Name.Value, diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/ObjectTypeFactory.cs b/src/HotChocolate/Core/src/Types/Types/Factories/ObjectTypeFactory.cs index 8bc5cabfa6d..f5214e2e760 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/ObjectTypeFactory.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/ObjectTypeFactory.cs @@ -14,7 +14,7 @@ internal sealed class ObjectTypeFactory public ObjectType Create(IDescriptorContext context, ObjectTypeDefinitionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new ObjectTypeDefinition( @@ -27,7 +27,7 @@ public ObjectType Create(IDescriptorContext context, ObjectTypeDefinitionNode no typeDefinition.SyntaxNode = node; } - foreach (NamedTypeNode typeNode in node.Interfaces) + foreach (var typeNode in node.Interfaces) { typeDefinition.Interfaces.Add(TypeReference.Create(typeNode)); } @@ -42,13 +42,13 @@ public ObjectType Create(IDescriptorContext context, ObjectTypeDefinitionNode no public ObjectTypeExtension Create(IDescriptorContext context, ObjectTypeExtensionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new ObjectTypeDefinition(node.Name.Value); typeDefinition.BindTo = node.GetBindingValue(); - foreach (NamedTypeNode typeNode in node.Interfaces) + foreach (var typeNode in node.Interfaces) { typeDefinition.Interfaces.Add(TypeReference.Create(typeNode)); } @@ -69,7 +69,7 @@ private static void DeclareFields( { path.Push(parent); - foreach (FieldDefinitionNode field in fields) + foreach (var field in fields) { var fieldDefinition = new ObjectFieldDefinition( field.Name.Value, @@ -106,7 +106,7 @@ private static void DeclareFieldArguments( { path.Push(parent); - foreach (InputValueDefinitionNode argument in field.Arguments) + foreach (var argument in field.Arguments) { var argumentDefinition = new ArgumentDefinition( argument.Name.Value, diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/SchemaSyntaxVisitor.cs b/src/HotChocolate/Core/src/Types/Types/Factories/SchemaSyntaxVisitor.cs index ab6c0a246e5..62a10723e39 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/SchemaSyntaxVisitor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/SchemaSyntaxVisitor.cs @@ -167,7 +167,7 @@ protected override ISyntaxVisitorAction VisitChildren( context.Description = node.Description?.Value; context.Directives = node.Directives; - foreach (OperationTypeDefinitionNode operationType in node.OperationTypes) + foreach (var operationType in node.OperationTypes) { switch (operationType.Operation) { diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/SdlToTypeSystemHelper.cs b/src/HotChocolate/Core/src/Types/Types/Factories/SdlToTypeSystemHelper.cs index f5ac5cf9574..12c9db1ee98 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/SdlToTypeSystemHelper.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/SdlToTypeSystemHelper.cs @@ -18,7 +18,7 @@ public static void AddDirectives( Stack path) where TOwner : IHasDirectiveDefinition, IDefinition { - foreach (DirectiveNode directive in ownerSyntax.Directives) + foreach (var directive in ownerSyntax.Directives) { if (context.TryGetSchemaDirective(directive, out var schemaDirective)) { @@ -38,7 +38,7 @@ public static void AddDirectives( public static string? DeprecationReason( this Language.IHasDirectives syntaxNode) { - DirectiveNode? directive = syntaxNode.Directives.FirstOrDefault( + var directive = syntaxNode.Directives.FirstOrDefault( t => t.Name.Value == WellKnownDirectives.Deprecated); if (directive is null) diff --git a/src/HotChocolate/Core/src/Types/Types/Factories/UnionTypeFactory.cs b/src/HotChocolate/Core/src/Types/Types/Factories/UnionTypeFactory.cs index 53959502ed9..f56661cc4a3 100644 --- a/src/HotChocolate/Core/src/Types/Types/Factories/UnionTypeFactory.cs +++ b/src/HotChocolate/Core/src/Types/Types/Factories/UnionTypeFactory.cs @@ -12,7 +12,7 @@ internal sealed class UnionTypeFactory public UnionType Create(IDescriptorContext context, UnionTypeDefinitionNode node) { var preserveSyntaxNodes = context.Options.PreserveSyntaxNodes; - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new UnionTypeDefinition(node.Name.Value, node.Description?.Value); @@ -24,7 +24,7 @@ public UnionType Create(IDescriptorContext context, UnionTypeDefinitionNode node typeDefinition.SyntaxNode = node; } - foreach (NamedTypeNode namedType in node.Types) + foreach (var namedType in node.Types) { typeDefinition.Types.Add(TypeReference.Create(namedType)); } @@ -36,13 +36,13 @@ public UnionType Create(IDescriptorContext context, UnionTypeDefinitionNode node public UnionTypeExtension Create(IDescriptorContext context, UnionTypeExtensionNode node) { - Stack path = context.GetOrCreateDefinitionStack(); + var path = context.GetOrCreateDefinitionStack(); path.Clear(); var typeDefinition = new UnionTypeDefinition(node.Name.Value); typeDefinition.BindTo = node.GetBindingValue(); - foreach (NamedTypeNode namedType in node.Types) + foreach (var namedType in node.Types) { typeDefinition.Types.Add(TypeReference.Create(namedType)); } diff --git a/src/HotChocolate/Core/src/Types/Types/FieldCollection.cs b/src/HotChocolate/Core/src/Types/Types/FieldCollection.cs index 08287c15a2a..aeed229c795 100644 --- a/src/HotChocolate/Core/src/Types/Types/FieldCollection.cs +++ b/src/HotChocolate/Core/src/Types/Types/FieldCollection.cs @@ -17,7 +17,7 @@ internal FieldCollection(T[] fields) _fields = fields ?? throw new ArgumentNullException(nameof(fields)); _fieldsLookup = new Dictionary(_fields.Length); - foreach (T? field in _fields) + foreach (var field in _fields) { _fieldsLookup.Add(field.Name, field); } @@ -36,7 +36,7 @@ public bool TryGetField(NameString fieldName, [NotNullWhen(true)] out T? field) { if (_fieldsLookup.TryGetValue( fieldName.EnsureNotEmpty(nameof(fieldName)), - out T? item)) + out var item)) { field = item; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/Helpers/CompleteInterfacesHelper.cs b/src/HotChocolate/Core/src/Types/Types/Helpers/CompleteInterfacesHelper.cs index 5327ed1006e..fc74600fe91 100644 --- a/src/HotChocolate/Core/src/Types/Types/Helpers/CompleteInterfacesHelper.cs +++ b/src/HotChocolate/Core/src/Types/Types/Helpers/CompleteInterfacesHelper.cs @@ -26,7 +26,7 @@ public static InterfaceType[] CompleteInterfaces( var implements = new InterfaceType[interfaceReferences.Count]; var index = 0; - foreach (ITypeReference interfaceRef in interfaceReferences) + foreach (var interfaceRef in interfaceReferences) { if (!context.TryGetType(interfaceRef, out InterfaceType? type)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Helpers/FieldDescriptorUtilities.cs b/src/HotChocolate/Core/src/Types/Types/Helpers/FieldDescriptorUtilities.cs index 33c992e6a89..a3560b913ed 100644 --- a/src/HotChocolate/Core/src/Types/Types/Helpers/FieldDescriptorUtilities.cs +++ b/src/HotChocolate/Core/src/Types/Types/Helpers/FieldDescriptorUtilities.cs @@ -22,14 +22,14 @@ public static void AddExplicitFields( where TMember : MemberInfo where TField : FieldDefinitionBase { - foreach (TField fieldDefinition in fieldDefinitions) + foreach (var fieldDefinition in fieldDefinitions) { if (!fieldDefinition.Ignore) { fields[fieldDefinition.Name] = fieldDefinition; } - TMember? member = resolveMember(fieldDefinition); + var member = resolveMember(fieldDefinition); if (member != null) { handledMembers.Add(member); @@ -73,11 +73,11 @@ public static void AddImplicitFields( .OfType() .ToList(); - foreach (TMember member in members) + foreach (var member in members) { if (include?.Invoke(members, member) ?? true) { - TField fieldDefinition = createdFieldDefinition(member); + var fieldDefinition = createdFieldDefinition(member); if (!handledMembers.Contains(member) && !fields.ContainsKey(fieldDefinition.Name) && @@ -107,15 +107,15 @@ public static void DiscoverArguments( try { - foreach (ArgumentDefinition argument in arguments) + foreach (var argument in arguments) { processedNames.Add(argument.Name); } - foreach (ParameterInfo parameter in + foreach (var parameter in context.ResolverCompiler.GetArgumentParameters(method.GetParameters())) { - ArgumentDefinition argumentDefinition = + var argumentDefinition = ArgumentDescriptor .New(context, parameter) .CreateDefinition(); diff --git a/src/HotChocolate/Core/src/Types/Types/Helpers/ResolverContextProxy.cs b/src/HotChocolate/Core/src/Types/Types/Helpers/ResolverContextProxy.cs index a636aacb2e4..3fda1b67eea 100644 --- a/src/HotChocolate/Core/src/Types/Types/Helpers/ResolverContextProxy.cs +++ b/src/HotChocolate/Core/src/Types/Types/Helpers/ResolverContextProxy.cs @@ -77,10 +77,10 @@ public void ReportError(Exception exception, Action? configure = => _resolverContext.ReportError(exception, configure); public IReadOnlyList GetSelections( - ObjectType typeContext, - ISelection? fieldSelection = null, + IObjectType typeContext, + ISelection? selection = null, bool allowInternals = false) - => _resolverContext.GetSelections(typeContext, fieldSelection, allowInternals); + => _resolverContext.GetSelections(typeContext, selection, allowInternals); public T GetQueryRoot() => _resolverContext.GetQueryRoot(); } diff --git a/src/HotChocolate/Core/src/Types/Types/Helpers/TypeNameHelper.cs b/src/HotChocolate/Core/src/Types/Types/Helpers/TypeNameHelper.cs index a01c1ffdcf3..940cabdc8fa 100644 --- a/src/HotChocolate/Core/src/Types/Types/Helpers/TypeNameHelper.cs +++ b/src/HotChocolate/Core/src/Types/Types/Helpers/TypeNameHelper.cs @@ -48,7 +48,7 @@ public static void AddNameFunction( .Extend() .OnBeforeNaming((ctx, definition) => { - IType type = ctx.GetType( + var type = ctx.GetType( ctx.DescriptorContext.TypeInspector.GetTypeRef(dependency)); definition.Name = createName(type.NamedType()); }) diff --git a/src/HotChocolate/Core/src/Types/Types/InputField.cs b/src/HotChocolate/Core/src/Types/Types/InputField.cs index c5e7a2de58d..7bdd803b5ab 100644 --- a/src/HotChocolate/Core/src/Types/Types/InputField.cs +++ b/src/HotChocolate/Core/src/Types/Types/InputField.cs @@ -20,7 +20,7 @@ public InputField(InputFieldDefinition definition, int index) DefaultValue = definition.DefaultValue; Property = definition.Property; - IReadOnlyList formatters = definition.GetFormatters(); + var formatters = definition.GetFormatters(); Formatter = formatters.Count switch { 0 => null, diff --git a/src/HotChocolate/Core/src/Types/Types/InputFormatter.cs b/src/HotChocolate/Core/src/Types/Types/InputFormatter.cs index ca8e4d5ca8d..1e24056aab5 100644 --- a/src/HotChocolate/Core/src/Types/Types/InputFormatter.cs +++ b/src/HotChocolate/Core/src/Types/Types/InputFormatter.cs @@ -74,13 +74,13 @@ private ObjectValueNode FormatValueObject( for (var i = 0; i < fieldValues.Length; i++) { - InputField field = type.Fields[i]; + var field = type.Fields[i]; var fieldValue = fieldValues[i]; Path fieldPath = PathFactory.Instance.Append(path, field.Name); if (field.IsOptional) { - IOptional optional = (IOptional)fieldValue!; + var optional = (IOptional)fieldValue!; if (optional.HasValue) { AddField(optional.Value, field.Name, field.Type, fieldPath); @@ -100,7 +100,7 @@ void AddField( IInputType fieldType, Path fieldPath) { - IValueNode value = FormatValueInternal(fieldValue, fieldType, fieldPath); + var value = FormatValueInternal(fieldValue, fieldType, fieldPath); fields.Add(new ObjectFieldNode(fieldName, value)); } } @@ -208,11 +208,11 @@ private ObjectValueNode FormatResultObject( var fields = new List(); var processed = 0; - foreach (InputField? field in type.Fields) + foreach (var field in type.Fields) { if (map.TryGetValue(field.Name, out var fieldValue)) { - IValueNode value = FormatResultInternal(fieldValue, field.Type, path); + var value = FormatResultInternal(fieldValue, field.Type, path); fields.Add(new ObjectFieldNode(field.Name, value)); processed++; } @@ -222,7 +222,7 @@ private ObjectValueNode FormatResultObject( { var invalidFieldNames = new List(); - foreach (KeyValuePair item in map) + foreach (var item in map) { if (!type.Fields.ContainsField(item.Key)) { diff --git a/src/HotChocolate/Core/src/Types/Types/InputObjectType.Initialization.cs b/src/HotChocolate/Core/src/Types/Types/InputObjectType.Initialization.cs index c3c9e355d50..708b3dfe14f 100644 --- a/src/HotChocolate/Core/src/Types/Types/InputObjectType.Initialization.cs +++ b/src/HotChocolate/Core/src/Types/Types/InputObjectType.Initialization.cs @@ -123,7 +123,7 @@ private object CreateDictionaryInstance(object?[] fieldValues) { var dictionary = new Dictionary(); - foreach (InputField? field in Fields) + foreach (var field in Fields) { dictionary.Add(field.Name, fieldValues[field.Index]); } @@ -135,7 +135,7 @@ private void CreateDictionaryGetValues(object obj, object?[] fieldValues) { var map = (Dictionary)obj; - foreach (InputField? field in Fields) + foreach (var field in Fields) { if (map.TryGetValue(field.Name, out var val)) { diff --git a/src/HotChocolate/Core/src/Types/Types/InputParser.cs b/src/HotChocolate/Core/src/Types/Types/InputParser.cs index 4cecb510930..dd0ae1d378a 100644 --- a/src/HotChocolate/Core/src/Types/Types/InputParser.cs +++ b/src/HotChocolate/Core/src/Types/Types/InputParser.cs @@ -119,10 +119,10 @@ private IList ParseList( { if (resultValue.Kind == SyntaxKind.ListValue) { - IList list = CreateList(type); - IReadOnlyList items = ((ListValueNode)resultValue).Items; + var list = CreateList(type); + var items = ((ListValueNode)resultValue).Items; var flatList = !type.ElementType.IsListType(); - IType elementType = type.ElementType; + var elementType = type.ElementType; if (flatList) { @@ -141,7 +141,7 @@ private IList ParseList( { for (var i = 0; i < items.Count; i++) { - IValueNode item = items[i]; + var item = items[i]; Path itemPath = PathFactory.Instance.Append(path, i); if (item.Kind != SyntaxKind.ListValue) @@ -163,7 +163,7 @@ private IList ParseList( } else { - IList list = CreateList(type); + var list = CreateList(type); list.Add(ParseLiteralInternal( resultValue, type.ElementType, @@ -185,7 +185,7 @@ private object ParseObject( { var processedCount = 0; bool[]? processedBuffer = null; - Span processed = stack <= 256 && type.Fields.Count <= 32 + var processed = stack <= 256 && type.Fields.Count <= 32 ? stackalloc bool[type.Fields.Count] : processedBuffer = ArrayPool.Shared.Rent(type.Fields.Count); @@ -204,7 +204,7 @@ private object ParseObject( try { - IReadOnlyList fields = ((ObjectValueNode)resultValue).Fields; + var fields = ((ObjectValueNode)resultValue).Fields; var oneOf = type.Directives.Contains(WellKnownDirectives.OneOf); if (oneOf && fields.Count is 0) @@ -219,11 +219,11 @@ private object ParseObject( for (var i = 0; i < fields.Count; i++) { - ObjectFieldNode fieldValue = fields[i]; + var fieldValue = fields[i]; - if (type.Fields.TryGetField(fieldValue.Name.Value, out InputField? field)) + if (type.Fields.TryGetField(fieldValue.Name.Value, out var field)) { - IValueNode literal = fieldValue.Value; + var literal = fieldValue.Value; Path fieldPath = PathFactory.Instance.Append(path, field.Name); @@ -276,7 +276,7 @@ private object ParseObject( { if (!processed[i]) { - InputField field = type.Fields[i]; + var field = type.Fields[i]; Path fieldPath = PathFactory.Instance.Append(path, field.Name); fieldValues[i] = CreateDefaultValue(field, fieldPath, stack); } @@ -314,7 +314,7 @@ private object ParseObject( throw new SerializationException(ex.Errors[0].WithPath(path), ex.Type, path); } - IError error = ErrorBuilder.FromError(ex.Errors[0]) + var error = ErrorBuilder.FromError(ex.Errors[0]) .SetPath(path) .SetExtension(nameof(field), field.Coordinate.ToString()) .SetExtension("fieldType", type.Name.Value) @@ -377,7 +377,7 @@ private object DeserializeList( { if (resultValue is IList serializedList) { - IList list = CreateList(type); + var list = CreateList(type); for (var i = 0; i < serializedList.Count; i++) { @@ -418,7 +418,7 @@ private object DeserializeObject(object resultValue, InputObjectType type, Path for (var i = 0; i < type.Fields.Count; i++) { - InputField field = type.Fields[i]; + var field = type.Fields[i]; if (map.TryGetValue(field.Name.Value, out var fieldValue)) { @@ -461,7 +461,7 @@ private object DeserializeObject(object resultValue, InputObjectType type, Path { var invalidFieldNames = new List(); - foreach (string key in map.Keys) + foreach (var key in map.Keys) { if (!type.Fields.ContainsField(key)) { @@ -511,7 +511,7 @@ private object DeserializeObject(object resultValue, InputObjectType type, Path throw new SerializationException(ex.Errors[0].WithPath(path), ex.Type, path); } - IError error = ErrorBuilder.FromError(ex.Errors[0]) + var error = ErrorBuilder.FromError(ex.Errors[0]) .SetPath(path) .SetExtension(nameof(field), field.Coordinate.ToString()) .SetExtension("fieldType", type.Name.Value) diff --git a/src/HotChocolate/Core/src/Types/Types/Interceptors/InterfaceCompletionTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Interceptors/InterfaceCompletionTypeInterceptor.cs index e7f57fa1020..ede10bdd4ae 100644 --- a/src/HotChocolate/Core/src/Types/Types/Interceptors/InterfaceCompletionTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Interceptors/InterfaceCompletionTypeInterceptor.cs @@ -38,7 +38,7 @@ public override void OnTypesInitialized( { // after all types have been initialized we will index the runtime // types of all interfaces. - foreach (TypeInfo interfaceTypeInfo in _typeInfos.Values + foreach (var interfaceTypeInfo in _typeInfos.Values .Where(t => t.Definition.RuntimeType is { } rt && rt != typeof(object) && t.Definition is InterfaceTypeDefinition)) @@ -52,7 +52,7 @@ public override void OnTypesInitialized( } // we now will use the runtime types to infer interface usage ... - foreach (TypeInfo typeInfo in _typeInfos.Values.Where(IsRelevant)) + foreach (var typeInfo in _typeInfos.Values.Where(IsRelevant)) { _interfaceRuntimeTypes.Clear(); @@ -65,9 +65,9 @@ public override void OnTypesInitialized( { // if we detect that this type implements an interface, // we will register it as a dependency. - foreach (Type interfaceRuntimeType in _interfaceRuntimeTypes) + foreach (var interfaceRuntimeType in _interfaceRuntimeTypes) { - TypeInfo interfaceTypeInfo = _allInterfaceRuntimeTypes[interfaceRuntimeType]; + var interfaceTypeInfo = _allInterfaceRuntimeTypes[interfaceRuntimeType]; var interfaceTypeDependency = new TypeDependency( interfaceTypeInfo.Context.TypeReference, TypeDependencyKind.Completed); @@ -88,7 +88,7 @@ private bool IsRelevant(TypeInfo typeInfo) return true; } - Type? runtimeType = typeInfo.Definition.RuntimeType; + var runtimeType = typeInfo.Definition.RuntimeType; return runtimeType is not null && runtimeType != typeof(object); } @@ -113,7 +113,7 @@ public override void OnBeforeCompleteType( _completedFields.Clear(); _backlog.Clear(); - foreach (ITypeReference? interfaceRef in typeDef.Interfaces) + foreach (var interfaceRef in typeDef.Interfaces) { if (completionContext.TryGetType( interfaceRef, @@ -124,7 +124,7 @@ public override void OnBeforeCompleteType( } } - foreach (InterfaceFieldDefinition? field in typeDef.Fields) + foreach (var field in typeDef.Fields) { _completedFields.Add(field.Name); } @@ -138,7 +138,7 @@ public override void OnBeforeCompleteType( _completedFields.Clear(); _backlog.Clear(); - foreach (ITypeReference? interfaceRef in objectTypeDef.Interfaces) + foreach (var interfaceRef in objectTypeDef.Interfaces) { if (completionContext.TryGetType( interfaceRef, @@ -149,7 +149,7 @@ public override void OnBeforeCompleteType( } } - foreach (ObjectFieldDefinition? field in objectTypeDef.Fields) + foreach (var field in objectTypeDef.Fields) { _completedFields.Add(field.Name); } @@ -162,13 +162,13 @@ private void CompleteInterfacesAndFields(IComplexOutputTypeDefinition definition { while (_backlog.Count > 0) { - InterfaceType current = _backlog.Dequeue(); - TypeInfo typeInfo = _typeInfos[current]; + var current = _backlog.Dequeue(); + var typeInfo = _typeInfos[current]; definition.Interfaces.Add(TypeReference.Create(current)); if (definition is InterfaceTypeDefinition interfaceDef) { - foreach (InterfaceFieldDefinition? field in ((InterfaceTypeDefinition)typeInfo.Definition).Fields) + foreach (var field in ((InterfaceTypeDefinition)typeInfo.Definition).Fields) { if (_completedFields.Add(field.Name)) { @@ -177,7 +177,7 @@ private void CompleteInterfacesAndFields(IComplexOutputTypeDefinition definition } } - foreach (InterfaceType? interfaceType in current.Implements) + foreach (var interfaceType in current.Implements) { if (_completed.Add(interfaceType.Name)) { @@ -197,7 +197,7 @@ private static void TryInferInterfaceFromRuntimeType( return; } - foreach (Type interfaceType in runtimeType.GetInterfaces()) + foreach (var interfaceType in runtimeType.GetInterfaces()) { if (allInterfaces.Contains(interfaceType)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Interceptors/MiddlewareValidationTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Interceptors/MiddlewareValidationTypeInterceptor.cs index aa99be27e6d..e4fa46c6dca 100644 --- a/src/HotChocolate/Core/src/Types/Types/Interceptors/MiddlewareValidationTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Interceptors/MiddlewareValidationTypeInterceptor.cs @@ -22,7 +22,7 @@ public override void OnValidateType( { if (definition is ObjectTypeDefinition objectTypeDef) { - foreach (ObjectFieldDefinition field in objectTypeDef.Fields) + foreach (var field in objectTypeDef.Fields) { if (field.MiddlewareDefinitions.Count > 1) { @@ -48,7 +48,7 @@ private void ValidatePipeline( var useSorting = false; var error = false; - foreach (FieldMiddlewareDefinition definition in middlewareDefinitions) + foreach (var definition in middlewareDefinitions) { if (definition.Key is not null) { @@ -108,7 +108,7 @@ private string PrintPipeline( var next = false; var other = false; - foreach (FieldMiddlewareDefinition definition in middlewareDefinitions) + foreach (var definition in middlewareDefinitions) { if (definition.Key is not null) { diff --git a/src/HotChocolate/Core/src/Types/Types/Interceptors/ResolverTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Interceptors/ResolverTypeInterceptor.cs index d9dba4fc19e..a4f650de18d 100644 --- a/src/HotChocolate/Core/src/Types/Types/Interceptors/ResolverTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Interceptors/ResolverTypeInterceptor.cs @@ -68,7 +68,7 @@ definition is ITypeDefinition typeDef && !typeDef.NeedsNameCompletion) { if (typeDef.RuntimeType == typeof(object) && - _runtimeTypes.TryGetValue(typeDef.Name, out Type? type)) + _runtimeTypes.TryGetValue(typeDef.Name, out var type)) { typeDef.RuntimeType = type; } @@ -87,7 +87,7 @@ public override IEnumerable RegisterMoreTypes( var list = new List(); - foreach (ITypeDefinition? typeDef in _typeDefs) + foreach (var typeDef in _typeDefs) { switch (typeDef) { @@ -114,7 +114,7 @@ completionContext.Type is IHasName namedType && definition is ITypeDefinition typeDef) { if (typeDef.RuntimeType == typeof(object) && - _runtimeTypes.TryGetValue(typeDef.Name, out Type? type)) + _runtimeTypes.TryGetValue(typeDef.Name, out var type)) { typeDef.RuntimeType = type; } @@ -135,18 +135,18 @@ private void ApplyResolver(CompletionContext context) { var completed = 0; - foreach (ObjectTypeDefinition objectTypeDef in _typeDefs.OfType()) + foreach (var objectTypeDef in _typeDefs.OfType()) { if (_configs.Contains(objectTypeDef.Name)) { - foreach (FieldResolverConfig config in _configs[objectTypeDef.Name]) + foreach (var config in _configs[objectTypeDef.Name]) { context.Resolvers[config.Field.FieldName] = config; } - foreach (ObjectFieldDefinition field in objectTypeDef.Fields) + foreach (var field in objectTypeDef.Fields) { - if (context.Resolvers.TryGetValue(field.Name, out FieldResolverConfig conf)) + if (context.Resolvers.TryGetValue(field.Name, out var conf)) { field.Resolvers = conf.ToFieldResolverDelegates(); TrySetRuntimeType(context, field, conf); @@ -174,10 +174,10 @@ private void ApplyResolverTypes( if (context.Members.Count > 0) { - foreach (ObjectFieldDefinition field in objectTypeDef.Fields) + foreach (var field in objectTypeDef.Fields) { if (!field.Resolvers.HasResolvers && - context.Members.TryGetValue(field.Name, out MemberInfo? member)) + context.Members.TryGetValue(field.Name, out var member)) { field.ResolverMember = member; @@ -197,7 +197,7 @@ private void ApplyResolverTypes( private void ApplySourceMembers(CompletionContext context) { - foreach (ITypeDefinition definition in + foreach (var definition in _typeDefs.Where(t => t.RuntimeType != typeof(object))) { context.TypesToAnalyze.Enqueue(definition); @@ -228,7 +228,7 @@ private void ApplyObjectSourceMembers( { var initialized = false; - foreach (ObjectFieldDefinition field in objectTypeDef.Fields) + foreach (var field in objectTypeDef.Fields) { if (!initialized && field.Member is null) { @@ -237,7 +237,7 @@ private void ApplyObjectSourceMembers( } if (field.Member is null && - context.Members.TryGetValue(field.Name, out MemberInfo? member)) + context.Members.TryGetValue(field.Name, out var member)) { field.Member = member; @@ -252,7 +252,7 @@ private void ApplyObjectSourceMembers( if (TrySetRuntimeTypeFromMember(context, field.Type, field.Member) is { } u) { - foreach (ITypeDefinition updated in u) + foreach (var updated in u) { context.TypesToAnalyze.Enqueue(updated); } @@ -270,7 +270,7 @@ private void ApplyInputSourceMembers( { var initialized = false; - foreach (InputFieldDefinition field in inputTypeDef.Fields) + foreach (var field in inputTypeDef.Fields) { if (!initialized && field.Property is null) { @@ -279,14 +279,14 @@ private void ApplyInputSourceMembers( } if (field.Property is null && - context.Members.TryGetValue(field.Name, out MemberInfo? member) && + context.Members.TryGetValue(field.Name, out var member) && member is PropertyInfo property) { field.Property = property; if (TrySetRuntimeTypeFromMember(context, field.Type, property) is { } upd) { - foreach (ITypeDefinition updated in upd) + foreach (var updated in upd) { context.TypesToAnalyze.Enqueue(updated); } @@ -303,14 +303,14 @@ private void ApplyEnumSourceMembers( { var initialized = false; - foreach (EnumValueDefinition enumValue in enumTypeDef.Values) + foreach (var enumValue in enumTypeDef.Values) { if (!initialized && enumValue.Member is null) { - foreach (object value in _typeInspector.GetEnumValues(enumTypeDef.RuntimeType)) + foreach (var value in _typeInspector.GetEnumValues(enumTypeDef.RuntimeType)) { - NameString name = _naming.GetEnumValueName(value); - MemberInfo? member = _typeInspector.GetEnumValueMember(enumTypeDef); + var name = _naming.GetEnumValueName(value); + var member = _typeInspector.GetEnumValueMember(enumTypeDef); context.Values.Add(name, (value, member!)); context.ValuesToName.Add(value.ToString()!, (value, member!)); } @@ -340,7 +340,7 @@ private void CollectResolverMembers(CompletionContext context, NameString typeNa return; } - foreach (Type? resolverType in _resolverTypes[typeName]) + foreach (var resolverType in _resolverTypes[typeName]) { CollectSourceMembers(context, resolverType); } @@ -348,9 +348,9 @@ private void CollectResolverMembers(CompletionContext context, NameString typeNa private void CollectSourceMembers(CompletionContext context, Type runtimeType) { - foreach (MemberInfo? member in _typeInspector.GetMembers(runtimeType, false)) + foreach (var member in _typeInspector.GetMembers(runtimeType, false)) { - NameString name = _naming.GetMemberName(member, MemberKind.ObjectField); + var name = _naming.GetMemberName(member, MemberKind.ObjectField); context.Members[name] = member; } } @@ -362,9 +362,9 @@ private void TrySetRuntimeType( { if (config.ResultType != typeof(object) && field.Type is not null && - _typeReferenceResolver.TryGetType(field.Type, out IType? type)) + _typeReferenceResolver.TryGetType(field.Type, out var type)) { - foreach (ITypeDefinition? typeDef in context.TypeDefs[type.NamedType().Name]) + foreach (var typeDef in context.TypeDefs[type.NamedType().Name]) { if (typeDef.RuntimeType == typeof(object)) { @@ -375,27 +375,27 @@ field.Type is not null && } private void TryBindArgumentRuntimeType( - ObjectFieldDefinition field, + ObjectFieldDefinition field, MemberInfo member) { if (member is MethodInfo method) { - foreach (ParameterInfo parameter in + foreach (var parameter in _resolverCompiler.GetArgumentParameters(method.GetParameters())) { _parameters[parameter.Name!] = parameter; } - foreach (ArgumentDefinition argument in field.Arguments) + foreach (var argument in field.Arguments) { - if (_parameters.TryGetValue(argument.Name.Value, out ParameterInfo? parameter)) + if (_parameters.TryGetValue(argument.Name.Value, out var parameter)) { argument.Parameter = parameter; argument.RuntimeType = parameter.ParameterType; - if (_typeReferenceResolver.TryGetType(argument.Type!, out IType? type)) + if (_typeReferenceResolver.TryGetType(argument.Type!, out var type)) { - Type? unwrapped = Unwrap(parameter.ParameterType, type); + var unwrapped = Unwrap(parameter.ParameterType, type); if (unwrapped is not null) { #if NET5_0_OR_GREATER @@ -420,12 +420,12 @@ private void TryBindArgumentRuntimeType( ITypeReference? typeRef, MemberInfo member) { - if (typeRef is not null && _typeReferenceResolver.TryGetType(typeRef, out IType? type)) + if (typeRef is not null && _typeReferenceResolver.TryGetType(typeRef, out var type)) { List? updated = null; Type? runtimeType = null; - foreach (ITypeDefinition? typeDef in context.TypeDefs[type.NamedType().Name]) + foreach (var typeDef in context.TypeDefs[type.NamedType().Name]) { if (typeDef.RuntimeType == typeof(object)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Interceptors/TypeValidationTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Interceptors/TypeValidationTypeInterceptor.cs index cb5e6cfe5a0..28a0924506e 100644 --- a/src/HotChocolate/Core/src/Types/Types/Interceptors/TypeValidationTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Interceptors/TypeValidationTypeInterceptor.cs @@ -119,7 +119,7 @@ private void ReportRuntimeTypeError( ITypeDiscoveryContext discoveryContext, Type runtimeType) { - ISchemaError schemaError = ErrorHelper + var schemaError = ErrorHelper .NoSchemaTypesAllowedAsRuntimeType(discoveryContext.Type, runtimeType); discoveryContext.ReportError(schemaError); } diff --git a/src/HotChocolate/Core/src/Types/Types/InterfaceType.Initialization.cs b/src/HotChocolate/Core/src/Types/Types/InterfaceType.Initialization.cs index 1967032f638..9fc1f4fbef0 100644 --- a/src/HotChocolate/Core/src/Types/Types/InterfaceType.Initialization.cs +++ b/src/HotChocolate/Core/src/Types/Types/InterfaceType.Initialization.cs @@ -83,7 +83,7 @@ private void CompleteAbstractTypeResolver(ResolveAbstractType? resolveAbstractTy { types ??= _schema.GetPossibleTypes(this); - foreach (ObjectType type in types) + foreach (var type in types) { if (type.IsInstanceOfType(c, r)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionFields.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionFields.cs index a74dbe898b7..69f19533bf7 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionFields.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionFields.cs @@ -56,7 +56,7 @@ internal static ObjectFieldDefinition CreateTypeField(IDescriptorContext context static INamedType? Resolve(IPureResolverContext ctx) { var name = ctx.ArgumentValue("name"); - return ctx.Schema.TryGetType(name, out INamedType? type) ? type : null; + return ctx.Schema.TryGetType(name, out var type) ? type : null; } return CreateDefinition(descriptor); @@ -80,7 +80,7 @@ static string Resolve(IPureResolverContext ctx) private static ObjectFieldDefinition CreateDefinition(ObjectFieldDescriptor descriptor) { - ObjectFieldDefinition definition = descriptor.CreateDefinition(); + var definition = descriptor.CreateDefinition(); definition.IsIntrospectionField = true; return definition; } diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionTypeInterceptor.cs index 8e3b6ef4595..ad5a54d0dee 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/IntrospectionTypeInterceptor.cs @@ -16,7 +16,7 @@ public override void OnBeforeCompleteType( if (definition is ObjectTypeDefinition objectTypeDefinition) { var position = 0; - IDescriptorContext context = completionContext.DescriptorContext; + var context = completionContext.DescriptorContext; if (completionContext.IsQueryType ?? false) { diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__AppliedDirective.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__AppliedDirective.cs index fdeca1373ae..e608814c5cb 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__AppliedDirective.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__AppliedDirective.cs @@ -20,8 +20,8 @@ internal sealed class __AppliedDirective : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference nonNullStringType = Parse($"{ScalarNames.String}!"); - SyntaxTypeReference locationListType = Parse($"[{nameof(__DirectiveArgument)}!]!"); + var nonNullStringType = Parse($"{ScalarNames.String}!"); + var locationListType = Parse($"[{nameof(__DirectiveArgument)}!]!"); return new ObjectTypeDefinition( Names.__AppliedDirective, diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__Directive.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__Directive.cs index 62ff3b380a8..a67c52fb5c2 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__Directive.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__Directive.cs @@ -18,12 +18,12 @@ internal sealed class __Directive : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference stringType = Create(ScalarNames.String); - SyntaxTypeReference nonNullStringType = Parse($"{ScalarNames.String}!"); - SyntaxTypeReference nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); - SyntaxTypeReference booleanType = Parse($"{ScalarNames.Boolean}"); - SyntaxTypeReference argumentListType = Parse($"[{nameof(__InputValue)}!]!"); - SyntaxTypeReference locationListType = Parse($"[{nameof(__DirectiveLocation)}!]!"); + var stringType = Create(ScalarNames.String); + var nonNullStringType = Parse($"{ScalarNames.String}!"); + var nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); + var booleanType = Parse($"{ScalarNames.Boolean}"); + var argumentListType = Parse($"[{nameof(__InputValue)}!]!"); + var locationListType = Parse($"[{nameof(__DirectiveLocation)}!]!"); return new ObjectTypeDefinition( Names.__Directive, @@ -87,7 +87,7 @@ public static object Locations(IPureResolverContext context) public static object Arguments(IPureResolverContext context) { - DirectiveType directive = context.Parent(); + var directive = context.Parent(); return context.ArgumentValue(Names.IncludeDeprecated) ? directive.Arguments : directive.Arguments.Where(t => !t.IsDeprecated); @@ -95,7 +95,7 @@ public static object Arguments(IPureResolverContext context) public static object OnOperation(IPureResolverContext context) { - ICollection locations = + var locations = context.Parent().Locations; return locations.Contains(DirectiveLocation.Query) @@ -105,7 +105,7 @@ public static object OnOperation(IPureResolverContext context) public static object OnFragment(IPureResolverContext context) { - ICollection locations = + var locations = context.Parent().Locations; return locations.Contains(DirectiveLocation.InlineFragment) @@ -115,7 +115,7 @@ public static object OnFragment(IPureResolverContext context) public static object OnField(IPureResolverContext context) { - ICollection locations = + var locations = context.Parent().Locations; return locations.Contains(DirectiveLocation.Field); diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__DirectiveArgument.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__DirectiveArgument.cs index ada88d4e60f..a7aeb7c70dc 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__DirectiveArgument.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__DirectiveArgument.cs @@ -22,7 +22,7 @@ internal sealed class __DirectiveArgument : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference nonNullStringType = Parse($"{ScalarNames.String}!"); + var nonNullStringType = Parse($"{ScalarNames.String}!"); return new ObjectTypeDefinition( Names.__DirectiveArgument, diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__EnumValue.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__EnumValue.cs index bf3a1e0d520..8af84cf0299 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__EnumValue.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__EnumValue.cs @@ -16,10 +16,10 @@ internal sealed class __EnumValue : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference stringType = Create(ScalarNames.String); - SyntaxTypeReference nonNullStringType = Parse($"{ScalarNames.String}!"); - SyntaxTypeReference nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); - SyntaxTypeReference appDirectiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); + var stringType = Create(ScalarNames.String); + var nonNullStringType = Parse($"{ScalarNames.String}!"); + var nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); + var appDirectiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); var def = new ObjectTypeDefinition( Names.__EnumValue, diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__Field.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__Field.cs index 42c6cab5059..073e849a8ab 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__Field.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__Field.cs @@ -17,13 +17,13 @@ internal sealed class __Field : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference stringType = Create(ScalarNames.String); - SyntaxTypeReference nonNullStringType = Parse($"{ScalarNames.String}!"); - SyntaxTypeReference nonNullTypeType = Parse($"{nameof(__Type)}!"); - SyntaxTypeReference nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); - SyntaxTypeReference booleanType = Parse($"{ScalarNames.Boolean}"); - SyntaxTypeReference argumentListType = Parse($"[{nameof(__InputValue)}!]!"); - SyntaxTypeReference directiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); + var stringType = Create(ScalarNames.String); + var nonNullStringType = Parse($"{ScalarNames.String}!"); + var nonNullTypeType = Parse($"{nameof(__Type)}!"); + var nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); + var booleanType = Parse($"{ScalarNames.Boolean}"); + var argumentListType = Parse($"[{nameof(__InputValue)}!]!"); + var directiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); var def = new ObjectTypeDefinition( Names.__Field, @@ -75,7 +75,7 @@ public static string Name(IPureResolverContext context) public static object? Arguments(IPureResolverContext context) { - IOutputField field = context.Parent(); + var field = context.Parent(); return context.ArgumentValue(Names.IncludeDeprecated) ? field.Arguments : field.Arguments.Where(t => !t.IsDeprecated); diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__InputValue.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__InputValue.cs index 030a10a4d83..d09c3291880 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__InputValue.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__InputValue.cs @@ -18,11 +18,11 @@ internal sealed class __InputValue : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference stringType = Create(ScalarNames.String); - SyntaxTypeReference nonNullStringType = Parse($"{ScalarNames.String}!"); - SyntaxTypeReference nonNullTypeType = Parse($"{nameof(__Type)}!"); - SyntaxTypeReference nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); - SyntaxTypeReference appDirectiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); + var stringType = Create(ScalarNames.String); + var nonNullStringType = Parse($"{ScalarNames.String}!"); + var nonNullTypeType = Parse($"{nameof(__Type)}!"); + var nonNullBooleanType = Parse($"{ScalarNames.Boolean}!"); + var appDirectiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); var def = new ObjectTypeDefinition( Names.__InputValue, @@ -77,7 +77,7 @@ public static object IsDeprecated(IPureResolverContext context) public static object? DefaultValue(IPureResolverContext context) { - IInputField field = context.Parent(); + var field = context.Parent(); return field.DefaultValue.IsNull() ? null : field.DefaultValue!.Print(); } diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__Schema.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__Schema.cs index b73ecece357..5b21f04bbbb 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__Schema.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__Schema.cs @@ -16,12 +16,12 @@ internal sealed class __Schema : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference stringType = Create(ScalarNames.String); - SyntaxTypeReference typeListType = Parse($"[{nameof(__Type)}!]!"); - SyntaxTypeReference typeType = Create(nameof(__Type)); - SyntaxTypeReference nonNullTypeType = Parse($"{nameof(__Type)}!"); - SyntaxTypeReference directiveListType = Parse($"[{nameof(__Directive)}!]!"); - SyntaxTypeReference appDirectiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); + var stringType = Create(ScalarNames.String); + var typeListType = Parse($"[{nameof(__Type)}!]!"); + var typeType = Create(nameof(__Type)); + var nonNullTypeType = Parse($"{nameof(__Type)}!"); + var directiveListType = Parse($"[{nameof(__Directive)}!]!"); + var appDirectiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); var def = new ObjectTypeDefinition(Names.__Schema, Schema_Description, typeof(ISchema)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Introspection/__Type.cs b/src/HotChocolate/Core/src/Types/Types/Introspection/__Type.cs index 9a1e754a4b2..ae70022fb62 100644 --- a/src/HotChocolate/Core/src/Types/Types/Introspection/__Type.cs +++ b/src/HotChocolate/Core/src/Types/Types/Introspection/__Type.cs @@ -17,15 +17,15 @@ internal sealed class __Type : ObjectType { protected override ObjectTypeDefinition CreateDefinition(ITypeDiscoveryContext context) { - SyntaxTypeReference stringType = Create(ScalarNames.String); - SyntaxTypeReference booleanType = Create(ScalarNames.Boolean); - SyntaxTypeReference kindType = Parse($"{nameof(__TypeKind)}!"); - SyntaxTypeReference typeType = Create(nameof(__Type)); - SyntaxTypeReference fieldListType = Parse($"[{nameof(__Field)}!]"); - SyntaxTypeReference typeListType = Parse($"[{nameof(__Type)}!]"); - SyntaxTypeReference enumValueListType = Parse($"[{nameof(__EnumValue)}!]"); - SyntaxTypeReference inputValueListType = Parse($"[{nameof(__InputValue)}!]"); - SyntaxTypeReference directiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); + var stringType = Create(ScalarNames.String); + var booleanType = Create(ScalarNames.Boolean); + var kindType = Parse($"{nameof(__TypeKind)}!"); + var typeType = Create(nameof(__Type)); + var fieldListType = Parse($"[{nameof(__Field)}!]"); + var typeListType = Parse($"[{nameof(__Type)}!]"); + var enumValueListType = Parse($"[{nameof(__EnumValue)}!]"); + var inputValueListType = Parse($"[{nameof(__InputValue)}!]"); + var directiveListType = Parse($"[{nameof(__AppliedDirective)}!]!"); var def = new ObjectTypeDefinition( Names.__Type, @@ -116,7 +116,7 @@ private static class Resolvers public static object? Fields(IPureResolverContext context) { - IType type = context.Parent(); + var type = context.Parent(); var includeDeprecated = context.ArgumentValue(Names.IncludeDeprecated); if (type is IComplexOutputType ct) diff --git a/src/HotChocolate/Core/src/Types/Types/ObjectType.Initialization.cs b/src/HotChocolate/Core/src/Types/Types/ObjectType.Initialization.cs index ce202378e94..a911ca4801d 100644 --- a/src/HotChocolate/Core/src/Types/Types/ObjectType.Initialization.cs +++ b/src/HotChocolate/Core/src/Types/Types/ObjectType.Initialization.cs @@ -81,7 +81,7 @@ private void CompleteTypeResolver(ITypeCompletionContext context) { if (context.IsOfType is not null) { - IsOfTypeFallback isOfType = context.IsOfType; + var isOfType = context.IsOfType; _isOfType = (ctx, obj) => isOfType(this, ctx, obj); } else if (RuntimeType == typeof(object)) @@ -101,7 +101,7 @@ private bool ValidateFields( { var hasErrors = false; - foreach (ObjectFieldDefinition field in definition.Fields.Where(t => t.Type is null)) + foreach (var field in definition.Fields.Where(t => t.Type is null)) { hasErrors = true; context.ReportError(ObjectType_UnableToInferOrResolveType(Name, this, field)); @@ -124,7 +124,7 @@ private bool IsOfTypeWithName( return true; } - Type type = result.GetType(); + var type = result.GetType(); return Name.Equals(type.Name); } } diff --git a/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension.cs b/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension.cs index c092c3fa1f2..9169c47ed85 100644 --- a/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension.cs +++ b/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension.cs @@ -122,13 +122,13 @@ private void ApplyGlobalFieldIgnores( ObjectTypeDefinition extensionDef, ObjectTypeDefinition typeDef) { - IReadOnlyList fieldIgnores = extensionDef.GetFieldIgnores(); + var fieldIgnores = extensionDef.GetFieldIgnores(); if (fieldIgnores.Count > 0) { var fields = new List(); - foreach (ObjectFieldBinding binding in fieldIgnores) + foreach (var binding in fieldIgnores) { switch (binding.Type) { @@ -151,7 +151,7 @@ private void ApplyGlobalFieldIgnores( } } - foreach (ObjectFieldDefinition? field in fields) + foreach (var field in fields) { typeDef.Fields.Remove(field); } diff --git a/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension~1.cs b/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension~1.cs index 22cbbab5e8c..825f7524297 100644 --- a/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/ObjectTypeExtension~1.cs @@ -25,7 +25,7 @@ public ObjectTypeExtension(Action> configure) protected override ObjectTypeDefinition CreateDefinition( ITypeDiscoveryContext context) { - ObjectTypeExtensionDescriptor descriptor = + var descriptor = ObjectTypeDescriptor.NewExtension(context.DescriptorContext); _configure!(descriptor); diff --git a/src/HotChocolate/Core/src/Types/Types/Pagination/PagingHelper.cs b/src/HotChocolate/Core/src/Types/Types/Pagination/PagingHelper.cs index 4f99456d9cd..01aeeffa1ad 100644 --- a/src/HotChocolate/Core/src/Types/Types/Pagination/PagingHelper.cs +++ b/src/HotChocolate/Core/src/Types/Types/Pagination/PagingHelper.cs @@ -30,7 +30,7 @@ public static IObjectFieldDescriptor UsePaging( FieldMiddlewareDefinition placeholder = new(_ => _ => default, key: Paging); - ObjectFieldDefinition definition = descriptor.Extend().Definition; + var definition = descriptor.Extend().Definition; definition.MiddlewareDefinitions.Add(placeholder); definition.Configurations.Add( new CompleteConfiguration( @@ -60,10 +60,10 @@ private static void ApplyConfiguration( options = context.GetSettings(options); entityType ??= context.GetType(definition.Type!).ToRuntimeType(); - IExtendedType source = GetSourceType(context.TypeInspector, definition, entityType); - IPagingProvider pagingProvider = resolvePagingProvider(context.Services, source, name); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(source, options); - FieldMiddleware middleware = CreateMiddleware(pagingHandler); + var source = GetSourceType(context.TypeInspector, definition, entityType); + var pagingProvider = resolvePagingProvider(context.Services, source, name); + var pagingHandler = pagingProvider.CreateHandler(source, options); + var middleware = CreateMiddleware(pagingHandler); var index = definition.MiddlewareDefinitions.IndexOf(placeholder); definition.MiddlewareDefinitions[index] = new(middleware, key: Paging); @@ -82,7 +82,7 @@ private static IExtendedType GetSourceType( } // Otherwise we will look at specified members and extract the return type. - MemberInfo? member = definition.ResolverMember ?? definition.Member; + var member = definition.ResolverMember ?? definition.Member; if (member is not null) { return typeInspector.GetReturnType(member, true); @@ -107,7 +107,7 @@ public static IExtendedType GetSchemaType( if (type is null && member is not null && typeInspector.GetOutputReturnTypeRef(member) is ExtendedTypeReference r && - typeInspector.TryCreateTypeInfo(r.Type, out ITypeInfo? typeInfo)) + typeInspector.TryCreateTypeInfo(r.Type, out var typeInfo)) { // if the member has already associated a schema type we will just take it. // Since we want the entity element we are going to take @@ -125,14 +125,14 @@ member is not null && if (SchemaTypeResolver.TryInferSchemaType( typeInspector, r.WithType(typeInspector.GetType(typeInfo.NamedType)), - out ExtendedTypeReference? schemaTypeRef)) + out var schemaTypeRef)) { // if we are able to infer the type we will reconstruct its structure so that // we can correctly extract from it the element type with the correct // nullability information. - Type current = schemaTypeRef.Type.Type; + var current = schemaTypeRef.Type.Type; - foreach (TypeComponent component in typeInfo.Components.Reverse().Skip(1)) + foreach (var component in typeInfo.Components.Reverse().Skip(1)) { if (component.Kind == TypeComponentKind.NonNull) { @@ -166,7 +166,7 @@ public static bool TryGetNamedType( { if (member is not null && typeInspector.GetReturnType(member) is { } returnType && - typeInspector.TryCreateTypeInfo(returnType, out ITypeInfo? typeInfo)) + typeInspector.TryCreateTypeInfo(returnType, out var typeInfo)) { namedType = typeInfo.NamedType; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/Attributes/NodeAttribute.cs b/src/HotChocolate/Core/src/Types/Types/Relay/Attributes/NodeAttribute.cs index 7decf02f7cf..2d06e53f318 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/Attributes/NodeAttribute.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/Attributes/NodeAttribute.cs @@ -52,7 +52,7 @@ public override void OnConfigure( // first we try to resolve the id field. if (IdField is not null) { - MemberInfo? idField = type.GetMember(IdField).FirstOrDefault(); + var idField = type.GetMember(IdField).FirstOrDefault(); if (idField is null) { @@ -75,7 +75,7 @@ public override void OnConfigure( { if (NodeResolver is not null) { - MethodInfo? method = NodeResolverType.GetMethod( + var method = NodeResolverType.GetMethod( NodeResolver, Instance | Static | Public | FlattenHierarchy); @@ -95,7 +95,7 @@ public override void OnConfigure( } else if (NodeResolver is not null) { - MethodInfo? method = type.GetMethod( + var method = type.GetMethod( NodeResolver, Instance | Static | Public | FlattenHierarchy); @@ -108,7 +108,7 @@ public override void OnConfigure( } else if (definition.RuntimeType != typeof(object) && definition.RuntimeType != type) { - MethodInfo? method = descriptorContext.TypeInspector.GetNodeResolverMethod( + var method = descriptorContext.TypeInspector.GetNodeResolverMethod( definition.RuntimeType, type); @@ -120,7 +120,7 @@ public override void OnConfigure( if (definition.Fields.Any( t => t.Member == method || t.ResolverMember == method)) { - foreach (ObjectFieldDefinition? fieldDefinition in definition.Fields + foreach (var fieldDefinition in definition.Fields .Where(t => t.Member == method || t.ResolverMember == method) .ToArray()) { diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor.cs b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor.cs index 445e0242a4d..3735305ba6b 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor.cs @@ -38,7 +38,7 @@ internal void ConfigureNodeField(IObjectTypeDescriptor typeDescriptor) { if (Definition.IdMember is null) { - IObjectFieldDescriptor descriptor = typeDescriptor + var descriptor = typeDescriptor .Field(NodeType.Names.Id) .Type>(); @@ -46,7 +46,7 @@ internal void ConfigureNodeField(IObjectTypeDescriptor typeDescriptor) } else { - IObjectFieldDescriptor descriptor = typeDescriptor + var descriptor = typeDescriptor .Field(Definition.IdMember) .Name(NodeType.Names.Id) .Type>(); @@ -59,7 +59,7 @@ protected override IObjectFieldDescriptor ConfigureNodeField() { if (Definition.IdMember is null) { - IObjectFieldDescriptor descriptor = _typeDescriptor + var descriptor = _typeDescriptor .Field(NodeType.Names.Id) .Type>(); @@ -67,7 +67,7 @@ protected override IObjectFieldDescriptor ConfigureNodeField() } else { - IObjectFieldDescriptor descriptor = _typeDescriptor + var descriptor = _typeDescriptor .Field(Definition.IdMember) .Name(NodeType.Names.Id) .Type>(); diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptorBase.cs b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptorBase.cs index a7cdaac88cf..bd3964f31f5 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptorBase.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptorBase.cs @@ -63,11 +63,11 @@ public IObjectFieldDescriptor ResolveNodeWith( throw new ArgumentNullException(nameof(method)); } - MemberInfo? member = method.TryExtractMember(); + var member = method.TryExtractMember(); if (member is MethodInfo m) { - FieldResolverDelegates resolver = + var resolver = Context.ResolverCompiler.CompileResolve( m, typeof(object), @@ -88,7 +88,7 @@ public IObjectFieldDescriptor ResolveNodeWith(MethodInfo method) throw new ArgumentNullException(nameof(method)); } - FieldResolverDelegates resolver = + var resolver = Context.ResolverCompiler.CompileResolve( method, typeof(object), @@ -109,7 +109,7 @@ private static ResultConverterDefinition Converter public static IObjectFieldDescriptor TryAdd(IObjectFieldDescriptor descriptor) { - IList converters = + var converters = descriptor.Extend().Definition.ResultConverters; if (!converters.Contains(Converter)) diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~1.cs b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~1.cs index ead6424e0ab..009c4564d10 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~1.cs @@ -53,7 +53,7 @@ protected override IObjectFieldDescriptor ConfigureNodeField() if (Definition.IdMember is null) { - IObjectFieldDescriptor descriptor = _typeDescriptor + var descriptor = _typeDescriptor .Field(NodeType.Names.Id) .Type>(); @@ -61,7 +61,7 @@ protected override IObjectFieldDescriptor ConfigureNodeField() } else { - IObjectFieldDescriptor descriptor = _typeDescriptor + var descriptor = _typeDescriptor .Field(Definition.IdMember) .Name(NodeType.Names.Id) .Type>(); @@ -78,7 +78,7 @@ public INodeDescriptor IdField( throw new ArgumentNullException(nameof(propertyOrMethod)); } - MemberInfo? member = propertyOrMethod.TryExtractMember(); + var member = propertyOrMethod.TryExtractMember(); if (member is MethodInfo or PropertyInfo) { diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~2.cs b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~2.cs index e22295d5e5a..a2a3f8e3dd2 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~2.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/Descriptors/NodeDescriptor~2.cs @@ -71,11 +71,11 @@ public IObjectFieldDescriptor ResolveNodeWith( throw new ArgumentNullException(nameof(method)); } - MemberInfo? member = method.TryExtractMember(); + var member = method.TryExtractMember(); if (member is MethodInfo m) { - FieldResolverDelegates resolver = + var resolver = Context.ResolverCompiler.CompileResolve( m, typeof(object), @@ -96,7 +96,7 @@ public IObjectFieldDescriptor ResolveNodeWith(MethodInfo method) throw new ArgumentNullException(nameof(method)); } - FieldResolverDelegates resolver = + var resolver = Context.ResolverCompiler.CompileResolve( method, typeof(object), diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/Extensions/RelayIdFieldHelpers.cs b/src/HotChocolate/Core/src/Types/Types/Relay/Extensions/RelayIdFieldHelpers.cs index 7995a07adb0..88bd9206d40 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/Extensions/RelayIdFieldHelpers.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/Extensions/RelayIdFieldHelpers.cs @@ -92,8 +92,8 @@ private static void RewriteDefinition( { if (definition.Type is ExtendedTypeReference typeReference) { - ITypeInfo typeInfo = context.TypeInspector.CreateTypeInfo(typeReference.Type); - IExtendedType type = RewriteType(context.TypeInspector, typeInfo); + var typeInfo = context.TypeInspector.CreateTypeInfo(typeReference.Type); + var type = RewriteType(context.TypeInspector, typeInfo); definition.Type = typeReference.WithType(type); } else @@ -106,11 +106,11 @@ private static void RewriteDefinition( private static IExtendedType RewriteType(ITypeInspector typeInspector, ITypeInfo typeInfo) { - Type current = typeof(IdType); + var current = typeof(IdType); if (typeInfo.Components.Count > 1) { - foreach (TypeComponent component in typeInfo.Components.Reverse().Skip(1)) + foreach (var component in typeInfo.Components.Reverse().Skip(1)) { if (component.Kind == TypeComponentKind.NonNull) { @@ -131,7 +131,7 @@ private static void AddSerializerToInputField( ArgumentDefinition definition, NameString typeName) { - ITypeInspector typeInspector = completionContext.TypeInspector; + var typeInspector = completionContext.TypeInspector; IExtendedType? resultType; if (definition is InputFieldDefinition { RuntimeType: { } runtimeType }) @@ -167,7 +167,7 @@ private static void AddSerializerToObjectField( ResultConverterDefinition placeholder, NameString typeName) { - ITypeInspector typeInspector = completionContext.TypeInspector; + var typeInspector = completionContext.TypeInspector; IExtendedType? resultType; if (definition.ResultType is not null) @@ -190,7 +190,7 @@ private static void AddSerializerToObjectField( completionContext.DescriptorContext.SchemaCompleted += (_, args) => schemaName = args.Schema.Name; - IIdSerializer serializer = + var serializer = completionContext.Services.GetService() ?? new IdSerializer(); var index = definition.ResultConverters.IndexOf(placeholder); @@ -232,7 +232,7 @@ private static IInputValueFormatter CreateSerializer( IExtendedType resultType, NameString typeName) { - IIdSerializer serializer = + var serializer = completionContext.Services.GetService() ?? (_idSerializer ??= new IdSerializer()); diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/GlobalIdInputValueFormatter.cs b/src/HotChocolate/Core/src/Types/Types/Relay/GlobalIdInputValueFormatter.cs index 1bbe80eecf8..8f23f01dda9 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/GlobalIdInputValueFormatter.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/GlobalIdInputValueFormatter.cs @@ -69,9 +69,9 @@ public GlobalIdInputValueFormatter( if (runtimeValue is IEnumerable nullableIdEnumerable) { - IList list = _createList(); + var list = _createList(); - foreach (IdValue? idv in nullableIdEnumerable) + foreach (var idv in nullableIdEnumerable) { if (!idv.HasValue) { @@ -90,9 +90,9 @@ public GlobalIdInputValueFormatter( if (runtimeValue is IEnumerable idEnumerable) { - IList list = _createList(); + var list = _createList(); - foreach (IdValue idv in idEnumerable) + foreach (var idv in idEnumerable) { if (!_validateType || _typeName.Equals(idv.TypeName)) { @@ -107,9 +107,9 @@ public GlobalIdInputValueFormatter( { try { - IList list = _createList(); + var list = _createList(); - foreach (string? sv in stringEnumerable) + foreach (var sv in stringEnumerable) { if (sv is null) { @@ -148,8 +148,8 @@ private static Func CreateListFactory(IExtendedType resultType) { if (resultType.IsArrayOrList) { - Type listType = typeof(List<>).MakeGenericType(resultType.ElementType!.Source); - ConstructorInfo constructor = listType.GetConstructors().Single(t => t.GetParameters().Length == 0); + var listType = typeof(List<>).MakeGenericType(resultType.ElementType!.Source); + var constructor = listType.GetConstructors().Single(t => t.GetParameters().Length == 0); Expression create = Expression.New(constructor); return Expression.Lambda>(create).Compile(); } diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/IdSerializer.cs b/src/HotChocolate/Core/src/Types/Types/Relay/IdSerializer.cs index 6448ee13da6..9b87af1921c 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/IdSerializer.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/IdSerializer.cs @@ -75,7 +75,7 @@ public string Serialize(NameString schemaName, NameString typeName, T id) byte[] serializedArray = null; - Span serialized = serializedSize <= _stackallocThreshold + var serialized = serializedSize <= _stackallocThreshold ? stackalloc byte[serializedSize] : (serializedArray = ArrayPool.Shared.Rent(serializedSize)); @@ -95,7 +95,7 @@ public string Serialize(NameString schemaName, NameString typeName, T id) serialized.Slice(position, nameSize)); serialized[position++] = _separator; - Span value = serialized.Slice(position + 1); + var value = serialized.Slice(position + 1); int bytesWritten; switch (id) @@ -130,7 +130,7 @@ public string Serialize(NameString schemaName, NameString typeName, T id) break; } - OperationStatus operationStatus = + var operationStatus = Base64.EncodeToUtf8InPlace(serialized, position, out bytesWritten); if (operationStatus != OperationStatus.Done) @@ -187,7 +187,7 @@ public IdValue Deserialize(string serializedId) byte[] serializedArray = null; - Span serialized = serializedSize <= _stackallocThreshold + var serialized = serializedSize <= _stackallocThreshold ? stackalloc byte[serializedSize] : (serializedArray = ArrayPool.Shared.Rent(serializedSize)); @@ -196,7 +196,7 @@ public IdValue Deserialize(string serializedId) var bytesWritten = CopyString(serializedId, serialized); serialized = serialized.Slice(0, bytesWritten); - OperationStatus operationStatus = + var operationStatus = Base64.DecodeFromUtf8InPlace(serialized, out bytesWritten); if (operationStatus != OperationStatus.Done) @@ -209,7 +209,7 @@ public IdValue Deserialize(string serializedId) int nextSeparator; - Span decoded = serialized.Slice(0, bytesWritten); + var decoded = serialized.Slice(0, bytesWritten); NameString schemaName = null; diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/NodeFieldTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Relay/NodeFieldTypeInterceptor.cs index 3ea0965457d..15e2469ec1d 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/NodeFieldTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/NodeFieldTypeInterceptor.cs @@ -37,13 +37,13 @@ public override void OnBeforeCompleteType( if ((completionContext.IsQueryType ?? false) && definition is ObjectTypeDefinition objectTypeDefinition) { - ITypeInspector typeInspector = completionContext.TypeInspector; + var typeInspector = completionContext.TypeInspector; - IIdSerializer serializer = + var serializer = completionContext.Services.GetService() ?? new IdSerializer(); - ObjectFieldDefinition typeNameField = objectTypeDefinition.Fields.First( + var typeNameField = objectTypeDefinition.Fields.First( t => t.Name.Equals(IntrospectionFields.TypeName) && t.IsIntrospectionField); var index = objectTypeDefinition.Fields.IndexOf(typeNameField); @@ -58,8 +58,8 @@ private static void CreateNodeField( IList fields, int index) { - ExtendedTypeReference node = typeInspector.GetTypeRef(typeof(NodeType)); - ExtendedTypeReference id = typeInspector.GetTypeRef(typeof(NonNullType)); + var node = typeInspector.GetTypeRef(typeof(NodeType)); + var id = typeInspector.GetTypeRef(typeof(NonNullType)); var field = new ObjectFieldDefinition( Node, @@ -78,8 +78,8 @@ private static void CreateNodesField( IList fields, int index) { - SyntaxTypeReference nodes = TypeReference.Parse("[Node]!"); - SyntaxTypeReference ids = TypeReference.Parse("[ID!]!"); + var nodes = TypeReference.Parse("[Node]!"); + var ids = TypeReference.Parse("[ID!]!"); var field = new ObjectFieldDefinition( Nodes, @@ -98,16 +98,16 @@ private static void CreateNodesField( IIdSerializer serializer, NameString argumentName) { - StringValueNode nodeId = context.ArgumentLiteral(argumentName); - IdValue deserializedId = serializer.Deserialize(nodeId.Value); - NameString typeName = deserializedId.TypeName; + var nodeId = context.ArgumentLiteral(argumentName); + var deserializedId = serializer.Deserialize(nodeId.Value); + var typeName = deserializedId.TypeName; context.SetLocalState(NodeId, nodeId.Value); context.SetLocalState(InternalId, deserializedId.Value); context.SetLocalState(InternalType, typeName); context.SetLocalState(WellKnownContextData.IdValue, deserializedId); - if (context.Schema.TryGetType(typeName, out ObjectType? type) && + if (context.Schema.TryGetType(typeName, out var type) && type.ContextData.TryGetValue(NodeResolver, out var o) && o is FieldResolverDelegate resolver) { @@ -123,8 +123,8 @@ private static void CreateNodesField( { if (context.ArgumentKind(Ids) == ValueKind.List) { - ListValueNode list = context.ArgumentLiteral(Ids); - Task[] tasks = ArrayPool>.Shared.Rent(list.Items.Count); + var list = context.ArgumentLiteral(Ids); + var tasks = ArrayPool>.Shared.Rent(list.Items.Count); var result = new object?[list.Items.Count]; try @@ -134,9 +134,9 @@ private static void CreateNodesField( context.RequestAborted.ThrowIfCancellationRequested(); // it is guaranteed that this is always a string literal. - StringValueNode nodeId = (StringValueNode)list.Items[i]; - IdValue deserializedId = serializer.Deserialize(nodeId.Value); - NameString typeName = deserializedId.TypeName; + var nodeId = (StringValueNode)list.Items[i]; + var deserializedId = serializer.Deserialize(nodeId.Value); + var typeName = deserializedId.TypeName; context.SetLocalState(NodeId, nodeId.Value); context.SetLocalState(InternalId, deserializedId.Value); @@ -144,7 +144,7 @@ private static void CreateNodesField( context.SetLocalState(WellKnownContextData.IdValue, deserializedId); tasks[i] = - context.Schema.TryGetType(typeName, out ObjectType? type) && + context.Schema.TryGetType(typeName, out var type) && type.ContextData.TryGetValue(NodeResolver, out var o) && o is FieldResolverDelegate resolver ? resolver.Invoke(new ResolverContextProxy(context)).AsTask() @@ -155,7 +155,7 @@ o is FieldResolverDelegate resolver { context.RequestAborted.ThrowIfCancellationRequested(); - Task task = tasks[i]; + var task = tasks[i]; if (task.IsCompleted) { if (task.Exception is null) diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/NodeResolver~2.cs b/src/HotChocolate/Core/src/Types/Types/Relay/NodeResolver~2.cs index 0ae481b3ff4..dd51316a1f1 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/NodeResolver~2.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/NodeResolver~2.cs @@ -28,7 +28,7 @@ async Task INodeResolver.ResolveAsync( return await ResolveAsync(context, c).ConfigureAwait(false); } - ITypeConverter typeConverter = context.Service().GetTypeConverter(); + var typeConverter = context.Service().GetTypeConverter(); c = typeConverter.Convert(id); return await ResolveAsync(context, c).ConfigureAwait(false); } diff --git a/src/HotChocolate/Core/src/Types/Types/Relay/QueryFieldTypeInterceptor.cs b/src/HotChocolate/Core/src/Types/Types/Relay/QueryFieldTypeInterceptor.cs index 1c601a5688d..8c038bf2105 100644 --- a/src/HotChocolate/Core/src/Types/Types/Relay/QueryFieldTypeInterceptor.cs +++ b/src/HotChocolate/Core/src/Types/Types/Relay/QueryFieldTypeInterceptor.cs @@ -43,7 +43,7 @@ public override void OnBeforeCompleteTypes() { if (_queryType is not null && _mutationDefinition is not null) { - MutationPayloadOptions options = _context.DescriptorContext.GetMutationPayloadOptions(); + var options = _context.DescriptorContext.GetMutationPayloadOptions(); ITypeReference queryType = TypeReference.Parse($"{_queryType.Name}!"); @@ -52,7 +52,7 @@ public override void OnBeforeCompleteTypes() type: queryType, resolver: ctx => new(ctx.GetQueryRoot())); - foreach (ObjectFieldDefinition field in _mutationDefinition.Fields) + foreach (var field in _mutationDefinition.Fields) { if (!field.IsIntrospectionField && _context.TryGetType(field.Type!, out IType? returnType) && diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/AnyType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/AnyType.cs index a60095014d3..8e54831106f 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/AnyType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/AnyType.cs @@ -140,10 +140,10 @@ private IValueNode ParseValue(object? value, ISet set) return new IntValueNode(b); } - Type type = value.GetType(); + var type = value.GetType(); if (type.IsValueType && _converter.TryConvert( - type, typeof(string), value, out object? converted) + type, typeof(string), value, out var converted) && converted is string c) { return new StringValueNode(c); @@ -154,7 +154,7 @@ private IValueNode ParseValue(object? value, ISet set) if (value is IReadOnlyDictionary dict) { var fields = new List(); - foreach (KeyValuePair field in dict) + foreach (var field in dict) { fields.Add(new ObjectFieldNode( field.Key, @@ -166,7 +166,7 @@ private IValueNode ParseValue(object? value, ISet set) if (value is IReadOnlyList list) { var valueList = new List(); - foreach (object element in list) + foreach (var element in list) { valueList.Add(ParseValue(element, set)); } @@ -208,10 +208,10 @@ public override bool TrySerialize(object? runtimeValue, out object? resultValue) return true; default: - Type type = runtimeValue.GetType(); + var type = runtimeValue.GetType(); if (type.IsValueType && - _converter.TryConvert(type, typeof(string), runtimeValue, out object? c) && + _converter.TryConvert(type, typeof(string), runtimeValue, out var c) && c is string casted) { resultValue = casted; @@ -232,7 +232,7 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu case IDictionary dictionary: { var result = new Dictionary(); - foreach (KeyValuePair element in dictionary) + foreach (var element in dictionary) { if (TryDeserialize(element.Value, out elementValue)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/DateTimeType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/DateTimeType.cs index dc94a133971..2f9b2bdff3b 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/DateTimeType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/DateTimeType.cs @@ -46,7 +46,7 @@ public DateTimeType( protected override DateTimeOffset ParseLiteral(StringValueNode valueSyntax) { - if (TryDeserializeFromString(valueSyntax.Value, out DateTimeOffset? value)) + if (TryDeserializeFromString(valueSyntax.Value, out var value)) { return value.Value; } @@ -120,7 +120,7 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu return true; } - if (resultValue is string s && TryDeserializeFromString(s, out DateTimeOffset? d)) + if (resultValue is string s && TryDeserializeFromString(s, out var d)) { runtimeValue = d; return true; @@ -168,7 +168,7 @@ private static bool TryDeserializeFromString( serialized, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, - out DateTime zuluTime)) + out var zuluTime)) { value = new DateTimeOffset( zuluTime.ToUniversalTime(), @@ -179,7 +179,7 @@ private static bool TryDeserializeFromString( if (serialized is not null && DateTimeOffset.TryParse( serialized, - out DateTimeOffset dt)) + out var dt)) { value = dt; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/DateType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/DateType.cs index 6ece15a17bc..5dbcc4dfa42 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/DateType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/DateType.cs @@ -33,7 +33,7 @@ public DateType( protected override DateTime ParseLiteral(StringValueNode valueSyntax) { - if (TryDeserializeFromString(valueSyntax.Value, out DateTime? value)) + if (TryDeserializeFromString(valueSyntax.Value, out var value)) { return value.Value; } @@ -99,7 +99,7 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu return true; } - if (resultValue is string s && TryDeserializeFromString(s, out DateTime? d)) + if (resultValue is string s && TryDeserializeFromString(s, out var d)) { runtimeValue = d; return true; @@ -132,7 +132,7 @@ private static bool TryDeserializeFromString( serialized, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, - out DateTime dateTime)) + out var dateTime)) { value = dateTime.Date; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/Iso8601Duration.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/Iso8601Duration.cs index 63fb5fb53ea..2261beda687 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/Iso8601Duration.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/Iso8601Duration.cs @@ -114,9 +114,9 @@ internal static bool TryParse(string s, out TimeSpan? result) int minutes = default; int seconds = default; uint nanoseconds = default; - bool isNegative = false; + var isNegative = false; - Parts parts = Parts.HasNone; + var parts = Parts.HasNone; result = default; diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.Initialization.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.Initialization.cs index f9f5b3d5585..ec4ef56065d 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.Initialization.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.Initialization.cs @@ -91,7 +91,7 @@ protected virtual void OnCompleteType( { _converter = context.Services.GetTypeConverter(); - DirectiveDefinition[] directiveDefinitions = + var directiveDefinitions = _specifiedBy is null ? Array.Empty() : new[] diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.cs index 770ea97be39..bdd4bf44229 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/ScalarType.cs @@ -233,7 +233,7 @@ protected bool TryConvertSerialized( ValueKind expectedKind, out T value) { - if (Scalars.TryGetKind(serialized, out ValueKind kind) + if (Scalars.TryGetKind(serialized, out var kind) && kind == expectedKind && _converter.TryConvert(serialized, out T c)) { diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/Scalars.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/Scalars.cs index fe90f949e72..b8ee9a3b5ab 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/Scalars.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/Scalars.cs @@ -145,7 +145,7 @@ public static bool TryGetKind(object? value, out ValueKind kind) return true; } - Type valueType = value.GetType(); + var valueType = value.GetType(); if (valueType.IsEnum) { diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/TimeSpanType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/TimeSpanType.cs index 7e8af7ecabb..4bc3c570c61 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/TimeSpanType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/TimeSpanType.cs @@ -41,7 +41,7 @@ public TimeSpanType( protected override TimeSpan ParseLiteral(StringValueNode valueSyntax) { - if (TryDeserializeFromString(valueSyntax.Value, _format, out TimeSpan? value) && + if (TryDeserializeFromString(valueSyntax.Value, _format, out var value) && value != null) { return value.Value; @@ -67,7 +67,7 @@ public override IValueNode ParseResult(object? resultValue) } if (resultValue is string s && - TryDeserializeFromString(s, _format, out TimeSpan? timeSpan)) + TryDeserializeFromString(s, _format, out var timeSpan)) { return ParseValue(timeSpan); } @@ -115,7 +115,7 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu } if (resultValue is string s && - TryDeserializeFromString(s, _format, out TimeSpan? timeSpan)) + TryDeserializeFromString(s, _format, out var timeSpan)) { runtimeValue = timeSpan; return true; @@ -156,7 +156,7 @@ private static bool TryDeserializeIso8601(string serialized, out TimeSpan? value private static bool TryDeserializeDotNet(string serialized, out TimeSpan? value) { - if (TimeSpan.TryParse(serialized, out TimeSpan timeSpan)) + if (TimeSpan.TryParse(serialized, out var timeSpan)) { value = timeSpan; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/UrlType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/UrlType.cs index ed5836b45bf..c673aff9f69 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/UrlType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/UrlType.cs @@ -39,7 +39,7 @@ protected override bool IsInstanceOfType(StringValueNode valueSyntax) protected override Uri ParseLiteral(StringValueNode valueSyntax) { - if (TryParseUri(valueSyntax.Value, out Uri? uri)) + if (TryParseUri(valueSyntax.Value, out var uri)) { return uri; } @@ -102,7 +102,7 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu return true; } - if (resultValue is string s && TryParseUri(s, out Uri? uri)) + if (resultValue is string s && TryParseUri(s, out var uri)) { runtimeValue = uri; return true; diff --git a/src/HotChocolate/Core/src/Types/Types/Scalars/UuidType.cs b/src/HotChocolate/Core/src/Types/Types/Scalars/UuidType.cs index 3f5585e97ea..67293cf2938 100644 --- a/src/HotChocolate/Core/src/Types/Types/Scalars/UuidType.cs +++ b/src/HotChocolate/Core/src/Types/Types/Scalars/UuidType.cs @@ -91,7 +91,7 @@ protected override bool IsInstanceOfType(StringValueNode valueSyntax) { if (_enforceFormat) { - ReadOnlySpan value = valueSyntax.AsSpan(); + var value = valueSyntax.AsSpan(); if (Utf8Parser.TryParse(value, out Guid _, out var consumed, _format[0]) && consumed == value.Length) @@ -111,7 +111,7 @@ protected override Guid ParseLiteral(StringValueNode valueSyntax) { if (_enforceFormat) { - ReadOnlySpan value = valueSyntax.AsSpan(); + var value = valueSyntax.AsSpan(); if (Utf8Parser.TryParse(value, out Guid g, out var consumed, _format[0]) && consumed == value.Length) @@ -119,7 +119,7 @@ protected override Guid ParseLiteral(StringValueNode valueSyntax) return g; } } - else if (Guid.TryParse(valueSyntax.Value, out Guid g)) + else if (Guid.TryParse(valueSyntax.Value, out var g)) { return g; } @@ -184,7 +184,7 @@ public override bool TryDeserialize(object? resultValue, out object? runtimeValu if (resultValue is string s) { - byte[] bytes = Encoding.UTF8.GetBytes(s); + var bytes = Encoding.UTF8.GetBytes(s); if (_enforceFormat && Utf8Parser.TryParse(bytes, out Guid guid, out var consumed, _format[0]) && diff --git a/src/HotChocolate/Core/src/Types/Types/TypeSystemObjectBase~1.cs b/src/HotChocolate/Core/src/Types/Types/TypeSystemObjectBase~1.cs index d0b8da0a5e1..ed3cacdce71 100644 --- a/src/HotChocolate/Core/src/Types/Types/TypeSystemObjectBase~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/TypeSystemObjectBase~1.cs @@ -77,7 +77,7 @@ internal sealed override void CompleteName(ITypeCompletionContext context) { AssertInitialized(); - TDefinition definition = _definition!; + var definition = _definition!; OnBeforeCompleteName(context, definition, definition.ContextData); @@ -118,7 +118,7 @@ internal sealed override void CompleteType(ITypeCompletionContext context) { AssertNamed(); - TDefinition definition = _definition!; + var definition = _definition!; OnBeforeCompleteType(context, definition, definition.ContextData); @@ -159,9 +159,9 @@ private void RegisterConfigurationDependencies( { OnBeforeRegisterDependencies(context, definition, definition.ContextData); - foreach (ITypeSystemMemberConfiguration? configuration in definition.GetConfigurations()) + foreach (var configuration in definition.GetConfigurations()) { - foreach (TypeDependency dependency in configuration.Dependencies) + foreach (var dependency in configuration.Dependencies) { context.Dependencies.Add(dependency); } @@ -176,7 +176,7 @@ private static void ExecuteConfigurations( TDefinition definition, ApplyConfigurationOn on) { - foreach (ITypeSystemMemberConfiguration config in definition.GetConfigurations()) + foreach (var config in definition.GetConfigurations()) { if (config.On == on) { diff --git a/src/HotChocolate/Core/src/Types/Types/UnionType.cs b/src/HotChocolate/Core/src/Types/Types/UnionType.cs index be8764cd7c5..0c46dc3dced 100644 --- a/src/HotChocolate/Core/src/Types/Types/UnionType.cs +++ b/src/HotChocolate/Core/src/Types/Types/UnionType.cs @@ -208,7 +208,7 @@ protected override void OnRegisterDependencies( { base.OnRegisterDependencies(context, definition); - foreach (ITypeReference typeRef in definition.Types) + foreach (var typeRef in definition.Types) { context.Dependencies.Add(new(typeRef)); } @@ -238,7 +238,7 @@ private void CompleteTypeSet( OnCompleteTypeSet(context, definition, typeSet); - foreach (ObjectType objectType in typeSet) + foreach (var objectType in typeSet) { _typeMap[objectType.Name] = objectType; } @@ -259,7 +259,7 @@ protected virtual void OnCompleteTypeSet( UnionTypeDefinition definition, ISet typeSet) { - foreach (ITypeReference typeReference in definition.Types) + foreach (var typeReference in definition.Types) { if (context.TryGetType(typeReference, out ObjectType? ot)) { @@ -287,7 +287,7 @@ private void CompleteResolveAbstractType( // abstract type resolver. _resolveAbstractType = (c, r) => { - foreach (ObjectType type in _typeMap.Values) + foreach (var type in _typeMap.Values) { if (type.IsInstanceOfType(c, r)) { diff --git a/src/HotChocolate/Core/src/Types/Types/UnionTypeExtension.cs b/src/HotChocolate/Core/src/Types/Types/UnionTypeExtension.cs index 3752b887c6e..7abf9879392 100644 --- a/src/HotChocolate/Core/src/Types/Types/UnionTypeExtension.cs +++ b/src/HotChocolate/Core/src/Types/Types/UnionTypeExtension.cs @@ -86,7 +86,7 @@ protected override void OnRegisterDependencies( { base.OnRegisterDependencies(context, definition); - foreach (ITypeReference typeRef in definition.Types) + foreach (var typeRef in definition.Types) { context.Dependencies.Add(new(typeRef)); } diff --git a/src/HotChocolate/Core/src/Types/Types/UnionType~1.cs b/src/HotChocolate/Core/src/Types/Types/UnionType~1.cs index cdffb1f75a4..52e09c18838 100644 --- a/src/HotChocolate/Core/src/Types/Types/UnionType~1.cs +++ b/src/HotChocolate/Core/src/Types/Types/UnionType~1.cs @@ -42,11 +42,11 @@ protected override void OnCompleteTypeSet( { base.OnCompleteTypeSet(context, definition, typeSet); - Type markerType = definition.RuntimeType; + var markerType = definition.RuntimeType; if (markerType != typeof(object)) { - foreach (ObjectType type in context.GetTypes()) + foreach (var type in context.GetTypes()) { if (type.RuntimeType != typeof(object) && markerType.IsAssignableFrom(type.RuntimeType)) diff --git a/src/HotChocolate/Core/src/Types/Utilities/AstUtilities.cs b/src/HotChocolate/Core/src/Types/Utilities/AstUtilities.cs index b0c847f6bc7..7f90728a386 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/AstUtilities.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/AstUtilities.cs @@ -8,7 +8,7 @@ public static class AstUtilities public static bool TryGetTypeFromAst(this ISchema schema, ITypeNode typeNode, out T type) where T : IType { - if (TryGetTypeFromAst(schema, typeNode, out IType internalType) + if (TryGetTypeFromAst(schema, typeNode, out var internalType) && internalType is T t) { type = t; diff --git a/src/HotChocolate/Core/src/Types/Utilities/DefaultTypeConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/DefaultTypeConverter.cs index 44b53071aff..db380ab3e2a 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/DefaultTypeConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/DefaultTypeConverter.cs @@ -29,7 +29,7 @@ public DefaultTypeConverter(IEnumerable? providers = null) public object? Convert(Type from, Type to, object? source) { - if (!TryConvert(from, to, source, out object? converted)) + if (!TryConvert(from, to, source, out var converted)) { throw new NotSupportedException( string.Format( @@ -66,7 +66,7 @@ public bool TryConvert(Type from, Type to, object? source, out object? converted try { - Type fromInternal = from == typeof(object) + var fromInternal = from == typeof(object) ? source.GetType() : from; @@ -89,7 +89,7 @@ private bool TryConvertInternal(Type from, Type to, object source, out object? c return true; } - if (TryGetOrCreateConverter(from, to, out ChangeType? converter)) + if (TryGetOrCreateConverter(from, to, out var converter)) { converted = converter(source); return true; @@ -124,7 +124,7 @@ private bool TryCreateConverterFromFactory( { if (_changeTypeProvider.Count > 0) { - foreach (IChangeTypeProvider provider in _changeTypeProvider) + foreach (var provider in _changeTypeProvider) { if (provider.TryCreateConverter( source, target, TryGetOrCreateConverter, out converter)) diff --git a/src/HotChocolate/Core/src/Types/Utilities/DictionaryToObjectConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/DictionaryToObjectConverter.cs index dc17073cc42..f249e70fcd1 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/DictionaryToObjectConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/DictionaryToObjectConverter.cs @@ -40,13 +40,13 @@ protected override void VisitObject( if (!context.ClrType.IsValueType && context.ClrType != typeof(string)) { - ILookup properties = + var properties = context.ClrType.CreatePropertyLookup(); context.Fields = properties; context.Object = Activator.CreateInstance(context.ClrType); - foreach (KeyValuePair field in dictionary) + foreach (var field in dictionary) { VisitField(field, context); } @@ -57,7 +57,7 @@ protected override void VisitField( KeyValuePair field, ConverterContext context) { - PropertyInfo property = context.Fields[field.Key].FirstOrDefault(); + var property = context.Fields[field.Key].FirstOrDefault(); if (property != null) { var valueContext = new ConverterContext(); @@ -71,11 +71,11 @@ protected override void VisitList( IReadOnlyList list, ConverterContext context) { - Type elementType = ExtendedType.Tools.GetElementType(context.ClrType); + var elementType = ExtendedType.Tools.GetElementType(context.ClrType); if (elementType is not null) { - Type listType = typeof(List<>).MakeGenericType(elementType); + var listType = typeof(List<>).MakeGenericType(elementType); var temp = (IList)Activator.CreateInstance(listType); for (var i = 0; i < list.Count; i++) diff --git a/src/HotChocolate/Core/src/Types/Utilities/DictionaryVisitor.cs b/src/HotChocolate/Core/src/Types/Utilities/DictionaryVisitor.cs index 148f51345f8..cb0ce401af6 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/DictionaryVisitor.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/DictionaryVisitor.cs @@ -28,7 +28,7 @@ protected virtual void VisitObject( IReadOnlyDictionary dictionary, TContext context) { - foreach (KeyValuePair field in dictionary) + foreach (var field in dictionary) { VisitField(field, context); } diff --git a/src/HotChocolate/Core/src/Types/Utilities/ITypeConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/ITypeConverter.cs index 50db3c79736..1ae4c11d26d 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/ITypeConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/ITypeConverter.cs @@ -1,4 +1,5 @@ using System; +using HotChocolate.Resolvers; #nullable enable diff --git a/src/HotChocolate/Core/src/Types/Utilities/InputObjectToDictionaryConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/InputObjectToDictionaryConverter.cs index 1a6ca0bd2b6..b27b6d5ae71 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/InputObjectToDictionaryConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/InputObjectToDictionaryConverter.cs @@ -75,7 +75,7 @@ private void VisitInputObject( for (var i = 0; i < type.Fields.Count; i++) { - InputField field = type.Fields[i]; + var field = type.Fields[i]; void SetField(object value) => dict[field.Name] = value; VisitValue(field.Type, fieldValues[i], SetField, processed); } @@ -105,7 +105,7 @@ private void VisitLeaf(INamedInputType type, object obj, Action setValue { if (type is IHasRuntimeType hasClrType) { - Type currentType = obj.GetType(); + var currentType = obj.GetType(); var normalized = currentType == hasClrType.RuntimeType ? obj : _converter.Convert(currentType, hasClrType.RuntimeType, obj); diff --git a/src/HotChocolate/Core/src/Types/Utilities/ListTypeConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/ListTypeConverter.cs index 9db1ddb4786..19a8bb32c0c 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/ListTypeConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/ListTypeConverter.cs @@ -22,12 +22,12 @@ public bool TryCreateConverter( ChangeTypeProvider root, [NotNullWhen(true)] out ChangeType? converter) { - Type? sourceElement = ExtendedType.Tools.GetElementType(source); - Type? targetElement = ExtendedType.Tools.GetElementType(target); + var sourceElement = ExtendedType.Tools.GetElementType(source); + var targetElement = ExtendedType.Tools.GetElementType(target); if (sourceElement is not null && targetElement is not null - && root(sourceElement, targetElement, out ChangeType? elementConverter)) + && root(sourceElement, targetElement, out var elementConverter)) { if (target.IsArray) { @@ -39,7 +39,7 @@ public bool TryCreateConverter( if (target.IsGenericType && target.GetGenericTypeDefinition() == typeof(Dictionary<,>)) { - MethodInfo converterMethod = + var converterMethod = _dictionaryConvert.MakeGenericMethod(targetElement.GetGenericArguments()); converter = source => converterMethod.Invoke( null, new[] { source, elementConverter }); @@ -49,7 +49,7 @@ public bool TryCreateConverter( if (target.IsGenericType && target.IsInterface) { - Type listType = typeof(List<>).MakeGenericType(targetElement); + var listType = typeof(List<>).MakeGenericType(targetElement); if (target.IsAssignableFrom(listType)) { converter = source => GenericListConverter( @@ -76,8 +76,8 @@ private static void ChangeListType( IEnumerable source, Action addToDestination) { - int i = 0; - foreach (object? item in source) + var i = 0; + foreach (var item in source) { addToDestination(item, i++); } diff --git a/src/HotChocolate/Core/src/Types/Utilities/NullableHelper.cs b/src/HotChocolate/Core/src/Types/Utilities/NullableHelper.cs index bfc3bdac02e..7624ecce9a2 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/NullableHelper.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/NullableHelper.cs @@ -22,7 +22,7 @@ public NullableHelper(Type type) { _context = GetContext(GetNullableContextAttribute(type.Assembly), true); - Type? current = type.DeclaringType; + var current = type.DeclaringType; while (current != null) { _context = GetContext(GetNullableContextAttribute(current), _context); @@ -39,13 +39,13 @@ public static bool IsParameterNullable(ParameterInfo parameter) => public bool? GetContext(MemberInfo member) { - NullableContextAttribute? attribute = GetNullableContextAttribute(member); + var attribute = GetNullableContextAttribute(member); return GetContext(attribute); } private bool? GetContext(ParameterInfo parameter) { - NullableContextAttribute? attribute = GetNullableContextAttribute(parameter); + var attribute = GetNullableContextAttribute(parameter); return GetContext(attribute, GetContext(parameter.Member)); } @@ -120,7 +120,7 @@ public static bool IsParameterNullable(ParameterInfo parameter) => private static NullableContextAttribute? GetNullableContextAttribute( IList attributes) { - CustomAttributeData? data = attributes.FirstOrDefault(t => + var data = attributes.FirstOrDefault(t => t.AttributeType.FullName.EqualsOrdinal(_nullableContextAttributeName)); if (data is not null) @@ -135,7 +135,7 @@ public static bool IsParameterNullable(ParameterInfo parameter) => private static NullableAttribute? GetNullableAttribute( MethodInfo method) { - object[] attributes = method.ReturnTypeCustomAttributes.GetCustomAttributes(false); + var attributes = method.ReturnTypeCustomAttributes.GetCustomAttributes(false); var attribute = attributes.FirstOrDefault(t => t.GetType().FullName.EqualsOrdinal(_nullableAttributeName)); @@ -168,7 +168,7 @@ public static bool IsParameterNullable(ParameterInfo parameter) => private static NullableAttribute? GetNullableAttribute( IList attributes) { - CustomAttributeData? data = attributes.FirstOrDefault(t => + var data = attributes.FirstOrDefault(t => t.AttributeType.FullName.EqualsOrdinal(_nullableAttributeName)); if (data is not null) diff --git a/src/HotChocolate/Core/src/Types/Utilities/NullableTypeConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/NullableTypeConverter.cs index e476365de06..82378af624c 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/NullableTypeConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/NullableTypeConverter.cs @@ -14,8 +14,8 @@ public bool TryCreateConverter( ChangeTypeProvider root, [NotNullWhen(true)] out ChangeType? converter) { - Type innerFrom = GetUnderlyingNullableType(source); - Type innerTo = GetUnderlyingNullableType(target); + var innerFrom = GetUnderlyingNullableType(source); + var innerTo = GetUnderlyingNullableType(target); if ((innerFrom != source || innerTo != target) && root(innerFrom, innerTo, out converter)) diff --git a/src/HotChocolate/Core/src/Types/Utilities/ObjectToDictionaryConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/ObjectToDictionaryConverter.cs index 6f1fd55bf99..c78e698cc8f 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/ObjectToDictionaryConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/ObjectToDictionaryConverter.cs @@ -60,10 +60,10 @@ private void VisitValue( return; } - Type type = obj.GetType(); + var type = obj.GetType(); if (type.IsValueType && _converter.TryConvert( - type, typeof(string), obj, out object converted) + type, typeof(string), obj, out var converted) && converted is string s) { setValue(s); @@ -92,7 +92,7 @@ private void VisitObject( if (obj is IReadOnlyDictionary d) { - foreach (KeyValuePair item in d) + foreach (var item in d) { Action setField = v => dict[item.Key] = v; VisitValue(item.Value, setField, processed); @@ -100,10 +100,10 @@ private void VisitObject( } else { - foreach (PropertyInfo property in GetProperties(obj)) + foreach (var property in GetProperties(obj)) { - string name = property.GetGraphQLName(); - object value = property.GetValue(obj); + var name = property.GetGraphQLName(); + var value = property.GetValue(obj); Action setField = v => dict[name] = v; VisitValue(value, setField, processed); } @@ -121,7 +121,7 @@ private void VisitList( Action addItem = item => valueList.Add(item); - foreach (object element in list) + foreach (var element in list) { VisitValue(element, addItem, processed); } @@ -129,8 +129,8 @@ private void VisitList( private IReadOnlyList GetProperties(object value) { - Type type = value.GetType(); - if (!_properties.TryGetValue(type, out List properties)) + var type = value.GetType(); + if (!_properties.TryGetValue(type, out var properties)) { properties = new List( ReflectionUtils.GetProperties(type).Values); diff --git a/src/HotChocolate/Core/src/Types/Utilities/ObjectValueToDictionaryConverter.cs b/src/HotChocolate/Core/src/Types/Utilities/ObjectValueToDictionaryConverter.cs index ad13cdd5f4e..df7efc70c39 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/ObjectValueToDictionaryConverter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/ObjectValueToDictionaryConverter.cs @@ -42,7 +42,7 @@ protected override void VisitObjectValue( var obj = new Dictionary(); setValue(obj); - foreach (ObjectFieldNode field in node.Fields) + foreach (var field in node.Fields) { Action setField = value => obj[field.Name.Value] = value; @@ -59,7 +59,7 @@ protected override void VisitListValue( Action addItem = item => list.Add(item); - foreach (IValueNode value in node.Items) + foreach (var value in node.Items) { VisitValue(value, addItem); } @@ -70,7 +70,7 @@ protected override void VisitIntValue( Action setValue) { if (int.TryParse(node.Value, NumberStyles.Integer, - CultureInfo.InvariantCulture, out int i)) + CultureInfo.InvariantCulture, out var i)) { setValue(i); } @@ -85,7 +85,7 @@ protected override void VisitFloatValue( Action setValue) { if (double.TryParse(node.Value, NumberStyles.Float, - CultureInfo.InvariantCulture, out double d)) + CultureInfo.InvariantCulture, out var d)) { setValue(d); } diff --git a/src/HotChocolate/Core/src/Types/Utilities/ReflectionUtils.cs b/src/HotChocolate/Core/src/Types/Utilities/ReflectionUtils.cs index 4ef482654a8..af561a30ac6 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/ReflectionUtils.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/ReflectionUtils.cs @@ -83,7 +83,7 @@ private static MemberInfo ExtractMemberInternal( Expression expression, bool allowStatic) { - MemberInfo member = ExtractMember(typeof(T), expression, allowStatic); + var member = ExtractMember(typeof(T), expression, allowStatic); if (member is null) { @@ -155,7 +155,7 @@ private static MemberInfo ExtractMember( type, unwrappedExpr, allowStatic, - out MemberInfo member) || + out var member) || TryExtractMemberFromMemberCallExpression( type, unwrappedExpr, @@ -206,7 +206,7 @@ public static string GetTypeName(this Type type) private static string CreateGenericTypeName(Type type) { var name = type.Name.Substring(0, type.Name.Length - 2); - IEnumerable arguments = type.GetGenericArguments().Select(GetTypeName); + var arguments = type.GetGenericArguments().Select(GetTypeName); return CreateTypeName(type, $"{name}<{string.Join(", ", arguments)}>"); } @@ -276,7 +276,7 @@ private static void AddProperties( Action add, Type type) { - foreach (PropertyInfo property in type.GetProperties( + foreach (var property in type.GetProperties( BindingFlags.Instance | BindingFlags.Public) .Where(p => !IsIgnored(p) && p.CanRead @@ -303,13 +303,13 @@ private static MethodInfo GetBestMatchingMethod( return method; } - Type[] parameters = method.GetParameters() + var parameters = method.GetParameters() .Select(t => t.ParameterType).ToArray(); - Type current = type; + var current = type; while (current is not null && current != typeof(object)) { - MethodInfo betterMatching = current.GetMethod(method.Name, parameters); + var betterMatching = current.GetMethod(method.Name, parameters); if (betterMatching != null) { @@ -330,11 +330,11 @@ private static PropertyInfo GetBestMatchingProperty( return property; } - Type current = type; + var current = type; while (current is not null && current != typeof(object)) { - PropertyInfo betterMatching = current.GetProperty(property.Name); + var betterMatching = current.GetProperty(property.Name); if (betterMatching != null) { diff --git a/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectCompiler.cs b/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectCompiler.cs index 391d02cdbca..c77b1c288d3 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectCompiler.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectCompiler.cs @@ -22,10 +22,10 @@ internal static class InputObjectCompiler InputObjectType inputType, ConstructorInfo? constructor = null) { - Dictionary fields = CreateFieldMap(inputType); + var fields = CreateFieldMap(inputType); constructor ??= GetCompatibleConstructor(inputType.RuntimeType, fields); - Expression instance = constructor is null + var instance = constructor is null ? Expression.New(inputType.RuntimeType) : CreateInstance(fields, constructor, _fieldValues); @@ -35,7 +35,7 @@ internal static class InputObjectCompiler return Expression.Lambda>(casted, _fieldValues).Compile(); } - ParameterExpression variable = Expression.Variable(inputType.RuntimeType, "obj"); + var variable = Expression.Variable(inputType.RuntimeType, "obj"); var expressions = new List(); expressions.Add(Expression.Assign(variable, instance)); @@ -48,7 +48,7 @@ internal static class InputObjectCompiler public static Action CompileGetFieldValues(InputObjectType inputType) { - Dictionary fields = CreateFieldMap(inputType); + var fields = CreateFieldMap(inputType); Expression instance = _obj; @@ -79,7 +79,7 @@ private static Expression[] CompileAssignParameters( ConstructorInfo constructor, Expression fieldValues) { - ParameterInfo[] parameters = constructor.GetParameters(); + var parameters = constructor.GetParameters(); if (parameters.Length == 0) { @@ -90,12 +90,12 @@ private static Expression[] CompileAssignParameters( for (var i = 0; i < parameters.Length; i++) { - ParameterInfo parameter = parameters[i]; + var parameter = parameters[i]; - if (fields.TryGetParameter(parameter, out InputField? field)) + if (fields.TryGetParameter(parameter, out var field)) { fields.Remove(field.Property!.Name); - Expression value = GetFieldValue(field, fieldValues); + var value = GetFieldValue(field, fieldValues); if (field.IsOptional) { @@ -119,10 +119,10 @@ private static void CompileSetProperties( Expression fieldValues, List currentBlock) { - foreach (InputField field in fields) + foreach (var field in fields) { - MethodInfo setter = field.Property!.GetSetMethod(true)!; - Expression value = GetFieldValue(field, fieldValues); + var setter = field.Property!.GetSetMethod(true)!; + var value = GetFieldValue(field, fieldValues); if (field.IsOptional) { @@ -141,9 +141,9 @@ private static void CompileGetProperties( Expression fieldValues, List currentBlock) { - foreach (InputField field in fields) + foreach (var field in fields) { - MethodInfo getter = field.Property!.GetGetMethod(true)!; + var getter = field.Property!.GetGetMethod(true)!; Expression fieldValue = Expression.Call(instance, getter); currentBlock.Add(SetFieldValue(field, fieldValues, fieldValue)); } @@ -168,7 +168,7 @@ private static Dictionary CreateFieldMap(InputObjectType typ private static Expression CreateOptional(Expression fieldValue, Type runtimeType) { - MethodInfo from = + var from = typeof(Optional<>) .MakeGenericType(runtimeType) .GetMethod("From", BindingFlags.Public | BindingFlags.Static)!; diff --git a/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectConstructorResolver.cs b/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectConstructorResolver.cs index 8827e56f026..6075483b9bb 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectConstructorResolver.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/Serialization/InputObjectConstructorResolver.cs @@ -15,9 +15,9 @@ internal static class InputObjectConstructorResolver Type type, IReadOnlyDictionary fields) { - ConstructorInfo[] constructors = type.GetConstructors( + var constructors = type.GetConstructors( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - ConstructorInfo? defaultConstructor = constructors.FirstOrDefault( + var defaultConstructor = constructors.FirstOrDefault( t => t.GetParameters().Length == 0); if (fields.Values.All(t => t.Property!.CanWrite)) @@ -38,7 +38,7 @@ internal static class InputObjectConstructorResolver if (constructors.Length > 0) { - foreach (ConstructorInfo constructor in + foreach (var constructor in constructors.OrderByDescending(t => t.GetParameters().Length)) { if (IsCompatibleConstructor(constructor, fields, required)) @@ -71,9 +71,9 @@ private static bool IsCompatibleConstructor( IReadOnlyDictionary fields, ISet required) { - foreach (ParameterInfo? parameter in parameters) + foreach (var parameter in parameters) { - if (fields.TryGetParameter(parameter, out InputField? field) && + if (fields.TryGetParameter(parameter, out var field) && parameter.ParameterType == field.Property!.PropertyType) { required.Remove(field.Name); @@ -93,7 +93,7 @@ private static void CollectReadOnlyProperties( { required.Clear(); - foreach (KeyValuePair item in fields) + foreach (var item in fields) { if (!item.Value.Property!.CanWrite) { @@ -107,8 +107,8 @@ public static bool TryGetParameter( ParameterInfo parameter, [NotNullWhen(true)] out InputField? field) { - string name = parameter.Name!; - string alternativeName = GetAlternativeParameterName(parameter.Name!); + var name = parameter.Name!; + var alternativeName = GetAlternativeParameterName(parameter.Name!); return (fields.TryGetValue(alternativeName, out field) || fields.TryGetValue(name, out field)); diff --git a/src/HotChocolate/Core/src/Types/Utilities/Subscriptions/ObservableSourceStreamAdapter.cs b/src/HotChocolate/Core/src/Types/Utilities/Subscriptions/ObservableSourceStreamAdapter.cs index 66f6a23bd4e..dfe4db85f01 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/Subscriptions/ObservableSourceStreamAdapter.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/Subscriptions/ObservableSourceStreamAdapter.cs @@ -32,7 +32,7 @@ public async IAsyncEnumerator GetAsyncEnumerator( while (!cancellationToken.IsCancellationRequested) { - if (_queue.TryDequeue(out T item)) + if (_queue.TryDequeue(out var item)) { yield return item; } diff --git a/src/HotChocolate/Core/src/Types/Utilities/ThrowHelper.cs b/src/HotChocolate/Core/src/Types/Utilities/ThrowHelper.cs index af8f9b13d66..8c46549c8ef 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/ThrowHelper.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/ThrowHelper.cs @@ -256,7 +256,7 @@ public static SerializationException OneOfNoFieldSet( InputObjectType type, Path? path) { - IErrorBuilder builder = ErrorBuilder.New() + var builder = ErrorBuilder.New() .SetMessage( ThrowHelper_OneOfNoFieldSet, type.Name.Value) @@ -270,7 +270,7 @@ public static SerializationException OneOfMoreThanOneFieldSet( InputObjectType type, Path? path) { - IErrorBuilder builder = ErrorBuilder.New() + var builder = ErrorBuilder.New() .SetMessage( ThrowHelper_OneOfMoreThanOneFieldSet, type.Name.Value) @@ -285,7 +285,7 @@ public static SerializationException OneOfFieldIsNull( Path? path, InputField field) { - IErrorBuilder builder = ErrorBuilder.New() + var builder = ErrorBuilder.New() .SetMessage( ThrowHelper_OneOfFieldIsNull, field.Name.Value, @@ -302,7 +302,7 @@ public static SerializationException NonNullInputViolation( Path? path, InputField? field = null) { - IErrorBuilder builder = ErrorBuilder.New() + var builder = ErrorBuilder.New() .SetMessage("Cannot accept null for non-nullable input.") .SetCode(ErrorCodes.Execution.NonNullViolation) .SetPath(path); diff --git a/src/HotChocolate/Core/src/Types/Utilities/TypeConverterExtensions.cs b/src/HotChocolate/Core/src/Types/Utilities/TypeConverterExtensions.cs index d71693651c1..cf1f11bda3d 100644 --- a/src/HotChocolate/Core/src/Types/Utilities/TypeConverterExtensions.cs +++ b/src/HotChocolate/Core/src/Types/Utilities/TypeConverterExtensions.cs @@ -22,7 +22,7 @@ public static bool TryConvert( if (typeConverter.TryConvert( typeof(TFrom), typeof(TTo), - source, out object conv) + source, out var conv) && conv is TTo convcasted) { converted = convcasted; From 066a51123dbabe9ddd76112bef45eeca21657217 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Thu, 23 Jun 2022 12:06:01 +0200 Subject: [PATCH 03/11] Added work scheduler --- .../Execution/HotChocolate.Execution.csproj | 9 + .../Execution/Processing/DirectiveContext.cs | 2 +- .../Execution/Processing/IWorkScheduler.cs | 5 - .../Processing/Internal/SuspendedWorkQueue.cs | 79 - .../Execution/Processing/OperationContext.cs | 2 +- .../Processing/WorkScheduler.Execute.cs | 193 + .../Processing/WorkScheduler.ExecuteAsync.cs | 114 - .../WorkScheduler.IQueryPlanState.cs | 32 - .../Processing/WorkScheduler.Pause.cs | 2 +- .../Processing/WorkScheduler.Pooling.cs | 100 +- .../src/Execution/Processing/WorkScheduler.cs | 321 +- .../ArgumentNonNullValidatorTests.cs | 73 +- .../AutoUpdateRequestExecutorProxyTests.cs | 141 +- .../Batching/BatchQueryExecutorTests.cs | 581 ++- .../Batching/CollectVariablesVisitorTests.cs | 221 +- .../test/Execution.Tests/CodeFirstTests.cs | 833 ++-- .../Configuration/TypeModuleTests.cs | 169 +- .../Core/test/Execution.Tests/DeferTests.cs | 205 +- ...torBuilderExtensions_IdSerializer.Tests.cs | 497 +- ...cutorBuilderExtensions_Validation.Tests.cs | 387 +- ...utorBuilderExtensions.Conventions.Tests.cs | 391 +- ...BuilderExtensions.TypeInterceptor.Tests.cs | 1451 +++--- ...stExecutorBuilderExtensions.Types.Tests.cs | 235 +- .../DependencyInjectionTests.cs | 301 +- .../Errors/ErrorBehaviorTests.cs | 489 +- .../Errors/ErrorHandlerTests.cs | 307 +- .../Instrumentation/ApolloTracingTests.cs | 161 +- .../DiagnosticListenerTests.cs | 185 +- .../Cancellation/CancellationTests.cs | 2 +- .../VariableCoercionIntegrationTests.cs | 317 +- .../Integration/DataLoader/DataLoaderTests.cs | 829 ++-- .../Integration/DataLoader/ITestDataLoader.cs | 11 +- .../Integration/DataLoader/MyCustomContext.cs | 11 +- .../Integration/DataLoader/Query.cs | 107 +- .../Integration/DataLoader/TestDataLoader.cs | 41 +- .../DataLoader/UseDataLoaderTests.cs | 509 ++- .../Directives/ConstantDirectiveType.cs | 33 +- .../Directives/DirectiveIntegrationTests.cs | 63 +- .../EmbeddedResolverTests.cs | 79 +- .../DataStoreHelloWorld.cs | 11 +- .../HelloWorldCodeFirstTests.cs | 75 +- .../HelloWorldCodeFirst/MutationHelloWorld.cs | 31 +- .../HelloWorldCodeFirst/QueryHelloWorld.cs | 33 +- .../HelloWorldCodeFirst/QueryHelloWorldClr.cs | 33 +- .../HelloWorldSchemaFirstTests.cs | 87 +- .../InputOutputObjectAreTheSame.cs | 75 +- .../InputOutputObjectAreTheSame/Person.cs | 14 +- .../InputOutputObjectAreTheSame/Query.cs | 14 +- .../Integration/Spec/ArgumentCoercionTests.cs | 201 +- .../Spec/InputObjectsCanBeVariablesTest.cs | 107 +- .../Integration/Spec/ListTypeTests.cs | 29 +- .../StarWarsCodeFirstTests.cs | 831 ++-- .../TypeConverter/TypeConverterTests.cs | 247 +- .../Execution.Tests/IntrospectionTests.cs | 633 ++- .../Execution.Tests/MiddlewareContextTests.cs | 215 +- .../NullErrorPropagationTests.cs | 265 +- .../Pipeline/ComplexityAnalyzerTests.cs | 437 +- .../Pipeline/DocumentCacheMiddlewareTests.cs | 401 +- .../Pipeline/DocumentParserMiddlewareTests.cs | 199 +- .../DocumentValidationMiddlewareTests.cs | 371 +- .../Pipeline/ExceptionMiddlewareTests.cs | 89 +- .../RequestClassMiddlewareFactoryTests.cs | 133 +- .../Pipeline/TimeoutMiddlewareTests.cs | 103 +- .../Pipeline/TransactionScopeHandlerTests.cs | 223 +- .../Internal/DeferredWorkQueueTests.cs | 201 +- .../Internal/SuspendedWorkQueueTests.cs | 77 - .../Processing/Internal/WorkQueueTests.cs | 271 +- .../Processing/OperationCompilerTests.cs | 43 +- .../Processing/ResultHelperTests.cs | 45 +- .../Processing/ResultMapTests.cs | 369 +- .../SelectionIncludeConditionTests.cs | 533 ++- .../Processing/VariableCoercionHelperTests.cs | 1673 ++++--- .../Processing/VisibilityTests.cs | 38 +- .../RequestExecutorProxyTests.cs | 103 +- .../Execution.Tests/RequestExecutorTests.cs | 211 +- .../ScalarExecutionErrorTests.cs | 339 +- .../Execution.Tests/SchemaDirectiveTests.cs | 393 +- .../test/Execution.Tests/SchemaFirstTests.cs | 261 +- .../Execution.Tests/ScopedContextDataTests.cs | 65 +- .../JsonArrayResponseStreamSerializerTests.cs | 93 +- .../MultiPartResponseStreamSerializerTests.cs | 93 +- .../SourceObjectConversionTests.cs | 141 +- .../Core/test/Execution.Tests/StreamTests.cs | 385 +- .../ConnectionTests.cs | 159 +- .../CursorPagingHandlerTests.cs | 1693 ++++--- .../CursorPagingQueryableExtensionsTests.cs | 233 +- .../CustomCursorHandlerTests.cs | 85 +- .../Types.CursorPagination.Tests/EdgeTests.cs | 141 +- .../IntegrationTests.cs | 1543 ++++--- .../MockExecutable.cs | 61 +- .../PagingObjectFieldDescriptorExtensions.cs | 59 +- .../QueryableCursorPagingProviderTests.cs | 1012 ++-- .../UsePagingAttributeTests.cs | 345 +- .../Core/test/Types.Tests/CodeFirstTests.cs | 459 +- .../MiddlewareConfigurationTests.cs | 153 +- .../ReadOnlySchemaOptionsTests.cs | 211 +- .../Configuration/SchemaConfigurationTests.cs | 157 +- .../Configuration/SchemaTypeDiscoveryTests.cs | 355 +- .../Configuration/SchemaTypeResolverTests.cs | 201 +- .../Configuration/TypeDiscovererTests.cs | 481 +- .../Configuration/TypeDiscoveryTests.cs | 107 +- .../TypeInitializationOrderTests.cs | 119 +- .../Configuration/TypeInitializerTests.cs | 459 +- .../TypeScopeInterceptorTests.cs | 175 +- .../Configuration/TypeTrimmerTests.cs | 487 +- .../Validation/InterfaceTypeValidation.cs | 33 +- .../Validation/ObjectTypeValidation.cs | 163 +- .../Validation/TypeValidationTestBase.cs | 55 +- .../DataLoaderResolverContextExtensions.cs | 713 ++- .../SchemaBuilderExtensions.Document.Tests.cs | 100 +- ...SchemaBuilderExtensions.Resolvers.Tests.cs | 614 ++- .../SchemaBuilderExtensions.Types.Tests.cs | 1951 ++++---- .../Types.Tests/ForbiddenRuntimeTypeTests.cs | 63 +- .../Types.Tests/GraphQLNonNullTypeTests.cs | 287 +- .../Core/test/Types.Tests/IgnoreTests.cs | 71 +- .../Internal/ExtendedTypeNullabilityTests.cs | 283 +- .../Types.Tests/Internal/ExtendedTypeTests.cs | 803 ++-- .../Types.Tests/Internal/TypeInfoTests.cs | 1175 +++-- .../test/Types.Tests/NamingConventionTests.cs | 139 +- .../Regressions/NestedOptionalInt_2114.cs | 227 +- .../ResolverContextStateExtensionTests.cs | 68 +- .../Resolvers/CustomResolverCompilerTests.cs | 353 +- .../Types.Tests/Resolvers/FieldMemberTests.cs | 667 ++- .../Resolvers/FieldMiddlewareTests.cs | 85 +- .../Resolvers/FieldReferenceTests.cs | 419 +- .../Resolvers/FieldResolverTests.cs | 643 ++- .../Resolvers/ResolverCompilerTests.cs | 2668 +++++------ .../Resolvers/ResolverDescriptorTests.cs | 79 +- .../Resolvers/ResolverServiceTests.cs | 4 +- .../Resolvers/ResolverTaskNullTests.cs | 127 +- .../test/Types.Tests/SchemaBuilderTests.cs | 4057 ++++++++--------- .../test/Types.Tests/SchemaCoordinateTests.cs | 204 +- .../Core/test/Types.Tests/SchemaErrorTests.cs | 287 +- .../Core/test/Types.Tests/SchemaFirstTests.cs | 975 ++-- .../test/Types.Tests/SchemaSerializerTests.cs | 405 +- .../Core/test/Types.Tests/TestUtils.cs | 19 +- .../Attributes/RequiredAttributeTests.cs | 81 +- .../UseServiceScopeAttributeTests.cs | 63 +- .../Descriptors/ArgumentDescriptorTests.cs | 477 +- .../DefaultNamingConventionsTypes.cs | 259 +- .../Conventions/DefaultTypeInspectorTests.cs | 1267 +++-- .../Conventions/NoOpStringBuilderPool.cs | 15 +- .../XmlDocumentationProviderTests.cs | 753 ++- .../Descriptors/DescriptorContextTests.cs | 187 +- .../Types/Descriptors/DescriptorTestBase.cs | 15 +- .../DirectiveArgumentDescriptorTests.cs | 27 +- .../Descriptors/DirectiveDescriptorTests.cs | 497 +- .../Descriptors/EnumTypeDescriptorTests.cs | 309 +- .../Descriptors/InputFieldDescriptorTests.cs | 513 ++- .../InputObjectTypeDescriptorTests.cs | 93 +- .../InterfaceFieldDescriptorTests.cs | 27 +- .../Descriptors/ObjectFieldDescriptorTests.cs | 403 +- .../Descriptors/ObjectTypeDescriptorTests.cs | 435 +- ...lveObjectFieldDescriptorExtensionsTests.cs | 885 ++-- ...verObjectFieldDescriptorExtensionsTests.cs | 763 ++-- .../TypeReferences/ClrTypeReferenceTests.cs | 1209 +++-- .../SchemaTypeReferenceTests.cs | 1081 +++-- .../SyntaxTypeReferenceTests.cs | 1165 +++-- .../Types/DirectiveCollectionTests.cs | 239 +- .../Types/DirectiveLocationTests.cs | 29 +- .../test/Types.Tests/Types/DirectiveTests.cs | 341 +- .../Types.Tests/Types/DirectiveTypeTests.cs | 1279 +++--- .../Types/Directives/CostDirectiveTests.cs | 105 +- .../Directives/CostDirectiveTypeTests.cs | 439 +- .../Directives/MultiplierPathStringTests.cs | 739 ++- .../Directives/SpecedDirectiveTypeTests.cs | 103 +- .../Types/EnumTypeDescriptorAttributeTests.cs | 143 +- .../Types/EnumTypeExtensionTests.cs | 377 +- .../test/Types.Tests/Types/EnumTypeTests.cs | 1235 +++-- .../Types.Tests/Types/EnumTypeUnsafeTests.cs | 111 +- .../Types.Tests/Types/InputCoercionTests.cs | 455 +- .../Types/InputObjectTypeAttributeTests.cs | 305 +- .../Types/InputObjectTypeDictionaryTests.cs | 79 +- .../Types/InputObjectTypeExtensionTests.cs | 471 +- .../Types.Tests/Types/InputObjectTypeTests.cs | 1617 ++++--- .../Types.Tests/Types/InputParserTests.cs | 757 ++- .../Types/InputValueFormatterTests.cs | 213 +- .../Types/InterfaceTypeAttributeTests.cs | 267 +- .../Types/InterfaceTypeExtensionTests.cs | 977 ++-- .../Types.Tests/Types/InterfaceTypeTests.cs | 1543 ++++--- .../test/Types.Tests/Types/ListTypeTests.cs | 267 +- .../test/Types.Tests/Types/NativeTypeTests.cs | 47 +- .../Types.Tests/Types/NonNullTypeTests.cs | 69 +- .../Types/ObjectFieldExpressionTests.cs | 117 +- .../Types/ObjectTypeAttributeTests.cs | 321 +- .../Types/ObjectTypeExtensionTests.cs | 1587 ++++--- .../test/Types.Tests/Types/ObjectTypeTests.cs | 3617 ++++++++------- .../test/Types.Tests/Types/PaginationTests.cs | 185 +- .../Types/Relay/IdAttributeTests.cs | 747 ++- .../Types/Relay/IdDescriptorTests.cs | 259 +- .../Types/Relay/IdMiddlewareTests.cs | 43 +- .../Types/Relay/IdSerializerTests.cs | 407 +- .../Types/Relay/NodeFieldSupportTests.cs | 1051 +++-- .../Types/Relay/NodeResolverTests.cs | 533 ++- .../Types.Tests/Types/Relay/NodeTypeTests.cs | 53 +- .../Types/Relay/RelaySchemaTests.cs | 389 +- .../Types/SDL/EnumTypeSchemaFirstTests.cs | 283 +- .../SDL/InputObjectTypeSchemaFirstTests.cs | 151 +- .../Types/SDL/ObjectTypeSchemaFirstTests.cs | 143 +- .../Types.Tests/Types/Scalars/AnyTypeTests.cs | 2213 +++++---- .../Types/Scalars/BooleanTypeTests.cs | 257 +- .../Types/Scalars/ByteArrayTypeTests.cs | 579 ++- .../Types/Scalars/ByteTypeTests.cs | 541 ++- .../Types/Scalars/DateTimeTypeTests.cs | 757 ++- .../Types/Scalars/DateTypeTests.cs | 689 ++- .../Types/Scalars/DecimalTypeTests.cs | 773 ++-- .../Types/Scalars/FloatTypeTests.cs | 637 ++- .../Types.Tests/Types/Scalars/IdTypeTests.cs | 665 ++- .../Types.Tests/Types/Scalars/IntTypeTests.cs | 541 ++- .../Types/Scalars/LongTypeTests.cs | 541 ++- .../Types/Scalars/MultiplierPathTypeTests.cs | 6 +- .../Types/Scalars/NameTypeTests.cs | 409 +- .../Types/Scalars/ScalarBindingTests.cs | 159 +- .../Types.Tests/Types/Scalars/ScalarsTests.cs | 281 +- .../Types/Scalars/ShortTypeTests.cs | 541 ++- .../Types/Scalars/StringTypeTests.cs | 375 +- .../Types/Scalars/TimeSpanTypeTests.cs | 515 ++- .../Types.Tests/Types/Scalars/UrlTypeTests.cs | 419 +- .../Types/Scalars/UuidTypeTests.cs | 927 ++-- .../Types/SubscriptionTypeTests.cs | 1750 ++++--- .../Types.Tests/Types/TypeExtensionsTests.cs | 1765 ++++--- .../Types.Tests/Types/TypeFactoryTests.cs | 565 ++- .../test/Types.Tests/Types/TypeTestBase.cs | 111 +- .../Types/UnionTypeAttributeTests.cs | 87 +- .../Types/UnionTypeExtensionTests.cs | 383 +- .../test/Types.Tests/Types/UnionTypeTests.cs | 429 +- .../Types.Tests/Utilities/BaseTypesTests.cs | 111 +- .../DictionaryToObjectConverterTests.cs | 225 +- .../Utilities/ExpressionUtilsTests.cs | 95 +- .../InputObjectToDictionaryConverterTests.cs | 205 +- .../ObjectValueToDictionaryConverterTests.cs | 123 +- .../Utilities/ReflectionUtilsTests.cs | 145 +- .../Utilities/TypeConversionTests.cs | 945 ++-- 233 files changed, 48403 insertions(+), 49089 deletions(-) delete mode 100644 src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs create mode 100644 src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs delete mode 100644 src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs delete mode 100644 src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs delete mode 100644 src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/SuspendedWorkQueueTests.cs diff --git a/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj b/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj index b67566d6515..e8e4a8c1890 100644 --- a/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj +++ b/src/HotChocolate/Core/src/Execution/HotChocolate.Execution.csproj @@ -78,6 +78,15 @@ ResolverTask.cs + + WorkScheduler.cs + + + WorkScheduler.cs + + + WorkScheduler.cs + diff --git a/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs b/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs index f6b93f059bd..2afdf3ef009 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/DirectiveContext.cs @@ -85,7 +85,7 @@ public void ReportError(Exception exception, Action? configure = => _middlewareContext.ReportError(exception, configure); public IReadOnlyList GetSelections( - ObjectType typeContext, + IObjectType typeContext, ISelection? selection = null, bool allowInternals = false) => _middlewareContext.GetSelections(typeContext, selection, allowInternals); diff --git a/src/HotChocolate/Core/src/Execution/Processing/IWorkScheduler.cs b/src/HotChocolate/Core/src/Execution/Processing/IWorkScheduler.cs index 13a0aa16e5e..c27d48f1825 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/IWorkScheduler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/IWorkScheduler.cs @@ -39,9 +39,4 @@ internal interface IWorkScheduler /// Execute the work. /// Task ExecuteAsync(); - - /// - /// Resets the execution state. - /// - void Reset(); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs b/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs deleted file mode 100644 index 41c3e9f5924..00000000000 --- a/src/HotChocolate/Core/src/Execution/Processing/Internal/SuspendedWorkQueue.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; -using HotChocolate.Execution.Processing.Plan; - -namespace HotChocolate.Execution.Processing.Internal; - -internal sealed class SuspendedWorkQueue -{ - private IExecutionTask? _head; - - public bool IsEmpty { get; private set; } = true; - - public bool HasWork => !IsEmpty; - - public void CopyTo(WorkQueue work, WorkQueue serial, QueryPlanStateMachine stateMachine) - { - var head = _head; - _head = null; - - while (head is not null) - { - var current = head; - head = head.Next; - current.Next = null; - - if (stateMachine.IsSuspended(current)) - { - AppendTask(ref _head, current); - } - else - { - (current.IsSerial ? serial : work).Push(current); - } - } - - IsEmpty = _head is null; - } - - public void Enqueue(IExecutionTask executionTask) - { - if (executionTask is null) - { - throw new ArgumentNullException(nameof(executionTask)); - } - - AppendTask(ref _head, executionTask); - IsEmpty = false; - } - - public bool TryDequeue([NotNullWhen(true)] out IExecutionTask? executionTask) - { - executionTask = _head; - - if (executionTask is null) - { - return false; - } - - _head = _head?.Next; - executionTask.Next = null; - IsEmpty = _head is null; - return true; - } - - private static void AppendTask(ref IExecutionTask? head, IExecutionTask executionTask) - { - executionTask.Previous = null; - executionTask.Next = head; - head = executionTask; - } - - public void Clear() - { - _head = null; - IsEmpty = true; - } -} diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationContext.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationContext.cs index e55c60353a4..d1afbc6334b 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationContext.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationContext.cs @@ -82,7 +82,7 @@ public PathFactory PathFactory } } - public ISelectionSet CollectFields(ISelection selection, ObjectType objectType) + public ISelectionSet CollectFields(ISelection selection, IObjectType objectType) { AssertInitialized(); return Operation.GetSelectionSet(selection, objectType); diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs new file mode 100644 index 00000000000..d360ed8f161 --- /dev/null +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs @@ -0,0 +1,193 @@ +using System; +using System.Threading.Tasks; +using static System.Environment; + +namespace HotChocolate.Execution.Processing; + +internal sealed partial class WorkScheduler +{ + private readonly IExecutionTask?[] _buffer = new IExecutionTask?[ProcessorCount * 2]; + + public async Task ExecuteAsync() + { + AssertNotPooled(); + + try + { + await ExecuteInternalAsync(_buffer); + } + finally + { + _buffer.AsSpan().Clear(); + } + } + + private async Task ExecuteInternalAsync(IExecutionTask?[] buffer) + { + RESTART: + _diagnosticEvents.StartProcessing(_requestContext); + + try + { + do + { + var work = TryTake(buffer); + + if (work is not 0) + { + if (!buffer[0]!.IsSerial) + { + // if work is not serial we will just enqueue it and not wait + // for it to finish. + for (var i = 0; i < work; i++) + { + buffer[i]!.BeginExecute(_ct); + buffer[i] = null; + } + } + else + { + // if work is serial we will synchronize the batch dispatcher and + // wait for the task to be finished. + try + { + _batchDispatcher.DispatchOnSchedule = true; + var task = buffer[0]!; + task.BeginExecute(_ct); + await task.WaitForCompletionAsync(_ct).ConfigureAwait(false); + buffer[0] = null; + } + finally + { + _batchDispatcher.DispatchOnSchedule = false; + } + } + } + else + { + break; + } + + } while (!_ct.IsCancellationRequested); + } + catch (Exception ex) + { + if (!_ct.IsCancellationRequested) + { + HandleError(ex); + } + } + + _ct.ThrowIfCancellationRequested(); + + if (!_isCompleted) + { + lock (_sync) + { + if (!_isCompleted) + { + var isWaitingForTaskCompletion = _work.HasRunningTasks && _work.IsEmpty; + var hasWork = !_work.IsEmpty || !_serial.IsEmpty; + + if (isWaitingForTaskCompletion && _hasBatches) + { + _hasBatches = false; + _pause.Reset(); + _batchDispatcher.BeginDispatch(_ct); + } + else if (!isWaitingForTaskCompletion && !_hasBatches && !hasWork) + { + _isCompleted = true; + } + } + } + } + + if (!_isCompleted) + { + await _pause; + goto RESTART; + } + } + + + + private int TryTake(IExecutionTask?[] buffer) + { + if (_isCompleted || _ct.IsCancellationRequested) + { + return default; + } + + var size = 0; + + lock (_sync) + { + var isDefault = !_work.IsEmpty || _work.HasRunningTasks; + var work = isDefault ? _work : _serial; + + if (isDefault) + { + // The default behavior for tasks is that they can be executed in parallel. + // We will always try to dequeue multiple tasks at once so that we avoid having + // many lock interactions. + for (var i = 0; i < buffer.Length; i++) + { + if (!work.TryTake(out var task)) + { + break; + } + + size++; + buffer[i] = task; + } + } + else + { + // For serial work we dequeue one task at a time. + // Parallel work is always preferred, so we take a single serial task and see if + // this results in more parallel work. + if (work.TryTake(out var task)) + { + size = 1; + buffer[0] = task; + } + } + } + + return size; + } + + private void BatchDispatcherEventHandler(object? source, EventArgs args) + { + lock (_sync) + { + _hasBatches = true; + } + + _pause.TryContinue(); + } + + private void HandleError(Exception exception) + { + var error = + _errorHandler + .CreateUnexpectedError(exception) + .SetCode(ErrorCodes.Execution.TaskProcessingError) + .Build(); + + error = _errorHandler.Handle(error); + + if (error is AggregateError aggregateError) + { + foreach (var innerError in aggregateError.Errors) + { + _result.AddError(innerError); + } + } + else + { + _result.AddError(error); + } + } +} diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs deleted file mode 100644 index 90a4646d596..00000000000 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.ExecuteAsync.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Threading.Tasks; - -namespace HotChocolate.Execution.Processing; - -internal partial class WorkScheduler -{ - private readonly IExecutionTask?[] _buffer = new IExecutionTask?[16]; - - public async Task ExecuteAsync() - { - _stateMachine.Start(); - - if (_suspended.HasWork) - { - _suspended.CopyTo(_work, _serial, _stateMachine); - } - - var buffer = _buffer; - -RESTART: - lock (_sync) - { - _processing = true; - } - - _diagnosticEvents.StartProcessing(_requestContext); - - try - { - do - { - var work = TryTake(buffer); - - if (work != 0) - { - if (!buffer[0]!.IsSerial) - { - for (var i = 0; i < work; i++) - { - buffer[i]!.BeginExecute(_requestAborted); - buffer[i] = null; - } - } - else - { - try - { - _batchDispatcher.DispatchOnSchedule = true; - - for (var i = 0; i < work; i++) - { - var task = buffer[i]!; - task.BeginExecute(_requestAborted); - await task.WaitForCompletionAsync(_requestAborted) - .ConfigureAwait(false); - buffer[i] = null; - } - } - finally - { - _batchDispatcher.DispatchOnSchedule = false; - } - } - } - else - { - break; - } - - } while (!_requestAborted.IsCancellationRequested); - } - catch (Exception ex) - { - if (!_requestAborted.IsCancellationRequested) - { - HandleError(ex); - } - } - - // if there is no more work we will try to scale down. - // Note: we always trigger this method, even if the request was canceled. - if (await TryStopProcessingAsync().ConfigureAwait(false) == false) - { - goto RESTART; - } - - buffer.AsSpan().Clear(); - _requestAborted.ThrowIfCancellationRequested(); - } - - private void HandleError(Exception exception) - { - var error = - _errorHandler - .CreateUnexpectedError(exception) - .SetCode(ErrorCodes.Execution.TaskProcessingError) - .Build(); - - error = _errorHandler.Handle(error); - - if (error is AggregateError aggregateError) - { - foreach (var innerError in aggregateError.Errors) - { - _result.AddError(innerError); - } - } - else - { - _result.AddError(error); - } - } -} diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs deleted file mode 100644 index de49acc6e18..00000000000 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.IQueryPlanState.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Collections.Generic; -using HotChocolate.Execution.Processing.Internal; -using HotChocolate.Execution.Processing.Plan; - -namespace HotChocolate.Execution.Processing; - -internal partial class WorkScheduler : IQueryPlanState -{ - IOperationContext IQueryPlanState.Context => _operationContext; - - ISet IQueryPlanState.Selections => _selections; - - void IQueryPlanState.RegisterUnsafe(IReadOnlyList tasks) - { - for (var i = 0; i < tasks.Count; i++) - { - var task = tasks[i]; - _stateMachine.TryInitializeTask(task); - task.IsRegistered = true; - - if (_stateMachine.RegisterTask(task)) - { - var work = task.IsSerial ? _serial : _work; - work.Push(task); - } - else - { - _suspended.Enqueue(task); - } - } - } -} diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs index b52333cbdc9..cbb3817f108 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs @@ -4,7 +4,7 @@ namespace HotChocolate.Execution.Processing; -internal partial class WorkScheduler +internal sealed partial class WorkScheduler { private sealed class ProcessingPause : INotifyCompletion { diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pooling.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pooling.cs index 91f94644af7..93107a9a593 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pooling.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pooling.cs @@ -1,37 +1,30 @@ -using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Threading; using HotChocolate.Execution.Instrumentation; using HotChocolate.Execution.Processing.Internal; -using HotChocolate.Execution.Processing.Plan; using HotChocolate.Fetching; using static HotChocolate.Execution.ThrowHelper; namespace HotChocolate.Execution.Processing; -internal partial class WorkScheduler +internal sealed partial class WorkScheduler { private readonly object _sync = new(); private readonly WorkQueue _work = new(); private readonly WorkQueue _serial = new(); - private readonly SuspendedWorkQueue _suspended = new(); - private readonly QueryPlanStateMachine _stateMachine = new(); - private readonly HashSet _selections = new(); - - private readonly OperationContext _operationContext; - private readonly DeferredWorkBacklog _deferredWorkBacklog = new(); + private readonly DeferredWorkBacklog _deferred = new(); private readonly ProcessingPause _pause = new(); - - - private bool _processing; - private bool _completed; + private readonly OperationContext _operationContext; private IRequestContext _requestContext = default!; private IBatchDispatcher _batchDispatcher = default!; private IErrorHandler _errorHandler = default!; private IResultHelper _result = default!; private IExecutionDiagnosticEvents _diagnosticEvents = default!; - private CancellationToken _requestAborted; + private CancellationToken _ct; + private bool _hasBatches; + private bool _isCompleted; private bool _isInitialized; public WorkScheduler(OperationContext operationContext) @@ -41,75 +34,42 @@ public WorkScheduler(OperationContext operationContext) public void Initialize(IBatchDispatcher batchDispatcher) { - Clear(); + _batchDispatcher = batchDispatcher; + _batchDispatcher.TaskEnqueued += BatchDispatcherEventHandler; _requestContext = _operationContext.RequestContext; _errorHandler = _operationContext.ErrorHandler; _result = _operationContext.Result; _diagnosticEvents = _operationContext.DiagnosticEvents; - _requestAborted = _operationContext.RequestAborted; - _batchDispatcher = batchDispatcher; - - _stateMachine.Initialize(this, _operationContext.QueryPlan); - - _batchDispatcher.TaskEnqueued += BatchDispatcherEventHandler; + _ct = _operationContext.RequestAborted; + _hasBatches = false; + _isCompleted = false; _isInitialized = true; } public void Clear() { - lock (_sync) - { - TryContinue(); - - if (_batchDispatcher is not null) - { - _batchDispatcher.TaskEnqueued -= BatchDispatcherEventHandler; - _batchDispatcher = default!; - } - - _work.Clear(); - _suspended.Clear(); - _stateMachine.Clear(); - _deferredWorkBacklog.Clear(); - _selections.Clear(); - _processing = false; - _completed = false; - - _requestContext = default!; - _errorHandler = default!; - _result = default!; - _diagnosticEvents = default!; - _requestAborted = default; - - _isInitialized = false; - } - } - - public void Reset() - { - ResetStateMachine(); - } - - public void ResetStateMachine() - { - lock (_sync) - { - TryContinue(); - - _work.Clear(); - _serial.Clear(); - _suspended.Clear(); - _stateMachine.Clear(); - _selections.Clear(); - _stateMachine.Initialize(this, _operationContext.QueryPlan); - - _processing = false; - _completed = false; - } + _work.Clear(); + _serial.Clear(); + _deferred.Clear(); + _pause.Reset(); + + _batchDispatcher.TaskEnqueued -= BatchDispatcherEventHandler; + _batchDispatcher = default!; + + _requestContext = default!; + _errorHandler = default!; + _result = default!; + _diagnosticEvents = default!; + _ct = default; + + _hasBatches = false; + _isCompleted = false; + _isInitialized = false; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AssertNotPooled() { if (!_isInitialized) diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs index 3abde433d3e..a24a6a8a184 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs @@ -1,350 +1,87 @@ -using System; using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using HotChocolate.Execution.Processing.Internal; -using HotChocolate.Execution.Processing.Tasks; namespace HotChocolate.Execution.Processing; -internal partial class WorkScheduler : IWorkScheduler +internal sealed partial class WorkScheduler : IWorkScheduler { - private bool _dispatch; - - /// - public bool IsCompleted => _completed; - - /// - public IDeferredWorkBacklog DeferredWork + public bool IsCompleted { get { AssertNotPooled(); - return _deferredWorkBacklog; + return _isCompleted; } } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool IsEmpty() => _work.IsEmpty && _serial.IsEmpty; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool ShouldStartProcessing() => !_processing && !IsEmpty(); - - /// - public void Register(IExecutionTask task) + public IDeferredWorkBacklog DeferredWork { - if (task is null) + get { - throw new ArgumentNullException(nameof(task)); + AssertNotPooled(); + return _deferred; } + } - var start = false; + public void Register(IExecutionTask task) + { + AssertNotPooled(); - // first we initialize the task execution state. - // This can be done without acquiring a lock since we only - // interact with the task object itself. - _stateMachine.TryInitializeTask(task); + var work = task.IsSerial ? _serial : _work; task.IsRegistered = true; lock (_sync) { - if (_stateMachine.RegisterTask(task)) - { - var work = task.IsSerial ? _serial : _work; - work.Push(task); - start = ShouldStartProcessing(); - } - else - { - _suspended.Enqueue(task); - } + work.Push(task); } - if (start) - { - TryContinue(); - } + _pause.TryContinue(); } - /// public void Register(IReadOnlyList tasks) { - if (tasks is null) - { - throw new ArgumentNullException(nameof(tasks)); - } - - if (tasks.Count == 1) - { - Register(tasks[0]); - return; - } - - var start = false; - - // first we initialize the task execution state. - // This can be done without acquiring a lock since we only - // interact with the task object itself. - for (var i = 0; i < tasks.Count; i++) - { - var task = tasks[i]; - _stateMachine.TryInitializeTask(task); - task.IsRegistered = true; - } + AssertNotPooled(); lock (_sync) { for (var i = 0; i < tasks.Count; i++) { var task = tasks[i]; + task.IsRegistered = true; - if (_stateMachine.RegisterTask(task)) + if (task.IsSerial) { - var work = task.IsSerial ? _serial : _work; - work.Push(task); - start = true; + _serial.Push(task); } else { - _suspended.Enqueue(task); + _work.Push(task); } } - - if (start) - { - start = ShouldStartProcessing(); - } } - if (start) - { - TryContinue(); - } + _pause.TryContinue(); } - /// public void Complete(IExecutionTask task) { - if (task is null) - { - throw new ArgumentNullException(nameof(task)); - } - - var start = false; + AssertNotPooled(); + + var hasWork = true; - lock (_sync) + if (task.IsRegistered) { - var registered = _serial.Count + _work.Count; + var work = task.IsSerial ? _serial : _work; - // we first complete the task on the state machine so that if we are completing - // the last task the state machine is marked as complete before the work queue - // signals that it is complete. - if (_stateMachine.Complete(task) && _suspended.HasWork) + lock (task) { - _suspended.CopyTo(_work, _serial, _stateMachine); - } - - // if was registered than we will mark it complete on the queue. - if (task.IsRegistered) - { - // determine the work queue. - var work = task.IsSerial ? _serial : _work; - - // now we complete the work queue which will signal to the execution context - // that work has been completed if it has no more tasks enqueued or marked - // running. work.Complete(); + hasWork = (!_work.IsEmpty && !_serial.IsEmpty) || _work.HasRunningTasks; } - - // if there is no more work and the state machine is not completed we will - // close open steps and reevaluate. This can happen if optional resolver tasks - // are not enqueued. - while (NeedsStateMachineCompletion()) - { - if (_stateMachine.CompleteNext() && _suspended.HasWork) - { - _suspended.CopyTo(_work, _serial, _stateMachine); - } - } - - // if the workload changed through completion we will ensure - // that the task processing is running. - if (registered != _serial.Count + _work.Count) - { - start = ShouldStartProcessing(); - } - - if (TryCompleteProcessingUnsafe()) - { - EnsureContextIsClean(); - start = true; - } - } - - if (start) - { - TryContinue(); } - bool NeedsStateMachineCompletion() - => !_stateMachine.IsCompleted && - IsEmpty() && - !_work.HasRunningTasks && - !_serial.HasRunningTasks; - } - - private int TryTake(IExecutionTask?[] buffer) - { - var size = 0; - - if (_completed || _requestAborted.IsCancellationRequested) + if (!hasWork) { - return default; - } - - lock (_sync) - { - var work = _stateMachine.IsSerial ? _serial : _work; - - for (var i = 0; i < buffer.Length; i++) - { - if (!work.TryTake(out var task)) - { - break; - } - - size++; - buffer[i] = task; - } - - return size; - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void TryContinue() => _pause.TryContinue(); - - private async ValueTask TryStopProcessingAsync() - { - var processingFinished = TryStopProcessing(); - - if (!_processing) - { - _diagnosticEvents.StopProcessing(_requestContext); - - if (_pause.IsPaused) - { - await _pause; - } - } - - return processingFinished; - } - - private bool TryStopProcessing() - { - // if there is still work we keep on processing. - // We check this here to try to avoid the lock. - if (!_work.IsEmpty && !_requestAborted.IsCancellationRequested) - { - return false; - } - - lock (_sync) - { - if (!_work.IsEmpty && !_requestAborted.IsCancellationRequested) - { - return false; - } - - if (_dispatch && _work.IsEmpty) - { - using (_diagnosticEvents.DispatchBatch(_requestContext)) - { - _batchDispatcher.BeginDispatch(_requestAborted); - _dispatch = false; - return false; - } - } - - _processing = false; - - if (TryCompleteProcessingUnsafe()) - { - EnsureContextIsClean(); - return true; - } - - _pause.Reset(); - return false; - } - } - - private void BatchDispatcherEventHandler(object? source, EventArgs args) - { - lock (_sync) - { - _dispatch = true; - if (!_processing) - { - TryContinue(); - } - } - } - - private bool TryCompleteProcessingUnsafe() - { - // if there are still running tasks we cannot complete the execution. - if (HasRunningTasks()) - { - return false; - } - - if (HasCompleted() || _requestAborted.IsCancellationRequested) - { - _completed = true; - return true; - } - - return false; - - bool HasRunningTasks() - => _processing || - _work.HasRunningTasks || - _serial.HasRunningTasks; - - bool HasCompleted() => IsEmpty() && _stateMachine.IsCompleted; - } - - private void EnsureContextIsClean() - { - // if there are still tasks enqueued when we cancel the execution - // we will try to reclaim the resolver tasks by properly cancelling - // them. - CancelTasks(_work); - CancelTasks(_serial); - CancelSuspendedTasks(_suspended); - - void CancelTasks(WorkQueue queue) - { - while (queue.TryTake(out var task)) - { - if (task is ResolverTask resolverTask) - { - resolverTask.Return(); - } - } - } - - void CancelSuspendedTasks(SuspendedWorkQueue queue) - { - while (queue.TryDequeue(out var task)) - { - if (task is ResolverTask resolverTask) - { - resolverTask.Return(); - } - } + _pause.TryContinue(); } } } diff --git a/src/HotChocolate/Core/test/Execution.Tests/ArgumentNonNullValidatorTests.cs b/src/HotChocolate/Core/test/Execution.Tests/ArgumentNonNullValidatorTests.cs index dfc8e78c04a..7c0e1baded6 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/ArgumentNonNullValidatorTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/ArgumentNonNullValidatorTests.cs @@ -4,16 +4,16 @@ using HotChocolate.Types; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class ArgumentNonNullValidatorTests { - public class ArgumentNonNullValidatorTests + [Fact] + public void Validate_Input_With_Non_Null_Props_That_Have_No_Value_But_A_DefaultValue() { - [Fact] - public void Validate_Input_With_Non_Null_Props_That_Have_No_Value_But_A_DefaultValue() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(@" + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(@" type Query { test(bar: Bar): String } @@ -22,27 +22,27 @@ input Bar { a: String! = ""bar"" } ") - .Use(next => context => default) - .Create(); + .Use(next => context => default) + .Create(); - IInputField field = schema.QueryType.Fields["test"].Arguments["bar"]; + IInputField field = schema.QueryType.Fields["test"].Arguments["bar"]; - // act - ArgumentNonNullValidator.ValidationResult report = - ArgumentNonNullValidator.Validate( - field, - new ObjectValueNode(), PathFactory.Instance.New("root")); + // act + var report = + ArgumentNonNullValidator.Validate( + field, + new ObjectValueNode(), PathFactory.Instance.New("root")); - // assert - Assert.False(report.HasErrors); - } + // assert + Assert.False(report.HasErrors); + } - [Fact] - public void Validate_Input_With_Non_Null_Props_That_Have_No_Value_And_No_DefaultValue() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(@" + [Fact] + public void Validate_Input_With_Non_Null_Props_That_Have_No_Value_And_No_DefaultValue() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(@" type Query { test(bar: Bar): String } @@ -51,19 +51,18 @@ input Bar { a: String! } ") - .Use(next => context => default(ValueTask)) - .Create(); + .Use(next => context => default(ValueTask)) + .Create(); - IInputField field = schema.QueryType.Fields["test"].Arguments["bar"]; + IInputField field = schema.QueryType.Fields["test"].Arguments["bar"]; - // act - var report = ArgumentNonNullValidator.Validate( - field, - new ObjectValueNode(), PathFactory.Instance.New("root")); + // act + var report = ArgumentNonNullValidator.Validate( + field, + new ObjectValueNode(), PathFactory.Instance.New("root")); - // assert - Assert.True(report.HasErrors); - Assert.Equal("/root/a", report.Path.ToString()); - } + // assert + Assert.True(report.HasErrors); + Assert.Equal("/root/a", report.Path.ToString()); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/AutoUpdateRequestExecutorProxyTests.cs b/src/HotChocolate/Core/test/Execution.Tests/AutoUpdateRequestExecutorProxyTests.cs index 9d32f4490ac..0e051428c84 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/AutoUpdateRequestExecutorProxyTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/AutoUpdateRequestExecutorProxyTests.cs @@ -4,90 +4,89 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class AutoUpdateRequestExecutorProxyTests { - public class AutoUpdateRequestExecutorProxyTests + [Fact] + public async Task Ensure_Executor_Is_Cached() { - [Fact] - public async Task Ensure_Executor_Is_Cached() - { - // arrange - IRequestExecutorResolver resolver = - new ServiceCollection() - .AddGraphQL() - .AddStarWarsRepositories() - .AddStarWarsTypes() - .Services - .BuildServiceProvider() - .GetRequiredService(); + // arrange + var resolver = + new ServiceCollection() + .AddGraphQL() + .AddStarWarsRepositories() + .AddStarWarsTypes() + .Services + .BuildServiceProvider() + .GetRequiredService(); - var innerProxy = new RequestExecutorProxy(resolver, Schema.DefaultName); + var innerProxy = new RequestExecutorProxy(resolver, Schema.DefaultName); - // act - var proxy = await AutoUpdateRequestExecutorProxy.CreateAsync(innerProxy); - IRequestExecutor a = proxy.InnerExecutor; - IRequestExecutor b = proxy.InnerExecutor; + // act + var proxy = await AutoUpdateRequestExecutorProxy.CreateAsync(innerProxy); + var a = proxy.InnerExecutor; + var b = proxy.InnerExecutor; - // assert - Assert.Same(a, b); - } + // assert + Assert.Same(a, b); + } - [Fact] - public async Task Ensure_Executor_Is_Correctly_Swapped_When_Evicted() - { - // arrange - IRequestExecutorResolver resolver = - new ServiceCollection() - .AddGraphQL() - .AddStarWarsRepositories() - .AddStarWarsTypes() - .Services - .BuildServiceProvider() - .GetRequiredService(); - var evicted = false; - var updated = false; + [Fact] + public async Task Ensure_Executor_Is_Correctly_Swapped_When_Evicted() + { + // arrange + var resolver = + new ServiceCollection() + .AddGraphQL() + .AddStarWarsRepositories() + .AddStarWarsTypes() + .Services + .BuildServiceProvider() + .GetRequiredService(); + var evicted = false; + var updated = false; - var innerProxy = new RequestExecutorProxy(resolver, Schema.DefaultName); - innerProxy.ExecutorEvicted += (sender, args) => - { - evicted = true; - updated = false; - }; - innerProxy.ExecutorUpdated += (sender, args) => updated = true; + var innerProxy = new RequestExecutorProxy(resolver, Schema.DefaultName); + innerProxy.ExecutorEvicted += (sender, args) => + { + evicted = true; + updated = false; + }; + innerProxy.ExecutorUpdated += (sender, args) => updated = true; - var proxy = await AutoUpdateRequestExecutorProxy.CreateAsync(innerProxy); + var proxy = await AutoUpdateRequestExecutorProxy.CreateAsync(innerProxy); - // act - IRequestExecutor a = proxy.InnerExecutor; - resolver.EvictRequestExecutor(); + // act + var a = proxy.InnerExecutor; + resolver.EvictRequestExecutor(); - var i = 0; - IRequestExecutor b = proxy.InnerExecutor; - while (ReferenceEquals(a, b)) + var i = 0; + var b = proxy.InnerExecutor; + while (ReferenceEquals(a, b)) + { + await Task.Delay(100); + b = proxy.InnerExecutor; + if (i++ > 10) { - await Task.Delay(100); - b = proxy.InnerExecutor; - if (i++ > 10) - { - break; - } + break; } - - // assert - Assert.NotSame(a, b); - Assert.True(evicted); - Assert.True(updated); } - [Fact] - public async Task Ensure_Manual_Proxy_Is_Not_Null() - { - // arrange - // act - async Task Action() => await AutoUpdateRequestExecutorProxy.CreateAsync(null!); + // assert + Assert.NotSame(a, b); + Assert.True(evicted); + Assert.True(updated); + } - // assert - await Assert.ThrowsAsync(Action); - } + [Fact] + public async Task Ensure_Manual_Proxy_Is_Not_Null() + { + // arrange + // act + async Task Action() => await AutoUpdateRequestExecutorProxy.CreateAsync(null!); + + // assert + await Assert.ThrowsAsync(Action); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Batching/BatchQueryExecutorTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Batching/BatchQueryExecutorTests.cs index 3827d5b54fe..5e08fde9551 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Batching/BatchQueryExecutorTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Batching/BatchQueryExecutorTests.cs @@ -9,69 +9,69 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Batching +namespace HotChocolate.Execution.Batching; + +public class BatchQueryExecutorTests { - public class BatchQueryExecutorTests + [Fact] + public async Task ExecuteExportScalar() { - [Fact] - public async Task ExecuteExportScalar() - { - // arrange - Snapshot.FullName(); + // arrange + Snapshot.FullName(); - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddStarWarsTypes() - .AddExportDirectiveType() - .Services - .AddStarWarsRepositories()); + var executor = await CreateExecutorAsync(c => c + .AddStarWarsTypes() + .AddExportDirectiveType() + .Services + .AddStarWarsRepositories()); - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @" + // act + var batch = new List + { + QueryRequestBuilder.New() + .SetQuery( + @" query getHero { hero(episode: EMPIRE) { id @export } }") - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @" + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @" query getHuman { human(id: $id) { name } }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteExportScalarList() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task ExecuteExportScalarList() + { + // arrange + Snapshot.FullName(); - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddStarWarsTypes() - .AddExportDirectiveType() - .Services - .AddStarWarsRepositories()); + var executor = await CreateExecutorAsync(c => c + .AddStarWarsTypes() + .AddExportDirectiveType() + .Services + .AddStarWarsRepositories()); - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @" + // act + var batch = new List + { + QueryRequestBuilder.New() + .SetQuery( + @" query getHero { hero(episode: EMPIRE) { friends { @@ -81,42 +81,42 @@ id @export(as: ""abc"") } } }") - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @" + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @" query getCharacter { character(characterIds: $abc) { name } }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteExportScalarList_ExplicitVariable() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task ExecuteExportScalarList_ExplicitVariable() + { + // arrange + Snapshot.FullName(); - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddStarWarsTypes() - .AddExportDirectiveType() - .Services - .AddStarWarsRepositories()); + var executor = await CreateExecutorAsync(c => c + .AddStarWarsTypes() + .AddExportDirectiveType() + .Services + .AddStarWarsRepositories()); - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @" + // act + var batch = new List + { + QueryRequestBuilder.New() + .SetQuery( + @" query getHero { hero(episode: EMPIRE) { friends { @@ -126,43 +126,43 @@ id @export(as: ""abc"") } } }") - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @" + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @" query getCharacter($abc: [String!]!) { character(characterIds: $abc) { name } }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteExportObject() + [Fact] + public async Task ExecuteExportObject() + { + // arrange + Snapshot.FullName(); + + var executor = await CreateExecutorAsync(c => c + .AddStarWarsTypes() + .AddExportDirectiveType() + .AddInMemorySubscriptions() + .Services + .AddStarWarsRepositories()); + + // act + var batch = new List { - // arrange - Snapshot.FullName(); - - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddStarWarsTypes() - .AddExportDirectiveType() - .AddInMemorySubscriptions() - .Services - .AddStarWarsRepositories()); - - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @"mutation firstReview { + QueryRequestBuilder.New() + .SetQuery( + @"mutation firstReview { createReview( episode: NEW_HOPE review: { commentary: ""foo"", stars: 4 }) @@ -171,10 +171,10 @@ public async Task ExecuteExportObject() stars } }") - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @" + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @" mutation secondReview { createReview( episode: EMPIRE @@ -183,76 +183,76 @@ mutation secondReview { stars } }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteExportLeafList() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task ExecuteExportLeafList() + { + // arrange + Snapshot.FullName(); + + var executor = await CreateExecutorAsync(c => c + .AddQueryType(d => d.Name("Query") + .Field("foo") + .Argument("bar", a => a.Type>()) + .Type>() + .Resolve(ctx => + { + var list = ctx.ArgumentValue>("bar"); - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType(d => d.Name("Query") - .Field("foo") - .Argument("bar", a => a.Type>()) - .Type>() - .Resolve(ctx => + if (list is null) { - List list = ctx.ArgumentValue>("bar"); - - if (list is null) + return new List { - return new List - { - "123", - "456" - }; - } + "123", + "456" + }; + } - list.Add("789"); - return list; - })) - .AddExportDirectiveType()); + list.Add("789"); + return list; + })) + .AddExportDirectiveType()); - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @"{ + // act + var batch = new List + { + QueryRequestBuilder.New() + .SetQuery( + @"{ foo @export(as: ""b"") }") - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @"{ foo(bar: $b) }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteExportObjectList() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task ExecuteExportObjectList() + { + // arrange + Snapshot.FullName(); - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - @" + var executor = await CreateExecutorAsync(c => c + .AddDocumentFromString( + @" type Query { foo(f: [FooInput]) : [Foo] } @@ -264,179 +264,178 @@ type Foo { input FooInput { bar: String! }") - .AddResolver("Query", "foo", ctx => - { - List list = ctx.ArgumentValue>("f"); + .AddResolver("Query", "foo", ctx => + { + var list = ctx.ArgumentValue>("f"); - if (list is null) + if (list is null) + { + return new List { - return new List + new Dictionary { - new Dictionary - { - { "bar" , "123" } - } - }; - } + { "bar" , "123" } + } + }; + } - list.Add(new Dictionary - { - { "bar" , "456" } - }); - return list; - }) - .UseField(next => context => + list.Add(new Dictionary { - var o = context.Parent(); - if (o is Dictionary d - && d.TryGetValue(context.ResponseName, out var v)) - { - context.Result = v; - } - return next(context); - }) - .AddExportDirectiveType()); - - // act - var batch = new List + { "bar" , "456" } + }); + return list; + }) + .UseField(next => context => { - QueryRequestBuilder.New() - .SetQuery( - @"{ + var o = context.Parent(); + if (o is Dictionary d + && d.TryGetValue(context.ResponseName, out var v)) + { + context.Result = v; + } + return next(context); + }) + .AddExportDirectiveType()); + + // act + var batch = new List + { + QueryRequestBuilder.New() + .SetQuery( + @"{ foo @export(as: ""b"") { bar } }") - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @"{ foo(f: $b) { bar } }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } + + [Fact] + public async Task Add_Value_To_Variable_List() + { + // arrange + Snapshot.FullName(); + + var executor = await CreateExecutorAsync(c => c + .AddQueryType(d => d.Name("Query") + .Field("foo") + .Argument("bar", a => a.Type>()) + .Type>() + .Resolve(ctx => + { + var list = ctx.ArgumentValue>("bar"); + list.Add("789"); + return list; + })) + .AddExportDirectiveType()); - [Fact] - public async Task Add_Value_To_Variable_List() + // act + var batch = new List { - // arrange - Snapshot.FullName(); + QueryRequestBuilder.New() + .SetQuery( + @"query foo1($b: [String]) { + foo(bar: $b) @export(as: ""b"") + }") + .AddVariableValue("b", new[] { "123" }) + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @"query foo2($b: [String]) { + foo(bar: $b) + }") + .Create() + }; - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType(d => d.Name("Query") - .Field("foo") + var batchResult = await executor.ExecuteBatchAsync(batch); + + // assert + await batchResult.MatchSnapshotAsync(); + } + + [Fact] + public async Task Convert_List_To_Single_Value_With_Converters() + { + // arrange + Snapshot.FullName(); + + var executor = await CreateExecutorAsync(c => c + .AddQueryType(d => + { + d.Name("Query"); + + d.Field("foo") .Argument("bar", a => a.Type>()) .Type>() .Resolve(ctx => { - List list = ctx.ArgumentValue>("bar"); + var list = ctx.ArgumentValue>("bar"); list.Add("789"); return list; - })) - .AddExportDirectiveType()); - - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @"query foo1($b: [String]) { - foo(bar: $b) @export(as: ""b"") - }") - .AddVariableValue("b", new[] { "123" }) - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @"query foo2($b: [String]) { - foo(bar: $b) - }") - .Create() - }; - - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + }); - // assert - await batchResult.MatchSnapshotAsync(); - } + d.Field("baz") + .Argument("bar", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("bar")); + }) + .AddExportDirectiveType()); - [Fact] - public async Task Convert_List_To_Single_Value_With_Converters() + // act + var batch = new List { - // arrange - Snapshot.FullName(); - - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType(d => - { - d.Name("Query"); - - d.Field("foo") - .Argument("bar", a => a.Type>()) - .Type>() - .Resolve(ctx => - { - List list = ctx.ArgumentValue>("bar"); - list.Add("789"); - return list; - }); - - d.Field("baz") - .Argument("bar", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("bar")); - }) - .AddExportDirectiveType()); - - // act - var batch = new List - { - QueryRequestBuilder.New() - .SetQuery( - @"query foo1($b1: [String]) { + QueryRequestBuilder.New() + .SetQuery( + @"query foo1($b1: [String]) { foo(bar: $b1) @export(as: ""b2"") }") - .AddVariableValue("b1", new[] { "123" }) - .Create(), - QueryRequestBuilder.New() - .SetQuery( - @"query foo2($b2: String) { + .AddVariableValue("b1", new[] { "123" }) + .Create(), + QueryRequestBuilder.New() + .SetQuery( + @"query foo2($b2: String) { baz(bar: $b2) }") - .Create() - }; + .Create() + }; - IResponseStream batchResult = await executor.ExecuteBatchAsync(batch); + var batchResult = await executor.ExecuteBatchAsync(batch); - // assert - await batchResult.MatchSnapshotAsync(); - } + // assert + await batchResult.MatchSnapshotAsync(); + } - [Fact] - public async Task Batch_Is_Null() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task Batch_Is_Null() + { + // arrange + Snapshot.FullName(); - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddStarWarsTypes() - .AddExportDirectiveType() - .Services - .AddStarWarsRepositories()); + var executor = await CreateExecutorAsync(c => c + .AddStarWarsTypes() + .AddExportDirectiveType() + .Services + .AddStarWarsRepositories()); - // act - Task Action() => executor.ExecuteBatchAsync(null!); + // act + Task Action() => executor.ExecuteBatchAsync(null!); - // assert - await Assert.ThrowsAsync(Action); - } + // assert + await Assert.ThrowsAsync(Action); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Batching/CollectVariablesVisitorTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Batching/CollectVariablesVisitorTests.cs index a00bc3f4b04..0b14375bd32 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Batching/CollectVariablesVisitorTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Batching/CollectVariablesVisitorTests.cs @@ -6,61 +6,61 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Batching +namespace HotChocolate.Execution.Batching; + +public class CollectVariablesVisitorTests { - public class CollectVariablesVisitorTests + [Fact] + public void FindUndeclaredVariables() { - [Fact] - public void FindUndeclaredVariables() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddStarWarsTypes() - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse( - @" + // arrange + var schema = SchemaBuilder.New() + .AddStarWarsTypes() + .Create(); + + var document = Utf8GraphQLParser.Parse( + @" query getHero { hero(episode: $ep) { name } }"); - OperationDefinitionNode operation = document.Definitions - .OfType() - .First(); - - var visitor = new CollectVariablesVisitor(schema); - var visitationMap = new CollectVariablesVisitationMap(); - - // act - operation.Accept( - visitor, - visitationMap, - _ => VisitorAction.Continue); - - // assert - var variables = operation.VariableDefinitions.ToList(); - variables.AddRange(visitor.VariableDeclarations); - operation = operation.WithVariableDefinitions(variables); - - new DocumentNode( - new IDefinitionNode[] - { - operation - }).Print().MatchSnapshot(); - } - - [Fact] - public void FindUndeclaredVariablesInlineFragment() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddStarWarsTypes() - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse( - @" + var operation = document.Definitions + .OfType() + .First(); + + var visitor = new CollectVariablesVisitor(schema); + var visitationMap = new CollectVariablesVisitationMap(); + + // act + operation.Accept( + visitor, + visitationMap, + _ => VisitorAction.Continue); + + // assert + var variables = operation.VariableDefinitions.ToList(); + variables.AddRange(visitor.VariableDeclarations); + operation = operation.WithVariableDefinitions(variables); + + new DocumentNode( + new IDefinitionNode[] + { + operation + }).Print().MatchSnapshot(); + } + + [Fact] + public void FindUndeclaredVariablesInlineFragment() + { + // arrange + var schema = SchemaBuilder.New() + .AddStarWarsTypes() + .Create(); + + var document = Utf8GraphQLParser.Parse( + @" query getHero { ... on Query { hero(episode: $ep) { @@ -69,41 +69,41 @@ ... on Query { } }"); - OperationDefinitionNode operation = document.Definitions - .OfType() - .First(); - - var visitor = new CollectVariablesVisitor(schema); - var visitationMap = new CollectVariablesVisitationMap(); - - // act - operation.Accept( - visitor, - visitationMap, - node => VisitorAction.Continue); - - // assert - var variables = operation.VariableDefinitions.ToList(); - variables.AddRange(visitor.VariableDeclarations); - operation = operation.WithVariableDefinitions(variables); - - new DocumentNode( - new IDefinitionNode[] - { - operation - }).Print().MatchSnapshot(); - } - - [Fact] - public void FindUndeclaredVariablesFragmentDefinition() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddStarWarsTypes() - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse( - @" + var operation = document.Definitions + .OfType() + .First(); + + var visitor = new CollectVariablesVisitor(schema); + var visitationMap = new CollectVariablesVisitationMap(); + + // act + operation.Accept( + visitor, + visitationMap, + node => VisitorAction.Continue); + + // assert + var variables = operation.VariableDefinitions.ToList(); + variables.AddRange(visitor.VariableDeclarations); + operation = operation.WithVariableDefinitions(variables); + + new DocumentNode( + new IDefinitionNode[] + { + operation + }).Print().MatchSnapshot(); + } + + [Fact] + public void FindUndeclaredVariablesFragmentDefinition() + { + // arrange + var schema = SchemaBuilder.New() + .AddStarWarsTypes() + .Create(); + + var document = Utf8GraphQLParser.Parse( + @" query getHero { ... q } @@ -115,33 +115,32 @@ fragment q on Query { } "); - OperationDefinitionNode operation = document.Definitions - .OfType() - .First(); - - var visitor = new CollectVariablesVisitor(schema); - var visitationMap = new CollectVariablesVisitationMap(); - visitationMap.Initialize( - document.Definitions.OfType() - .ToDictionary(t => t.Name.Value)); - - // act - operation.Accept( - visitor, - visitationMap, - _ => VisitorAction.Continue); - - // assert - var variables = operation.VariableDefinitions.ToList(); - variables.AddRange(visitor.VariableDeclarations); - operation = operation.WithVariableDefinitions(variables); - - var definitions = new List(); - definitions.Add(operation); - definitions.AddRange( - document.Definitions.OfType()); - - new DocumentNode(definitions).Print().MatchSnapshot(); - } + var operation = document.Definitions + .OfType() + .First(); + + var visitor = new CollectVariablesVisitor(schema); + var visitationMap = new CollectVariablesVisitationMap(); + visitationMap.Initialize( + document.Definitions.OfType() + .ToDictionary(t => t.Name.Value)); + + // act + operation.Accept( + visitor, + visitationMap, + _ => VisitorAction.Continue); + + // assert + var variables = operation.VariableDefinitions.ToList(); + variables.AddRange(visitor.VariableDeclarations); + operation = operation.WithVariableDefinitions(variables); + + var definitions = new List(); + definitions.Add(operation); + definitions.AddRange( + document.Definitions.OfType()); + + new DocumentNode(definitions).Print().MatchSnapshot(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs index 229b00400c8..ef7cc6ff941 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs @@ -12,72 +12,72 @@ #nullable enable -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class CodeFirstTests { - public class CodeFirstTests + [Fact] + public async Task ExecuteOneFieldQueryWithProperty() { - [Fact] - public async Task ExecuteOneFieldQueryWithProperty() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync("{ test }"); - - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } - - [Fact] - public async Task ExecuteOneFieldQueryWithMethod() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync("{ test }"); - - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } - - [Fact] - public async Task ExecuteOneFieldQueryWithQuery() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync("{ test }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync("{ query }"); + [Fact] + public async Task ExecuteOneFieldQueryWithMethod() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync("{ test }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + [Fact] + public async Task ExecuteOneFieldQueryWithQuery() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync("{ query }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task ExecuteWithUnionType() - { - // arrange - ISchema schema = CreateSchema(); - - // act - IExecutionResult result = - await schema.MakeExecutable() - .ExecuteAsync( - @" + [Fact] + public async Task ExecuteWithUnionType() + { + // arrange + var schema = CreateSchema(); + + // act + var result = + await schema.MakeExecutable() + .ExecuteAsync( + @" { fooOrBar { ... on Bar { nameBar } @@ -86,454 +86,453 @@ ... on Foo { nameFoo } } "); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public void UnionTypeResolveType() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public void UnionTypeResolveType() + { + // arrange + var schema = CreateSchema(); - var context = new Mock( - MockBehavior.Strict); + var context = new Mock( + MockBehavior.Strict); - // act - UnionType fooBar = schema.GetType("FooBar"); - ObjectType? teaType = fooBar.ResolveConcreteType(context.Object, "tea"); - ObjectType? barType = fooBar.ResolveConcreteType(context.Object, "bar"); + // act + var fooBar = schema.GetType("FooBar"); + var teaType = fooBar.ResolveConcreteType(context.Object, "tea"); + var barType = fooBar.ResolveConcreteType(context.Object, "bar"); - // assert - Assert.Null(teaType); - Assert.NotNull(barType); - } + // assert + Assert.Null(teaType); + Assert.NotNull(barType); + } - [Fact] - public void UnionType_Contains_TypeName() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public void UnionType_Contains_TypeName() + { + // arrange + var schema = CreateSchema(); - UnionType fooBar = schema.GetType("FooBar"); + var fooBar = schema.GetType("FooBar"); - // act - var shouldBeFalse = fooBar.ContainsType("Tea"); - var shouldBeTrue = fooBar.ContainsType("Bar"); + // act + var shouldBeFalse = fooBar.ContainsType("Tea"); + var shouldBeTrue = fooBar.ContainsType("Bar"); - // assert - Assert.True(shouldBeTrue); - Assert.False(shouldBeFalse); - } + // assert + Assert.True(shouldBeTrue); + Assert.False(shouldBeFalse); + } - [Fact] - public void UnionType_Contains_ObjectType() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public void UnionType_Contains_ObjectType() + { + // arrange + var schema = CreateSchema(); - UnionType fooBar = schema.GetType("FooBar"); - ObjectType bar = schema.GetType("Bar"); - ObjectType tea = schema.GetType("Tea"); + var fooBar = schema.GetType("FooBar"); + var bar = schema.GetType("Bar"); + var tea = schema.GetType("Tea"); - // act - var shouldBeTrue = fooBar.ContainsType(bar); - var shouldBeFalse = fooBar.ContainsType(tea); + // act + var shouldBeTrue = fooBar.ContainsType(bar); + var shouldBeFalse = fooBar.ContainsType(tea); - // assert - Assert.True(shouldBeTrue); - Assert.False(shouldBeFalse); - } + // assert + Assert.True(shouldBeTrue); + Assert.False(shouldBeFalse); + } - [Fact] - public void UnionType_Contains_IObjectType() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public void UnionType_Contains_IObjectType() + { + // arrange + var schema = CreateSchema(); - IUnionType fooBar = schema.GetType("FooBar"); - IObjectType tea = schema.GetType("Tea"); - IObjectType bar = schema.GetType("Bar"); + IUnionType fooBar = schema.GetType("FooBar"); + IObjectType tea = schema.GetType("Tea"); + IObjectType bar = schema.GetType("Bar"); - // act - var shouldBeFalse = fooBar.ContainsType(tea); - var shouldBeTrue = fooBar.ContainsType(bar); + // act + var shouldBeFalse = fooBar.ContainsType(tea); + var shouldBeTrue = fooBar.ContainsType(bar); - // assert - Assert.True(shouldBeTrue); - Assert.False(shouldBeFalse); - } + // assert + Assert.True(shouldBeTrue); + Assert.False(shouldBeFalse); + } - [Fact] - public async Task ExecuteWithInterface() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public async Task ExecuteWithInterface() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ drink { ... on Tea { kind } } }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ drink { ... on Tea { kind } } }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public void InterfaceTypeResolveType() - { - // arrange - ISchema schema = CreateSchema(); - var context = new Mock( - MockBehavior.Strict); - - // act - InterfaceType drink = schema.GetType("Drink"); - ObjectType? teaType = drink.ResolveConcreteType(context.Object, "tea"); - ObjectType? barType = drink.ResolveConcreteType(context.Object, "bar"); - - // assert - Assert.NotNull(teaType); - Assert.Null(barType); - } + [Fact] + public void InterfaceTypeResolveType() + { + // arrange + var schema = CreateSchema(); + var context = new Mock( + MockBehavior.Strict); + + // act + var drink = schema.GetType("Drink"); + var teaType = drink.ResolveConcreteType(context.Object, "tea"); + var barType = drink.ResolveConcreteType(context.Object, "bar"); + + // assert + Assert.NotNull(teaType); + Assert.Null(barType); + } - [Fact] - public async Task ExecuteImplicitField() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public async Task ExecuteImplicitField() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ dog { name } }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ dog { name } }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task ExecuteImplicitFieldWithNameAttribute() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public async Task ExecuteImplicitFieldWithNameAttribute() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ dog { desc } }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ dog { desc } }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task ExecuteImplicitAsyncField() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public async Task ExecuteImplicitAsyncField() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ dog { name2 } }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ dog { name2 } }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task ExecuteExplicitAsyncField() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public async Task ExecuteExplicitAsyncField() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ dog { names } }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ dog { names } }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + await result.MatchSnapshotAsync(); + } - [Fact] - public async Task CannotCreateRootValue() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ hello }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task CannotCreateRootValue() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ hello }") + .MatchSnapshotAsync(); + } + + // https://github.com/ChilliCream/hotchocolate/issues/2617 + [Fact] + public async Task EnsureThatFieldsWithDifferentCasingAreNotMerged() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + // https://github.com/ChilliCream/hotchocolate/issues/2305 + [Fact] + public async Task EnsureThatArgumentDefaultIsUsedWhenVariableValueIsOmitted() + { + var request = + QueryRequestBuilder.New() + .SetQuery("query($v: String) { foo(value: $v) }") + .Create(); - // https://github.com/ChilliCream/hotchocolate/issues/2617 - [Fact] - public async Task EnsureThatFieldsWithDifferentCasingAreNotMerged() + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync(request) + .MatchSnapshotAsync(); + } + + private static ISchema CreateSchema() + => SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .AddType() + .AddType() + .AddType() + .AddType() + .Create(); + + public class Query + { + public string GetTest() { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); + return "Hello World!"; } - // https://github.com/ChilliCream/hotchocolate/issues/2305 - [Fact] - public async Task EnsureThatArgumentDefaultIsUsedWhenVariableValueIsOmitted() + public IExecutable GetQuery() { - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery("query($v: String) { foo(value: $v) }") - .Create(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync(request) - .MatchSnapshotAsync(); + return new MockExecutable(new[] { "foo", "bar" }.AsQueryable()); } - private static ISchema CreateSchema() - => SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .AddType() - .AddType() - .AddType() - .AddType() - .Create(); + public string TestProp => "Hello World!"; + } - public class Query + public class QueryTypeWithProperty : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public string GetTest() - { - return "Hello World!"; - } - - public IExecutable GetQuery() - { - return new MockExecutable(new[] { "foo", "bar" }.AsQueryable()); - } - - public string TestProp => "Hello World!"; + descriptor.Name("Query"); + descriptor.Field(t => t.TestProp).Name("test"); } + } - public class QueryTypeWithProperty : ObjectType + public class QueryTypeWithMethod : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field(t => t.TestProp).Name("test"); - } + descriptor.Name("Query"); + descriptor.Field(t => t.GetTest()).Name("test"); + descriptor.Field(t => t.GetQuery()).Name("query"); } + } - public class QueryTypeWithMethod : ObjectType - { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field(t => t.GetTest()).Name("test"); - descriptor.Field(t => t.GetQuery()).Name("query"); - } + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) + { + descriptor.Name("Query"); + descriptor.Field("foo") + .Type>() + .Resolve(() => "foo"); + descriptor.Field("bar") + .Type>() + .Resolve(c => "bar"); + descriptor.Field("fooOrBar") + .Type>>>() + .Resolve(() => new object[] { "foo", "bar" }); + descriptor.Field("tea") + .Type() + .Resolve(() => "tea"); + descriptor.Field("drink") + .Type() + .Resolve(() => "tea"); + descriptor.Field("dog") + .Type() + .Resolve(() => new Dog()); } + } - public class QueryType : ObjectType + public class FooType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("foo") - .Type>() - .Resolve(() => "foo"); - descriptor.Field("bar") - .Type>() - .Resolve(c => "bar"); - descriptor.Field("fooOrBar") - .Type>>>() - .Resolve(() => new object[] { "foo", "bar" }); - descriptor.Field("tea") - .Type() - .Resolve(() => "tea"); - descriptor.Field("drink") - .Type() - .Resolve(() => "tea"); - descriptor.Field("dog") - .Type() - .Resolve(() => new Dog()); - } + descriptor.Name("Foo"); + descriptor.Field("bar") + .Type>() + .Resolve(() => "bar"); + descriptor.Field("nameFoo").Resolve(() => "foo"); + descriptor.IsOfType((c, obj) => obj.Equals("foo")); } + } - public class FooType : ObjectType + public class BarType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Field("bar") - .Type>() - .Resolve(() => "bar"); - descriptor.Field("nameFoo").Resolve(() => "foo"); - descriptor.IsOfType((c, obj) => obj.Equals("foo")); - } + descriptor.Name("Bar"); + descriptor.Field("foo") + .Type>() + .Resolve(() => "foo"); + descriptor.Field("nameBar").Resolve(() => "bar"); + descriptor.IsOfType((c, obj) => obj.Equals("bar")); } + } - public class BarType : ObjectType + public class TeaType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Bar"); - descriptor.Field("foo") - .Type>() - .Resolve(() => "foo"); - descriptor.Field("nameBar").Resolve(() => "bar"); - descriptor.IsOfType((c, obj) => obj.Equals("bar")); - } + descriptor.Name("Tea"); + descriptor.Implements(); + descriptor.Field("kind") + .Type>() + .Resolve(() => DrinkKind.BlackTea); + descriptor.IsOfType((c, obj) => obj.Equals("tea")); } + } - public class TeaType : ObjectType + public class DrinkType : InterfaceType + { + protected override void Configure(IInterfaceTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Tea"); - descriptor.Implements(); - descriptor.Field("kind") - .Type>() - .Resolve(() => DrinkKind.BlackTea); - descriptor.IsOfType((c, obj) => obj.Equals("tea")); - } + descriptor.Name("Drink"); + descriptor.Field("kind") + .Type>(); } + } - public class DrinkType : InterfaceType + public class DrinkKindType : EnumType + { + protected override void Configure( + IEnumTypeDescriptor descriptor) { - protected override void Configure(IInterfaceTypeDescriptor descriptor) - { - descriptor.Name("Drink"); - descriptor.Field("kind") - .Type>(); - } + descriptor.Name("DrinkKind"); } + } - public class DrinkKindType : EnumType - { - protected override void Configure( - IEnumTypeDescriptor descriptor) - { - descriptor.Name("DrinkKind"); - } - } + public enum DrinkKind + { + BlackTea, + Water + } - public enum DrinkKind + public class FooBarUnionType : UnionType + { + protected override void Configure(IUnionTypeDescriptor descriptor) { - BlackTea, - Water + descriptor.Name("FooBar"); + descriptor.Type(); + descriptor.Type(); } + } + + public class Pet + { + public bool WithTail { get; set; } + } + + public class Dog : Pet + { + public string Name { get; } = "a"; + + [GraphQLName("desc")] + public string Descriptor { get; } = "desc"; - public class FooBarUnionType : UnionType + public Task GetName2() { - protected override void Configure(IUnionTypeDescriptor descriptor) - { - descriptor.Name("FooBar"); - descriptor.Type(); - descriptor.Type(); - } + return Task.FromResult("b"); } - public class Pet + public Task> GetNames() { - public bool WithTail { get; set; } + return Task.FromResult>(new[] { "a", "b" }); } + } - public class Dog : Pet + public class DogType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public string Name { get; } = "a"; - - [GraphQLName("desc")] - public string Descriptor { get; } = "desc"; + descriptor.Field(t => t.WithTail) + .Type>(); + descriptor.Field(t => t.GetNames()) + .Type>(); + } + } - public Task GetName2() - { - return Task.FromResult("b"); - } + public class MockExecutable : IExecutable + { + private readonly IQueryable _source; - public Task> GetNames() - { - return Task.FromResult>(new[] { "a", "b" }); - } + public MockExecutable(IQueryable source) + { + _source = source; } - public class DogType : ObjectType + public object Source => _source; + + public ValueTask ToListAsync(CancellationToken cancellationToken) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.WithTail) - .Type>(); - descriptor.Field(t => t.GetNames()) - .Type>(); - } + return new ValueTask(_source.ToList()); } - public class MockExecutable : IExecutable + public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken) { - private readonly IQueryable _source; - - public MockExecutable(IQueryable source) - { - _source = source; - } - - public object Source => _source; - - public ValueTask ToListAsync(CancellationToken cancellationToken) - { - return new ValueTask(_source.ToList()); - } - - public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken) - { - return new ValueTask(_source.FirstOrDefault()); - } - - public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) - { - return new ValueTask(_source.SingleOrDefault()); - } - - public string Print() - { - return _source.ToString()!; - } + return new ValueTask(_source.FirstOrDefault()); } - public class QueryPrivateConstructor + public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) { - private QueryPrivateConstructor() - { - } - - public string Hello() => "Hello"; + return new ValueTask(_source.SingleOrDefault()); } - public class QueryFieldCasing + public string Print() { - public string YourFieldName { get; set; } = default!; - - [GraphQLDeprecated("This is deprecated")] - public string YourFieldname { get; set; } = default!; + return _source.ToString()!; } + } - public class QueryWithDefaultValue + public class QueryPrivateConstructor + { + private QueryPrivateConstructor() { - public string Foo(string value = "abc") => value; } + + public string Hello() => "Hello"; + } + + public class QueryFieldCasing + { + public string YourFieldName { get; set; } = default!; + + [GraphQLDeprecated("This is deprecated")] + public string YourFieldname { get; set; } = default!; + } + + public class QueryWithDefaultValue + { + public string Foo(string value = "abc") => value; } } diff --git a/src/HotChocolate/Core/test/Execution.Tests/Configuration/TypeModuleTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Configuration/TypeModuleTests.cs index 8caf9482165..43295c6cb76 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Configuration/TypeModuleTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Configuration/TypeModuleTests.cs @@ -9,103 +9,102 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate.Execution.Configuration +namespace HotChocolate.Execution.Configuration; + +public class TypeModuleTests { - public class TypeModuleTests + [Fact] + public async Task Use_Type_Module_From_DI() { - [Fact] - public async Task Use_Type_Module_From_DI() - { - await new ServiceCollection() - .AddSingleton() - .AddGraphQLServer() - .AddTypeModule() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddSingleton() + .AddGraphQLServer() + .AddTypeModule() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Use_Type_Module_From_DI_And_Execute() - { - await new ServiceCollection() - .AddSingleton() - .AddGraphQLServer() - .AddTypeModule() - .ExecuteRequestAsync("{ hello }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Use_Type_Module_From_DI_And_Execute() + { + await new ServiceCollection() + .AddSingleton() + .AddGraphQLServer() + .AddTypeModule() + .ExecuteRequestAsync("{ hello }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Extend_Type_From_TypeModule() - { - await new ServiceCollection() - .AddSingleton() - .AddGraphQLServer() - .AddTypeExtension() - .AddTypeModule() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Extend_Type_From_TypeModule() + { + await new ServiceCollection() + .AddSingleton() + .AddGraphQLServer() + .AddTypeExtension() + .AddTypeModule() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Extend_Type_From_TypeModule_Execute() - { - await new ServiceCollection() - .AddSingleton() - .AddGraphQLServer() - .AddTypeExtension() - .AddTypeModule() - .ExecuteRequestAsync("{ hello person { name dynamic } }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Extend_Type_From_TypeModule_Execute() + { + await new ServiceCollection() + .AddSingleton() + .AddGraphQLServer() + .AddTypeExtension() + .AddTypeModule() + .ExecuteRequestAsync("{ hello person { name dynamic } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Use_Type_Module_From_Factory() - { - await new ServiceCollection() - .AddGraphQLServer() - .AddTypeModule(_ => new DummyTypeModule()) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Use_Type_Module_From_Factory() + { + await new ServiceCollection() + .AddGraphQLServer() + .AddTypeModule(_ => new DummyTypeModule()) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - public class DummyTypeModule : ITypeModule - { - public event EventHandler TypesChanged; + public class DummyTypeModule : ITypeModule + { + public event EventHandler TypesChanged; - public ValueTask> CreateTypesAsync( - IDescriptorContext context, - CancellationToken cancellationToken) - { - var list = new List(); + public ValueTask> CreateTypesAsync( + IDescriptorContext context, + CancellationToken cancellationToken) + { + var list = new List(); - var typeDefinition = new ObjectTypeDefinition("Query"); - typeDefinition.Fields.Add(new( - "hello", - type: TypeReference.Parse("String!"), - pureResolver: _ => "world")); - list.Add(ObjectType.CreateUnsafe(typeDefinition)); + var typeDefinition = new ObjectTypeDefinition("Query"); + typeDefinition.Fields.Add(new( + "hello", + type: TypeReference.Parse("String!"), + pureResolver: _ => "world")); + list.Add(ObjectType.CreateUnsafe(typeDefinition)); - var typeExtensionDefinition = new ObjectTypeDefinition("Person"); - typeExtensionDefinition.Fields.Add(new( - "dynamic", - type: TypeReference.Parse("String!"), - pureResolver: _ => "value")); - list.Add(ObjectTypeExtension.CreateUnsafe(typeExtensionDefinition)); + var typeExtensionDefinition = new ObjectTypeDefinition("Person"); + typeExtensionDefinition.Fields.Add(new( + "dynamic", + type: TypeReference.Parse("String!"), + pureResolver: _ => "value")); + list.Add(ObjectTypeExtension.CreateUnsafe(typeExtensionDefinition)); - return new(list); - } + return new(list); } + } - [ExtendObjectType("Query")] - public class Query - { - public Person GetPerson() => new(); - } + [ExtendObjectType("Query")] + public class Query + { + public Person GetPerson() => new(); + } - public class Person - { - public string Name => "Doe"; - } + public class Person + { + public string Name => "Doe"; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs b/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs index a0a14b8fe58..50140f402dd 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DeferTests.cs @@ -6,20 +6,20 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class DeferTests { - public class DeferTests + [Fact] + public async Task NoOptimization_Defer_Single_Scalar_Field() { - [Fact] - public async Task NoOptimization_Defer_Single_Scalar_Field() - { - var result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... @defer { @@ -28,29 +28,29 @@ ... @defer { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); + var results = new StringBuilder(); - await foreach (var payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } - - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task NoOptimization_Defer_Only_Root() - { - var result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task NoOptimization_Defer_Only_Root() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ ... @defer { hero(episode: NEW_HOPE) { id @@ -59,19 +59,19 @@ ... @defer { } }"); - await Assert.IsType(result).MatchSnapshotAsync(); - } + await Assert.IsType(result).MatchSnapshotAsync(); + } - [Fact] - public async Task NoOptimization_Defer_One_Root() - { - var result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + [Fact] + public async Task NoOptimization_Defer_One_Root() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ ... @defer { a: hero(episode: NEW_HOPE) { id @@ -84,29 +84,29 @@ ... @defer { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); + var results = new StringBuilder(); - await foreach (var payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } - - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task NoOptimization_Nested_Defer() - { - var result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task NoOptimization_Nested_Defer() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { @@ -122,29 +122,29 @@ ... @defer { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); + var results = new StringBuilder(); - await foreach (var payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } - - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task NoOptimization_Spread_Defer() - { - var result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task NoOptimization_Spread_Defer() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... deferred @defer(label: ""friends"") @@ -159,29 +159,29 @@ fragment deferred on Character { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); + var results = new StringBuilder(); - await foreach (var payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } - - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact(Skip = "needs to be fixed.")] - public async Task Do_Not_Defer() - { - var result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact(Skip = "needs to be fixed.")] + public async Task Do_Not_Defer() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... deferred @defer(label: ""friends"", if: false) @@ -196,7 +196,6 @@ fragment deferred on Character { } }"); - Assert.IsType(result).MatchSnapshot(); - } + Assert.IsType(result).MatchSnapshot(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_IdSerializer.Tests.cs b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_IdSerializer.Tests.cs index 22ecc2612e3..97dd593e04c 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_IdSerializer.Tests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_IdSerializer.Tests.cs @@ -4,281 +4,280 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate.Execution.DependencyInjection +namespace HotChocolate.Execution.DependencyInjection; + +public class RequestExecutorBuilderExtensionsIdSerializerTests { - public class RequestExecutorBuilderExtensionsIdSerializerTests + [Fact] + public void AddIdSerializer_Include_Schema() { - [Fact] - public void AddIdSerializer_Include_Schema() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .TryAddIdSerializer() - .AddIdSerializer(true) - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - IdValue id = serializer.Deserialize(serializedId); - Assert.Equal("abc", id.SchemaName); - Assert.Equal("def", id.TypeName); - Assert.Equal("ghi", id.Value); - } + // arrange + var serializer = + new ServiceCollection() + .TryAddIdSerializer() + .AddIdSerializer(true) + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + var id = serializer.Deserialize(serializedId); + Assert.Equal("abc", id.SchemaName); + Assert.Equal("def", id.TypeName); + Assert.Equal("ghi", id.Value); + } - [Fact] - public void AddIdSerializer_Exclude_Schema() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .TryAddIdSerializer() - .AddIdSerializer(false) - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - IdValue id = serializer.Deserialize(serializedId); - Assert.False(id.SchemaName.HasValue); - Assert.Equal("def", id.TypeName); - Assert.Equal("ghi", id.Value); - } + [Fact] + public void AddIdSerializer_Exclude_Schema() + { + // arrange + var serializer = + new ServiceCollection() + .TryAddIdSerializer() + .AddIdSerializer(false) + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + var id = serializer.Deserialize(serializedId); + Assert.False(id.SchemaName.HasValue); + Assert.Equal("def", id.TypeName); + Assert.Equal("ghi", id.Value); + } - [Fact] - public void AddIdSerializer_Include_Schema_Services_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer(default(IServiceCollection)!, true); + [Fact] + public void AddIdSerializer_Include_Schema_Services_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer(default(IServiceCollection)!, true); - // assert - Assert.Throws(Fail); - } + // assert + Assert.Throws(Fail); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Include_Schema() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .AddGraphQL() - .AddIdSerializer(true) - .Services - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - IdValue id = serializer.Deserialize(serializedId); - Assert.Equal("abc", id.SchemaName); - Assert.Equal("def", id.TypeName); - Assert.Equal("ghi", id.Value); - } + [Fact] + public void RequestBuilder_AddIdSerializer_Include_Schema() + { + // arrange + var serializer = + new ServiceCollection() + .AddGraphQL() + .AddIdSerializer(true) + .Services + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + var id = serializer.Deserialize(serializedId); + Assert.Equal("abc", id.SchemaName); + Assert.Equal("def", id.TypeName); + Assert.Equal("ghi", id.Value); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Exclude_Schema() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .AddGraphQL() - .AddIdSerializer(false) - .Services - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - IdValue id = serializer.Deserialize(serializedId); - Assert.False(id.SchemaName.HasValue); - Assert.Equal("def", id.TypeName); - Assert.Equal("ghi", id.Value); - } + [Fact] + public void RequestBuilder_AddIdSerializer_Exclude_Schema() + { + // arrange + var serializer = + new ServiceCollection() + .AddGraphQL() + .AddIdSerializer(false) + .Services + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + var id = serializer.Deserialize(serializedId); + Assert.False(id.SchemaName.HasValue); + Assert.Equal("def", id.TypeName); + Assert.Equal("ghi", id.Value); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Include_Schema_Services_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer(default(IRequestExecutorBuilder)!, true); + [Fact] + public void RequestBuilder_AddIdSerializer_Include_Schema_Services_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer(default(IRequestExecutorBuilder)!, true); - // assert - Assert.Throws(Fail); - } + // assert + Assert.Throws(Fail); + } - [Fact] - public void AddIdSerializer_Custom_Serializer() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .TryAddIdSerializer() - .AddIdSerializer() - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - Assert.Equal("mock", serializedId); - } + [Fact] + public void AddIdSerializer_Custom_Serializer() + { + // arrange + var serializer = + new ServiceCollection() + .TryAddIdSerializer() + .AddIdSerializer() + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + Assert.Equal("mock", serializedId); + } - [Fact] - public void AddIdSerializer_Custom_Serializer_Services_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer(default(IServiceCollection)!); + [Fact] + public void AddIdSerializer_Custom_Serializer_Services_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer(default(IServiceCollection)!); - // assert - Assert.Throws(Fail); - } + // assert + Assert.Throws(Fail); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Custom_Serializer() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .AddGraphQL() - .AddIdSerializer() - .Services - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - Assert.Equal("mock", serializedId); - } + [Fact] + public void RequestBuilder_AddIdSerializer_Custom_Serializer() + { + // arrange + var serializer = + new ServiceCollection() + .AddGraphQL() + .AddIdSerializer() + .Services + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + Assert.Equal("mock", serializedId); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Custom_Serializer_Services_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer(default(IRequestExecutorBuilder)!); + [Fact] + public void RequestBuilder_AddIdSerializer_Custom_Serializer_Services_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer(default(IRequestExecutorBuilder)!); - // assert - Assert.Throws(Fail); - } + // assert + Assert.Throws(Fail); + } - [Fact] - public void AddIdSerializer_Custom_Serializer_With_Factory() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .TryAddIdSerializer() - .AddIdSerializer(s => new MockSerializer()) - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - Assert.Equal("mock", serializedId); - } + [Fact] + public void AddIdSerializer_Custom_Serializer_With_Factory() + { + // arrange + var serializer = + new ServiceCollection() + .TryAddIdSerializer() + .AddIdSerializer(s => new MockSerializer()) + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + Assert.Equal("mock", serializedId); + } - [Fact] - public void AddIdSerializer_Custom_Serializer_With_Factory_Services_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer(default(IServiceCollection)!, s => new MockSerializer()); + [Fact] + public void AddIdSerializer_Custom_Serializer_With_Factory_Services_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer(default(IServiceCollection)!, s => new MockSerializer()); - // assert - Assert.Throws(Fail); - } + // assert + Assert.Throws(Fail); + } - [Fact] - public void AddIdSerializer_Custom_Serializer_With_Factory_Factory_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer( - new ServiceCollection(), - default(Func)!); - - // assert - Assert.Throws(Fail); - } + [Fact] + public void AddIdSerializer_Custom_Serializer_With_Factory_Factory_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer( + new ServiceCollection(), + default(Func)!); + + // assert + Assert.Throws(Fail); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Custom_Serializer_With_Factory() - { - // arrange - IIdSerializer serializer = - new ServiceCollection() - .AddGraphQL() - .AddIdSerializer(s => new MockSerializer()) - .Services - .BuildServiceProvider() - .GetRequiredService(); - - // act - var serializedId = serializer.Serialize("abc", "def", "ghi"); - - // assert - Assert.Equal("mock", serializedId); - } + [Fact] + public void RequestBuilder_AddIdSerializer_Custom_Serializer_With_Factory() + { + // arrange + var serializer = + new ServiceCollection() + .AddGraphQL() + .AddIdSerializer(s => new MockSerializer()) + .Services + .BuildServiceProvider() + .GetRequiredService(); + + // act + var serializedId = serializer.Serialize("abc", "def", "ghi"); + + // assert + Assert.Equal("mock", serializedId); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Custom_Serializer_With_Fac_Services_Is_Null() - { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer(default(IRequestExecutorBuilder)!, s => new MockSerializer()); + [Fact] + public void RequestBuilder_AddIdSerializer_Custom_Serializer_With_Fac_Services_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer(default(IRequestExecutorBuilder)!, s => new MockSerializer()); - // assert - Assert.Throws(Fail); - } + // assert + Assert.Throws(Fail); + } - [Fact] - public void RequestBuilder_AddIdSerializer_Custom_Serializer_With_Fact_Factory_Is_Null() + [Fact] + public void RequestBuilder_AddIdSerializer_Custom_Serializer_With_Fact_Factory_Is_Null() + { + // arrange + // act + void Fail() => RequestExecutorBuilderExtensions + .AddIdSerializer( + new DefaultRequestExecutorBuilder(new ServiceCollection(), "Foo"), + default(Func)!); + + // assert + Assert.Throws(Fail); + } + + private sealed class MockSerializer : IIdSerializer + { + public string Serialize(NameString schemaName, NameString typeName, T id) { - // arrange - // act - void Fail() => RequestExecutorBuilderExtensions - .AddIdSerializer( - new DefaultRequestExecutorBuilder(new ServiceCollection(), "Foo"), - default(Func)!); - - // assert - Assert.Throws(Fail); + return "mock"; } - private sealed class MockSerializer : IIdSerializer + public IdValue Deserialize(string serializedId) { - public string Serialize(NameString schemaName, NameString typeName, T id) - { - return "mock"; - } - - public IdValue Deserialize(string serializedId) - { - return new IdValue(null, null, "mock"); - } + return new IdValue(null, null, "mock"); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_Validation.Tests.cs b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_Validation.Tests.cs index 0fd6702ad84..b24a2a50c18 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_Validation.Tests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/RequestExecutorBuilderExtensions_Validation.Tests.cs @@ -10,230 +10,229 @@ using HotChocolate.Types; using Snapshooter.Xunit; -namespace HotChocolate.DependencyInjection +namespace HotChocolate.DependencyInjection; + +public class RequestExecutorBuilderExtensionsValidationTests { - public class RequestExecutorBuilderExtensionsValidationTests + [Fact] + public void AddValidationVisitor_1_Builder_Is_Null() { - [Fact] - public void AddValidationVisitor_1_Builder_Is_Null() - { - void Fail() => RequestExecutorBuilderExtensions - .AddValidationVisitor(null!); - - Assert.Throws(Fail); - } - - [Fact] - public void AddValidationVisitor_2_Builder_Is_Null() - { - void Fail() => RequestExecutorBuilderExtensions - .AddValidationVisitor( - null!, - (_, _) => throw new NotImplementedException()); + void Fail() => RequestExecutorBuilderExtensions + .AddValidationVisitor(null!); - Assert.Throws(Fail); - } - - [Fact] - public void AddValidationVisitor_2_Factory_Is_Null() - { - void Fail() => new ServiceCollection() - .AddGraphQL() - .AddValidationVisitor(null!); - - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void AddValidationRuler_1_Builder_Is_Null() - { - void Fail() => RequestExecutorBuilderExtensions - .AddValidationRule(null!); + [Fact] + public void AddValidationVisitor_2_Builder_Is_Null() + { + void Fail() => RequestExecutorBuilderExtensions + .AddValidationVisitor( + null!, + (_, _) => throw new NotImplementedException()); - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void AddValidationRule_2_Builder_Is_Null() - { - void Fail() => RequestExecutorBuilderExtensions - .AddValidationRule( - null!, - (_, _) => throw new NotImplementedException()); + [Fact] + public void AddValidationVisitor_2_Factory_Is_Null() + { + void Fail() => new ServiceCollection() + .AddGraphQL() + .AddValidationVisitor(null!); - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void AddValidationRule_2_Factory_Is_Null() - { - void Fail() => new ServiceCollection() - .AddGraphQL() - .AddValidationRule(null!); + [Fact] + public void AddValidationRuler_1_Builder_Is_Null() + { + void Fail() => RequestExecutorBuilderExtensions + .AddValidationRule(null!); - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public async Task AddIntrospectionAllowedRule_IntegrationTest_NotAllowed() - { - Snapshot.FullName(); + [Fact] + public void AddValidationRule_2_Builder_Is_Null() + { + void Fail() => RequestExecutorBuilderExtensions + .AddValidationRule( + null!, + (_, _) => throw new NotImplementedException()); - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AddIntrospectionAllowedRule() - .ExecuteRequestAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .Create()) - .MatchSnapshotAsync(); - } + Assert.Throws(Fail); + } - [Fact] - public async Task AllowIntrospection_IntegrationTest_NotAllowed() - { - Snapshot.FullName(); + [Fact] + public void AddValidationRule_2_Factory_Is_Null() + { + void Fail() => new ServiceCollection() + .AddGraphQL() + .AddValidationRule(null!); - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AllowIntrospection(false) - .ExecuteRequestAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .Create()) - .MatchSnapshotAsync(); - } + Assert.Throws(Fail); + } - [Fact] - public async Task AllowIntrospection_IntegrationTest_Allowed() - { - Snapshot.FullName(); + [Fact] + public async Task AddIntrospectionAllowedRule_IntegrationTest_NotAllowed() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQLServer() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AddIntrospectionAllowedRule() + .ExecuteRequestAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .Create()) + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AllowIntrospection(true) - .ExecuteRequestAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .Create()) - .MatchSnapshotAsync(); - } + [Fact] + public async Task AllowIntrospection_IntegrationTest_NotAllowed() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQLServer() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AllowIntrospection(false) + .ExecuteRequestAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .Create()) + .MatchSnapshotAsync(); + } - [Fact] - public async Task AllowIntrospection_IntegrationTest_NotAllowed_CustomMessage() - { - Snapshot.FullName(); + [Fact] + public async Task AllowIntrospection_IntegrationTest_Allowed() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQLServer() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AllowIntrospection(true) + .ExecuteRequestAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .Create()) + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AllowIntrospection(false) - .ExecuteRequestAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .SetIntrospectionNotAllowedMessage("Bar") - .Create()) - .MatchSnapshotAsync(); - } + [Fact] + public async Task AllowIntrospection_IntegrationTest_NotAllowed_CustomMessage() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQLServer() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AllowIntrospection(false) + .ExecuteRequestAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .SetIntrospectionNotAllowedMessage("Bar") + .Create()) + .MatchSnapshotAsync(); + } - [Fact] - public async Task AddIntrospectionAllowedRule_IntegrationTest_NotAllowed_CustomMessageFact() - { - Snapshot.FullName(); + [Fact] + public async Task AddIntrospectionAllowedRule_IntegrationTest_NotAllowed_CustomMessageFact() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQLServer() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AddIntrospectionAllowedRule() + .ExecuteRequestAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .SetIntrospectionNotAllowedMessage(() => "Bar") + .Create()) + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AddIntrospectionAllowedRule() - .ExecuteRequestAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .SetIntrospectionNotAllowedMessage(() => "Bar") - .Create()) - .MatchSnapshotAsync(); - } + [Fact] + public async Task AddIntrospectionAllowedRule_IntegrationTest_NotAllowed_CustomMessage() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQLServer() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AddIntrospectionAllowedRule() + .ExecuteRequestAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .SetIntrospectionNotAllowedMessage("Baz") + .Create()) + .MatchSnapshotAsync(); + } - [Fact] - public async Task AddIntrospectionAllowedRule_IntegrationTest_NotAllowed_CustomMessage() - { - Snapshot.FullName(); + [Fact] + public async Task AddIntrospectionAllowedRule_IntegrationTest_Allowed() + { + Snapshot.FullName(); + var executor = await new ServiceCollection() .AddGraphQLServer() .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) .AddIntrospectionAllowedRule() - .ExecuteRequestAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .SetIntrospectionNotAllowedMessage("Baz") - .Create()) - .MatchSnapshotAsync(); - } + .BuildRequestExecutorAsync(); + + var results = new List(); + + var result = + await executor.ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .AllowIntrospection() + .Create()); + results.Add(result.ToJson()); + + result = + await executor.ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ __schema { description } }") + .Create()); + results.Add(result.ToJson()); + + results.MatchSnapshot(); + } - [Fact] - public async Task AddIntrospectionAllowedRule_IntegrationTest_Allowed() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AddIntrospectionAllowedRule() - .BuildRequestExecutorAsync(); - - var results = new List(); - - IExecutionResult result = - await executor.ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .AllowIntrospection() - .Create()); - results.Add(result.ToJson()); - - result = - await executor.ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ __schema { description } }") - .Create()); - results.Add(result.ToJson()); - - results.MatchSnapshot(); - } + [Fact] + public void SetMaxAllowedValidationErrors_Builder_Is_Null() + { + void Fail() + => RequestExecutorBuilderExtensions.SetMaxAllowedValidationErrors(null!, 6); - [Fact] - public void SetMaxAllowedValidationErrors_Builder_Is_Null() - { - void Fail() - => RequestExecutorBuilderExtensions.SetMaxAllowedValidationErrors(null!, 6); + Assert.Throws(Fail); + } - Assert.Throws(Fail); - } + public class MockVisitor : DocumentValidatorVisitor + { + } - public class MockVisitor : DocumentValidatorVisitor - { - } + public class MockRule : IDocumentValidatorRule + { + public bool IsCacheable => true; - public class MockRule : IDocumentValidatorRule + public void Validate(IDocumentValidatorContext context, DocumentNode document) { - public bool IsCacheable => true; - - public void Validate(IDocumentValidatorContext context, DocumentNode document) - { - throw new NotImplementedException(); - } + throw new NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Conventions.Tests.cs b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Conventions.Tests.cs index 63d5ce69062..69e62a55cb9 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Conventions.Tests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Conventions.Tests.cs @@ -7,202 +7,201 @@ #nullable enable -namespace HotChocolate.Execution.DependencyInjection +namespace HotChocolate.Execution.DependencyInjection; + +public class SchemaRequestExecutorBuilderExtensionsConventionsTests { - public class SchemaRequestExecutorBuilderExtensionsConventionsTests + [Fact] + public void AddConventionWithFactory_BuilderNull() + { + void Verify() => default(ServiceCollection)! + .AddGraphQL() + .AddConvention(typeof(Foo), _ => new Foo()); + + Assert.Throws(Verify); + } + + [Fact] + public void AddConventionWithFactory_TypeNull() + { + void Verify() => new ServiceCollection() + .AddGraphQL() + .AddConvention(default!, _ => new Foo()); + + Assert.Throws(Verify); + } + + [Fact] + public void AddConventionWithFactory_FactoryNull() + { + void Verify() => new ServiceCollection() + .AddGraphQL() + .AddConvention(typeof(Foo), default(CreateConvention)!); + + Assert.Throws(Verify); + } + + [Fact] + public async Task AddConventionWithFactory() + { + var conventionCreated = false; + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AddConvention(typeof(Foo), _ => + { + conventionCreated = true; + return new Foo(); + }) + .OnBeforeCompleteType((c, _, _) => + { + c.DescriptorContext.GetConventionOrDefault( + () => throw new NotSupportedException()); + }) + .BuildSchemaAsync(); + + Assert.True(conventionCreated); + } + + [Fact] + public async Task AddConventionWithFactoryAndScope() + { + var conventionCreated = false; + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AddConvention(typeof(Foo), _ => + { + conventionCreated = true; + return new Foo(); + }, "bar") + .OnBeforeCompleteType((c, _, _) => + { + c.DescriptorContext.GetConventionOrDefault( + () => throw new NotSupportedException(), + "bar"); + }) + .BuildSchemaAsync(); + + Assert.True(conventionCreated); + } + + [Fact] + public void AddConventionWithType_BuilderNull() + { + void Verify() => default(ServiceCollection)! + .AddGraphQL() + .AddConvention(typeof(Foo)); + + Assert.Throws(Verify); + } + + [Fact] + public void AddConventionWithType_TypeNull() + { + void Verify() => new ServiceCollection() + .AddGraphQL() + .AddConvention(default(Type)!); + + Assert.Throws(Verify); + } + + [Fact] + public async Task AddConventionWithType() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .AddConvention(typeof(Foo)) + .OnBeforeCompleteType((c, _, _) => + { + c.DescriptorContext.GetConventionOrDefault( + () => throw new NotSupportedException()); + }) + .BuildSchemaAsync(); + } + + [Fact] + public void TryAddConventionWithFactory_BuilderNull() + { + void Verify() => default(ServiceCollection)! + .AddGraphQL() + .TryAddConvention(typeof(Foo), _ => new Foo()); + + Assert.Throws(Verify); + } + + [Fact] + public void TryAddConventionWithFactory_TypeNull() + { + void Verify() => new ServiceCollection() + .AddGraphQL() + .TryAddConvention(default!, _ => new Foo()); + + Assert.Throws(Verify); + } + + [Fact] + public void TryAddConventionWithFactory_FactoryNull() + { + void Verify() => new ServiceCollection() + .AddGraphQL() + .TryAddConvention(typeof(Foo), default(CreateConvention)!); + + Assert.Throws(Verify); + } + + [Fact] + public async Task TryAddConventionWithFactory() + { + var conventionCreated = false; + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .TryAddConvention(typeof(Foo), _ => + { + conventionCreated = true; + return new Foo(); + }) + .OnBeforeCompleteType((c, _, _) => + { + c.DescriptorContext.GetConventionOrDefault( + () => throw new NotSupportedException()); + }) + .BuildSchemaAsync(); + + Assert.True(conventionCreated); + } + + [Fact] + public async Task TryAddConventionWithFactoryAndScope() + { + var conventionCreated = false; + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) + .TryAddConvention(typeof(Foo), _ => + { + conventionCreated = true; + return new Foo(); + }, "bar") + .OnBeforeCompleteType((c, _, _) => + { + c.DescriptorContext.GetConventionOrDefault( + () => throw new NotSupportedException(), + "bar"); + }) + .BuildSchemaAsync(); + + Assert.True(conventionCreated); + } + + public class Foo : IConvention { - [Fact] - public void AddConventionWithFactory_BuilderNull() - { - void Verify() => default(ServiceCollection)! - .AddGraphQL() - .AddConvention(typeof(Foo), _ => new Foo()); - - Assert.Throws(Verify); - } - - [Fact] - public void AddConventionWithFactory_TypeNull() - { - void Verify() => new ServiceCollection() - .AddGraphQL() - .AddConvention(default!, _ => new Foo()); - - Assert.Throws(Verify); - } - - [Fact] - public void AddConventionWithFactory_FactoryNull() - { - void Verify() => new ServiceCollection() - .AddGraphQL() - .AddConvention(typeof(Foo), default(CreateConvention)!); - - Assert.Throws(Verify); - } - - [Fact] - public async Task AddConventionWithFactory() - { - var conventionCreated = false; - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AddConvention(typeof(Foo), _ => - { - conventionCreated = true; - return new Foo(); - }) - .OnBeforeCompleteType((c, _, _) => - { - c.DescriptorContext.GetConventionOrDefault( - () => throw new NotSupportedException()); - }) - .BuildSchemaAsync(); - - Assert.True(conventionCreated); - } - - [Fact] - public async Task AddConventionWithFactoryAndScope() - { - var conventionCreated = false; - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AddConvention(typeof(Foo), _ => - { - conventionCreated = true; - return new Foo(); - }, "bar") - .OnBeforeCompleteType((c, _, _) => - { - c.DescriptorContext.GetConventionOrDefault( - () => throw new NotSupportedException(), - "bar"); - }) - .BuildSchemaAsync(); - - Assert.True(conventionCreated); - } - - [Fact] - public void AddConventionWithType_BuilderNull() - { - void Verify() => default(ServiceCollection)! - .AddGraphQL() - .AddConvention(typeof(Foo)); - - Assert.Throws(Verify); - } - - [Fact] - public void AddConventionWithType_TypeNull() - { - void Verify() => new ServiceCollection() - .AddGraphQL() - .AddConvention(default(Type)!); - - Assert.Throws(Verify); - } - - [Fact] - public async Task AddConventionWithType() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .AddConvention(typeof(Foo)) - .OnBeforeCompleteType((c, _, _) => - { - c.DescriptorContext.GetConventionOrDefault( - () => throw new NotSupportedException()); - }) - .BuildSchemaAsync(); - } - - [Fact] - public void TryAddConventionWithFactory_BuilderNull() - { - void Verify() => default(ServiceCollection)! - .AddGraphQL() - .TryAddConvention(typeof(Foo), _ => new Foo()); - - Assert.Throws(Verify); - } - - [Fact] - public void TryAddConventionWithFactory_TypeNull() - { - void Verify() => new ServiceCollection() - .AddGraphQL() - .TryAddConvention(default!, _ => new Foo()); - - Assert.Throws(Verify); - } - - [Fact] - public void TryAddConventionWithFactory_FactoryNull() - { - void Verify() => new ServiceCollection() - .AddGraphQL() - .TryAddConvention(typeof(Foo), default(CreateConvention)!); - - Assert.Throws(Verify); - } - - [Fact] - public async Task TryAddConventionWithFactory() - { - var conventionCreated = false; - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .TryAddConvention(typeof(Foo), _ => - { - conventionCreated = true; - return new Foo(); - }) - .OnBeforeCompleteType((c, _, _) => - { - c.DescriptorContext.GetConventionOrDefault( - () => throw new NotSupportedException()); - }) - .BuildSchemaAsync(); - - Assert.True(conventionCreated); - } - - [Fact] - public async Task TryAddConventionWithFactoryAndScope() - { - var conventionCreated = false; - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Name("Query").Field("foo").Resolve("bar")) - .TryAddConvention(typeof(Foo), _ => - { - conventionCreated = true; - return new Foo(); - }, "bar") - .OnBeforeCompleteType((c, _, _) => - { - c.DescriptorContext.GetConventionOrDefault( - () => throw new NotSupportedException(), - "bar"); - }) - .BuildSchemaAsync(); - - Assert.True(conventionCreated); - } - - public class Foo : IConvention - { - public string? Scope { get; set; } - } + public string? Scope { get; set; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.TypeInterceptor.Tests.cs b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.TypeInterceptor.Tests.cs index 9cc6fa765ec..d8a3417b1a0 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.TypeInterceptor.Tests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.TypeInterceptor.Tests.cs @@ -9,801 +9,800 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.DependencyInjection +namespace HotChocolate.Execution.DependencyInjection; + +public class SchemaRequestExecutorBuilderExtensionsTypeInterceptorTests { - public class SchemaRequestExecutorBuilderExtensionsTypeInterceptorTests + [Fact] + public async Task OnBeforeRegisterDependencies() { - [Fact] - public async Task OnBeforeRegisterDependencies() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeRegisterDependencies( - (_, def, _) => + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + })); - [Fact] - public async Task OnBeforeRegisterDependencies_Generic() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeRegisterDependencies( - (_, def, _) => - { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + // assert + Assert.True(found); + } - [Fact] - public async Task OnBeforeRegisterDependencies_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeRegisterDependencies( - (_, def, _) => + [Fact] + public async Task OnBeforeRegisterDependencies_Generic() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + })); - [Fact] - public async Task OnBeforeRegisterDependencies_Generic_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeRegisterDependencies( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnBeforeRegisterDependencies_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnAfterRegisterDependencies() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterRegisterDependencies( - (_, def, _) => + [Fact] + public async Task OnBeforeRegisterDependencies_Generic_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnAfterRegisterDependencies_Generic() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterRegisterDependencies( - (_, def, _) => + [Fact] + public async Task OnAfterRegisterDependencies() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + })); - [Fact] - public async Task OnAfterRegisterDependencies_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterRegisterDependencies( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnAfterRegisterDependencies_Generic() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + })); - [Fact] - public async Task OnAfterRegisterDependencies_Generic_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterRegisterDependencies( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnAfterRegisterDependencies_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnBeforeCompleteName() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteName( - (_, def, _) => + [Fact] + public async Task OnAfterRegisterDependencies_Generic_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterRegisterDependencies( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnBeforeCompleteName_Generic() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteName( - (_, def, _) => + [Fact] + public async Task OnBeforeCompleteName() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + })); - [Fact] - public async Task OnBeforeCompleteName_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteName( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnBeforeCompleteName_Generic() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + })); - [Fact] - public async Task OnBeforeCompleteName_Generic_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteName( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnBeforeCompleteName_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnAfterCompleteName() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteName( - (_, def, _) => + [Fact] + public async Task OnBeforeCompleteName_Generic_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnAfterCompleteName_Generic() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteName( - (_, def, _) => + [Fact] + public async Task OnAfterCompleteName() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + })); - [Fact] - public async Task OnAfterCompleteName_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteName( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnAfterCompleteName_Generic() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + })); - [Fact] - public async Task OnAfterCompleteName_Generic_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteName( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnAfterCompleteName_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnBeforeCompleteType() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteType( - (_, def, _) => + [Fact] + public async Task OnAfterCompleteName_Generic_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteName( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnBeforeCompleteType_Generic() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteType( - (_, def, _) => + [Fact] + public async Task OnBeforeCompleteType() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + })); - [Fact] - public async Task OnBeforeCompleteType_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteType( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnBeforeCompleteType_Generic() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + })); - [Fact] - public async Task OnBeforeCompleteType_Generic_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteType( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnBeforeCompleteType_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnAfterCompleteType() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteType( - (_, def, _) => + [Fact] + public async Task OnBeforeCompleteType_Generic_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnAfterCompleteType_Generic() - { - // arrange - Snapshot.FullName(); - var found = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteType( - (_, def, _) => + [Fact] + public async Task OnAfterCompleteType() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - })); - - // assert - Assert.True(found); - } + found = true; + } + })); - [Fact] - public async Task OnAfterCompleteType_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterCompleteType( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnAfterCompleteType_Generic() + { + // arrange + Snapshot.FullName(); + var found = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + })); - [Fact] - public async Task OnAfterCompleteType_Generic_CanHandle() - { - // arrange - Snapshot.FullName(); - var found = false; - var canHandleInvoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeCompleteType( - (_, def, _) => + // assert + Assert.True(found); + } + + [Fact] + public async Task OnAfterCompleteType_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - if (def is not null && def.Name.Equals("Query")) - { - found = true; - } - }, - _ => canHandleInvoked = true)); - - // assert - Assert.True(found); - Assert.True(canHandleInvoked); - } + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - [Fact] - public async Task OnBeforeSchemaCreate() - { - // arrange - Snapshot.FullName(); - var invoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnBeforeSchemaCreate( - (_, _) => + [Fact] + public async Task OnAfterCompleteType_Generic_CanHandle() + { + // arrange + Snapshot.FullName(); + var found = false; + var canHandleInvoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeCompleteType( + (_, def, _) => + { + if (def is not null && def.Name.Equals("Query")) { - invoked = true; - })); + found = true; + } + }, + _ => canHandleInvoked = true)); + + // assert + Assert.True(found); + Assert.True(canHandleInvoked); + } - // assert - Assert.True(invoked); - } + [Fact] + public async Task OnBeforeSchemaCreate() + { + // arrange + Snapshot.FullName(); + var invoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnBeforeSchemaCreate( + (_, _) => + { + invoked = true; + })); + + // assert + Assert.True(invoked); + } - [Fact] - public void OnBeforeSchemaCreate_Builder_IsNull() - { - void Action() => - SchemaRequestExecutorBuilderExtensions - .OnBeforeSchemaCreate(null!, (_, _) => { }); + [Fact] + public void OnBeforeSchemaCreate_Builder_IsNull() + { + void Action() => + SchemaRequestExecutorBuilderExtensions + .OnBeforeSchemaCreate(null!, (_, _) => { }); - Assert.Throws(Action); - } + Assert.Throws(Action); + } - [Fact] - public void OnBeforeSchemaCreate_OnError_IsNull() - { - var builder = new Mock(); + [Fact] + public void OnBeforeSchemaCreate_OnError_IsNull() + { + var builder = new Mock(); - void Action() => - builder.Object.OnBeforeSchemaCreate(null!); + void Action() => + builder.Object.OnBeforeSchemaCreate(null!); - Assert.Throws(Action); - } + Assert.Throws(Action); + } - [Fact] - public async Task OnAfterSchemaCreate() - { - // arrange - Snapshot.FullName(); - var invoked = false; - - // act - await CreateSchemaAsync(c => c - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .OnAfterSchemaCreate( - (_, _) => - { - invoked = true; - })); + [Fact] + public async Task OnAfterSchemaCreate() + { + // arrange + Snapshot.FullName(); + var invoked = false; + + // act + await CreateSchemaAsync(c => c + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .OnAfterSchemaCreate( + (_, _) => + { + invoked = true; + })); + + // assert + Assert.True(invoked); + } - // assert - Assert.True(invoked); - } + [Fact] + public void OnAfterSchemaCreate_Builder_IsNull() + { + void Action() => + SchemaRequestExecutorBuilderExtensions + .OnAfterSchemaCreate(null!, (_, _) => { }); - [Fact] - public void OnAfterSchemaCreate_Builder_IsNull() - { - void Action() => - SchemaRequestExecutorBuilderExtensions - .OnAfterSchemaCreate(null!, (_, _) => { }); + Assert.Throws(Action); + } - Assert.Throws(Action); - } + [Fact] + public void OnAfterSchemaCreate_OnError_IsNull() + { + var builder = new Mock(); - [Fact] - public void OnAfterSchemaCreate_OnError_IsNull() - { - var builder = new Mock(); + void Action() => + builder.Object.OnAfterSchemaCreate(null!); - void Action() => - builder.Object.OnAfterSchemaCreate(null!); + Assert.Throws(Action); + } - Assert.Throws(Action); - } + [Fact] + public async Task OnSchemaError() + { + // arrange + Snapshot.FullName(); + Exception ex = null; - [Fact] - public async Task OnSchemaError() + // act + try { - // arrange - Snapshot.FullName(); - Exception ex = null; - - // act - try - { - await new ServiceCollection() - .AddGraphQL() - .OnSchemaError((_, exception) => ex = exception) - .BuildSchemaAsync(); - } - catch - { - // ignored - } - - // assert - Assert.IsType(ex); + await new ServiceCollection() + .AddGraphQL() + .OnSchemaError((_, exception) => ex = exception) + .BuildSchemaAsync(); } - - [Fact] - public void OnSchemaError_Builder_IsNull() + catch { - void Action() => - SchemaRequestExecutorBuilderExtensions - .OnSchemaError(null!, (_, _) => { }); - - Assert.Throws(Action); + // ignored } - [Fact] - public void OnSchemaError_OnError_IsNull() - { - var builder = new Mock(); + // assert + Assert.IsType(ex); + } - void Action() => - builder.Object.OnSchemaError(null!); + [Fact] + public void OnSchemaError_Builder_IsNull() + { + void Action() => + SchemaRequestExecutorBuilderExtensions + .OnSchemaError(null!, (_, _) => { }); - Assert.Throws(Action); - } + Assert.Throws(Action); + } + + [Fact] + public void OnSchemaError_OnError_IsNull() + { + var builder = new Mock(); + + void Action() => + builder.Object.OnSchemaError(null!); + + Assert.Throws(Action); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Types.Tests.cs b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Types.Tests.cs index f3767079bdf..714fb0f9ca1 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Types.Tests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjection/SchemaRequestExecutorBuilderExtensions.Types.Tests.cs @@ -5,138 +5,137 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.DependencyInjection +namespace HotChocolate.Execution.DependencyInjection; + +public class SchemaRequestExecutorBuilderExtensionsTypesTests { - public class SchemaRequestExecutorBuilderExtensionsTypesTests + [Fact] + public async Task AddObjectType_TIsSchemaType() { - [Fact] - public async Task AddObjectType_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => + (await Assert.ThrowsAsync(async () => await new ServiceCollection() .AddGraphQL() .AddQueryType() .AddObjectType() .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddObjectType_Configure_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddObjectType(d => { }) - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddObjectType_Configure_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddObjectType(d => { }) + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddInterfaceType_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddInterfaceType() - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddInterfaceType_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddInterfaceType() + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddInterfaceType_Configure_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddInterfaceType(d => { }) - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddInterfaceType_Configure_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddInterfaceType(d => { }) + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddUnionType_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddUnionType() - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddUnionType_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddUnionType() + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddUnionType_Configure_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddObjectType(d => { }) - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddUnionType_Configure_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddObjectType(d => { }) + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddEnumType_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddEnumType() - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddEnumType_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddEnumType() + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddEnumType_Configure_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddEnumType(d => { }) - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddEnumType_Configure_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddEnumType(d => { }) + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddInputObjectType_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddInputObjectType() - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddInputObjectType_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddInputObjectType() + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); + } - [Fact] - public async Task AddInputObjectType_Configure_TIsSchemaType() - { - (await Assert.ThrowsAsync(async () => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddInputObjectType(d => { }) - .BuildSchemaAsync())) - .Message - .MatchSnapshot(); - } + [Fact] + public async Task AddInputObjectType_Configure_TIsSchemaType() + { + (await Assert.ThrowsAsync(async () => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddInputObjectType(d => { }) + .BuildSchemaAsync())) + .Message + .MatchSnapshot(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjectionTests.cs b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjectionTests.cs index 69612528fcc..5388c02b7eb 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/DependencyInjectionTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/DependencyInjectionTests.cs @@ -7,181 +7,180 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class DependencyInjectionTests { - public class DependencyInjectionTests + [Fact] + public async Task Extension_With_Constructor_Injection() { - [Fact] - public async Task Extension_With_Constructor_Injection() + // this test ensures that we inject services into type instances without the need of + // registering the type into the dependency container. + var executor = + await new ServiceCollection() + .AddSingleton() + .AddGraphQL() + .AddQueryType() + .AddType() + .BuildRequestExecutorAsync(); + + new { - // this test ensures that we inject services into type instances without the need of - // registering the type into the dependency container. - IRequestExecutor executor = - await new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddQueryType() - .AddType() - .BuildRequestExecutorAsync(); - - new - { - result1 = await executor - .ExecuteAsync("{ hello }") - .ToJsonAsync(), - result2 = await executor - .ExecuteAsync("{ hello }") - .ToJsonAsync() - }.MatchSnapshot(); - } + result1 = await executor + .ExecuteAsync("{ hello }") + .ToJsonAsync(), + result2 = await executor + .ExecuteAsync("{ hello }") + .ToJsonAsync() + }.MatchSnapshot(); + } - [Fact] - public async Task Extension_With_Scoped_Constructor_Injection() - { - IServiceProvider services = - new ServiceCollection() - .AddScoped() - .AddScoped() - .AddGraphQL() - .AddQueryType() - .AddType() - .Services - .BuildServiceProvider(); - - IRequestExecutor executor = await services.GetRequestExecutorAsync(); - - var result = new string[2]; - - using (IServiceScope scope = services.CreateScope()) - { - result[0] = await executor - .ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ hello }") - .SetServices(scope.ServiceProvider) - .Create()) - .ToJsonAsync(); - } - - using (IServiceScope scope = services.CreateScope()) - { - result[1] = await executor - .ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ hello }") - .SetServices(scope.ServiceProvider) - .Create()) - .ToJsonAsync(); - } - - result.MatchSnapshot(); - } + [Fact] + public async Task Extension_With_Scoped_Constructor_Injection() + { + IServiceProvider services = + new ServiceCollection() + .AddScoped() + .AddScoped() + .AddGraphQL() + .AddQueryType() + .AddType() + .Services + .BuildServiceProvider(); + + var executor = await services.GetRequestExecutorAsync(); - [Fact] - public async Task Type_With_Constructor_Injection() + var result = new string[2]; + + using (var scope = services.CreateScope()) { - // this test ensures that we inject services into type instances without the need of - // registering the type into the dependency container. - IRequestExecutor executor = - await new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - new - { - result1 = await executor - .ExecuteAsync("{ hello }") - .ToJsonAsync(), - result2 = await executor - .ExecuteAsync("{ hello }") - .ToJsonAsync() - }.MatchSnapshot(); + result[0] = await executor + .ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ hello }") + .SetServices(scope.ServiceProvider) + .Create()) + .ToJsonAsync(); } - [Fact] - public async Task Type_With_Scoped_Constructor_Injection() + using (var scope = services.CreateScope()) { - IServiceProvider services = - new ServiceCollection() - .AddScoped() - .AddScoped() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider(); - - IRequestExecutor executor = await services.GetRequestExecutorAsync(); - - var result = new string[2]; - - using (IServiceScope scope = services.CreateScope()) - { - result[0] = await executor - .ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ hello }") - .SetServices(scope.ServiceProvider) - .Create()) - .ToJsonAsync(); - } - - using (IServiceScope scope = services.CreateScope()) - { - result[1] = await executor - .ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ hello }") - .SetServices(scope.ServiceProvider) - .Create()) - .ToJsonAsync(); - } - - result.MatchSnapshot(); + result[1] = await executor + .ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ hello }") + .SetServices(scope.ServiceProvider) + .Create()) + .ToJsonAsync(); } - public class SomeService + result.MatchSnapshot(); + } + + [Fact] + public async Task Type_With_Constructor_Injection() + { + // this test ensures that we inject services into type instances without the need of + // registering the type into the dependency container. + var executor = + await new ServiceCollection() + .AddSingleton() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + new { - private int _i; + result1 = await executor + .ExecuteAsync("{ hello }") + .ToJsonAsync(), + result2 = await executor + .ExecuteAsync("{ hello }") + .ToJsonAsync() + }.MatchSnapshot(); + } - public int Count => _i; + [Fact] + public async Task Type_With_Scoped_Constructor_Injection() + { + IServiceProvider services = + new ServiceCollection() + .AddScoped() + .AddScoped() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider(); - public string SayHello() => "Hello_" + _i++; - } + var executor = await services.GetRequestExecutorAsync(); - public class Query1 - { + var result = new string[2]; + using (var scope = services.CreateScope()) + { + result[0] = await executor + .ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ hello }") + .SetServices(scope.ServiceProvider) + .Create()) + .ToJsonAsync(); } - [ExtendObjectType(typeof(Query1))] - public class ExtendQuery1 + using (var scope = services.CreateScope()) { - private readonly SomeService _service; + result[1] = await executor + .ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ hello }") + .SetServices(scope.ServiceProvider) + .Create()) + .ToJsonAsync(); + } - public ExtendQuery1(SomeService service) - { - _service = service ?? throw new ArgumentNullException(nameof(service)); - } + result.MatchSnapshot(); + } - public string Hello() => _service.SayHello(); - } + public class SomeService + { + private int _i; + + public int Count => _i; + + public string SayHello() => "Hello_" + _i++; + } + + public class Query1 + { + + } - public class Query2 + [ExtendObjectType(typeof(Query1))] + public class ExtendQuery1 + { + private readonly SomeService _service; + + public ExtendQuery1(SomeService service) { - private readonly SomeService _service; + _service = service ?? throw new ArgumentNullException(nameof(service)); + } + + public string Hello() => _service.SayHello(); + } - public Query2(SomeService service) - { - _service = service ?? throw new ArgumentNullException(nameof(service)); - } + public class Query2 + { + private readonly SomeService _service; - public string Hello() => _service.SayHello(); + public Query2(SomeService service) + { + _service = service ?? throw new ArgumentNullException(nameof(service)); } + + public string Hello() => _service.SayHello(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorBehaviorTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorBehaviorTests.cs index 391b47afeda..d4f4b8c2d8a 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorBehaviorTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorBehaviorTests.cs @@ -6,298 +6,297 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Errors +namespace HotChocolate.Execution.Errors; + +public class ErrorBehaviorTests { - public class ErrorBehaviorTests + [Fact] + public Task SyntaxError() { - [Fact] - public Task SyntaxError() - { - Snapshot.FullName(); - return ExpectError("{ error1"); - } + Snapshot.FullName(); + return ExpectError("{ error1"); + } - [Fact] - public Task AsyncMethod_NoAwait_Throw_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error1 }"); - } + [Fact] + public Task AsyncMethod_NoAwait_Throw_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error1 }"); + } - [Fact] - public Task AsyncMethod_Await_Throw_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error4 }"); - } + [Fact] + public Task AsyncMethod_Await_Throw_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error4 }"); + } - [Fact] - public Task SyncMethod_Throw_ApplicationError() - { + [Fact] + public Task SyncMethod_Throw_ApplicationError() + { - Snapshot.FullName(); - return ExpectError("{ error7 }"); - } + Snapshot.FullName(); + return ExpectError("{ error7 }"); + } - [Fact] - public Task Property_Throw_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error10 }"); - } + [Fact] + public Task Property_Throw_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error10 }"); + } - [Fact] - public Task AsyncMethod_NoAwait_Throw_UnexpectedError() - { - Snapshot.FullName(); - return ExpectError("{ error2 }"); - } + [Fact] + public Task AsyncMethod_NoAwait_Throw_UnexpectedError() + { + Snapshot.FullName(); + return ExpectError("{ error2 }"); + } - [Fact] - public Task AsyncMethod_Await_Throw_UnexpectedError() - { - Snapshot.FullName(); - return ExpectError("{ error5 }"); - } + [Fact] + public Task AsyncMethod_Await_Throw_UnexpectedError() + { + Snapshot.FullName(); + return ExpectError("{ error5 }"); + } - [Fact] - public Task SyncMethod_Throw_UnexpectedError() - { - Snapshot.FullName(); - return ExpectError("{ error8 }"); - } + [Fact] + public Task SyncMethod_Throw_UnexpectedError() + { + Snapshot.FullName(); + return ExpectError("{ error8 }"); + } - [Fact] - public Task Property_Throw_UnexpectedError() - { - Snapshot.FullName(); - return ExpectError("{ error11 }"); - } + [Fact] + public Task Property_Throw_UnexpectedError() + { + Snapshot.FullName(); + return ExpectError("{ error11 }"); + } - [Fact] - public Task AsyncMethod_NoAwait_Return_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error3 }"); - } + [Fact] + public Task AsyncMethod_NoAwait_Return_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error3 }"); + } - [Fact] - public Task AsyncMethod_Await_Return_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error6 }"); - } + [Fact] + public Task AsyncMethod_Await_Return_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error6 }"); + } - [Fact] - public Task SyncMethod_Return_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error9 }"); - } + [Fact] + public Task SyncMethod_Return_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error9 }"); + } - [Fact] - public Task Property_Return_ApplicationError() - { - Snapshot.FullName(); - return ExpectError("{ error12 }"); - } + [Fact] + public Task Property_Return_ApplicationError() + { + Snapshot.FullName(); + return ExpectError("{ error12 }"); + } + + [Fact] + public Task Property_Return_UnexpectedErrorWithPath() + { + Snapshot.FullName(); + return ExpectError("{ error13 }", 0); + } + + [Fact] + public Task RootTypeNotDefined() + { + Snapshot.FullName(); + return TestHelper.ExpectError( + "type Query { foo: String }", + "mutation { foo }"); + } + + [Fact] + public Task RootFieldNotDefined() + { + Snapshot.FullName(); + return TestHelper.ExpectError( + @"type Query { a: String } type Mutation { bar: String }", + "mutation { foo }"); + } + + [Fact] + public Task ErrorFilterHandlesException() + { + Snapshot.FullName(); + return TestHelper.ExpectError( + "{ error14 }", + b => b + .AddQueryType() + .ModifyRequestOptions(o => o.IncludeExceptionDetails = false)); + } + + [Fact] + public async void Resolver_InvalidParentCast() + { + Snapshot.FullName(); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d + .Field("foo") + .Type>() + .Extend() + // in the pure resolver we will return the wrong type + .Definition.Resolver = _ => new ValueTask(new Baz())) + .ExecuteRequestAsync("{ foo { bar } }") + .MatchSnapshotAsync(); + } + + [Fact] + public async void PureResolver_InvalidParentCast() + { + Snapshot.FullName(); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d + .Field("foo") + .Type>() + .Extend() + // in the pure resolver we will return the wrong type + .Definition.PureResolver = _ => new Baz()) + .ExecuteRequestAsync("{ foo { bar } }") + .MatchSnapshotAsync(); + } - [Fact] - public Task Property_Return_UnexpectedErrorWithPath() + [Fact] + public async void SetMaxAllowedValidationErrors_To_1() + { + Snapshot.FullName(); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d + .Field("foo") + .Type>() + .Extend() + // in the pure resolver we will return the wrong type + .Definition.PureResolver = _ => new Baz()) + .SetMaxAllowedValidationErrors(1) + .ExecuteRequestAsync("{ a b c d }") + .MatchSnapshotAsync(); + } + + + private async Task ExpectError( + string query, + int expectedErrorCount = 1) + { + var errors = 0; + + await TestHelper.ExpectError( + query, + b => b + .AddQueryType() + .AddErrorFilter(error => + { + errors++; + return error; + })); + + Assert.Equal(expectedErrorCount, errors); + } + + public class QueryType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - Snapshot.FullName(); - return ExpectError("{ error13 }", 0); + descriptor.Field(t => t.Error3()).Type(); + descriptor.Field(t => t.Error6()).Type(); + descriptor.Field(t => t.Error9()).Type(); + descriptor.Field(t => t.Error12).Type(); } + } - [Fact] - public Task RootTypeNotDefined() + public class Query + { + public Task Error1() { - Snapshot.FullName(); - return TestHelper.ExpectError( - "type Query { foo: String }", - "mutation { foo }"); + throw new QueryException("query error 1"); } - [Fact] - public Task RootFieldNotDefined() + public Task Error2() { - Snapshot.FullName(); - return TestHelper.ExpectError( - @"type Query { a: String } type Mutation { bar: String }", - "mutation { foo }"); + throw new Exception("query error 2"); } - [Fact] - public Task ErrorFilterHandlesException() + public Task Error3() { - Snapshot.FullName(); - return TestHelper.ExpectError( - "{ error14 }", - b => b - .AddQueryType() - .ModifyRequestOptions(o => o.IncludeExceptionDetails = false)); + return Task.FromResult( + ErrorBuilder.New() + .SetMessage("query error 3") + .Build()); } - [Fact] - public async void Resolver_InvalidParentCast() + public async Task Error4() { - Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d - .Field("foo") - .Type>() - .Extend() - // in the pure resolver we will return the wrong type - .Definition.Resolver = _ => new ValueTask(new Baz())) - .ExecuteRequestAsync("{ foo { bar } }") - .MatchSnapshotAsync(); + await Task.Delay(1); + throw new QueryException("query error 4"); } - [Fact] - public async void PureResolver_InvalidParentCast() + public async Task Error5() { - Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d - .Field("foo") - .Type>() - .Extend() - // in the pure resolver we will return the wrong type - .Definition.PureResolver = _ => new Baz()) - .ExecuteRequestAsync("{ foo { bar } }") - .MatchSnapshotAsync(); + await Task.Delay(1); + throw new Exception("query error 5"); } - [Fact] - public async void SetMaxAllowedValidationErrors_To_1() + public async Task Error6() { - Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d - .Field("foo") - .Type>() - .Extend() - // in the pure resolver we will return the wrong type - .Definition.PureResolver = _ => new Baz()) - .SetMaxAllowedValidationErrors(1) - .ExecuteRequestAsync("{ a b c d }") - .MatchSnapshotAsync(); + await Task.Delay(1); + return await Task.FromResult( + ErrorBuilder.New() + .SetMessage("query error 6") + .Build()); } - - private async Task ExpectError( - string query, - int expectedErrorCount = 1) + public string Error7() { - int errors = 0; - - await TestHelper.ExpectError( - query, - b => b - .AddQueryType() - .AddErrorFilter(error => - { - errors++; - return error; - })); - - Assert.Equal(expectedErrorCount, errors); + throw new QueryException("query error 7"); } - public class QueryType : ObjectType + public string Error8() { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Error3()).Type(); - descriptor.Field(t => t.Error6()).Type(); - descriptor.Field(t => t.Error9()).Type(); - descriptor.Field(t => t.Error12).Type(); - } + throw new Exception("query error 8"); } - public class Query + public object Error9() { - public Task Error1() - { - throw new QueryException("query error 1"); - } - - public Task Error2() - { - throw new Exception("query error 2"); - } - - public Task Error3() - { - return Task.FromResult( - ErrorBuilder.New() - .SetMessage("query error 3") - .Build()); - } - - public async Task Error4() - { - await Task.Delay(1); - throw new QueryException("query error 4"); - } - - public async Task Error5() - { - await Task.Delay(1); - throw new Exception("query error 5"); - } - - public async Task Error6() - { - await Task.Delay(1); - return await Task.FromResult( - ErrorBuilder.New() - .SetMessage("query error 6") - .Build()); - } - - public string Error7() - { - throw new QueryException("query error 7"); - } - - public string Error8() - { - throw new Exception("query error 8"); - } - - public object Error9() - { - return ErrorBuilder.New() - .SetMessage("query error 9") - .Build(); - } - - public string Error10 => throw new QueryException("query error 10"); - - public string Error11 => throw new Exception("query error 11"); - - public object Error12 => ErrorBuilder.New() - .SetMessage("query error 12") + return ErrorBuilder.New() + .SetMessage("query error 9") .Build(); + } - public Foo Error13 => new Foo(); + public string Error10 => throw new QueryException("query error 10"); - public string Error14 => throw new ArgumentNullException("Error14"); - } + public string Error11 => throw new Exception("query error 11"); - public class Foo - { - public string Bar => throw new Exception("baz"); - } + public object Error12 => ErrorBuilder.New() + .SetMessage("query error 12") + .Build(); - public class Baz - { - public string Bar => throw new Exception("baz"); - } + public Foo Error13 => new Foo(); + + public string Error14 => throw new ArgumentNullException("Error14"); + } + + public class Foo + { + public string Bar => throw new Exception("baz"); + } + + public class Baz + { + public string Bar => throw new Exception("baz"); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorHandlerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorHandlerTests.cs index ba07973474f..8b06d6509a9 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorHandlerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Errors/ErrorHandlerTests.cs @@ -6,181 +6,180 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Errors +namespace HotChocolate.Execution.Errors; + +public class ErrorHandlerTests { - public class ErrorHandlerTests + [Fact] + public async Task AddFuncErrorFilter() { - [Fact] - public async Task AddFuncErrorFilter() - { - Snapshot.FullName(); - await ExpectError( - "{ foo }", - b => b - .AddDocumentFromString("type Query { foo: String }") - .UseField(_ => _ => throw new Exception("Foo")) - .Services - .AddErrorFilter(error => error.WithCode("Foo123"))); - } + Snapshot.FullName(); + await ExpectError( + "{ foo }", + b => b + .AddDocumentFromString("type Query { foo: String }") + .UseField(_ => _ => throw new Exception("Foo")) + .Services + .AddErrorFilter(error => error.WithCode("Foo123"))); + } - [Fact] - public async Task FilterOnlyNullRefExceptions() - { - Snapshot.FullName(); - await ExpectError( - "{ foo bar }", - b => b - .AddDocumentFromString("type Query { foo: String bar: String }") - .AddResolver("Query", "foo", _ => throw new Exception("Foo")) - .AddResolver("Query", "bar", _ => throw new NullReferenceException("Foo")) - .AddErrorFilter(error => + [Fact] + public async Task FilterOnlyNullRefExceptions() + { + Snapshot.FullName(); + await ExpectError( + "{ foo bar }", + b => b + .AddDocumentFromString("type Query { foo: String bar: String }") + .AddResolver("Query", "foo", _ => throw new Exception("Foo")) + .AddResolver("Query", "bar", _ => throw new NullReferenceException("Foo")) + .AddErrorFilter(error => + { + if (error.Exception is NullReferenceException) { - if (error.Exception is NullReferenceException) - { - return error.WithCode("NullRef"); - } - return error; - }), - - expectedErrorCount: 2); - } + return error.WithCode("NullRef"); + } + return error; + }), - [Fact] - public async Task AddClassErrorFilter() - { - Snapshot.FullName(); - await ExpectError( - "{ foo }", - b => b - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", _ => throw new Exception("Foo")) - .Services - .AddErrorFilter()); - } + expectedErrorCount: 2); + } - [Fact] - public async Task AddClassErrorFilter_SchemaBuiltViaServiceExtensions_ErrorFilterWorks() - { - // arrange - var serviceCollection = new ServiceCollection(); - IRequestExecutor schema = await serviceCollection - .AddGraphQLServer() - .AddErrorFilter() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult resp = await schema.ExecuteAsync("{ foo }"); - - // assert - resp.MatchSnapshot(); - } + [Fact] + public async Task AddClassErrorFilter() + { + Snapshot.FullName(); + await ExpectError( + "{ foo }", + b => b + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", _ => throw new Exception("Foo")) + .Services + .AddErrorFilter()); + } - [Fact] - public async Task AddClassErrorFilterUsingFactory_SchemaBuiltViaServiceExtensions_ErrorFilterWorks() - { - // arrange - var serviceCollection = new ServiceCollection(); - IRequestExecutor schema = await serviceCollection - .AddGraphQLServer() - .AddErrorFilter(f => new DummyErrorFilter()) - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult resp = await schema.ExecuteAsync("{ foo }"); - - // assert - resp.MatchSnapshot(); - } + [Fact] + public async Task AddClassErrorFilter_SchemaBuiltViaServiceExtensions_ErrorFilterWorks() + { + // arrange + var serviceCollection = new ServiceCollection(); + var schema = await serviceCollection + .AddGraphQLServer() + .AddErrorFilter() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var resp = await schema.ExecuteAsync("{ foo }"); + + // assert + resp.MatchSnapshot(); + } - [Fact] - public async Task AddClassErrorFilterWithFactory() - { - Snapshot.FullName(); - await ExpectError( - "{ foo }", - b => b - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", _ => throw new Exception("Foo")) - .Services - .AddErrorFilter(_ => new DummyErrorFilter())); - } + [Fact] + public async Task AddClassErrorFilterUsingFactory_SchemaBuiltViaServiceExtensions_ErrorFilterWorks() + { + // arrange + var serviceCollection = new ServiceCollection(); + var schema = await serviceCollection + .AddGraphQLServer() + .AddErrorFilter(f => new DummyErrorFilter()) + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var resp = await schema.ExecuteAsync("{ foo }"); + + // assert + resp.MatchSnapshot(); + } - [Fact] - public async Task UseAggregateError_In_ErrorFilter() - { - Snapshot.FullName(); - - await ExpectError( - "{ foo }", - b => b - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", _ => throw new Exception("Foo")) - .Services - .AddErrorFilter(_ => new AggregateErrorFilter())); - } + [Fact] + public async Task AddClassErrorFilterWithFactory() + { + Snapshot.FullName(); + await ExpectError( + "{ foo }", + b => b + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", _ => throw new Exception("Foo")) + .Services + .AddErrorFilter(_ => new DummyErrorFilter())); + } - [Fact] - public async Task ReportAggregateError_In_Resolver() - { - Snapshot.FullName(); + [Fact] + public async Task UseAggregateError_In_ErrorFilter() + { + Snapshot.FullName(); + + await ExpectError( + "{ foo }", + b => b + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", _ => throw new Exception("Foo")) + .Services + .AddErrorFilter(_ => new AggregateErrorFilter())); + } - await ExpectError( - "{ foo }", - b => b - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", ctx => - { - ctx.ReportError(new AggregateError(new Error("abc"), new Error("def"))); - return "Hello"; - }), - expectedErrorCount: 2); - } + [Fact] + public async Task ReportAggregateError_In_Resolver() + { + Snapshot.FullName(); - private async Task ExpectError( - string query, - Action configure, - int expectedErrorCount = 1) - { - var errors = 0; + await ExpectError( + "{ foo }", + b => b + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", ctx => + { + ctx.ReportError(new AggregateError(new Error("abc"), new Error("def"))); + return "Hello"; + }), + expectedErrorCount: 2); + } - await TestHelper.ExpectError( - query, - b => + private async Task ExpectError( + string query, + Action configure, + int expectedErrorCount = 1) + { + var errors = 0; + + await TestHelper.ExpectError( + query, + b => + { + configure(b); + b.AddErrorFilter(error => { - configure(b); - b.AddErrorFilter(error => - { - errors++; - return error; - }); + errors++; + return error; }); + }); - Assert.Equal(expectedErrorCount, errors); - } + Assert.Equal(expectedErrorCount, errors); + } - public class DummyErrorFilter : IErrorFilter + public class DummyErrorFilter : IErrorFilter + { + public IError OnError(IError error) { - public IError OnError(IError error) - { - return error.WithCode("Foo123"); - } + return error.WithCode("Foo123"); } + } - public class AggregateErrorFilter : IErrorFilter + public class AggregateErrorFilter : IErrorFilter + { + public IError OnError(IError error) { - public IError OnError(IError error) - { - return new AggregateError( - error.WithCode("A"), - error.WithCode("B")); - } + return new AggregateError( + error.WithCode("A"), + error.WithCode("B")); } + } - public class Query - { - public string GetFoo() => throw new Exception("FooError"); - } + public class Query + { + public string GetFoo() => throw new Exception("FooError"); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/ApolloTracingTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/ApolloTracingTests.cs index 510a08b7d33..d34403f4824 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/ApolloTracingTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/ApolloTracingTests.cs @@ -6,113 +6,112 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Instrumentation +namespace HotChocolate.Execution.Instrumentation; + +public class DiagnosticsEventsTests { - public class DiagnosticsEventsTests + [Fact] + public async Task ApolloTracing_Always() { - [Fact] - public async Task ApolloTracing_Always() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - @" + // arrange + var executor = await CreateExecutorAsync(c => c + .AddDocumentFromString( + @" type Query { a: String }") - .AddResolver("Query", "a", () => "hello world a") - .AddApolloTracing(TracingPreference.Always, new TestTimestampProvider())); + .AddResolver("Query", "a", () => "hello world a") + .AddApolloTracing(TracingPreference.Always, new TestTimestampProvider())); - // act - IExecutionResult result = await executor.ExecuteAsync("{ a }"); + // act + var result = await executor.ExecuteAsync("{ a }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task ApolloTracing_Always_Parsing_And_Validation_Is_Cached() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - @" + [Fact] + public async Task ApolloTracing_Always_Parsing_And_Validation_Is_Cached() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddDocumentFromString( + @" type Query { a: String }") - .AddResolver("Query", "a", () => "hello world a") - .AddApolloTracing(TracingPreference.Always, new TestTimestampProvider())); + .AddResolver("Query", "a", () => "hello world a") + .AddApolloTracing(TracingPreference.Always, new TestTimestampProvider())); - // act - await executor.ExecuteAsync("{ a }"); + // act + await executor.ExecuteAsync("{ a }"); - // the second execution will not parse or validate since these steps are cached. - IExecutionResult result = await executor.ExecuteAsync("{ a }"); + // the second execution will not parse or validate since these steps are cached. + var result = await executor.ExecuteAsync("{ a }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task ApolloTracing_OnDemand_NoHeader() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - @" + [Fact] + public async Task ApolloTracing_OnDemand_NoHeader() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddDocumentFromString( + @" type Query { a: String }") - .AddResolver("Query", "a", () => "hello world a") - .AddApolloTracing(TracingPreference.OnDemand, new TestTimestampProvider())); + .AddResolver("Query", "a", () => "hello world a") + .AddApolloTracing(TracingPreference.OnDemand, new TestTimestampProvider())); - // act - IExecutionResult result = await executor.ExecuteAsync("{ a }"); + // act + var result = await executor.ExecuteAsync("{ a }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task ApolloTracing_OnDemand_WithHeader() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - @" + [Fact] + public async Task ApolloTracing_OnDemand_WithHeader() + { + // arrange + var 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( - QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetProperty(WellKnownContextData.EnableTracing, true) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); + .AddResolver("Query", "a", () => "hello world a") + .AddApolloTracing(TracingPreference.OnDemand, new TestTimestampProvider())); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetProperty(WellKnownContextData.EnableTracing, true) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + private sealed class TestTimestampProvider : ITimestampProvider + { + private DateTime _utcNow = new DateTime(2010, 10, 10, 12, 00, 00); + private long _nowInNanoseconds = 10; + + public DateTime UtcNow() + { + var time = _utcNow; + _utcNow = _utcNow.AddMilliseconds(50); + return time; } - private sealed class TestTimestampProvider : ITimestampProvider + public long NowInNanoseconds() { - private DateTime _utcNow = new DateTime(2010, 10, 10, 12, 00, 00); - private long _nowInNanoseconds = 10; - - public DateTime UtcNow() - { - DateTime time = _utcNow; - _utcNow = _utcNow.AddMilliseconds(50); - return time; - } - - public long NowInNanoseconds() - { - return _nowInNanoseconds += 20; - } + return _nowInNanoseconds += 20; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/DiagnosticListenerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/DiagnosticListenerTests.cs index 52b5e40a296..50df35b3b5b 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/DiagnosticListenerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Instrumentation/DiagnosticListenerTests.cs @@ -8,119 +8,118 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Instrumentation +namespace HotChocolate.Execution.Instrumentation; + +public class DiagnosticListenerTests { - public class DiagnosticListenerTests + [Fact] + public async Task Intercept_Resolver_Result_With_Listener() { - [Fact] - public async Task Intercept_Resolver_Result_With_Listener() - { - // arrange - var listener = new TestListener(); - var executor = await CreateExecutorAsync(c => c - .AddDiagnosticEventListener(_ => listener) - .AddStarWarsTypes() - .Services - .AddStarWarsRepositories()); - - // act - var result = await executor.ExecuteAsync("{ hero { name } }"); - - // assert - Assert.Null(Assert.IsType(result).Errors); - Assert.Collection(listener.Results, r => Assert.IsType(r)); - } + // arrange + var listener = new TestListener(); + var executor = await CreateExecutorAsync(c => c + .AddDiagnosticEventListener(_ => listener) + .AddStarWarsTypes() + .Services + .AddStarWarsRepositories()); + + // act + var result = await executor.ExecuteAsync("{ hero { name } }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + Assert.Collection(listener.Results, r => Assert.IsType(r)); + } - [Fact] - public async Task Intercept_Resolver_Result_With_Listener_2() - { - // arrange - var services = new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddDiagnosticEventListener() - .AddStarWars() - .Services - .BuildServiceProvider(); - - // act - await services.ExecuteRequestAsync("{ hero { name } }"); - - // assert - Assert.True(services.GetRequiredService().Signal); - } + [Fact] + public async Task Intercept_Resolver_Result_With_Listener_2() + { + // arrange + var services = new ServiceCollection() + .AddSingleton() + .AddGraphQL() + .AddDiagnosticEventListener() + .AddStarWars() + .Services + .BuildServiceProvider(); + + // act + await services.ExecuteRequestAsync("{ hero { name } }"); + + // assert + Assert.True(services.GetRequiredService().Signal); + } - [Fact] - public async Task Intercept_Resolver_Result_With_Multiple_Listener() + [Fact] + public async Task Intercept_Resolver_Result_With_Multiple_Listener() + { + // arrange + var listenerA = new TestListener(); + var listenerB = new TestListener(); + var executor = await CreateExecutorAsync(c => c + .AddDiagnosticEventListener(_ => listenerA) + .AddDiagnosticEventListener(_ => listenerB) + .AddStarWarsTypes() + .Services + .AddStarWarsRepositories()); + + // act + var result = await executor.ExecuteAsync("{ hero { name } }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + Assert.Collection(listenerA.Results, r => Assert.IsType(r)); + Assert.Collection(listenerB.Results, r => Assert.IsType(r)); + } + + public class Touched + { + public bool Signal = false; + } + + private class TouchedListener : ExecutionDiagnosticEventListener + { + private readonly Touched _touched; + + public TouchedListener(Touched touched) { - // arrange - var listenerA = new TestListener(); - var listenerB = new TestListener(); - var executor = await CreateExecutorAsync(c => c - .AddDiagnosticEventListener(_ => listenerA) - .AddDiagnosticEventListener(_ => listenerB) - .AddStarWarsTypes() - .Services - .AddStarWarsRepositories()); - - // act - var result = await executor.ExecuteAsync("{ hero { name } }"); - - // assert - Assert.Null(Assert.IsType(result).Errors); - Assert.Collection(listenerA.Results, r => Assert.IsType(r)); - Assert.Collection(listenerB.Results, r => Assert.IsType(r)); + _touched = touched; } - public class Touched + public override IDisposable ExecuteRequest(IRequestContext context) { - public bool Signal = false; + _touched.Signal = true; + return EmptyScope; } + } - private class TouchedListener : ExecutionDiagnosticEventListener - { - private readonly Touched _touched; + private sealed class TestListener : ExecutionDiagnosticEventListener + { + public List Results { get; } = new(); - public TouchedListener(Touched touched) - { - _touched = touched; - } + public override bool EnableResolveFieldValue => true; - public override IDisposable ExecuteRequest(IRequestContext context) - { - _touched.Signal = true; - return EmptyScope; - } + public override IDisposable ResolveFieldValue(IMiddlewareContext context) + { + return new ResolverActivityScope(context, Results); } - private sealed class TestListener : ExecutionDiagnosticEventListener + private sealed class ResolverActivityScope : IDisposable { - public List Results { get; } = new(); - - public override bool EnableResolveFieldValue => true; - - public override IDisposable ResolveFieldValue(IMiddlewareContext context) + public ResolverActivityScope(IMiddlewareContext context, List results) { - return new ResolverActivityScope(context, Results); + Context = context; + Results = results; } - private sealed class ResolverActivityScope : IDisposable - { - public ResolverActivityScope(IMiddlewareContext context, List results) - { - Context = context; - Results = results; - } - - private IMiddlewareContext Context { get; } + private IMiddlewareContext Context { get; } - public List Results { get; } + public List Results { get; } - public void Dispose() - { - Results.Add(Context.Result); - } + public void Dispose() + { + Results.Add(Context.Result); } } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Cancellation/CancellationTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Cancellation/CancellationTests.cs index 30c264c164c..ad97e331f6a 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Cancellation/CancellationTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Cancellation/CancellationTests.cs @@ -15,7 +15,7 @@ public async Task Ensure_Execution_Waits_For_Tasks() // arrange var query = new Query(); - IRequestExecutor executor = + var executor = await new ServiceCollection() .AddSingleton(query) .AddGraphQL() diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Components/VariableCoercionIntegrationTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Components/VariableCoercionIntegrationTests.cs index c61101bad27..0392626fbbc 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Components/VariableCoercionIntegrationTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Components/VariableCoercionIntegrationTests.cs @@ -6,214 +6,213 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Integration.Components +namespace HotChocolate.Execution.Integration.Components; + +public class VariableCoercionIntegrationTests { - public class VariableCoercionIntegrationTests + [Fact] + public async Task Nullables_And_NonNullables_Are_Set() { - [Fact] - public async Task Nullables_And_NonNullables_Are_Set() - { - Snapshot.FullName(); + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - var user = new ObjectValueNode( - new ObjectFieldNode("name", "Oliver"), - new ObjectFieldNode("surname", "Smith")); + var user = new ObjectValueNode( + new ObjectFieldNode("name", "Oliver"), + new ObjectFieldNode("surname", "Smith")); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", user) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", user) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Nullables_Are_Not_Set_NonNullables_Are_Set() - { - Snapshot.FullName(); + [Fact] + public async Task Nullables_Are_Not_Set_NonNullables_Are_Set() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - var user = new ObjectValueNode( - new ObjectFieldNode("name", "Oliver")); + var user = new ObjectValueNode( + new ObjectFieldNode("name", "Oliver")); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", user) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", user) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Nullables_Are_Set_And_NonNullables_Are_Set_To_Null() - { - Snapshot.FullName(); + [Fact] + public async Task Nullables_Are_Set_And_NonNullables_Are_Set_To_Null() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - var user = new ObjectValueNode( - new ObjectFieldNode("name", NullValueNode.Default), - new ObjectFieldNode("surname", "Smith")); + var user = new ObjectValueNode( + new ObjectFieldNode("name", NullValueNode.Default), + new ObjectFieldNode("surname", "Smith")); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", user) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", user) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Nullables_Are_Set_And_NonNullables_Not_Are_Set() - { - Snapshot.FullName(); + [Fact] + public async Task Nullables_Are_Set_And_NonNullables_Not_Are_Set() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - var user = new ObjectValueNode( - new ObjectFieldNode("surname", "Smith")); + var user = new ObjectValueNode( + new ObjectFieldNode("surname", "Smith")); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", user) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", user) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Empty_Object() - { - Snapshot.FullName(); + [Fact] + public async Task Empty_Object() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - var user = new ObjectValueNode(); + var user = new ObjectValueNode(); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", user) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", user) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Variable_Null() - { - Snapshot.FullName(); + [Fact] + public async Task Variable_Null() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", null) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", null) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Variable_Not_Provided() - { - Snapshot.FullName(); + [Fact] + public async Task Variable_Not_Provided() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - [Fact] - public async Task Invalid_Field_Provided() - { - Snapshot.FullName(); + [Fact] + public async Task Invalid_Field_Provided() + { + Snapshot.FullName(); - IRequestExecutor executor = await CreateSchemaAsync(); + var executor = await CreateSchemaAsync(); - var user = new ObjectValueNode( - new ObjectFieldNode("name", "Oliver"), - new ObjectFieldNode("surname", "Smith"), - new ObjectFieldNode("foo", "bar")); + var user = new ObjectValueNode( + new ObjectFieldNode("name", "Oliver"), + new ObjectFieldNode("surname", "Smith"), + new ObjectFieldNode("foo", "bar")); - IReadOnlyQueryRequest request = - QueryRequestBuilder - .New() - .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") - .SetVariableValue("user", user) - .Create(); + var request = + QueryRequestBuilder + .New() + .SetQuery("mutation($user: UserInput!) { addUser(user: $user) }") + .SetVariableValue("user", user) + .Create(); - await executor.ExecuteAsync(request).MatchSnapshotAsync(); - } + await executor.ExecuteAsync(request).MatchSnapshotAsync(); + } - private static async Task CreateSchemaAsync() - { - return await new ServiceCollection() - .AddGraphQL() - .AddQueryType(t => t.Field("a").Resolve("b")) - .AddMutationType() - .BuildRequestExecutorAsync(); - } + private static async Task CreateSchemaAsync() + { + return await new ServiceCollection() + .AddGraphQL() + .AddQueryType(t => t.Field("a").Resolve("b")) + .AddMutationType() + .BuildRequestExecutorAsync(); + } - public class UserMutation + public class UserMutation + { + public string AddUser(User user) { - public string AddUser(User user) - { - return user.Name + " " + user.Surname + " was added!"; - } + return user.Name + " " + user.Surname + " was added!"; } + } - public class UserMutationType : ObjectType + public class UserMutationType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(um => um.AddUser(default)) - .Description("Add user to db") - .Argument("user", d => d.Type>() - .Description("User input type, required")); - } + descriptor + .Field(um => um.AddUser(default)) + .Description("Add user to db") + .Argument("user", d => d.Type>() + .Description("User input type, required")); } + } - public class User - { - public string Name { get; set; } + public class User + { + public string Name { get; set; } - public string Surname { get; set; } - } + public string Surname { get; set; } + } - public class UserInputType : InputObjectType + public class UserInputType : InputObjectType + { + protected override void Configure(IInputObjectTypeDescriptor descriptor) { - protected override void Configure(IInputObjectTypeDescriptor descriptor) - { - descriptor - .Field(f => f.Name) - .Type>() - .Description("User's name, required"); - - descriptor.Field(f => f.Surname) - .Description("User's surname"); - } + descriptor + .Field(f => f.Name) + .Type>() + .Description("User's name, required"); + + descriptor.Field(f => f.Surname) + .Description("User's surname"); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs index cad1b1922b6..fa0145e6e8b 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs @@ -18,122 +18,74 @@ #nullable enable -namespace HotChocolate.Execution.Integration.DataLoader +namespace HotChocolate.Execution.Integration.DataLoader; + +public class DataLoaderTests { - public class DataLoaderTests + [Fact] + public async Task FetchOnceDataLoader() { - [Fact] - public async Task FetchOnceDataLoader() - { - Snapshot.FullName(); - await ExpectValid( - "{ fetchItem }", - configure: b => b - .AddGraphQL() - .AddDocumentFromString("type Query { fetchItem: String }") - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .AddResolver( - "Query", "fetchItem", - async ctx => await ctx.FetchOnceAsync(_ => Task.FromResult("fooBar"))) - ) - .MatchSnapshotAsync(); - } - - [Fact] - public async Task FetchSingleDataLoader() - { - Snapshot.FullName(); - await ExpectValid( - "{ fetchItem }", - configure: b => b - .AddGraphQL() - .AddDocumentFromString("type Query { fetchItem: String }") - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .AddResolver( - "Query", "fetchItem", - async ctx => await ctx.CacheDataLoader( - (key, _) => Task.FromResult(key)) - .LoadAsync("fooBar")) - ) - .MatchSnapshotAsync(); - } - - [Fact] - public async Task FetchDataLoader() - { - Snapshot.FullName(); - await ExpectValid( - "{ fetchItem }", - configure: b => b - .AddGraphQL() - .AddDocumentFromString("type Query { fetchItem: String }") - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .AddResolver( - "Query", "fetchItem", - async ctx => await ctx.BatchDataLoader( - (keys, _) => Task.FromResult>( - keys.ToDictionary(t => t))) - .LoadAsync("fooBar")) - ) - .MatchSnapshotAsync(); - } - - [Fact] - public async Task FetchGroupDataLoader() - { - Snapshot.FullName(); - await ExpectValid( - "{ fetchItem }", - configure: b => b - .AddGraphQL() - .AddDocumentFromString("type Query { fetchItem: String }") - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .AddResolver( - "Query", "fetchItem", - async ctx => await ctx.GroupDataLoader( - (keys, _) => Task.FromResult( - keys.ToLookup(t => t))) - .LoadAsync("fooBar")) - ) - .MatchSnapshotAsync(); - } - - [Fact] - public async Task AddSingleDiagnosticEventListener() - { - var listener = new DataLoaderListener(); + Snapshot.FullName(); + await ExpectValid( + "{ fetchItem }", + configure: b => b + .AddGraphQL() + .AddDocumentFromString("type Query { fetchItem: String }") + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .AddResolver( + "Query", "fetchItem", + async ctx => await ctx.FetchOnceAsync(_ => Task.FromResult("fooBar"))) + ) + .MatchSnapshotAsync(); + } - await ExpectValid( + [Fact] + public async Task FetchSingleDataLoader() + { + Snapshot.FullName(); + await ExpectValid( "{ fetchItem }", - b => b + configure: b => b .AddGraphQL() - .AddDiagnosticEventListener(_ => listener) .AddDocumentFromString("type Query { fetchItem: String }") .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) .AddResolver( "Query", "fetchItem", - async ctx => await ctx.GroupDataLoader( - (keys, _) => Task.FromResult( - keys.ToLookup(t => t))) + async ctx => await ctx.CacheDataLoader( + (key, _) => Task.FromResult(key)) .LoadAsync("fooBar")) - ); - - Assert.True(listener.ExecuteBatchTouched); - Assert.True(listener.BatchResultsTouched); - } + ) + .MatchSnapshotAsync(); + } - [Fact] - public async Task AddMultipleDiagnosticEventListener() - { - var listener1 = new DataLoaderListener(); - var listener2 = new DataLoaderListener(); + [Fact] + public async Task FetchDataLoader() + { + Snapshot.FullName(); + await ExpectValid( + "{ fetchItem }", + configure: b => b + .AddGraphQL() + .AddDocumentFromString("type Query { fetchItem: String }") + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .AddResolver( + "Query", "fetchItem", + async ctx => await ctx.BatchDataLoader( + (keys, _) => Task.FromResult>( + keys.ToDictionary(t => t))) + .LoadAsync("fooBar")) + ) + .MatchSnapshotAsync(); + } - await ExpectValid( + [Fact] + public async Task FetchGroupDataLoader() + { + Snapshot.FullName(); + await ExpectValid( "{ fetchItem }", - b => b + configure: b => b .AddGraphQL() - .AddDiagnosticEventListener(_ => listener1) - .AddDiagnosticEventListener(_ => listener2) .AddDocumentFromString("type Query { fetchItem: String }") .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) .AddResolver( @@ -142,407 +94,454 @@ await ExpectValid( (keys, _) => Task.FromResult( keys.ToLookup(t => t))) .LoadAsync("fooBar")) - ); + ) + .MatchSnapshotAsync(); + } - Assert.True(listener1.ExecuteBatchTouched); - Assert.True(listener1.BatchResultsTouched); - Assert.True(listener2.ExecuteBatchTouched); - Assert.True(listener2.BatchResultsTouched); - } + [Fact] + public async Task AddSingleDiagnosticEventListener() + { + var listener = new DataLoaderListener(); - [Fact] - public async Task ClassDataLoader() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType() - .AddDataLoader() + await ExpectValid( + "{ fetchItem }", + b => b + .AddGraphQL() + .AddDiagnosticEventListener(_ => listener) + .AddDocumentFromString("type Query { fetchItem: String }") + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .AddResolver( + "Query", "fetchItem", + async ctx => await ctx.GroupDataLoader( + (keys, _) => Task.FromResult( + keys.ToLookup(t => t))) + .LoadAsync("fooBar")) + ); + + Assert.True(listener.ExecuteBatchTouched); + Assert.True(listener.BatchResultsTouched); + } + + [Fact] + public async Task AddMultipleDiagnosticEventListener() + { + var listener1 = new DataLoaderListener(); + var listener2 = new DataLoaderListener(); + + await ExpectValid( + "{ fetchItem }", + b => b + .AddGraphQL() + .AddDiagnosticEventListener(_ => listener1) + .AddDiagnosticEventListener(_ => listener2) + .AddDocumentFromString("type Query { fetchItem: String }") .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .UseRequest(next => async context => - { - await next(context); - - TestDataLoader dataLoader = - context.Services - .GetRequiredService() - .GetOrRegister(() => throw new Exception()); - - context.Result = QueryResultBuilder - .FromResult(((IQueryResult)context.Result!)) - .AddExtension("loads", dataLoader.Loads) - .Create(); - }) - .UseDefaultPipeline()); - - // act - var results = new List + .AddResolver( + "Query", "fetchItem", + async ctx => await ctx.GroupDataLoader( + (keys, _) => Task.FromResult( + keys.ToLookup(t => t))) + .LoadAsync("fooBar")) + ); + + Assert.True(listener1.ExecuteBatchTouched); + Assert.True(listener1.BatchResultsTouched); + Assert.True(listener2.ExecuteBatchTouched); + Assert.True(listener2.BatchResultsTouched); + } + + [Fact] + public async Task ClassDataLoader() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddQueryType() + .AddDataLoader() + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .UseRequest(next => async context => { - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + await next(context); + + var dataLoader = + context.Services + .GetRequiredService() + .GetOrRegister(() => throw new Exception()); + + context.Result = QueryResultBuilder + .FromResult(((IQueryResult)context.Result!)) + .AddExtension("loads", dataLoader.Loads) + .Create(); + }) + .UseDefaultPipeline()); + + // act + var results = new List + { + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: withDataLoader(key: ""a"") b: withDataLoader(key: ""b"") bar { c: withDataLoader(key: ""c"") } }") - .Create()), - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create()), + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: withDataLoader(key: ""a"") }") - .Create()), - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create()), + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ c: withDataLoader(key: ""c"") }") - .Create()) - }; + .Create()) + }; - // assert - results.MatchSnapshot(); - } + // assert + results.MatchSnapshot(); + } - [Fact] - public async Task ClassDataLoaderWithKey() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType() - .AddDataLoader() - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .UseRequest(next => async context => - { - await next(context); - - TestDataLoader dataLoader = - context.Services - .GetRequiredService() - .GetOrRegister("fooBar", () => throw new Exception()); - - context.Result = QueryResultBuilder - .FromResult(((IQueryResult)context.Result!)) - .AddExtension("loads", dataLoader.Loads) - .Create(); - }) - .UseDefaultPipeline()); - - // act - var results = new List + [Fact] + public async Task ClassDataLoaderWithKey() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddQueryType() + .AddDataLoader() + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .UseRequest(next => async context => { - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + await next(context); + + var dataLoader = + context.Services + .GetRequiredService() + .GetOrRegister("fooBar", () => throw new Exception()); + + context.Result = QueryResultBuilder + .FromResult(((IQueryResult)context.Result!)) + .AddExtension("loads", dataLoader.Loads) + .Create(); + }) + .UseDefaultPipeline()); + + // act + var results = new List + { + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: withDataLoader2(key: ""a"") b: withDataLoader2(key: ""b"") }") - .Create()), - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create()), + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: withDataLoader2(key: ""a"") }") - .Create()), - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create()), + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ c: withDataLoader2(key: ""c"") }") - .Create()) - }; + .Create()) + }; - // assert - results.MatchSnapshot(); - } + // assert + results.MatchSnapshot(); + } - [Fact] - public async Task StackedDataLoader() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType() - .AddDataLoader() - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true)); - - // act - var results = new List(); - - results.Add( - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + [Fact] + public async Task StackedDataLoader() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddQueryType() + .AddDataLoader() + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true)); + + // act + var results = new List(); + + results.Add( + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: withStackedDataLoader(key: ""a"") b: withStackedDataLoader(key: ""b"") }") - .Create())); + .Create())); - results.Add( - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + results.Add( + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: withStackedDataLoader(key: ""a"") }") - .Create())); + .Create())); - results.Add( - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + results.Add( + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ c: withStackedDataLoader(key: ""c"") }") - .Create())); + .Create())); - // assert - results.MatchSnapshot(); - } + // assert + results.MatchSnapshot(); + } - [Fact] - public async Task ClassDataLoader_Resolve_From_DependencyInjection() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddQueryType() - .AddDataLoader() - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .UseRequest(next => async context => - { - await next(context); - - var dataLoader = - (TestDataLoader)context.Services.GetRequiredService(); - - context.Result = QueryResultBuilder - .FromResult(((IQueryResult)context.Result!)) - .AddExtension("loads", dataLoader.Loads) - .Create(); - }) - .UseDefaultPipeline()); - - // act - var results = new List + [Fact] + public async Task ClassDataLoader_Resolve_From_DependencyInjection() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddQueryType() + .AddDataLoader() + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .UseRequest(next => async context => { - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + await next(context); + + var dataLoader = + (TestDataLoader)context.Services.GetRequiredService(); + + context.Result = QueryResultBuilder + .FromResult(((IQueryResult)context.Result!)) + .AddExtension("loads", dataLoader.Loads) + .Create(); + }) + .UseDefaultPipeline()); + + // act + var results = new List + { + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: dataLoaderWithInterface(key: ""a"") b: dataLoaderWithInterface(key: ""b"") }") - .Create()), - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create()), + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ a: dataLoaderWithInterface(key: ""a"") }") - .Create()), - await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"{ + .Create()), + await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"{ c: dataLoaderWithInterface(key: ""c"") }") - .Create()) - }; + .Create()) + }; - // assert - results.MatchSnapshot(); - } + // assert + results.MatchSnapshot(); + } - [Fact] - public async Task NestedDataLoader() - { - using var cts = new CancellationTokenSource(500); + [Fact] + public async Task NestedDataLoader() + { + using var cts = new CancellationTokenSource(500); + + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .AddDataLoader() + .AddDataLoader() + .ExecuteRequestAsync("query Foo { foo { id field } }", cancellationToken: cts.Token) + .MatchSnapshotAsync(); + } - Snapshot.FullName(); + [Fact] + public async Task Ensure_That_DataLoader_Dispatch_Correctly_When_Used_Serially() + { + Snapshot.FullName(); + var executor = await new ServiceCollection() - .AddGraphQL() + .AddGraphQLServer() .AddQueryType() - .AddType() - .AddDataLoader() - .AddDataLoader() - .ExecuteRequestAsync("query Foo { foo { id field } }", cancellationToken: cts.Token) - .MatchSnapshotAsync(); - } + .AddMutationType() + .AddDataLoader() + .ModifyOptions(o => o.StrictValidation = false) + .BuildRequestExecutorAsync(); - [Fact] - public async Task Ensure_That_DataLoader_Dispatch_Correctly_When_Used_Serially() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQLServer() - .AddQueryType() - .AddMutationType() - .AddDataLoader() - .ModifyOptions(o => o.StrictValidation = false) - .BuildRequestExecutorAsync(); - - IExecutionResult result = await executor.ExecuteAsync( - @"mutation { + var result = await executor.ExecuteAsync( + @"mutation { a: doSomething(key: ""a"") b: doSomething(key: ""b"") }"); - result.MatchSnapshot(); - } - - public class DataLoaderListener : DataLoaderDiagnosticEventListener - { - public bool ResolvedTaskFromCacheTouched; - public bool ExecuteBatchTouched; - public bool BatchResultsTouched; - public bool BatchErrorTouched; - public bool BatchItemErrorTouched; - - public override void ResolvedTaskFromCache(IDataLoader dataLoader, TaskCacheKey cacheKey, Task task) - { - ResolvedTaskFromCacheTouched = true; - } + result.MatchSnapshot(); + } - public override IDisposable ExecuteBatch(IDataLoader dataLoader, IReadOnlyList keys) - { - ExecuteBatchTouched = true; - return base.ExecuteBatch(dataLoader, keys); - } + public class DataLoaderListener : DataLoaderDiagnosticEventListener + { + public bool ResolvedTaskFromCacheTouched; + public bool ExecuteBatchTouched; + public bool BatchResultsTouched; + public bool BatchErrorTouched; + public bool BatchItemErrorTouched; - public override void BatchResults(IReadOnlyList keys, - ReadOnlySpan> values) - { - BatchResultsTouched = true; - } + public override void ResolvedTaskFromCache(IDataLoader dataLoader, TaskCacheKey cacheKey, Task task) + { + ResolvedTaskFromCacheTouched = true; + } - public override void BatchError(IReadOnlyList keys, Exception error) - { - BatchErrorTouched = true; - } + public override IDisposable ExecuteBatch(IDataLoader dataLoader, IReadOnlyList keys) + { + ExecuteBatchTouched = true; + return base.ExecuteBatch(dataLoader, keys); + } - public override void BatchItemError(TKey key, Exception error) - { - BatchItemErrorTouched = true; - } + public override void BatchResults(IReadOnlyList keys, + ReadOnlySpan> values) + { + BatchResultsTouched = true; } - [ExtendObjectType("Query")] - public class FooQueries + public override void BatchError(IReadOnlyList keys, Exception error) { - public async Task GetFoo(IResolverContext context, CancellationToken ct) => - await FooObject.Get(context, "hello", ct); + BatchErrorTouched = true; } - [GraphQLName("Foo")] - [Node] - public class FooObject + public override void BatchItemError(TKey key, Exception error) { - public FooObject(string field) - { - id = field; - } + BatchItemErrorTouched = true; + } + } - public string id { get; } - public string field => id; + [ExtendObjectType("Query")] + public class FooQueries + { + public async Task GetFoo(IResolverContext context, CancellationToken ct) => + await FooObject.Get(context, "hello", ct); + } - public static async Task Get(IResolverContext context, string id, - CancellationToken ct) => - new((await context.DataLoader().LoadAsync(id, ct)).Field); + [GraphQLName("Foo")] + [Node] + public class FooObject + { + public FooObject(string field) + { + id = field; } - public class FooDataLoader : BatchDataLoader - { - private readonly FooNestedDataLoader _nestedDataLoader; + public string id { get; } + public string field => id; - public FooDataLoader( - IBatchScheduler batchScheduler, - FooNestedDataLoader nestedDataLoader, - DataLoaderOptions? options = null) - : base(batchScheduler, options) - { - _nestedDataLoader = nestedDataLoader; - } + public static async Task Get(IResolverContext context, string id, + CancellationToken ct) => + new((await context.DataLoader().LoadAsync(id, ct)).Field); + } + + public class FooDataLoader : BatchDataLoader + { + private readonly FooNestedDataLoader _nestedDataLoader; - protected override async Task> LoadBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) - => (await _nestedDataLoader.LoadAsync(keys, cancellationToken)) - .ToImmutableDictionary(x => x.Field); + public FooDataLoader( + IBatchScheduler batchScheduler, + FooNestedDataLoader nestedDataLoader, + DataLoaderOptions? options = null) + : base(batchScheduler, options) + { + _nestedDataLoader = nestedDataLoader; } - public class FooNestedDataLoader : BatchDataLoader + protected override async Task> LoadBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) + => (await _nestedDataLoader.LoadAsync(keys, cancellationToken)) + .ToImmutableDictionary(x => x.Field); + } + + public class FooNestedDataLoader : BatchDataLoader + { + public FooNestedDataLoader( + IBatchScheduler batchScheduler, + DataLoaderOptions? options = null) + : base(batchScheduler, options) { - public FooNestedDataLoader( - IBatchScheduler batchScheduler, - DataLoaderOptions? options = null) - : base(batchScheduler, options) - { - } + } - protected override async Task> LoadBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) - { - await Task.Delay(1, cancellationToken); - return keys.ToImmutableDictionary(key => key, key => new FooRecord(key)); - } + protected override async Task> LoadBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) + { + await Task.Delay(1, cancellationToken); + return keys.ToImmutableDictionary(key => key, key => new FooRecord(key)); } + } - public class FooRecord + public class FooRecord + { + public FooRecord(string field) { - public FooRecord(string field) - { - Field = field; - } + Field = field; + } - public string Field { get; } + public string Field { get; } + } + + public class SerialMutation + { + [Serial] + public async Task DoSomethingAsync( + CustomDataLoader dataLoader, + string key, + CancellationToken cancellationToken) + { + var value = await dataLoader.LoadAsync(key, cancellationToken); + return value; } + } - public class SerialMutation + public class CustomDataLoader : BatchDataLoader + { + public CustomDataLoader( + IBatchScheduler batchScheduler, + DataLoaderOptions? options = null) + : base(batchScheduler, options) { - [Serial] - public async Task DoSomethingAsync( - CustomDataLoader dataLoader, - string key, - CancellationToken cancellationToken) - { - string value = await dataLoader.LoadAsync(key, cancellationToken); - return value; - } } - public class CustomDataLoader : BatchDataLoader + protected override Task> LoadBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) { - public CustomDataLoader( - IBatchScheduler batchScheduler, - DataLoaderOptions? options = null) - : base(batchScheduler, options) - { - } + var dict = new Dictionary(); - protected override Task> LoadBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) + foreach (var s in keys) { - var dict = new Dictionary(); - - foreach (string s in keys) - { - dict[s] = s + "_value"; - } - - return Task.FromResult>(dict); + dict[s] = s + "_value"; } + + return Task.FromResult>(dict); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/ITestDataLoader.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/ITestDataLoader.cs index 70d5e07b7e0..90aa4001a8a 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/ITestDataLoader.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/ITestDataLoader.cs @@ -1,10 +1,9 @@ using GreenDonut; -namespace HotChocolate.Execution.Integration.DataLoader +namespace HotChocolate.Execution.Integration.DataLoader; + +public interface ITestDataLoader + : IDataLoader { - public interface ITestDataLoader - : IDataLoader - { - } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/MyCustomContext.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/MyCustomContext.cs index 665b30db2d3..bc7ec18d678 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/MyCustomContext.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/MyCustomContext.cs @@ -1,7 +1,6 @@ -namespace HotChocolate.Execution.Integration.DataLoader +namespace HotChocolate.Execution.Integration.DataLoader; + +public class MyCustomContext { - public class MyCustomContext - { - public int Count { get; set; } - } -} + public int Count { get; set; } +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs index d9c23d0999d..05a35e50099 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs @@ -2,67 +2,66 @@ using System.Threading.Tasks; using HotChocolate.Language; -namespace HotChocolate.Execution.Integration.DataLoader +namespace HotChocolate.Execution.Integration.DataLoader; + +public class Query { - public class Query + public Task GetWithDataLoader( + string key, + FieldNode fieldSelection, + [DataLoader] TestDataLoader testDataLoader, + CancellationToken cancellationToken) { - public Task GetWithDataLoader( - string key, - FieldNode fieldSelection, - [DataLoader] TestDataLoader testDataLoader, - CancellationToken cancellationToken) - { - return testDataLoader.LoadAsync(key, cancellationToken); - } - - public Bar Bar => new Bar(); + return testDataLoader.LoadAsync(key, cancellationToken); + } - public Task GetWithDataLoader2( - string key, - FieldNode fieldSelection, - [DataLoader("fooBar")] TestDataLoader testDataLoader, - CancellationToken cancellationToken) - { - return testDataLoader.LoadAsync(key, cancellationToken); - } + public Bar Bar => new Bar(); - public Task GetDataLoaderWithInterface( - string key, - FieldNode fieldSelection, - ITestDataLoader testDataLoader, - CancellationToken cancellationToken) - { - return testDataLoader.LoadAsync(key, cancellationToken); - } + public Task GetWithDataLoader2( + string key, + FieldNode fieldSelection, + [DataLoader("fooBar")] TestDataLoader testDataLoader, + CancellationToken cancellationToken) + { + return testDataLoader.LoadAsync(key, cancellationToken); + } - public async Task GetWithStackedDataLoader( - string key, - [DataLoader("fooBar")] TestDataLoader testDataLoader, - CancellationToken cancellationToken) - { - var s = await testDataLoader.LoadAsync(key + "a", cancellationToken); - s += await testDataLoader.LoadAsync(key + "b", cancellationToken); - s += await testDataLoader.LoadAsync(key + "c", cancellationToken); - s += await testDataLoader.LoadAsync(key + "d", cancellationToken); - await Task.Delay(10, cancellationToken); - s += await testDataLoader.LoadAsync(key + "e", cancellationToken); - s += await testDataLoader.LoadAsync(key + "f", cancellationToken); - s += await testDataLoader.LoadAsync(key + "g", cancellationToken); - await Task.Delay(10, cancellationToken); - s += await testDataLoader.LoadAsync(key + "h", cancellationToken); - return s; - } + public Task GetDataLoaderWithInterface( + string key, + FieldNode fieldSelection, + ITestDataLoader testDataLoader, + CancellationToken cancellationToken) + { + return testDataLoader.LoadAsync(key, cancellationToken); } - public class Bar + public async Task GetWithStackedDataLoader( + string key, + [DataLoader("fooBar")] TestDataLoader testDataLoader, + CancellationToken cancellationToken) { - public Task GetWithDataLoader( - string key, - FieldNode fieldSelection, - [DataLoader] TestDataLoader testDataLoader, - CancellationToken cancellationToken) - { - return testDataLoader.LoadAsync(key, cancellationToken); - } + var s = await testDataLoader.LoadAsync(key + "a", cancellationToken); + s += await testDataLoader.LoadAsync(key + "b", cancellationToken); + s += await testDataLoader.LoadAsync(key + "c", cancellationToken); + s += await testDataLoader.LoadAsync(key + "d", cancellationToken); + await Task.Delay(10, cancellationToken); + s += await testDataLoader.LoadAsync(key + "e", cancellationToken); + s += await testDataLoader.LoadAsync(key + "f", cancellationToken); + s += await testDataLoader.LoadAsync(key + "g", cancellationToken); + await Task.Delay(10, cancellationToken); + s += await testDataLoader.LoadAsync(key + "h", cancellationToken); + return s; } } + +public class Bar +{ + public Task GetWithDataLoader( + string key, + FieldNode fieldSelection, + [DataLoader] TestDataLoader testDataLoader, + CancellationToken cancellationToken) + { + return testDataLoader.LoadAsync(key, cancellationToken); + } +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/TestDataLoader.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/TestDataLoader.cs index 3237ee9a6ad..dde62b8e0cf 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/TestDataLoader.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/TestDataLoader.cs @@ -6,32 +6,31 @@ using System.Threading.Tasks; using GreenDonut; -namespace HotChocolate.Execution.Integration.DataLoader +namespace HotChocolate.Execution.Integration.DataLoader; + +public class TestDataLoader : BatchDataLoader, ITestDataLoader { - public class TestDataLoader : BatchDataLoader, ITestDataLoader + public TestDataLoader(IBatchScheduler batchScheduler, DataLoaderOptions options) + : base(batchScheduler, options) { - public TestDataLoader(IBatchScheduler batchScheduler, DataLoaderOptions options) - : base(batchScheduler, options) - { - } + } - public List> Loads { get; } = new(); + public List> Loads { get; } = new(); - protected override async Task> LoadBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) - { - Loads.Add(keys.OrderBy(t => t).ToArray()); - - var dict = new Dictionary(); + protected override async Task> LoadBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) + { + Loads.Add(keys.OrderBy(t => t).ToArray()); - for (var i = 0; i < keys.Count; i++) - { - dict.Add( keys[i], keys[i]); - } + var dict = new Dictionary(); - await Task.Delay(1, cancellationToken); - return dict; + for (var i = 0; i < keys.Count; i++) + { + dict.Add( keys[i], keys[i]); } + + await Task.Delay(1, cancellationToken); + return dict; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/UseDataLoaderTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/UseDataLoaderTests.cs index 074243f00f3..c5f30e083aa 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/UseDataLoaderTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/UseDataLoaderTests.cs @@ -8,300 +8,299 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Integration.DataLoader +namespace HotChocolate.Execution.Integration.DataLoader; + +public class UseDataLoaderTests { - public class UseDataLoaderTests + [Fact] + public void UseDataLoader_Should_ThrowException_When_NotADataLoader() { - [Fact] - public void UseDataLoader_Should_ThrowException_When_NotADataLoader() - { - // arrange - // act - SchemaException exception = - Assert.Throws( - () => SchemaBuilder.New() - .AddQueryType(x => x - .BindFieldsExplicitly() - .Field(y => y.Single) - .UseDataloader(typeof(Foo))) - .Create()); - - // assert - exception.Message.MatchSnapshot(); - } + // arrange + // act + var exception = + Assert.Throws( + () => SchemaBuilder.New() + .AddQueryType(x => x + .BindFieldsExplicitly() + .Field(y => y.Single) + .UseDataloader(typeof(Foo))) + .Create()); - [Fact] - public void UseDataLoader_Schema_BatchDataloader_Single() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(x => x - .BindFieldsExplicitly() + // assert + exception.Message.MatchSnapshot(); + } + + [Fact] + public void UseDataLoader_Schema_BatchDataloader_Single() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(x => x + .BindFieldsExplicitly() + .Field(y => y.Single) + .UseDataloader()) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoader_Schema_BatchDataloader_Many() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(x => x + .BindFieldsExplicitly() + .Field(y => y.Multiple) + .UseDataloader()) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoader_Schema_GroupedDataloader_Single() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(x => x + .BindFieldsExplicitly() + .Field(y => y.Single) + .UseDataloader()) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoader_Schema_GroupedDataloader_Many() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(x => x + .BindFieldsExplicitly() + .Field(y => y.Multiple) + .UseDataloader()) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoaderAttribute_Schema_BatchDataloader_Single() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() + .Field(y => y.Single)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoaderAttribute_Schema_BatchDataloader_Many() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() + .Field(y => y.Multiple)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoaderAttribute_Schema_GroupedDataloader_Single() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() + .Field(y => y.Single)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void UseDataLoaderAttribute_Schema_GroupedDataloader_Many() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() + .Field(y => y.Multiple)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public async Task UseDataLoader_Schema_BatchDataloader_Single_Execute() + { + // arrange + var executor = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() .Field(y => y.Single) .UseDataloader()) - .Create(); + .Create() + .MakeExecutable(); - // assert - schema.ToString().MatchSnapshot(); - } + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.Create(@"{ single { id }}")); - [Fact] - public void UseDataLoader_Schema_BatchDataloader_Many() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(x => x - .BindFieldsExplicitly() + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task UseDataLoader_Schema_BatchDataloader_Multiple_Execute() + { + // arrange + var executor = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() .Field(y => y.Multiple) .UseDataloader()) - .Create(); + .Create() + .MakeExecutable(); - // assert - schema.ToString().MatchSnapshot(); - } + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.Create(@"{ multiple { id }}")); - [Fact] - public void UseDataLoader_Schema_GroupedDataloader_Single() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(x => x - .BindFieldsExplicitly() + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task UseDataLoader_Schema_GroupedDataloader_Single_Execute() + { + // arrange + var executor = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() .Field(y => y.Single) .UseDataloader()) - .Create(); + .Create() + .MakeExecutable(); - // assert - schema.ToString().MatchSnapshot(); - } + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.Create(@"{ single { id }}")); - [Fact] - public void UseDataLoader_Schema_GroupedDataloader_Many() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(x => x - .BindFieldsExplicitly() + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task UseDataLoader_Schema_GroupedDataloader_Multiple_Execute() + { + // arrange + var executor = SchemaBuilder.New() + .AddQueryType( + x => x.BindFieldsExplicitly() .Field(y => y.Multiple) .UseDataloader()) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void UseDataLoaderAttribute_Schema_BatchDataloader_Single() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Single)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void UseDataLoaderAttribute_Schema_BatchDataloader_Many() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Multiple)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void UseDataLoaderAttribute_Schema_GroupedDataloader_Single() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Single)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + .Create() + .MakeExecutable(); - [Fact] - public void UseDataLoaderAttribute_Schema_GroupedDataloader_Many() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Multiple)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.Create(@"{ multiple { id }}")); - [Fact] - public async Task UseDataLoader_Schema_BatchDataloader_Single_Execute() - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Single) - .UseDataloader()) - .Create() - .MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.Create(@"{ single { id }}")); + // assert + result.ToJson().MatchSnapshot(); + } - // assert - result.ToJson().MatchSnapshot(); - } + public class Query + { + public int Single { get; } = 1; - [Fact] - public async Task UseDataLoader_Schema_BatchDataloader_Multiple_Execute() - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Multiple) - .UseDataloader()) - .Create() - .MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.Create(@"{ multiple { id }}")); - - // assert - result.ToJson().MatchSnapshot(); - } + public int[] Multiple { get; } = { 1, 2, 3, 4 }; + } - [Fact] - public async Task UseDataLoader_Schema_GroupedDataloader_Single_Execute() - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Single) - .UseDataloader()) - .Create() - .MakeExecutable(); + public class BatchQuery + { + [UseDataLoader(typeof(TestBatchLoader))] + public int Single { get; } = 1; - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.Create(@"{ single { id }}")); + [UseDataLoader(typeof(TestBatchLoader))] + public int[] Multiple { get; } = { 1, 2, 3, 4 }; + } - // assert - result.ToJson().MatchSnapshot(); - } + public class GroupedQuery + { + [UseDataLoader(typeof(TestGroupedLoader))] + public int Single { get; } = 1; - [Fact] - public async Task UseDataLoader_Schema_GroupedDataloader_Multiple_Execute() - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType( - x => x.BindFieldsExplicitly() - .Field(y => y.Multiple) - .UseDataloader()) - .Create() - .MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.Create(@"{ multiple { id }}")); - - // assert - result.ToJson().MatchSnapshot(); - } + [UseDataLoader(typeof(TestGroupedLoader))] + public int[] Multiple { get; } = { 1, 2, 3, 4 }; + } - public class Query + public class TestGroupedLoader : GroupedDataLoader + { + public TestGroupedLoader( + IBatchScheduler batchScheduler, + DataLoaderOptions options = null) + : base(batchScheduler, options) { - public int Single { get; } = 1; - - public int[] Multiple { get; } = { 1, 2, 3, 4 }; } - public class BatchQuery + protected override Task> LoadGroupedBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) { - [UseDataLoader(typeof(TestBatchLoader))] - public int Single { get; } = 1; - - [UseDataLoader(typeof(TestBatchLoader))] - public int[] Multiple { get; } = { 1, 2, 3, 4 }; + return Task.FromResult(keys.ToLookup(x => x, x => new Foo(x))); } + } - public class GroupedQuery + public class TestBatchLoader : BatchDataLoader + { + public TestBatchLoader( + IBatchScheduler batchScheduler, + DataLoaderOptions options = null) + : base(batchScheduler, options) { - [UseDataLoader(typeof(TestGroupedLoader))] - public int Single { get; } = 1; - - [UseDataLoader(typeof(TestGroupedLoader))] - public int[] Multiple { get; } = { 1, 2, 3, 4 }; } - public class TestGroupedLoader : GroupedDataLoader + protected override Task> LoadBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) { - public TestGroupedLoader( - IBatchScheduler batchScheduler, - DataLoaderOptions options = null) - : base(batchScheduler, options) - { - } - - protected override Task> LoadGroupedBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) - { - return Task.FromResult(keys.ToLookup(x => x, x => new Foo(x))); - } + return Task.FromResult( + (IReadOnlyDictionary)keys.ToDictionary(x => x, x => new Foo(x))); } + } - public class TestBatchLoader : BatchDataLoader + public class Foo + { + public Foo(int id) { - public TestBatchLoader( - IBatchScheduler batchScheduler, - DataLoaderOptions options = null) - : base(batchScheduler, options) - { - } - - protected override Task> LoadBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) - { - return Task.FromResult( - (IReadOnlyDictionary)keys.ToDictionary(x => x, x => new Foo(x))); - } + Id = id; } - public class Foo - { - public Foo(int id) - { - Id = id; - } - - public int Id { get; } - } + public int Id { get; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/ConstantDirectiveType.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/ConstantDirectiveType.cs index 883cae1feb1..41e25ff056d 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/ConstantDirectiveType.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/ConstantDirectiveType.cs @@ -1,24 +1,23 @@ using HotChocolate.Types; -namespace HotChocolate.Execution.Integration.Directives +namespace HotChocolate.Execution.Integration.Directives; + +public class ConstantDirectiveType + : DirectiveType { - public class ConstantDirectiveType - : DirectiveType + protected override void Configure(IDirectiveTypeDescriptor descriptor) { - protected override void Configure(IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("constant"); - descriptor.Argument("value").Type(); + descriptor.Name("constant"); + descriptor.Argument("value").Type(); - descriptor.Location(DirectiveLocation.Object) - .Location(DirectiveLocation.FieldDefinition) - .Location(DirectiveLocation.Field); + descriptor.Location(DirectiveLocation.Object) + .Location(DirectiveLocation.FieldDefinition) + .Location(DirectiveLocation.Field); - descriptor.Use(next => context => - { - context.Result = context.Directive.GetArgument("value"); - return next(context); - }); - } + descriptor.Use(next => context => + { + context.Result = context.Directive.GetArgument("value"); + return next(context); + }); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/DirectiveIntegrationTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/DirectiveIntegrationTests.cs index 897aec43c69..f243bbab8d0 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/DirectiveIntegrationTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Directives/DirectiveIntegrationTests.cs @@ -4,43 +4,42 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.Directives +namespace HotChocolate.Execution.Integration.Directives; + +public class DirectiveIntegrationTests { - public class DirectiveIntegrationTests + [Fact] + public async Task UniqueDirectives_OnFieldLevel_OverwriteOnesOnObjectLevel() { - [Fact] - public async Task UniqueDirectives_OnFieldLevel_OverwriteOnesOnObjectLevel() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - "type Query @constant(value: \"foo\") " + - "{ bar: String baz: String @constant(value: \"bar\") }") - .AddDirectiveType()); + // arrange + var executor = await CreateExecutorAsync(c => c + .AddDocumentFromString( + "type Query @constant(value: \"foo\") " + + "{ bar: String baz: String @constant(value: \"bar\") }") + .AddDirectiveType()); - // act - IExecutionResult result = await executor.ExecuteAsync("{ bar baz }"); + // act + var result = await executor.ExecuteAsync("{ bar baz }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task UniqueDirectives_FieldSelection_OverwriteTypeSystemOnes() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(c => c - .AddDocumentFromString( - "type Query @constant(value: \"foo\") " + - "{ bar: String baz: String @constant(value: \"bar\") }") - .AddDirectiveType()); + [Fact] + public async Task UniqueDirectives_FieldSelection_OverwriteTypeSystemOnes() + { + // arrange + var executor = await CreateExecutorAsync(c => c + .AddDocumentFromString( + "type Query @constant(value: \"foo\") " + + "{ bar: String baz: String @constant(value: \"bar\") }") + .AddDirectiveType()); - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ bar baz @constant(value: \"baz\") }"); + // act + var result = await executor.ExecuteAsync( + "{ bar baz @constant(value: \"baz\") }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/EmbeddedResolvers/EmbeddedResolverTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/EmbeddedResolvers/EmbeddedResolverTests.cs index c6eacf629bd..12d8db3c57c 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/EmbeddedResolvers/EmbeddedResolverTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/EmbeddedResolvers/EmbeddedResolverTests.cs @@ -6,61 +6,60 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.EmbeddedResolvers +namespace HotChocolate.Execution.Integration.EmbeddedResolvers; + +public class EmbeddedResolverTests { - public class EmbeddedResolverTests + [Fact] + public async Task ResolverResultIsObject() { - [Fact] - public async Task ResolverResultIsObject() - { - Snapshot.FullName(); - await ExpectValid( + Snapshot.FullName(); + await ExpectValid( "{ foo { bar { baz }}}", configure: c => c.AddQueryType()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - public class QueryType - : ObjectType + public class QueryType + : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field(t => t.GetFoo()).Type(); - } - - public object GetFoo() - { - return new object(); - } + descriptor.Name("Query"); + descriptor.Field(t => t.GetFoo()).Type(); } - public class FooType - : ObjectType + public object GetFoo() { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Field(t => t.Bar()).Type(); - } + return new object(); + } + } - public Bar Bar() - { - return new Bar(); - } + public class FooType + : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) + { + descriptor.Name("Foo"); + descriptor.Field(t => t.Bar()).Type(); } - public class BarType - : ObjectType + public Bar Bar() { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - } + return new Bar(); } + } - public class Bar + public class BarType + : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - public string Baz { get; } = "Bar"; } } -} + + public class Bar + { + public string Baz { get; } = "Bar"; + } +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/DataStoreHelloWorld.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/DataStoreHelloWorld.cs index 8164c90b408..591abdd7cba 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/DataStoreHelloWorld.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/DataStoreHelloWorld.cs @@ -1,7 +1,6 @@ -namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst +namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst; + +public class DataStoreHelloWorld { - public class DataStoreHelloWorld - { - public string State { get; set; } = "initial"; - } -} + public string State { get; set; } = "initial"; +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/HelloWorldCodeFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/HelloWorldCodeFirstTests.cs index 98c6ea4222d..8d5a24d21db 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/HelloWorldCodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/HelloWorldCodeFirstTests.cs @@ -5,76 +5,75 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst +namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst; + +public class HelloWorldCodeFirstTests { - public class HelloWorldCodeFirstTests + [Fact] + public async Task ExecuteHelloWorldCodeFirstQuery() { - [Fact] - public async Task ExecuteHelloWorldCodeFirstQuery() - { - Snapshot.FullName(); - await ExpectValid( + Snapshot.FullName(); + await ExpectValid( "{ hello state }", configure: c => c .AddQueryType() .AddMutationType() .Services .AddSingleton()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteHelloWorldCodeFirstQueryWithArgument() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task ExecuteHelloWorldCodeFirstQueryWithArgument() + { + Snapshot.FullName(); + await ExpectValid( "{ hello(to: \"me\") state }", configure: c => c .AddQueryType() .AddMutationType() .Services .AddSingleton()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteHelloWorldCodeFirstClrQuery() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task ExecuteHelloWorldCodeFirstClrQuery() + { + Snapshot.FullName(); + await ExpectValid( "{ hello state }", configure: c => c .AddQueryType() .Services .AddSingleton()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteHelloWorldCodeFirstClrQueryWithArgument() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task ExecuteHelloWorldCodeFirstClrQueryWithArgument() + { + Snapshot.FullName(); + await ExpectValid( "{ hello(to: \"me\") state }", configure: c => c .AddQueryType() .Services .AddSingleton()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task ExecuteHelloWorldCodeFirstMutation() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task ExecuteHelloWorldCodeFirstMutation() + { + Snapshot.FullName(); + await ExpectValid( "mutation { newState(state:\"1234567\") }", configure: c => c .AddQueryType() .AddMutationType() .Services .AddSingleton()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/MutationHelloWorld.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/MutationHelloWorld.cs index 40683eb3f60..f3dbf659dde 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/MutationHelloWorld.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/MutationHelloWorld.cs @@ -1,25 +1,24 @@ using HotChocolate.Types; -namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst +namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst; + +public class MutationHelloWorld + : ObjectType { - public class MutationHelloWorld - : ObjectType + public MutationHelloWorld(DataStoreHelloWorld dataStore) { - public MutationHelloWorld(DataStoreHelloWorld dataStore) - { - DataStore = dataStore; - } + DataStore = dataStore; + } - public DataStoreHelloWorld DataStore { get; } + public DataStoreHelloWorld DataStore { get; } - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Mutation"); + protected override void Configure(IObjectTypeDescriptor descriptor) + { + descriptor.Name("Mutation"); - descriptor.Field("newState") - .Argument("state", a => a.Type()) - .Resolve(c => DataStore.State = c.ArgumentValue("state")); - } + descriptor.Field("newState") + .Argument("state", a => a.Type()) + .Resolve(c => DataStore.State = c.ArgumentValue("state")); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorld.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorld.cs index 31616a07cfa..f8417b71935 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorld.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorld.cs @@ -1,26 +1,25 @@ using HotChocolate.Types; -namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst +namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst; + +public class QueryHelloWorld + : ObjectType { - public class QueryHelloWorld - : ObjectType + public QueryHelloWorld(DataStoreHelloWorld dataStore) { - public QueryHelloWorld(DataStoreHelloWorld dataStore) - { - DataStore = dataStore; - } + DataStore = dataStore; + } - public DataStoreHelloWorld DataStore { get; } + public DataStoreHelloWorld DataStore { get; } - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("QueryHelloWorld"); + protected override void Configure(IObjectTypeDescriptor descriptor) + { + descriptor.Name("QueryHelloWorld"); - descriptor.Field("hello") - .Argument("to", a => a.Type()) - .Resolve(c => c.ArgumentValue("to") ?? "world"); + descriptor.Field("hello") + .Argument("to", a => a.Type()) + .Resolve(c => c.ArgumentValue("to") ?? "world"); - descriptor.Field("state").Resolve(() => DataStore.State); - } + descriptor.Field("state").Resolve(() => DataStore.State); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorldClr.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorldClr.cs index e142989da92..e98ea9acddb 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorldClr.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldCodeFirst/QueryHelloWorldClr.cs @@ -1,22 +1,21 @@ -namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst +namespace HotChocolate.Execution.Integration.HelloWorldCodeFirst; + +public class QueryHelloWorldClr { - public class QueryHelloWorldClr - { - private readonly DataStoreHelloWorld _dataStore; + private readonly DataStoreHelloWorld _dataStore; - public QueryHelloWorldClr(DataStoreHelloWorld dataStore) - { - _dataStore = dataStore; - } + public QueryHelloWorldClr(DataStoreHelloWorld dataStore) + { + _dataStore = dataStore; + } - public string GetHello(string to) - { - return to ?? "world"; - } + public string GetHello(string to) + { + return to ?? "world"; + } - public string GetState() - { - return _dataStore.State; - } + public string GetState() + { + return _dataStore.State; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldSchemaFirst/HelloWorldSchemaFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldSchemaFirst/HelloWorldSchemaFirstTests.cs index 8ee8627cb1f..78e1fbfd3ca 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldSchemaFirst/HelloWorldSchemaFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/HelloWorldSchemaFirst/HelloWorldSchemaFirstTests.cs @@ -6,15 +6,15 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.HelloWorldSchemaFirst +namespace HotChocolate.Execution.Integration.HelloWorldSchemaFirst; + +public class HelloWorldSchemaFirstTests { - public class HelloWorldSchemaFirstTests + [Fact] + public async Task SimpleHelloWorldWithoutTypeBinding() { - [Fact] - public async Task SimpleHelloWorldWithoutTypeBinding() - { - Snapshot.FullName(); - await ExpectValid( + Snapshot.FullName(); + await ExpectValid( "{ hello }", c => c .AddDocumentFromString( @@ -23,14 +23,14 @@ type Query { hello: String }") .AddResolver("Query", "hello", () => "world")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SimpleHelloWorldWithArgumentWithoutTypeBinding() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task SimpleHelloWorldWithArgumentWithoutTypeBinding() + { + Snapshot.FullName(); + await ExpectValid( "{ hello(a: \"foo\") }", c => c .AddDocumentFromString( @@ -39,14 +39,14 @@ type Query { hello(a: String!): String }") .AddResolver("Query", "hello", ctx => ctx.ArgumentValue("a"))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SimpleHelloWorldWithResolverType() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task SimpleHelloWorldWithResolverType() + { + Snapshot.FullName(); + await ExpectValid( "{ hello world }", c => c .AddDocumentFromString( @@ -57,14 +57,14 @@ type Query { }") .AddResolver("Query") .AddResolver("Query")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SimpleHelloWorldWithResolverTypeAndArgument() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task SimpleHelloWorldWithResolverTypeAndArgument() + { + Snapshot.FullName(); + await ExpectValid( "{ hello(a: \"foo_\") }", c => c .AddDocumentFromString( @@ -72,25 +72,24 @@ await ExpectValid( hello(a: String!): String }") .AddResolver("Query")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - public class QueryA - { - public string Hello => "World"; - } + public class QueryA + { + public string Hello => "World"; + } - public class QueryB - { - public string World => "Hello"; - } + public class QueryB + { + public string World => "Hello"; + } - public class QueryC + public class QueryC + { + public string GetHello(string a, IResolverContext context) { - public string GetHello(string a, IResolverContext context) - { - return a + context.ArgumentValue("a"); - } + return a + context.ArgumentValue("a"); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/InputOutputObjectAreTheSame.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/InputOutputObjectAreTheSame.cs index a04a1558317..53f0aab16e7 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/InputOutputObjectAreTheSame.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/InputOutputObjectAreTheSame.cs @@ -3,50 +3,49 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Integration.InputOutputObjectAreTheSame +namespace HotChocolate.Execution.Integration.InputOutputObjectAreTheSame; + +public class InputOutputObjectAreTheSame { - public class InputOutputObjectAreTheSame + [Fact] + public void CheckIfTypesAreRegisteredCorrectly() + { + // arrange + var schema = CreateSchema(); + + // act + var containsPersonInputType = schema.TryGetType("PersonInput", out INamedInputType _); + var containsPersonOutputType = schema.TryGetType("Person", out INamedOutputType _); + + // assert + Assert.True(containsPersonInputType); + Assert.True(containsPersonOutputType); + } + + [Fact] + public async Task ExecuteQueryThatReturnsPerson() { - [Fact] - public void CheckIfTypesAreRegisteredCorrectly() - { - // arrange - ISchema schema = CreateSchema(); - - // act - var containsPersonInputType = schema.TryGetType("PersonInput", out INamedInputType _); - var containsPersonOutputType = schema.TryGetType("Person", out INamedOutputType _); - - // assert - Assert.True(containsPersonInputType); - Assert.True(containsPersonOutputType); - } - - [Fact] - public async Task ExecuteQueryThatReturnsPerson() - { - // arrange - ISchema schema = CreateSchema(); - - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync(@"{ + // arrange + var schema = CreateSchema(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync(@"{ person(person: { firstName:""a"", lastName:""b"" }) { lastName firstName } }"); - // assert - result.ToJson().MatchSnapshot(); - } - - private static ISchema CreateSchema() - => SchemaBuilder.New() - .AddQueryType() - .AddType>() - .AddType(new InputObjectType( - d => d.Name("PersonInput"))) - .Create(); + // assert + result.ToJson().MatchSnapshot(); } -} + + private static ISchema CreateSchema() + => SchemaBuilder.New() + .AddQueryType() + .AddType>() + .AddType(new InputObjectType( + d => d.Name("PersonInput"))) + .Create(); +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Person.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Person.cs index b36d95c5b54..77a0f3874ed 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Person.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Person.cs @@ -1,10 +1,8 @@ -namespace HotChocolate.Execution.Integration.InputOutputObjectAreTheSame -{ - public class Person - { - public string FirstName { get; set; } +namespace HotChocolate.Execution.Integration.InputOutputObjectAreTheSame; - public string LastName { get; set; } - } +public class Person +{ + public string FirstName { get; set; } -} + public string LastName { get; set; } +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Query.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Query.cs index 7d78fa94383..929dcb6da78 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Query.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/InputOutputObjectAreTheSame/Query.cs @@ -1,11 +1,9 @@ -namespace HotChocolate.Execution.Integration.InputOutputObjectAreTheSame +namespace HotChocolate.Execution.Integration.InputOutputObjectAreTheSame; + +public class Query { - public class Query + public Person GetPerson(Person person) { - public Person GetPerson(Person person) - { - return person; - } + return person; } - -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ArgumentCoercionTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ArgumentCoercionTests.cs index db889fccd06..ee9e26dcfac 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ArgumentCoercionTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ArgumentCoercionTests.cs @@ -6,107 +6,106 @@ #nullable enable -namespace HotChocolate.Execution.Integration.Spec +namespace HotChocolate.Execution.Integration.Spec; + +public class ArgumentCoercionTests { - public class ArgumentCoercionTests + [Fact] + public async Task Pass_In_Null_To_NonNullArgument_With_DefaultValue() + { + // arrange + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync("{ sayHello(name: null) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Pass_In_Nothing_To_NonNullArgument_With_DefaultValue() + { + // arrange + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync("{ sayHello }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Pass_In_Nothing_To_NonNullArgument_With_DefaultValue_By_Variable() + { + // arrange + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync( + "query ($a: String!) { sayHello(name: $a) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Pass_In_Null_To_NonNullArgument_With_DefaultValue_By_Variable() + { + // arrange + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + var variables = new Dictionary { { "a", null } }; + + // act + var result = await executor.ExecuteAsync( + "query ($a: String!) { sayHello(name: $a) }", + variables); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Pass_In_Sydney_To_NonNullArgument_With_DefaultValue_By_Variable() + { + // arrange + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + var variables = new Dictionary { { "a", "Sydney" } }; + + // act + var result = await executor.ExecuteAsync( + "query ($a: String!) { sayHello(name: $a) }", + variables); + + // assert + result.ToJson().MatchSnapshot(); + } + + public class Query { - [Fact] - public async Task Pass_In_Null_To_NonNullArgument_With_DefaultValue() - { - // arrange - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ sayHello(name: null) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Pass_In_Nothing_To_NonNullArgument_With_DefaultValue() - { - // arrange - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ sayHello }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Pass_In_Nothing_To_NonNullArgument_With_DefaultValue_By_Variable() - { - // arrange - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "query ($a: String!) { sayHello(name: $a) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Pass_In_Null_To_NonNullArgument_With_DefaultValue_By_Variable() - { - // arrange - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - var variables = new Dictionary { { "a", null } }; - - // act - IExecutionResult result = await executor.ExecuteAsync( - "query ($a: String!) { sayHello(name: $a) }", - variables); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Pass_In_Sydney_To_NonNullArgument_With_DefaultValue_By_Variable() - { - // arrange - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - var variables = new Dictionary { { "a", "Sydney" } }; - - // act - IExecutionResult result = await executor.ExecuteAsync( - "query ($a: String!) { sayHello(name: $a) }", - variables); - - // assert - result.ToJson().MatchSnapshot(); - } - - public class Query - { - public string SayHello(string name = "Michael") => $"Hello {name}."; - } + public string SayHello(string name = "Michael") => $"Hello {name}."; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/InputObjectsCanBeVariablesTest.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/InputObjectsCanBeVariablesTest.cs index 3e3f1799322..5503b766229 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/InputObjectsCanBeVariablesTest.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/InputObjectsCanBeVariablesTest.cs @@ -5,18 +5,18 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.Spec +namespace HotChocolate.Execution.Integration.Spec; + +public class InputObjectsCanBeVariablesTest { - public class InputObjectsCanBeVariablesTest + // http://facebook.github.io/graphql/draft/#sec-All-Variable-Usages-are-Allowed + [Fact] + public async Task EnsureInputObjectsCanBeVariablesTest() { - // http://facebook.github.io/graphql/draft/#sec-All-Variable-Usages-are-Allowed - [Fact] - public async Task EnsureInputObjectsCanBeVariablesTest() - { - Snapshot.FullName(); + Snapshot.FullName(); - await ExpectValid( - @" + await ExpectValid( + @" query ($a: String $b: String) { anything(foo: { a: $a @@ -27,25 +27,25 @@ await ExpectValid( } } ", - r => r.AddQueryType(), - r => r.SetVariableValue( - "a", - "a" - ) - .SetVariableValue( - "b", - "b" - ) - ).MatchSnapshotAsync(); - } + r => r.AddQueryType(), + r => r.SetVariableValue( + "a", + "a" + ) + .SetVariableValue( + "b", + "b" + ) + ).MatchSnapshotAsync(); + } - [Fact] - public async Task EnsureInputObjectsCanBeVariablesAndLiteralsTest() - { - Snapshot.FullName(); + [Fact] + public async Task EnsureInputObjectsCanBeVariablesAndLiteralsTest() + { + Snapshot.FullName(); - await ExpectValid( - @" + await ExpectValid( + @" query ($a: String) { anything(foo: { a: $a @@ -56,21 +56,21 @@ await ExpectValid( } } ", - r => r.AddQueryType(), - r => r.SetVariableValue( - "a", - "a" - ) - ).MatchSnapshotAsync(); - } + r => r.AddQueryType(), + r => r.SetVariableValue( + "a", + "a" + ) + ).MatchSnapshotAsync(); + } - [Fact] - public async Task EnsureInputObjectsCanBeLiteralsTest() - { - Snapshot.FullName(); + [Fact] + public async Task EnsureInputObjectsCanBeLiteralsTest() + { + Snapshot.FullName(); - await ExpectValid( - @" + await ExpectValid( + @" { anything(foo: { a: ""a"" @@ -81,23 +81,22 @@ await ExpectValid( } } ", - r => r.AddQueryType(), - r => { } - ).MatchSnapshotAsync(); - } + r => r.AddQueryType(), + r => { } + ).MatchSnapshotAsync(); + } - public class Query + public class Query + { + public Foo Anything(Foo foo) { - public Foo Anything(Foo foo) - { - return foo; - } + return foo; } + } - public class Foo - { - public string A { get; set; } - public string B { get; set; } - } + public class Foo + { + public string A { get; set; } + public string B { get; set; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ListTypeTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ListTypeTests.cs index 111df966686..7705a307965 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ListTypeTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/Spec/ListTypeTests.cs @@ -7,17 +7,17 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.Spec +namespace HotChocolate.Execution.Integration.Spec; + +public class ListTypeTests { - public class ListTypeTests + // http://facebook.github.io/graphql/draft/#sec-All-Variable-Usages-are-Allowed + [Fact] + public async Task Ensure_List_Elements_Can_Be_Variables() { - // http://facebook.github.io/graphql/draft/#sec-All-Variable-Usages-are-Allowed - [Fact] - public async Task Ensure_List_Elements_Can_Be_Variables() - { - Snapshot.FullName(); + Snapshot.FullName(); - await ExpectValid( + await ExpectValid( @" query ($a: String $b: String) { list(items: [$a $b]) @@ -27,12 +27,11 @@ await ExpectValid( r => r .SetVariableValue("a", "a") .SetVariableValue("b", "b")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - public class Query - { - public List GetList(List items) => items; - } + public class Query + { + public List GetList(List items) => items; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs index d4d10a8817a..9d056c9f08f 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs @@ -11,41 +11,41 @@ using Snapshot = Snapshooter.Xunit.Snapshot; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.StarWarsCodeFirst +namespace HotChocolate.Execution.Integration.StarWarsCodeFirst; + +public class StarWarsCodeFirstTests { - public class StarWarsCodeFirstTests + [Fact] + public async Task Schema() { - [Fact] - public async Task Schema() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(); + // arrange + var executor = await CreateExecutorAsync(); - // act - var schema = executor.Schema.Print(); + // act + var schema = executor.Schema.Print(); - // assert - schema.MatchSnapshot(); - } + // assert + schema.MatchSnapshot(); + } - [Fact] - public async Task GetHeroName() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GetHeroName() + { + Snapshot.FullName(); + await ExpectValid(@" { hero { name } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgFieldExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgFieldExample() + { + Snapshot.FullName(); + await ExpectValid(@" { hero { name @@ -57,42 +57,42 @@ await ExpectValid(@" } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgFieldArgumentExample1() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgFieldArgumentExample1() + { + Snapshot.FullName(); + await ExpectValid(@" { human(id: ""1000"") { name height } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgFieldArgumentExample2() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgFieldArgumentExample2() + { + Snapshot.FullName(); + await ExpectValid(@" { human(id: ""1000"") { name height(unit: FOOT) } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgAliasExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgAliasExample() + { + Snapshot.FullName(); + await ExpectValid(@" { empireHero: hero(episode: EMPIRE) { name @@ -101,14 +101,14 @@ await ExpectValid(@" name } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgFragmentExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgFragmentExample() + { + Snapshot.FullName(); + await ExpectValid(@" { leftComparison: hero(episode: EMPIRE) { ...comparisonFields @@ -127,14 +127,14 @@ fragment comparisonFields on Character { } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgOperationNameExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgOperationNameExample() + { + Snapshot.FullName(); + await ExpectValid(@" query HeroNameAndFriends { hero { name @@ -145,14 +145,14 @@ query HeroNameAndFriends { } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgVariableExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgVariableExample() + { + Snapshot.FullName(); + await ExpectValid(@" query HeroNameAndFriends($episode: Episode) { hero(episode: $episode) { name @@ -164,14 +164,14 @@ query HeroNameAndFriends($episode: Episode) { } }", request: c => c.SetVariableValue("episode", new EnumValueNode("JEDI"))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgVariableWithDefaultValueExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgVariableWithDefaultValueExample() + { + Snapshot.FullName(); + await ExpectValid(@" query HeroNameAndFriends($episode: Episode = JEDI) { hero(episode: $episode) { name @@ -182,14 +182,14 @@ query HeroNameAndFriends($episode: Episode = JEDI) { } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgDirectiveIncludeExample1() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgDirectiveIncludeExample1() + { + Snapshot.FullName(); + await ExpectValid(@" query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name @@ -203,14 +203,14 @@ friends @include(if: $withFriends) { request: c => c .SetVariableValue("episode", new EnumValueNode("JEDI")) .SetVariableValue("withFriends", new BooleanValueNode(false))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgDirectiveIncludeExample2() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgDirectiveIncludeExample2() + { + Snapshot.FullName(); + await ExpectValid(@" query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name @@ -224,14 +224,14 @@ friends @include(if: $withFriends) { request: r => r .SetVariableValue("episode", new EnumValueNode("JEDI")) .SetVariableValue("withFriends", new BooleanValueNode(true))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgDirectiveSkipExample1() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgDirectiveSkipExample1() + { + Snapshot.FullName(); + await ExpectValid(@" query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name @@ -245,14 +245,14 @@ friends @skip(if: $withFriends) { request: r => r .SetVariableValue("episode", new EnumValueNode("JEDI")) .SetVariableValue("withFriends", new BooleanValueNode(false))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgDirectiveSkipExample2() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgDirectiveSkipExample2() + { + Snapshot.FullName(); + await ExpectValid(@" query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name @@ -266,14 +266,14 @@ friends @skip(if: $withFriends) { request: r => r .SetVariableValue("episode", new EnumValueNode("JEDI")) .SetVariableValue("withFriends", new BooleanValueNode(true))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgDirectiveSkipExample1WithPlainClrVarTypes() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgDirectiveSkipExample1WithPlainClrVarTypes() + { + Snapshot.FullName(); + await ExpectValid(@" query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name @@ -287,14 +287,14 @@ friends @skip(if: $withFriends) { request: r => r .SetVariableValue("episode", "JEDI") .SetVariableValue("withFriends", false)) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgMutationExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgMutationExample() + { + Snapshot.FullName(); + await ExpectValid(@" mutation CreateReviewForEpisode( $ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { @@ -308,14 +308,14 @@ mutation CreateReviewForEpisode( new ObjectFieldNode("stars", new IntValueNode(5)), new ObjectFieldNode("commentary", new StringValueNode("This is a great movie!"))))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgTwoMutationsExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgTwoMutationsExample() + { + Snapshot.FullName(); + await ExpectValid(@" mutation CreateReviewForEpisode( $ep: Episode!, $ep2: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { @@ -334,14 +334,14 @@ mutation CreateReviewForEpisode( new ObjectFieldNode("stars", new IntValueNode(5)), new ObjectFieldNode("commentary", new StringValueNode("This is a great movie!"))))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgMutationExample_With_ValueVariables() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgMutationExample_With_ValueVariables() + { + Snapshot.FullName(); + await ExpectValid(@" mutation CreateReviewForEpisode( $ep: Episode! $stars: Int! @@ -357,14 +357,14 @@ mutation CreateReviewForEpisode( .SetVariableValue("ep", new EnumValueNode("JEDI")) .SetVariableValue("stars", new IntValueNode(5)) .SetVariableValue("commentary", new StringValueNode("This is a great movie!"))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgInlineFragmentExample1() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgInlineFragmentExample1() + { + Snapshot.FullName(); + await ExpectValid(@" query HeroForEpisode($ep: Episode!) { hero(episode: $ep) { name @@ -377,14 +377,14 @@ ... on Human { } }", request: r => r.SetVariableValue("ep", new EnumValueNode("JEDI"))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgInlineFragmentExample2() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgInlineFragmentExample2() + { + Snapshot.FullName(); + await ExpectValid(@" query HeroForEpisode($ep: Episode!) { hero(episode: $ep) { name @@ -397,14 +397,14 @@ ... on Human { } }", request: r => r.SetVariableValue("ep", new EnumValueNode("EMPIRE"))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLOrgMetaFieldAndUnionExample() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task GraphQLOrgMetaFieldAndUnionExample() + { + Snapshot.FullName(); + await ExpectValid(@" { search(text: ""an"") { __typename @@ -422,14 +422,14 @@ ... on Starship { } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task NonNullListVariableValues() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task NonNullListVariableValues() + { + Snapshot.FullName(); + await ExpectValid(@" query op($ep: [Episode!]!) { heroes(episodes: $ep) { @@ -438,14 +438,14 @@ query op($ep: [Episode!]!) }", request: r => r .SetVariableValue("ep", new ListValueNode(new EnumValueNode("EMPIRE")))) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task ConditionalInlineFragment() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task ConditionalInlineFragment() + { + Snapshot.FullName(); + await ExpectValid(@" { heroes(episodes: [EMPIRE]) { name @@ -454,41 +454,41 @@ ... @include(if: true) { } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task NonNullEnumsSerializeCorrectlyFromVariables() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task NonNullEnumsSerializeCorrectlyFromVariables() + { + Snapshot.FullName(); + await ExpectValid(@" query getHero($episode: Episode!) { hero(episode: $episode) { name } }", request: r => r.SetVariableValue("episode", "NEW_HOPE")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task EnumValueIsCoercedToListValue() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task EnumValueIsCoercedToListValue() + { + Snapshot.FullName(); + await ExpectValid(@" { heroes(episodes: EMPIRE) { name } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task TypeNameFieldIsCorrectlyExecutedOnInterfaces() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task TypeNameFieldIsCorrectlyExecutedOnInterfaces() + { + Snapshot.FullName(); + await ExpectValid(@" query foo { hero(episode: NEW_HOPE) { __typename @@ -517,14 +517,14 @@ ... on Droid { } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Execute_ListWithNullValues_ResultContainsNullElement() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task Execute_ListWithNullValues_ResultContainsNullElement() + { + Snapshot.FullName(); + await ExpectValid(@" query { human(id: ""1001"") { id @@ -534,23 +534,23 @@ await ExpectValid(@" } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SubscribeToReview() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(); + [Fact] + public async Task SubscribeToReview() + { + // arrange + var executor = await CreateExecutorAsync(); - // act - var subscriptionResult = - (IResponseStream)await executor.ExecuteAsync( - "subscription { onReview(episode: NEW_HOPE) " + - "{ stars } }"); + // act + var subscriptionResult = + (IResponseStream)await executor.ExecuteAsync( + "subscription { onReview(episode: NEW_HOPE) " + + "{ stars } }"); - // assert - await executor.ExecuteAsync(@" + // assert + await executor.ExecuteAsync(@" mutation { createReview(episode: NEW_HOPE, review: { stars: 5 commentary: ""foo"" }) { @@ -559,31 +559,31 @@ await executor.ExecuteAsync(@" } }"); - IQueryResult eventResult = null; + IQueryResult eventResult = null; - using (var cts = new CancellationTokenSource(2000)) + using (var cts = new CancellationTokenSource(2000)) + { + await foreach (var queryResult in + subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) { - await foreach (IQueryResult queryResult in - subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) - { - eventResult = queryResult; - break; - } + eventResult = queryResult; + break; } - - eventResult?.MatchSnapshot(); } - [Fact] - public async Task SubscribeToReview_WithInlineFragment() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(); + eventResult?.MatchSnapshot(); + } + + [Fact] + public async Task SubscribeToReview_WithInlineFragment() + { + // arrange + var executor = await CreateExecutorAsync(); - // act - var subscriptionResult = - (IResponseStream)await executor.ExecuteAsync( - @"subscription { + // act + var subscriptionResult = + (IResponseStream)await executor.ExecuteAsync( + @"subscription { onReview(episode: NEW_HOPE) { ... on Review { stars @@ -591,8 +591,8 @@ ... on Review { } }"); - // assert - await executor.ExecuteAsync(@" + // assert + await executor.ExecuteAsync(@" mutation { createReview(episode: NEW_HOPE, review: { stars: 5 commentary: ""foo"" }) { @@ -601,31 +601,31 @@ await executor.ExecuteAsync(@" } }"); - IQueryResult eventResult = null; + IQueryResult eventResult = null; - using (var cts = new CancellationTokenSource(2000)) + using (var cts = new CancellationTokenSource(2000)) + { + await foreach (var queryResult in + subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) { - await foreach (IQueryResult queryResult in - subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) - { - eventResult = queryResult; - break; - } + eventResult = queryResult; + break; } - - eventResult?.MatchSnapshot(); } - [Fact] - public async Task SubscribeToReview_FragmentDefinition() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(); + eventResult?.MatchSnapshot(); + } - // act - var subscriptionResult = - (IResponseStream)await executor.ExecuteAsync( - @"subscription { + [Fact] + public async Task SubscribeToReview_FragmentDefinition() + { + // arrange + var executor = await CreateExecutorAsync(); + + // act + var subscriptionResult = + (IResponseStream)await executor.ExecuteAsync( + @"subscription { onReview(episode: NEW_HOPE) { ... SomeFrag } @@ -635,8 +635,8 @@ fragment SomeFrag on Review { stars }"); - // assert - await executor.ExecuteAsync(@" + // assert + await executor.ExecuteAsync(@" mutation { createReview(episode: NEW_HOPE, review: { stars: 5 commentary: ""foo"" }) { @@ -645,40 +645,40 @@ await executor.ExecuteAsync(@" } }"); - IQueryResult eventResult = null; + IQueryResult eventResult = null; - using (var cts = new CancellationTokenSource(2000)) + using (var cts = new CancellationTokenSource(2000)) + { + await foreach (var queryResult in + subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) { - await foreach (IQueryResult queryResult in - subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) - { - eventResult = queryResult; - break; - } + eventResult = queryResult; + break; } - - eventResult?.MatchSnapshot(); } - [Fact] - public async Task SubscribeToReview_With_Variables() - { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(); + eventResult?.MatchSnapshot(); + } + + [Fact] + public async Task SubscribeToReview_With_Variables() + { + // arrange + var executor = await CreateExecutorAsync(); - // act - var subscriptionResult = - (IResponseStream)await executor.ExecuteAsync( - @"subscription ($ep: Episode!) { + // act + var subscriptionResult = + (IResponseStream)await executor.ExecuteAsync( + @"subscription ($ep: Episode!) { onReview(episode: $ep) { stars } }", - new Dictionary { { "ep", "NEW_HOPE" } }, - CancellationToken.None); + new Dictionary { { "ep", "NEW_HOPE" } }, + CancellationToken.None); - // assert - await executor.ExecuteAsync(@" + // assert + await executor.ExecuteAsync(@" mutation { createReview(episode: NEW_HOPE, review: { stars: 5 commentary: ""foo"" }) { @@ -687,32 +687,32 @@ await executor.ExecuteAsync(@" } }"); - IQueryResult eventResult = null; + IQueryResult eventResult = null; - using (var cts = new CancellationTokenSource(2000)) + using (var cts = new CancellationTokenSource(2000)) + { + await foreach (var queryResult in + subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) { - await foreach (IQueryResult queryResult in - subscriptionResult.ReadResultsAsync().WithCancellation(cts.Token)) - { - eventResult = queryResult; - break; - } + eventResult = queryResult; + break; } - - eventResult?.MatchSnapshot(); } - /// - /// An error caused by the violating the max execution depth rule should - /// not lead to partial results. - /// The result should consist of a single error stating the allowed depth. - /// - /// - [Fact] - public async Task ExecutionDepthShouldNotLeadToEmptyObjects() - { - Snapshot.FullName(); - await ExpectError(@" + eventResult?.MatchSnapshot(); + } + + /// + /// An error caused by the violating the max execution depth rule should + /// not lead to partial results. + /// The result should consist of a single error stating the allowed depth. + /// + /// + [Fact] + public async Task ExecutionDepthShouldNotLeadToEmptyObjects() + { + Snapshot.FullName(); + await ExpectError(@" query ExecutionDepthShouldNotLeadToEmptyObjects { hero(episode: NEW_HOPE) { __typename @@ -751,18 +751,18 @@ ... on Droid { } } }", - configure: c => - { - AddDefaultConfiguration(c); - c.AddMaxExecutionDepthRule(3); - }); - } + configure: c => + { + AddDefaultConfiguration(c); + c.AddMaxExecutionDepthRule(3); + }); + } - [Fact] - public async Task Execution_Depth_Is_Skipped_For_Introspection() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task Execution_Depth_Is_Skipped_For_Introspection() + { + Snapshot.FullName(); + await ExpectValid(@" query { __schema { types { @@ -787,36 +787,36 @@ await ExpectValid(@" } } }", - configure: c => - { - AddDefaultConfiguration(c); - c.AddMaxExecutionDepthRule(3, skipIntrospectionFields: true); - }); - } + configure: c => + { + AddDefaultConfiguration(c); + c.AddMaxExecutionDepthRule(3, skipIntrospectionFields: true); + }); + } - [InlineData("true")] - [InlineData("false")] - [Theory] - public async Task Include_With_Literal(string ifValue) - { - Snapshot.FullName(new SnapshotNameExtension(ifValue)); - await ExpectValid($@" + [InlineData("true")] + [InlineData("false")] + [Theory] + public async Task Include_With_Literal(string ifValue) + { + Snapshot.FullName(new SnapshotNameExtension(ifValue)); + await ExpectValid($@" {{ human(id: ""1000"") {{ name @include(if: {ifValue}) height }} }}") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [InlineData(true)] - [InlineData(false)] - [Theory] - public async Task Include_With_Variable(bool ifValue) - { - Snapshot.FullName(new SnapshotNameExtension(ifValue)); - await ExpectValid($@" + [InlineData(true)] + [InlineData(false)] + [Theory] + public async Task Include_With_Variable(bool ifValue) + { + Snapshot.FullName(new SnapshotNameExtension(ifValue)); + await ExpectValid($@" query ($if: Boolean!) {{ human(id: ""1000"") {{ name @include(if: $if) @@ -824,32 +824,32 @@ name @include(if: $if) }} }}", request: r => r.SetVariableValue("if", ifValue)) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [InlineData("true")] - [InlineData("false")] - [Theory] - public async Task Skip_With_Literal(string ifValue) - { - Snapshot.FullName(new SnapshotNameExtension(ifValue)); - await ExpectValid($@" + [InlineData("true")] + [InlineData("false")] + [Theory] + public async Task Skip_With_Literal(string ifValue) + { + Snapshot.FullName(new SnapshotNameExtension(ifValue)); + await ExpectValid($@" {{ human(id: ""1000"") {{ name @skip(if: {ifValue}) height }} }}") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [InlineData(true)] - [InlineData(false)] - [Theory] - public async Task Skip_With_Variable(bool ifValue) - { - Snapshot.FullName(new SnapshotNameExtension(ifValue)); - await ExpectValid(@" + [InlineData(true)] + [InlineData(false)] + [Theory] + public async Task Skip_With_Variable(bool ifValue) + { + Snapshot.FullName(new SnapshotNameExtension(ifValue)); + await ExpectValid(@" query ($if: Boolean!) { human(id: ""1000"") { name @skip(if: $if) @@ -857,15 +857,15 @@ name @skip(if: $if) } }", request: r => r.SetVariableValue("if", ifValue)) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SkipAll() - { - Snapshot.FullName(); + [Fact] + public async Task SkipAll() + { + Snapshot.FullName(); - await ExpectValid(@" + await ExpectValid(@" query ($if: Boolean!) { human(id: ""1000"") @skip(if: $if) { name @@ -873,59 +873,59 @@ await ExpectValid(@" } }", request: r => r.SetVariableValue("if", true)) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SkipAll_Default_False() - { - Snapshot.FullName(); + [Fact] + public async Task SkipAll_Default_False() + { + Snapshot.FullName(); - await ExpectValid(@" + await ExpectValid(@" query ($if: Boolean! = false) { human(id: ""1000"") @skip(if: $if) { name height } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SkipAll_Default_True() - { - Snapshot.FullName(); + [Fact] + public async Task SkipAll_Default_True() + { + Snapshot.FullName(); - await ExpectValid(@" + await ExpectValid(@" query ($if: Boolean! = true) { human(id: ""1000"") @skip(if: $if) { name height } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SkipAllSecondLevelFields() - { - Snapshot.FullName(); + [Fact] + public async Task SkipAllSecondLevelFields() + { + Snapshot.FullName(); - await ExpectValid(@" + await ExpectValid(@" query ($if: Boolean!) { human(id: ""1000"") { name @skip(if: $if) } }", request: r => r.SetVariableValue("if", true)) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Type_Introspection_Returns_Null_If_Type_Not_Found() - { - Snapshot.FullName(); - await ExpectValid(@" + [Fact] + public async Task Ensure_Type_Introspection_Returns_Null_If_Type_Not_Found() + { + Snapshot.FullName(); + await ExpectValid(@" query { a: __type(name: ""Foo"") { name @@ -934,51 +934,51 @@ await ExpectValid(@" name } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Benchmark_Query_GetHeroQuery() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task Ensure_Benchmark_Query_GetHeroQuery() + { + Snapshot.FullName(); + await ExpectValid( FileResource.Open("GetHeroQuery.graphql")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Benchmark_Query_GetHeroWithFriendsQuery() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task Ensure_Benchmark_Query_GetHeroWithFriendsQuery() + { + Snapshot.FullName(); + await ExpectValid( FileResource.Open("GetHeroWithFriendsQuery.graphql")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Benchmark_Query_GetTwoHerosWithFriendsQuery() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task Ensure_Benchmark_Query_GetTwoHerosWithFriendsQuery() + { + Snapshot.FullName(); + await ExpectValid( FileResource.Open("GetTwoHerosWithFriendsQuery.graphql")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Benchmark_Query_LargeQuery() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task Ensure_Benchmark_Query_LargeQuery() + { + Snapshot.FullName(); + await ExpectValid( FileResource.Open("LargeQuery.graphql")) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task NestedFragmentsWithNestedObjectFieldsAndSkip() - { - Snapshot.FullName(); + [Fact] + public async Task NestedFragmentsWithNestedObjectFieldsAndSkip() + { + Snapshot.FullName(); - await ExpectValid(@" + await ExpectValid(@" query ($if: Boolean!) { human(id: ""1000"") { ... Human1 @include(if: $if) @@ -1022,7 +1022,6 @@ fragment Human3 on Human { } ", request: r => r.SetVariableValue("if", true)) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/TypeConverter/TypeConverterTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/TypeConverter/TypeConverterTests.cs index 581c6c54365..55cdf0724db 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/TypeConverter/TypeConverterTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/TypeConverter/TypeConverterTests.cs @@ -9,15 +9,15 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Integration.TypeConverter +namespace HotChocolate.Execution.Integration.TypeConverter; + +public class TypeConverterTests { - public class TypeConverterTests + [Fact] + public async Task VariablesAreCoercedToTypesOtherThanTheDefinedClrTypes() { - [Fact] - public async Task VariablesAreCoercedToTypesOtherThanTheDefinedClrTypes() - { - Snapshot.FullName(); - await ExpectValid( + Snapshot.FullName(); + await ExpectValid( @" query foo($a: FooInput) { foo(foo: $a) { @@ -34,43 +34,43 @@ query foo($a: FooInput) { {"number", (byte)123} }), configure: c => c.AddQueryType()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task VariableIsCoercedToTypesOtherThanTheDefinedClrTypes() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task VariableIsCoercedToTypesOtherThanTheDefinedClrTypes() + { + Snapshot.FullName(); + await ExpectValid( @" query foo($time: DateTime) { time(time: $time) }", request: r => r.AddVariableValue("time", "2018-05-29T01:00Z"), configure: c => c.AddQueryType()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task VariableIsNotSerializedAndMustBeConvertedToClrType() - { - Snapshot.FullName(); - var time = new DateTime(2018, 01, 01, 12, 10, 10, DateTimeKind.Utc); - await ExpectValid( + [Fact] + public async Task VariableIsNotSerializedAndMustBeConvertedToClrType() + { + Snapshot.FullName(); + var time = new DateTime(2018, 01, 01, 12, 10, 10, DateTimeKind.Utc); + await ExpectValid( @" query foo($time: DateTime) { time(time: $time) }", request: r => r.AddVariableValue("time", time), configure: c => c.AddQueryType()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task VariableIsPartlyNotSerializedAndMustBeConvertedToClrType() - { - Snapshot.FullName(); - await ExpectValid( + [Fact] + public async Task VariableIsPartlyNotSerializedAndMustBeConvertedToClrType() + { + Snapshot.FullName(); + await ExpectValid( @" query foo($a: FooInput) { foo(foo: $a) { @@ -87,125 +87,124 @@ query foo($a: FooInput) { {"number", (byte)123} }), configure: c => c.AddQueryType()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public void Register_TypeConverter_As_Service() - { - // arrange - var services = new ServiceCollection(); + [Fact] + public void Register_TypeConverter_As_Service() + { + // arrange + var services = new ServiceCollection(); - // act - services.AddGraphQL().AddTypeConverter(); + // act + services.AddGraphQL().AddTypeConverter(); - // assert - ITypeConverter conversion = - services.BuildServiceProvider().GetService(); - Assert.Equal("123", conversion.Convert(123)); - } + // assert + var conversion = + services.BuildServiceProvider().GetService(); + Assert.Equal("123", conversion.Convert(123)); + } - [Fact] - public void Register_DelegateTypeConverter_As_Service() - { - // arrange - var services = new ServiceCollection(); + [Fact] + public void Register_DelegateTypeConverter_As_Service() + { + // arrange + var services = new ServiceCollection(); - // act - services.AddGraphQL().AddTypeConverter( - from => from.ToString() + "_123"); + // act + services.AddGraphQL().AddTypeConverter( + from => from.ToString() + "_123"); - // assert - ITypeConverter conversion = - services.BuildServiceProvider().GetService(); - Assert.Equal("123_123", conversion.Convert(123)); - } + // assert + var conversion = + services.BuildServiceProvider().GetService(); + Assert.Equal("123_123", conversion.Convert(123)); + } + + [Fact] + public void Register_Multiple_TypeConverters_As_Service() + { + // arrange + var services = new ServiceCollection(); + services.AddGraphQLCore(); + + // act + services.AddTypeConverter( + from => from.ToString() + "_123"); + services.AddTypeConverter( + from => from + "_123"); + + // assert + var conversion = + services.BuildServiceProvider().GetService(); + Assert.Equal("123_123", conversion.Convert(123)); + Assert.Equal("a_123", conversion.Convert('a')); + } - [Fact] - public void Register_Multiple_TypeConverters_As_Service() - { - // arrange - var services = new ServiceCollection(); - services.AddGraphQLCore(); - - // act - services.AddTypeConverter( - from => from.ToString() + "_123"); - services.AddTypeConverter( - from => from + "_123"); - - // assert - ITypeConverter conversion = - services.BuildServiceProvider().GetService(); - Assert.Equal("123_123", conversion.Convert(123)); - Assert.Equal("a_123", conversion.Convert('a')); - } + [Fact] + public void Convert_Null_To_Value_Type_Default() + { + var empty = TypeConverterExtensions.Convert( + DefaultTypeConverter.Default, + null); + Assert.Equal(Guid.Empty, empty); + } - [Fact] - public void Convert_Null_To_Value_Type_Default() + public class QueryType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - Guid empty = TypeConverterExtensions.Convert( - DefaultTypeConverter.Default, - null); - Assert.Equal(Guid.Empty, empty); + descriptor.Field(t => t.GetTime(default)) + .Argument("time", a => a.Type()) + .Type(); } + } - public class QueryType - : ObjectType + public class Query + { + public Foo GetFoo(Foo foo) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.GetTime(default)) - .Argument("time", a => a.Type()) - .Type(); - } + return foo; } - public class Query + public DateTime? GetTime(DateTime? time) { - public Foo GetFoo(Foo foo) - { - return foo; - } - - public DateTime? GetTime(DateTime? time) - { - return time; - } + return time; } + } - public class Foo - { - [GraphQLType(typeof(NonNullType))] - public Guid Id { get; set; } + public class Foo + { + [GraphQLType(typeof(NonNullType))] + public Guid Id { get; set; } - [GraphQLType(typeof(DateTimeType))] - public DateTime? Time { get; set; } + [GraphQLType(typeof(DateTimeType))] + public DateTime? Time { get; set; } - [GraphQLType(typeof(LongType))] - public int? Number { get; set; } - } + [GraphQLType(typeof(LongType))] + public int? Number { get; set; } + } - public class IntToStringConverter : IChangeTypeProvider + public class IntToStringConverter : IChangeTypeProvider + { + public bool TryCreateConverter( + Type source, + Type target, + ChangeTypeProvider root, + out ChangeType converter) { - public bool TryCreateConverter( - Type source, - Type target, - ChangeTypeProvider root, - out ChangeType converter) + if (source == typeof(int) && target == typeof(string)) { - if (source == typeof(int) && target == typeof(string)) - { - converter = input => input?.ToString(); - return true; - } - - converter = null; - return false; + converter = input => input?.ToString(); + return true; } + + converter = null; + return false; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/IntrospectionTests.cs b/src/HotChocolate/Core/test/Execution.Tests/IntrospectionTests.cs index e48988d075e..54375d9e3d1 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/IntrospectionTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/IntrospectionTests.cs @@ -9,231 +9,231 @@ using Xunit; using Snapshot = Snapshooter.Xunit.Snapshot; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class IntrospectionTests { - public class IntrospectionTests + [Fact] + public async Task TypeNameIntrospectionOnQuery() { - [Fact] - public async Task TypeNameIntrospectionOnQuery() - { - // arrange - var query = "{ __typename }"; - IRequestExecutor executor = CreateSchema().MakeExecutable(); + // arrange + var query = "{ __typename }"; + var executor = CreateSchema().MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync(query); + // act + var result = await executor.ExecuteAsync(query); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task TypeNameIntrospectionNotOnQuery() - { - // arrange - var query = "{ b { __typename } }"; - IRequestExecutor executor = CreateSchema().MakeExecutable(); + [Fact] + public async Task TypeNameIntrospectionNotOnQuery() + { + // arrange + var query = "{ b { __typename } }"; + var executor = CreateSchema().MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync(query); + // act + var result = await executor.ExecuteAsync(query); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task Query_Specified_By() - { - // arrange - var query = "{ __type (name: \"DateTime\") { specifiedByURL } }"; - - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(default(DateTime))) - .Create() - .MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync(query); - - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + [Fact] + public async Task Query_Specified_By() + { + // arrange + var query = "{ __type (name: \"DateTime\") { specifiedByURL } }"; + + var executor = + SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(default(DateTime))) + .Create() + .MakeExecutable(); - [Fact] - public async Task TypeIntrospectionOnQuery() - { - // arrange - var query = "{ __type (name: \"Foo\") { name } }"; - IRequestExecutor executor = CreateSchema().MakeExecutable(); + // act + var result = await executor.ExecuteAsync(query); - // act - IExecutionResult result = await executor.ExecuteAsync(query); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + [Fact] + public async Task TypeIntrospectionOnQuery() + { + // arrange + var query = "{ __type (name: \"Foo\") { name } }"; + var executor = CreateSchema().MakeExecutable(); - [Fact] - public async Task TypeIntrospectionOnQueryWithFields() - { - // arrange - var query = - "{ __type (name: \"Foo\") " + - "{ name fields { name type { name } } } }"; - IRequestExecutor executor = CreateSchema().MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync(query); - - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // act + var result = await executor.ExecuteAsync(query); - [Fact] - public async Task ExecuteGraphiQLIntrospectionQuery() - { - // arrange - var query = FileResource.Open("IntrospectionQuery.graphql"); - IRequestExecutor executor = CreateSchema().MakeExecutable(); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // act - IExecutionResult result = await executor.ExecuteAsync(query); + [Fact] + public async Task TypeIntrospectionOnQueryWithFields() + { + // arrange + var query = + "{ __type (name: \"Foo\") " + + "{ name fields { name type { name } } } }"; + var executor = CreateSchema().MakeExecutable(); + + // act + var result = await executor.ExecuteAsync(query); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + [Fact] + public async Task ExecuteGraphiQLIntrospectionQuery() + { + // arrange + var query = FileResource.Open("IntrospectionQuery.graphql"); + var executor = CreateSchema().MakeExecutable(); - [Fact] - public async Task ExecuteGraphiQLIntrospectionQuery_ToJson() - { - // arrange - var query = FileResource.Open("IntrospectionQuery.graphql"); - IRequestExecutor executor = CreateSchema().MakeExecutable(); + // act + var result = await executor.ExecuteAsync(query); - // act - IExecutionResult result = await executor.ExecuteAsync(query); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // assert - Assert.Null(Assert.IsType(result).Errors); - result.ToJson().MatchSnapshot(); - } + [Fact] + public async Task ExecuteGraphiQLIntrospectionQuery_ToJson() + { + // arrange + var query = FileResource.Open("IntrospectionQuery.graphql"); + var executor = CreateSchema().MakeExecutable(); - [Fact] - public async Task FieldMiddlewareDoesNotHaveAnEffectOnIntrospection() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Use(next => async context => - { - await next.Invoke(context); + // act + var result = await executor.ExecuteAsync(query); - if (context.Result is string s) - { - context.Result = s.ToUpperInvariant(); - } - }) - .Create(); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.ToJson().MatchSnapshot(); + } - IRequestExecutor executor = schema.MakeExecutable(); + [Fact] + public async Task FieldMiddlewareDoesNotHaveAnEffectOnIntrospection() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Use(next => async context => + { + await next.Invoke(context); - // act - IExecutionResult result = await executor.ExecuteAsync("{ __typename a }"); + if (context.Result is string s) + { + context.Result = s.ToUpperInvariant(); + } + }) + .Create(); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [Fact] - public async Task FieldMiddlewareHasAnEffectOnIntrospectIfSwitchedOn() - { - // arrange - var query = "{ __typename a }"; + // act + var result = await executor.ExecuteAsync("{ __typename a }"); - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Use(next => async context => - { - await next.Invoke(context); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - if (context.Result is string s) - { - context.Result = s.ToUpperInvariant(); - } - }) - .ModifyOptions(o => - o.FieldMiddleware = FieldMiddlewareApplication.AllFields) - .Create(); + [Fact] + public async Task FieldMiddlewareHasAnEffectOnIntrospectIfSwitchedOn() + { + // arrange + var query = "{ __typename a }"; - IRequestExecutor executor = schema.MakeExecutable(); + var schema = SchemaBuilder.New() + .AddQueryType() + .Use(next => async context => + { + await next.Invoke(context); - // act - IExecutionResult result = await executor.ExecuteAsync(query); + if (context.Result is string s) + { + context.Result = s.ToUpperInvariant(); + } + }) + .ModifyOptions(o => + o.FieldMiddleware = FieldMiddlewareApplication.AllFields) + .Create(); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [Fact] - public async Task DirectiveMiddlewareDoesWorkOnIntrospection() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddDirectiveType() - .Create(); + // act + var result = await executor.ExecuteAsync(query); - IRequestExecutor executor = schema.MakeExecutable(); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // act - IExecutionResult result = await executor.ExecuteAsync("{ __typename @upper a }"); + [Fact] + public async Task DirectiveMiddlewareDoesWorkOnIntrospection() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .AddDirectiveType() + .Create(); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [Fact] - public async Task DefaultValueIsInputObject() - { - // arrange - var query = FileResource.Open("IntrospectionQuery.graphql"); - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType() - .ModifyOptions(o => o.RemoveUnreachableTypes = false) - .Create() - .MakeExecutable(); + // act + var result = await executor.ExecuteAsync("{ __typename @upper a }"); - // act - IExecutionResult result = await executor.ExecuteAsync(query); + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + [Fact] + public async Task DefaultValueIsInputObject() + { + // arrange + var query = FileResource.Open("IntrospectionQuery.graphql"); + var executor = SchemaBuilder.New() + .AddQueryType() + .ModifyOptions(o => o.RemoveUnreachableTypes = false) + .Create() + .MakeExecutable(); + + // act + var result = await executor.ExecuteAsync(query); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task DirectiveIntrospection_AllDirectives_Public() - { - Snapshot.FullName(); + [Fact] + public async Task DirectiveIntrospection_AllDirectives_Public() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString( - @" + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString( + @" type Query { foo: String @foo @@ -252,10 +252,10 @@ directive @foo on FIELD_DEFINITION directive @bar(baz: String quox: SomeInput) repeatable on FIELD_DEFINITION ") - .UseField(next => next) - .ModifyOptions(o => o.EnableDirectiveIntrospection = true) - .ExecuteRequestAsync( - @" + .UseField(next => next) + .ModifyOptions(o => o.EnableDirectiveIntrospection = true) + .ExecuteRequestAsync( + @" { __schema { types { @@ -272,18 +272,18 @@ directive @bar(baz: String quox: SomeInput) repeatable on FIELD_DEFINITION } } ") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task DirectiveIntrospection_AllDirectives_Internal() - { - Snapshot.FullName(); + [Fact] + public async Task DirectiveIntrospection_AllDirectives_Internal() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString( - @" + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString( + @" type Query { foo: String @foo @@ -302,11 +302,11 @@ directive @foo on FIELD_DEFINITION directive @bar(baz: String quox: SomeInput) repeatable on FIELD_DEFINITION ") - .UseField(next => next) - .ModifyOptions(o => o.EnableDirectiveIntrospection = true) - .ModifyOptions(o => o.DefaultDirectiveVisibility = DirectiveVisibility.Internal) - .ExecuteRequestAsync( - @" + .UseField(next => next) + .ModifyOptions(o => o.EnableDirectiveIntrospection = true) + .ModifyOptions(o => o.DefaultDirectiveVisibility = DirectiveVisibility.Internal) + .ExecuteRequestAsync( + @" { __schema { types { @@ -323,18 +323,18 @@ directive @bar(baz: String quox: SomeInput) repeatable on FIELD_DEFINITION } } ") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task DirectiveIntrospection_SomeDirectives_Internal() - { - Snapshot.FullName(); + [Fact] + public async Task DirectiveIntrospection_SomeDirectives_Internal() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString( - @" + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString( + @" type Query { foo: String @foo @@ -351,16 +351,16 @@ input SomeInput { directive @bar(baz: String quox: SomeInput) repeatable on FIELD_DEFINITION ") - .UseField(next => next) - .ModifyOptions(o => o.EnableDirectiveIntrospection = true) - .AddDirectiveType(new DirectiveType(d => - { - d.Name("foo"); - d.Location(DirectiveLocation.FieldDefinition); - d.Internal(); - })) - .ExecuteRequestAsync( - @" + .UseField(next => next) + .ModifyOptions(o => o.EnableDirectiveIntrospection = true) + .AddDirectiveType(new DirectiveType(d => + { + d.Name("foo"); + d.Location(DirectiveLocation.FieldDefinition); + d.Internal(); + })) + .ExecuteRequestAsync( + @" { __schema { types { @@ -377,123 +377,122 @@ directive @bar(baz: String quox: SomeInput) repeatable on FIELD_DEFINITION } } ") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - private static ISchema CreateSchema() - { - return SchemaBuilder.New() - .AddType() - .AddQueryType() - .ModifyOptions(o => o.RemoveUnreachableTypes = false) - .Create(); - } + private static ISchema CreateSchema() + { + return SchemaBuilder.New() + .AddType() + .AddQueryType() + .ModifyOptions(o => o.RemoveUnreachableTypes = false) + .Create(); + } - private sealed class Query : ObjectType + private sealed class Query : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - - descriptor.Field("a") - .Type() - .Resolve(() => "a"); - - descriptor.Field("b") - .Type() - .Resolve(() => new object()); - - descriptor.Field("c") - .Type() - .Argument("c_arg", x => x.Type().Deprecated("TEST")) - .Resolve(() => "c"); - - descriptor.Field("d") - .Type() - .Argument("d_arg", x => x.Type()) - .Resolve(() => "d"); - } + descriptor.Name("Query"); + + descriptor.Field("a") + .Type() + .Resolve(() => "a"); + + descriptor.Field("b") + .Type() + .Resolve(() => new object()); + + descriptor.Field("c") + .Type() + .Argument("c_arg", x => x.Type().Deprecated("TEST")) + .Resolve(() => "c"); + + descriptor.Field("d") + .Type() + .Argument("d_arg", x => x.Type()) + .Resolve(() => "d"); } + } - private sealed class BarDirectiveType : DirectiveType + private sealed class BarDirectiveType : DirectiveType + { + protected override void Configure(IDirectiveTypeDescriptor descriptor) { - protected override void Configure(IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("Bar"); - descriptor.Location(DirectiveLocation.Query | DirectiveLocation.Field); - descriptor.Argument("a").Type(); - descriptor.Argument("b").Type().Deprecated("TEST 3"); - } + descriptor.Name("Bar"); + descriptor.Location(DirectiveLocation.Query | DirectiveLocation.Field); + descriptor.Argument("a").Type(); + descriptor.Argument("b").Type().Deprecated("TEST 3"); } + } - private sealed class FooInput : InputObjectType + private sealed class FooInput : InputObjectType + { + protected override void Configure(IInputObjectTypeDescriptor descriptor) { - protected override void Configure(IInputObjectTypeDescriptor descriptor) - { - descriptor.Name("FooInput"); + descriptor.Name("FooInput"); - descriptor.Field("a").Type(); + descriptor.Field("a").Type(); - descriptor.Field("b").Type().Deprecated("TEST 2"); - } + descriptor.Field("b").Type().Deprecated("TEST 2"); } + } - private sealed class Foo : ObjectType + private sealed class Foo : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Foo"); + descriptor.Name("Foo"); - descriptor.Field("a") - .Type() - .Resolve(() => "foo.a"); - } + descriptor.Field("a") + .Type() + .Resolve(() => "foo.a"); } + } - private sealed class BarType : ObjectType + private sealed class BarType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Bar"); - descriptor.Field("a") - .Type() - .Argument("b", - a => a.Type() - .DefaultValue(new Baz { Qux = "fooBar" })) - .Resolve(() => "foo.a"); - } + descriptor.Name("Bar"); + descriptor.Field("a") + .Type() + .Argument("b", + a => a.Type() + .DefaultValue(new Baz { Qux = "fooBar" })) + .Resolve(() => "foo.a"); } + } - public class BazType : InputObjectType + public class BazType : InputObjectType + { + protected override void Configure(IInputObjectTypeDescriptor descriptor) { - protected override void Configure(IInputObjectTypeDescriptor descriptor) - { - descriptor.Name("Baz"); - descriptor.Field(t => t.Qux).DefaultValue("123456"); - } + descriptor.Name("Baz"); + descriptor.Field(t => t.Qux).DefaultValue("123456"); } + } - public class Baz - { - public string Qux { get; set; } - } + public class Baz + { + public string Qux { get; set; } + } - private sealed class UpperDirectiveType : DirectiveType + private sealed class UpperDirectiveType : DirectiveType + { + protected override void Configure(IDirectiveTypeDescriptor descriptor) { - protected override void Configure(IDirectiveTypeDescriptor descriptor) + descriptor.Name("upper"); + descriptor.Location(DirectiveLocation.Field); + descriptor.Use(next => async context => { - descriptor.Name("upper"); - descriptor.Location(DirectiveLocation.Field); - descriptor.Use(next => async context => + await next.Invoke(context); + + if (context.Result is string s) { - await next.Invoke(context); - - if (context.Result is string s) - { - context.Result = s.ToUpperInvariant(); - } - }); - } + context.Result = s.ToUpperInvariant(); + } + }); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/MiddlewareContextTests.cs b/src/HotChocolate/Core/test/Execution.Tests/MiddlewareContextTests.cs index 911038d9b41..33b266dfb0e 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/MiddlewareContextTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/MiddlewareContextTests.cs @@ -10,67 +10,67 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class MiddlewareContextTests { - public class MiddlewareContextTests + [Fact] + public async Task AccessVariables() { - [Fact] - public async Task AccessVariables() - { - // arrange - var schema = SchemaBuilder.New() - .AddDocumentFromString( - "type Query { foo(bar: String) : String }") - .AddResolver("Query", "foo", ctx => - ctx.Variables.GetVariable("abc")) - .Create(); - - var request = QueryRequestBuilder.New() - .SetQuery("query abc($abc: String){ foo(bar: $abc) }") - .SetVariableValue("abc", "def") - .Create(); - - // act - var result = - await schema.MakeExecutable().ExecuteAsync(request); - - // assert - result.MatchSnapshot(); - } - - [Fact] - public async Task AccessVariables_Fails_When_Variable_Not_Exists() - { - // arrange - var schema = SchemaBuilder.New() - .AddDocumentFromString( - "type Query { foo(bar: String) : String }") - .AddResolver("Query", "foo", ctx => - ctx.Variables.GetVariable("abc")) - .Create(); - - var request = QueryRequestBuilder.New() - .SetQuery("query abc($def: String){ foo(bar: $def) }") - .SetVariableValue("def", "ghi") - .Create(); - - // act - var result = - await schema.MakeExecutable().ExecuteAsync(request); + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + "type Query { foo(bar: String) : String }") + .AddResolver("Query", "foo", ctx => + ctx.Variables.GetVariable("abc")) + .Create(); + + var request = QueryRequestBuilder.New() + .SetQuery("query abc($abc: String){ foo(bar: $abc) }") + .SetVariableValue("abc", "def") + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync(request); + + // assert + result.MatchSnapshot(); + } - // assert - result.MatchSnapshot(); - } + [Fact] + public async Task AccessVariables_Fails_When_Variable_Not_Exists() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + "type Query { foo(bar: String) : String }") + .AddResolver("Query", "foo", ctx => + ctx.Variables.GetVariable("abc")) + .Create(); + + var request = QueryRequestBuilder.New() + .SetQuery("query abc($def: String){ foo(bar: $def) }") + .SetVariableValue("def", "ghi") + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync(request); + + // assert + result.MatchSnapshot(); + } - [Fact] - public async Task CollectFields() - { - // arrange - var list = new List(); + [Fact] + public async Task CollectFields() + { + // arrange + var list = new List(); - var schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { foo: Foo } @@ -82,21 +82,21 @@ type Foo { type Bar { baz: String }") - .Use(_ => context => + .Use(_ => context => + { + if (context.Selection.Type.NamedType() is ObjectType type) { - if (context.Selection.Type.NamedType() is ObjectType type) + foreach (var selection in context.GetSelections(type)) { - foreach (var selection in context.GetSelections(type)) - { - CollectSelections(context, selection, list); - } + CollectSelections(context, selection, list); } - return default; - }) - .Create(); + } + return default; + }) + .Create(); - // act - await schema.MakeExecutable().ExecuteAsync( + // act + await schema.MakeExecutable().ExecuteAsync( @"{ foo { bar { @@ -105,55 +105,54 @@ await schema.MakeExecutable().ExecuteAsync( } }"); - // assert - list.Select(t => t.SyntaxNode.Name.Value).ToList().MatchSnapshot(); - } + // assert + list.Select(t => t.SyntaxNode.Name.Value).ToList().MatchSnapshot(); + } - [Fact] - public async Task CustomServiceProvider() - { - // arrange - Snapshot.FullName(); - var services = new DictionaryServiceProvider(typeof(string), "hello"); + [Fact] + public async Task CustomServiceProvider() + { + // arrange + Snapshot.FullName(); + var services = new DictionaryServiceProvider(typeof(string), "hello"); + + // assert + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => + { + d.Name(OperationTypeNames.Query); - // assert - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => - { - d.Name(OperationTypeNames.Query); - - d.Field("foo") - .Resolve(ctx => ctx.Service()) - .Use(next => async context => - { - context.Services = services; - await next(context); - }); - }) - .ExecuteRequestAsync("{ foo }") + d.Field("foo") + .Resolve(ctx => ctx.Service()) + .Use(next => async context => + { + context.Services = services; + await next(context); + }); + }) + .ExecuteRequestAsync("{ foo }") // assert - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - private static void CollectSelections( - IResolverContext context, - ISelection selection, - ICollection collected) + private static void CollectSelections( + IResolverContext context, + ISelection selection, + ICollection collected) + { + if (selection.Type.IsLeafType()) { - if (selection.Type.IsLeafType()) - { - collected.Add(selection); - } + collected.Add(selection); + } - if (selection.Type.NamedType() is ObjectType objectType) + if (selection.Type.NamedType() is ObjectType objectType) + { + foreach (var child in context.GetSelections(objectType, selection)) { - foreach (var child in context.GetSelections(objectType, selection)) - { - CollectSelections(context, child, collected); - } + CollectSelections(context, child, collected); } } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/NullErrorPropagationTests.cs b/src/HotChocolate/Core/test/Execution.Tests/NullErrorPropagationTests.cs index 7140e9a81b3..dc6e6b93dc4 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/NullErrorPropagationTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/NullErrorPropagationTests.cs @@ -3,19 +3,19 @@ using HotChocolate.Tests; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class NullErrorPropagation { - public class NullErrorPropagation + [Fact] + public async Task Lists_NullableElementIsNull() { - [Fact] - public async Task Lists_NullableElementIsNull() - { - // arrange - IRequestExecutor executor = CreateExecutor(); - - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery(@" + // arrange + var executor = CreateExecutor(); + + var request = + QueryRequestBuilder.New() + .SetQuery(@" { foo { nullable_list_nullable_element @@ -40,112 +40,112 @@ public async Task Lists_NullableElementIsNull() } } }") - .AddGlobalState("a", null) - .AddGlobalState("b", "not_null") - .Create(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - request, CancellationToken.None); - - // assert - result.MatchSnapshot(); - } - - [InlineData("nullable_list_nullable_element")] - [InlineData("nonnull_list_nullable_element")] - [InlineData("nullable_list_nonnull_element")] - [InlineData("nonnull_list_nonnull_element")] - [Theory] - public async Task List_NonNullElementIsNull(string fieldType) - { - // arrange - IRequestExecutor executor = CreateExecutor(); - - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery($"{{ foo {{ {fieldType} {{ b }} }} }}") - .AddGlobalState("b", null) - .Create(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - request, CancellationToken.None); - - // assert - result.MatchSnapshot(fieldType); - } - - [InlineData("nullable_list_nullable_element")] - [InlineData("nullable_list_nonnull_element")] - [InlineData("nonnull_list_nullable_element")] - [InlineData("nonnull_list_nonnull_element")] - [Theory] - public async Task List_NonNullElementHasError(string fieldType) - { - // arrange - IRequestExecutor executor = CreateExecutor(); - - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery($"{{ foo {{ {fieldType} {{ c }} }} }}") - .AddGlobalState("b", null) - .Create(); - - // act - IExecutionResult result = await executor.ExecuteAsync(request, CancellationToken.None); - - // assert - result.MatchSnapshot(fieldType); - } - - [InlineData("nonnull_prop")] - [InlineData("nullable_prop")] - [Theory] - public async Task Object_NonNullElementIsNull(string fieldType) - { - // arrange - IRequestExecutor executor = CreateExecutor(); - - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery($"{{ foo {{ {fieldType} {{ b }} }} }}") - .AddGlobalState("b", null) - .Create(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - request, CancellationToken.None); - - // assert - result.MatchSnapshot(fieldType); - } - - [InlineData("nonnull_prop")] - [InlineData("nullable_prop")] - [Theory] - public async Task Object_NonNullElementHasError(string fieldType) - { - // arrange - IRequestExecutor executor = CreateExecutor(); - - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery($"{{ foo {{ {fieldType} {{ c }} }} }}") - .AddGlobalState("b", null) - .Create(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - request, CancellationToken.None); - - // assert - result.MatchSnapshot(fieldType); - } - - private IRequestExecutor CreateExecutor() - { - var schema = @" + .AddGlobalState("a", null) + .AddGlobalState("b", "not_null") + .Create(); + + // act + var result = await executor.ExecuteAsync( + request, CancellationToken.None); + + // assert + result.MatchSnapshot(); + } + + [InlineData("nullable_list_nullable_element")] + [InlineData("nonnull_list_nullable_element")] + [InlineData("nullable_list_nonnull_element")] + [InlineData("nonnull_list_nonnull_element")] + [Theory] + public async Task List_NonNullElementIsNull(string fieldType) + { + // arrange + var executor = CreateExecutor(); + + var request = + QueryRequestBuilder.New() + .SetQuery($"{{ foo {{ {fieldType} {{ b }} }} }}") + .AddGlobalState("b", null) + .Create(); + + // act + var result = await executor.ExecuteAsync( + request, CancellationToken.None); + + // assert + result.MatchSnapshot(fieldType); + } + + [InlineData("nullable_list_nullable_element")] + [InlineData("nullable_list_nonnull_element")] + [InlineData("nonnull_list_nullable_element")] + [InlineData("nonnull_list_nonnull_element")] + [Theory] + public async Task List_NonNullElementHasError(string fieldType) + { + // arrange + var executor = CreateExecutor(); + + var request = + QueryRequestBuilder.New() + .SetQuery($"{{ foo {{ {fieldType} {{ c }} }} }}") + .AddGlobalState("b", null) + .Create(); + + // act + var result = await executor.ExecuteAsync(request, CancellationToken.None); + + // assert + result.MatchSnapshot(fieldType); + } + + [InlineData("nonnull_prop")] + [InlineData("nullable_prop")] + [Theory] + public async Task Object_NonNullElementIsNull(string fieldType) + { + // arrange + var executor = CreateExecutor(); + + var request = + QueryRequestBuilder.New() + .SetQuery($"{{ foo {{ {fieldType} {{ b }} }} }}") + .AddGlobalState("b", null) + .Create(); + + // act + var result = await executor.ExecuteAsync( + request, CancellationToken.None); + + // assert + result.MatchSnapshot(fieldType); + } + + [InlineData("nonnull_prop")] + [InlineData("nullable_prop")] + [Theory] + public async Task Object_NonNullElementHasError(string fieldType) + { + // arrange + var executor = CreateExecutor(); + + var request = + QueryRequestBuilder.New() + .SetQuery($"{{ foo {{ {fieldType} {{ c }} }} }}") + .AddGlobalState("b", null) + .Create(); + + // act + var result = await executor.ExecuteAsync( + request, CancellationToken.None); + + // assert + result.MatchSnapshot(fieldType); + } + + private IRequestExecutor CreateExecutor() + { + var schema = @" type Query { foo: Foo } @@ -166,20 +166,19 @@ type Bar { } "; - return SchemaBuilder.New() - .AddDocumentFromString(schema) - .AddResolver("Query.foo", _ => new(new object())) - .AddResolver("Foo.nullable_list_nullable_element", _ => new(new[] { new object() })) - .AddResolver("Foo.nonnull_list_nullable_element", _ => new(new[] { new object() })) - .AddResolver("Foo.nullable_list_nonnull_element", _ => new(new[] { new object() })) - .AddResolver("Foo.nonnull_list_nonnull_element", _ => new(new[] { new object() })) - .AddResolver("Foo.nonnull_prop", _ => new(new object())) - .AddResolver("Foo.nullable_prop", _ => new(new object())) - .AddResolver("Bar.a", c => new(c.GetGlobalStateOrDefault("a"))) - .AddResolver("Bar.b", c => new(c.GetGlobalStateOrDefault("b"))) - .AddResolver("Bar.c", _ => throw new GraphQLException("ERROR")) - .Create() - .MakeExecutable(); - } + return SchemaBuilder.New() + .AddDocumentFromString(schema) + .AddResolver("Query.foo", _ => new(new object())) + .AddResolver("Foo.nullable_list_nullable_element", _ => new(new[] { new object() })) + .AddResolver("Foo.nonnull_list_nullable_element", _ => new(new[] { new object() })) + .AddResolver("Foo.nullable_list_nonnull_element", _ => new(new[] { new object() })) + .AddResolver("Foo.nonnull_list_nonnull_element", _ => new(new[] { new object() })) + .AddResolver("Foo.nonnull_prop", _ => new(new object())) + .AddResolver("Foo.nullable_prop", _ => new(new object())) + .AddResolver("Bar.a", c => new(c.GetGlobalStateOrDefault("a"))) + .AddResolver("Bar.b", c => new(c.GetGlobalStateOrDefault("b"))) + .AddResolver("Bar.c", _ => throw new GraphQLException("ERROR")) + .Create() + .MakeExecutable(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ComplexityAnalyzerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ComplexityAnalyzerTests.cs index 7a1fa48a7a6..0dc2c628fa6 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ComplexityAnalyzerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ComplexityAnalyzerTests.cs @@ -9,17 +9,17 @@ using static HotChocolate.WellKnownContextData; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class ComplexityAnalyzerTests { - public class ComplexityAnalyzerTests + [Fact] + public async Task MaxComplexity_Not_Reached() { - [Fact] - public async Task MaxComplexity_Not_Reached() - { - var complexity = 0; + var complexity = 0; - await ExpectValid( - @" + await ExpectValid( + @" { foo { ... on Foo { @@ -37,30 +37,30 @@ ... on Bar { } } ", - configure: b => b - .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) - .UseField(_ => _ => default) - .ConfigureSchema(s => s.AddCostDirectiveType()) - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 9; - }) - .UseRequest(next => async context => - { - await next(context); - complexity = (int)context.ContextData[OperationComplexity]!; - }) - .UseDefaultPipeline()); + configure: b => b + .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) + .UseField(_ => _ => default) + .ConfigureSchema(s => s.AddCostDirectiveType()) + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 9; + }) + .UseRequest(next => async context => + { + await next(context); + complexity = (int)context.ContextData[OperationComplexity]!; + }) + .UseDefaultPipeline()); - Assert.Equal(9, complexity); - } + Assert.Equal(9, complexity); + } - [Fact] - public async Task MaxComplexity_Reached() - { - await ExpectError( - @" + [Fact] + public async Task MaxComplexity_Reached() + { + await ExpectError( + @" { foo { ... on Foo { @@ -78,23 +78,23 @@ ... on Bar { } } ", - configure: b => b - .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) - .UseField(_ => _ => default) - .ConfigureSchema(s => s.AddCostDirectiveType()) - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 8; - }) - .UseDefaultPipeline()); - } + configure: b => b + .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) + .UseField(_ => _ => default) + .ConfigureSchema(s => s.AddCostDirectiveType()) + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 8; + }) + .UseDefaultPipeline()); + } - [Fact] - public async Task MaxComplexity_Analysis_Skipped() - { - await ExpectValid( - @" + [Fact] + public async Task MaxComplexity_Analysis_Skipped() + { + await ExpectValid( + @" { foo { ... on Foo { @@ -112,24 +112,24 @@ ... on Bar { } } ", - request: b => b.SkipComplexityAnalysis(), - configure: b => b - .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) - .UseField(_ => _ => default) - .ConfigureSchema(s => s.AddCostDirectiveType()) - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 8; - }) - .UseDefaultPipeline()); - } + request: b => b.SkipComplexityAnalysis(), + configure: b => b + .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) + .UseField(_ => _ => default) + .ConfigureSchema(s => s.AddCostDirectiveType()) + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 8; + }) + .UseDefaultPipeline()); + } - [Fact] - public async Task MaxComplexity_Analysis_Request_Maximum() - { - await ExpectValid( - @" + [Fact] + public async Task MaxComplexity_Analysis_Request_Maximum() + { + await ExpectValid( + @" { foo { ... on Foo { @@ -147,26 +147,26 @@ ... on Bar { } } ", - request: b => b.SetMaximumAllowedComplexity(1000), - configure: b => b - .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) - .UseField(_ => _ => default) - .ConfigureSchema(s => s.AddCostDirectiveType()) - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 8; - }) - .UseDefaultPipeline()); - } + request: b => b.SetMaximumAllowedComplexity(1000), + configure: b => b + .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) + .UseField(_ => _ => default) + .ConfigureSchema(s => s.AddCostDirectiveType()) + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 8; + }) + .UseDefaultPipeline()); + } - [Fact] - public async Task MaxComplexity_Custom_Calculation() - { - var complexity = 0; + [Fact] + public async Task MaxComplexity_Custom_Calculation() + { + var complexity = 0; - await ExpectValid( - @" + await ExpectValid( + @" { foo { ... on Foo { @@ -184,64 +184,64 @@ ... on Bar { } } ", - configure: b => b - .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) - .UseField(_ => _ => default) - .ConfigureSchema(s => s.AddCostDirectiveType()) - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 1000; - o.Complexity.Calculation = context => - ComplexityAnalyzerSettings.DefaultCalculation(context) * 2; - }) - .UseRequest(next => async context => - { - await next(context); - complexity = (int)context.ContextData[OperationComplexity]!; - }) - .UseDefaultPipeline()); + configure: b => b + .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) + .UseField(_ => _ => default) + .ConfigureSchema(s => s.AddCostDirectiveType()) + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 1000; + o.Complexity.Calculation = context => + ComplexityAnalyzerSettings.DefaultCalculation(context) * 2; + }) + .UseRequest(next => async context => + { + await next(context); + complexity = (int)context.ContextData[OperationComplexity]!; + }) + .UseDefaultPipeline()); - Assert.Equal(50, complexity); - } + Assert.Equal(50, complexity); + } - [Fact] - public async Task Apply_Complexity_Defaults_For_Connections() - { - var complexity = 0; + [Fact] + public async Task Apply_Complexity_Defaults_For_Connections() + { + var complexity = 0; - await ExpectValid( - @"{ + await ExpectValid( + @"{ persons { nodes { name } } }", - configure: b => b - .AddQueryType() - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 1000; - }) - .UseRequest(next => async context => - { - await next(context); - complexity = (int)context.ContextData[OperationComplexity]!; - }) - .UseDefaultPipeline()); + configure: b => b + .AddQueryType() + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 1000; + }) + .UseRequest(next => async context => + { + await next(context); + complexity = (int)context.ContextData[OperationComplexity]!; + }) + .UseDefaultPipeline()); - Assert.Equal(70, complexity); - } + Assert.Equal(70, complexity); + } - [Fact] - public async Task Apply_Complexity_Defaults_For_Connections_And_Resolvers() - { - var complexity = 0; + [Fact] + public async Task Apply_Complexity_Defaults_For_Connections_And_Resolvers() + { + var complexity = 0; - await ExpectValid( - @"{ + await ExpectValid( + @"{ persons { nodes { name @@ -251,30 +251,30 @@ await ExpectValid( name } }", - configure: b => b - .AddQueryType() - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 1000; - }) - .UseRequest(next => async context => - { - await next(context); - complexity = (int)context.ContextData[OperationComplexity]!; - }) - .UseDefaultPipeline()); + configure: b => b + .AddQueryType() + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 1000; + }) + .UseRequest(next => async context => + { + await next(context); + complexity = (int)context.ContextData[OperationComplexity]!; + }) + .UseDefaultPipeline()); - Assert.Equal(76, complexity); - } + Assert.Equal(76, complexity); + } - [Fact] - public async Task Apply_Complexity_Defaults_For_Connections_And_Resolvers_And_InMemField() - { - var complexity = 0; + [Fact] + public async Task Apply_Complexity_Defaults_For_Connections_And_Resolvers_And_InMemField() + { + var complexity = 0; - await ExpectValid( - @"{ + await ExpectValid( + @"{ persons { nodes { name @@ -285,45 +285,45 @@ await ExpectValid( } sayHello }", - configure: b => b - .AddQueryType() - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 1000; - }) - .UseRequest(next => async context => - { - await next(context); - complexity = (int)context.ContextData[OperationComplexity]!; - }) - .UseDefaultPipeline()); - - Assert.Equal(77, complexity); - } - - [Fact] - public async Task Apply_Complexity_Defaults() - { - await new ServiceCollection() - .AddGraphQL() + configure: b => b .AddQueryType() .ModifyRequestOptions(o => { o.Complexity.Enable = true; o.Complexity.MaximumAllowed = 1000; }) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + .UseRequest(next => async context => + { + await next(context); + complexity = (int)context.ContextData[OperationComplexity]!; + }) + .UseDefaultPipeline()); + + Assert.Equal(77, complexity); + } + + [Fact] + public async Task Apply_Complexity_Defaults() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 1000; + }) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task MaxComplexity_Not_With_Union() - { - var complexity = 0; + [Fact] + public async Task MaxComplexity_Not_With_Union() + { + var complexity = 0; - await ExpectValid( - @" + await ExpectValid( + @" { bazOrBar { ... on Foo { @@ -348,50 +348,49 @@ ... on Bar { } } ", - configure: b => b - .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) - .UseField(_ => _ => default) - .ConfigureSchema(s => s.AddCostDirectiveType()) - .ModifyRequestOptions(o => - { - o.Complexity.Enable = true; - o.Complexity.MaximumAllowed = 1000; - }) - .UseRequest(next => async context => - { - await next(context); - complexity = (int)context.ContextData[OperationComplexity]!; - }) - .UseDefaultPipeline()); + configure: b => b + .AddDocumentFromString(FileResource.Open("CostSchema.graphql")) + .UseField(_ => _ => default) + .ConfigureSchema(s => s.AddCostDirectiveType()) + .ModifyRequestOptions(o => + { + o.Complexity.Enable = true; + o.Complexity.MaximumAllowed = 1000; + }) + .UseRequest(next => async context => + { + await next(context); + complexity = (int)context.ContextData[OperationComplexity]!; + }) + .UseDefaultPipeline()); - Assert.Equal(16, complexity); - } + Assert.Equal(16, complexity); + } - private static ISchema CreateSchema() - { - return SchemaBuilder.New() - .AddDocumentFromString( - FileResource.Open("CostSchema.graphql")) - .AddCostDirectiveType() - .Use(_ => _ => default) - .Create(); - } + private static ISchema CreateSchema() + { + return SchemaBuilder.New() + .AddDocumentFromString( + FileResource.Open("CostSchema.graphql")) + .AddCostDirectiveType() + .Use(_ => _ => default) + .Create(); + } - public class Query - { - [UsePaging] - public IQueryable GetPersons() => - new[] { new Person() }.AsQueryable(); + public class Query + { + [UsePaging] + public IQueryable GetPersons() => + new[] { new Person() }.AsQueryable(); - public Task GetPersonAsync() => - Task.FromResult(new Person()); + public Task GetPersonAsync() => + Task.FromResult(new Person()); - public string SayHello() => "Hello"; - } + public string SayHello() => "Hello"; + } - public class Person - { - public string Name { get; set; } = "Luke"; - } + public class Person + { + public string Name { get; set; } = "Luke"; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentCacheMiddlewareTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentCacheMiddlewareTests.cs index cf5b3d07865..461ac77839e 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentCacheMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentCacheMiddlewareTests.cs @@ -4,207 +4,206 @@ using Moq; using Xunit; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class DocumentCacheMiddlewareTests { - public class DocumentCacheMiddlewareTests + [Fact] + public async Task RetrieveItemFromCache_DocumentFoundOnCache() + { + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var middleware = new DocumentCacheMiddleware( + context => default, + new NoopExecutionDiagnosticEvents(), + cache, + hashProvider); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + cache.TryAddDocument("a", document); + + var requestContext = new Mock(); + var schema = new Mock(); + requestContext.SetupGet(t => t.Schema).Returns(schema.Object); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.DocumentId); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.ValidationResult); + schema.Setup(s => s.Name).Returns("SchemaName"); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Equal(document, requestContext.Object.Document); + Assert.Equal("a", requestContext.Object.DocumentId); + } + + [Fact] + public async Task RetrieveItemFromCacheByHash_DocumentFoundOnCache() + { + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var middleware = new DocumentCacheMiddleware( + context => default, + new NoopExecutionDiagnosticEvents(), + cache, + hashProvider); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryHash("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + cache.TryAddDocument("a", document); + + var requestContext = new Mock(); + var schema = new Mock(); + requestContext.SetupGet(t => t.Schema).Returns(schema.Object); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.DocumentId); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.ValidationResult); + schema.Setup(s => s.Name).Returns("SchemaName"); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Equal(document, requestContext.Object.Document); + Assert.Equal("a", requestContext.Object.DocumentId); + } + + [Fact] + public async Task RetrieveItemFromCache_DocumentNotFoundOnCache() + { + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var middleware = new DocumentCacheMiddleware( + context => default, + new NoopExecutionDiagnosticEvents(), + cache, + hashProvider); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + cache.TryAddDocument("b", document); + + var requestContext = new Mock(); + var schema = new Mock(); + requestContext.SetupGet(t => t.Schema).Returns(schema.Object); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.DocumentId); + requestContext.SetupProperty(t => t.DocumentHash); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.ValidationResult); + schema.Setup(s => s.Name).Returns("SchemaName"); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Null(requestContext.Object.Document); + Assert.Null(requestContext.Object.DocumentId); + Assert.Equal("1/4JnW9GhGu3YdhGeMefaA==", requestContext.Object.DocumentHash); + } + + [Fact] + public async Task AddItemToCacheWithDocumentId() + { + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + + var middleware = new DocumentCacheMiddleware( + context => + { + context.Document = document; + context.DocumentId = "a"; + return default; + }, + new NoopExecutionDiagnosticEvents(), + cache, + hashProvider); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.DocumentId); + requestContext.SetupProperty(t => t.DocumentHash); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.ValidationResult); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Equal(document, requestContext.Object.Document); + Assert.Equal("a", requestContext.Object.DocumentId); + Assert.Equal("1/4JnW9GhGu3YdhGeMefaA==", requestContext.Object.DocumentHash); + } + + [Fact] + public async Task AddItemToCacheWithDocumentHash() { - [Fact] - public async Task RetrieveItemFromCache_DocumentFoundOnCache() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var middleware = new DocumentCacheMiddleware( - context => default, - new NoopExecutionDiagnosticEvents(), - cache, - hashProvider); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - cache.TryAddDocument("a", document); - - var requestContext = new Mock(); - var schema = new Mock(); - requestContext.SetupGet(t => t.Schema).Returns(schema.Object); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.DocumentId); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.ValidationResult); - schema.Setup(s => s.Name).Returns("SchemaName"); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Equal(document, requestContext.Object.Document); - Assert.Equal("a", requestContext.Object.DocumentId); - } - - [Fact] - public async Task RetrieveItemFromCacheByHash_DocumentFoundOnCache() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var middleware = new DocumentCacheMiddleware( - context => default, - new NoopExecutionDiagnosticEvents(), - cache, - hashProvider); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryHash("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - cache.TryAddDocument("a", document); - - var requestContext = new Mock(); - var schema = new Mock(); - requestContext.SetupGet(t => t.Schema).Returns(schema.Object); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.DocumentId); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.ValidationResult); - schema.Setup(s => s.Name).Returns("SchemaName"); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Equal(document, requestContext.Object.Document); - Assert.Equal("a", requestContext.Object.DocumentId); - } - - [Fact] - public async Task RetrieveItemFromCache_DocumentNotFoundOnCache() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var middleware = new DocumentCacheMiddleware( - context => default, - new NoopExecutionDiagnosticEvents(), - cache, - hashProvider); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - cache.TryAddDocument("b", document); - - var requestContext = new Mock(); - var schema = new Mock(); - requestContext.SetupGet(t => t.Schema).Returns(schema.Object); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.DocumentId); - requestContext.SetupProperty(t => t.DocumentHash); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.ValidationResult); - schema.Setup(s => s.Name).Returns("SchemaName"); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Null(requestContext.Object.Document); - Assert.Null(requestContext.Object.DocumentId); - Assert.Equal("1/4JnW9GhGu3YdhGeMefaA==", requestContext.Object.DocumentHash); - } - - [Fact] - public async Task AddItemToCacheWithDocumentId() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - - var middleware = new DocumentCacheMiddleware( - context => - { - context.Document = document; - context.DocumentId = "a"; - return default; - }, - new NoopExecutionDiagnosticEvents(), - cache, - hashProvider); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.DocumentId); - requestContext.SetupProperty(t => t.DocumentHash); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.ValidationResult); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Equal(document, requestContext.Object.Document); - Assert.Equal("a", requestContext.Object.DocumentId); - Assert.Equal("1/4JnW9GhGu3YdhGeMefaA==", requestContext.Object.DocumentHash); - } - - [Fact] - public async Task AddItemToCacheWithDocumentHash() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - - var parserMiddleware = new DocumentParserMiddleware( - context => default, - new NoopExecutionDiagnosticEvents(), - hashProvider); - - var middleware = new DocumentCacheMiddleware( - context => - { - return parserMiddleware.InvokeAsync(context); - }, - new NoopExecutionDiagnosticEvents(), - cache, - hashProvider); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.DocumentId); - requestContext.SetupProperty(t => t.DocumentHash); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.ValidationResult); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.NotNull(requestContext.Object.Document); - Assert.Equal(requestContext.Object.DocumentHash, requestContext.Object.DocumentId); - Assert.Equal("1/4JnW9GhGu3YdhGeMefaA==", requestContext.Object.DocumentHash); - } + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + + var parserMiddleware = new DocumentParserMiddleware( + context => default, + new NoopExecutionDiagnosticEvents(), + hashProvider); + + var middleware = new DocumentCacheMiddleware( + context => + { + return parserMiddleware.InvokeAsync(context); + }, + new NoopExecutionDiagnosticEvents(), + cache, + hashProvider); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.DocumentId); + requestContext.SetupProperty(t => t.DocumentHash); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.ValidationResult); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.NotNull(requestContext.Object.Document); + Assert.Equal(requestContext.Object.DocumentHash, requestContext.Object.DocumentId); + Assert.Equal("1/4JnW9GhGu3YdhGeMefaA==", requestContext.Object.DocumentHash); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentParserMiddlewareTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentParserMiddlewareTests.cs index 71a3d2ffd46..7a484b439c4 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentParserMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentParserMiddlewareTests.cs @@ -7,106 +7,105 @@ using Moq; using Xunit; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class DocumentParserMiddlewareTests { - public class DocumentParserMiddlewareTests + [Fact] + public async Task DocumentExists_SkipParsing_DocumentIsUnchanged() + { + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var middleware = new DocumentParserMiddleware( + context => default, + new NoopExecutionDiagnosticEvents(), + hashProvider); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.Document, document); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Equal(document, requestContext.Object.Document); + } + + [Fact] + public async Task NoDocument_ParseQuery_DocumentParsedAndHashed() + { + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var middleware = new DocumentParserMiddleware( + context => default, + new NoopExecutionDiagnosticEvents(), + hashProvider); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.DocumentId); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.NotNull(requestContext.Object.Document); + Assert.NotNull(requestContext.Object.DocumentId); + } + + [Fact] + public async Task InvalidQuery_SyntaxError_ContextHasErrorResult() { - [Fact] - public async Task DocumentExists_SkipParsing_DocumentIsUnchanged() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var middleware = new DocumentParserMiddleware( - context => default, - new NoopExecutionDiagnosticEvents(), - hashProvider); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.Document, document); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Equal(document, requestContext.Object.Document); - } - - [Fact] - public async Task NoDocument_ParseQuery_DocumentParsedAndHashed() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var middleware = new DocumentParserMiddleware( - context => default, - new NoopExecutionDiagnosticEvents(), - hashProvider); - - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.DocumentId); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.NotNull(requestContext.Object.Document); - Assert.NotNull(requestContext.Object.DocumentId); - } - - [Fact] - public async Task InvalidQuery_SyntaxError_ContextHasErrorResult() - { - // arrange - var cache = new Caching.DefaultDocumentCache(); - var hashProvider = new MD5DocumentHashProvider(); - - var middleware = new DocumentParserMiddleware( - context => throw new Exception("Should not be invoked."), - new NoopExecutionDiagnosticEvents(), - hashProvider); - - var request = QueryRequestBuilder.New() - .SetQuery("{") - .SetQueryId("a") - .Create(); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupGet(t => t.ErrorHandler).Returns( - new DefaultErrorHandler( - Array.Empty(), - new RequestExecutorOptions())); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.DocumentId); - requestContext.SetupProperty(t => t.Exception); - requestContext.SetupProperty(t => t.Result); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Null(requestContext.Object.Document); - Assert.NotNull(requestContext.Object.DocumentId); - Assert.NotNull(requestContext.Object.Exception); - Assert.NotNull(requestContext.Object.Result); - } + // arrange + var cache = new Caching.DefaultDocumentCache(); + var hashProvider = new MD5DocumentHashProvider(); + + var middleware = new DocumentParserMiddleware( + context => throw new Exception("Should not be invoked."), + new NoopExecutionDiagnosticEvents(), + hashProvider); + + var request = QueryRequestBuilder.New() + .SetQuery("{") + .SetQueryId("a") + .Create(); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupGet(t => t.ErrorHandler).Returns( + new DefaultErrorHandler( + Array.Empty(), + new RequestExecutorOptions())); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.DocumentId); + requestContext.SetupProperty(t => t.Exception); + requestContext.SetupProperty(t => t.Result); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Null(requestContext.Object.Document); + Assert.NotNull(requestContext.Object.DocumentId); + Assert.NotNull(requestContext.Object.Exception); + Assert.NotNull(requestContext.Object.Result); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentValidationMiddlewareTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentValidationMiddlewareTests.cs index 129e13a570e..fcb7777fd10 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentValidationMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/DocumentValidationMiddlewareTests.cs @@ -7,204 +7,203 @@ using Moq; using Xunit; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class DocumentValidationMiddlewareTests { - public class DocumentValidationMiddlewareTests + [Fact] + public async Task DocumentIsValidated_SkipValidation() { - [Fact] - public async Task DocumentIsValidated_SkipValidation() - { - // arrange - var validator = new Mock(); - validator.SetupGet(t => t.HasDynamicRules).Returns(false); - validator.Setup(t => t.Validate( + // arrange + var validator = new Mock(); + validator.SetupGet(t => t.HasDynamicRules).Returns(false); + validator.Setup(t => t.Validate( It.IsAny(), It.IsAny(), It.IsAny>(), It.Is(b => true))) - .Returns(DocumentValidatorResult.Ok); - - var middleware = new DocumentValidationMiddleware( - _ => default, - new NoopExecutionDiagnosticEvents(), - validator.Object); - - IReadOnlyQueryRequest request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - var validationResult = new DocumentValidatorResult(Array.Empty()); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); - requestContext.SetupProperty(t => t.Document, document); - requestContext.SetupProperty(t => t.ValidationResult, validationResult); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Equal(validationResult, requestContext.Object.ValidationResult); - Assert.False(requestContext.Object.ValidationResult!.HasErrors); - } - - [Fact] - public async Task DocumentIsValidated_Dynamic() - { - // arrange - var validator = new Mock(); - validator.SetupGet(t => t.HasDynamicRules).Returns(true); - validator.Setup(t => t.Validate( - It.IsAny(), - It.IsAny(), - It.IsAny>(), - It.Is(b => true))) - .Returns(DocumentValidatorResult.Ok); - - var middleware = new DocumentValidationMiddleware( - _ => default, - new NoopExecutionDiagnosticEvents(), - validator.Object); - - IReadOnlyQueryRequest request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - var validationResult = new DocumentValidatorResult(Array.Empty()); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); - requestContext.SetupProperty(t => t.Document, document); - requestContext.SetupProperty(t => t.ValidationResult, validationResult); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.NotEqual(validationResult, requestContext.Object.ValidationResult); - Assert.False(requestContext.Object.ValidationResult!.HasErrors); - } - - [Fact] - public async Task DocumentNeedsValidation_DocumentIsValid() - { - // arrange - var validator = new Mock(); - validator.Setup(t => t.Validate( + .Returns(DocumentValidatorResult.Ok); + + var middleware = new DocumentValidationMiddleware( + _ => default, + new NoopExecutionDiagnosticEvents(), + validator.Object); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + var validationResult = new DocumentValidatorResult(Array.Empty()); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); + requestContext.SetupProperty(t => t.Document, document); + requestContext.SetupProperty(t => t.ValidationResult, validationResult); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Equal(validationResult, requestContext.Object.ValidationResult); + Assert.False(requestContext.Object.ValidationResult!.HasErrors); + } + + [Fact] + public async Task DocumentIsValidated_Dynamic() + { + // arrange + var validator = new Mock(); + validator.SetupGet(t => t.HasDynamicRules).Returns(true); + validator.Setup(t => t.Validate( + It.IsAny(), + It.IsAny(), + It.IsAny>(), + It.Is(b => true))) + .Returns(DocumentValidatorResult.Ok); + + var middleware = new DocumentValidationMiddleware( + _ => default, + new NoopExecutionDiagnosticEvents(), + validator.Object); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + var validationResult = new DocumentValidatorResult(Array.Empty()); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); + requestContext.SetupProperty(t => t.Document, document); + requestContext.SetupProperty(t => t.ValidationResult, validationResult); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.NotEqual(validationResult, requestContext.Object.ValidationResult); + Assert.False(requestContext.Object.ValidationResult!.HasErrors); + } + + [Fact] + public async Task DocumentNeedsValidation_DocumentIsValid() + { + // arrange + var validator = new Mock(); + validator.Setup(t => t.Validate( It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())) - .Returns(DocumentValidatorResult.Ok); - - var middleware = new DocumentValidationMiddleware( - _ => default, - new NoopExecutionDiagnosticEvents(), - validator.Object); - - IReadOnlyQueryRequest request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); - requestContext.SetupGet(t => t.ContextData).Returns(new Dictionary()); - requestContext.SetupProperty(t => t.Document, document); - requestContext.SetupProperty(t => t.ValidationResult); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.Equal(DocumentValidatorResult.Ok, requestContext.Object.ValidationResult); - } - - [Fact] - public async Task DocumentNeedsValidation_DocumentInvalid() - { - // arrange - var validationResult = new DocumentValidatorResult( - new[] { ErrorBuilder.New().SetMessage("Foo").Build() }); - - var validator = new Mock(); - validator.Setup(t => t.Validate( - It.IsAny(), - It.IsAny(), - It.IsAny>(), - It.IsAny())) - .Returns(validationResult); - - var middleware = new DocumentValidationMiddleware( - _ => throw new Exception("Should not be called."), - new NoopExecutionDiagnosticEvents(), - validator.Object); - - IReadOnlyQueryRequest request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); - requestContext.SetupGet(t => t.ContextData).Returns(new Dictionary()); - requestContext.SetupProperty(t => t.Document, document); - requestContext.SetupProperty(t => t.ValidationResult); - requestContext.SetupProperty(t => t.Result); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.NotNull(requestContext.Object.ValidationResult); - Assert.NotNull(requestContext.Object.Result); - } - - [Fact] - public async Task NoDocument_MiddlewareWillFail() - { - // arrange - var validator = new Mock(); - validator.Setup(t => t.Validate( + .Returns(DocumentValidatorResult.Ok); + + var middleware = new DocumentValidationMiddleware( + _ => default, + new NoopExecutionDiagnosticEvents(), + validator.Object); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); + requestContext.SetupGet(t => t.ContextData).Returns(new Dictionary()); + requestContext.SetupProperty(t => t.Document, document); + requestContext.SetupProperty(t => t.ValidationResult); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.Equal(DocumentValidatorResult.Ok, requestContext.Object.ValidationResult); + } + + [Fact] + public async Task DocumentNeedsValidation_DocumentInvalid() + { + // arrange + var validationResult = new DocumentValidatorResult( + new[] { ErrorBuilder.New().SetMessage("Foo").Build() }); + + var validator = new Mock(); + validator.Setup(t => t.Validate( + It.IsAny(), + It.IsAny(), + It.IsAny>(), + It.IsAny())) + .Returns(validationResult); + + var middleware = new DocumentValidationMiddleware( + _ => throw new Exception("Should not be called."), + new NoopExecutionDiagnosticEvents(), + validator.Object); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var document = Utf8GraphQLParser.Parse("{ a }"); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); + requestContext.SetupGet(t => t.ContextData).Returns(new Dictionary()); + requestContext.SetupProperty(t => t.Document, document); + requestContext.SetupProperty(t => t.ValidationResult); + requestContext.SetupProperty(t => t.Result); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.NotNull(requestContext.Object.ValidationResult); + Assert.NotNull(requestContext.Object.Result); + } + + [Fact] + public async Task NoDocument_MiddlewareWillFail() + { + // arrange + var validator = new Mock(); + validator.Setup(t => t.Validate( It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny())) - .Returns(DocumentValidatorResult.Ok); - - var middleware = new DocumentValidationMiddleware( - _ => throw new Exception("Should not be called."), - new NoopExecutionDiagnosticEvents(), - validator.Object); - - IReadOnlyQueryRequest request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); - - var requestContext = new Mock(); - requestContext.SetupGet(t => t.Request).Returns(request); - requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); - requestContext.SetupProperty(t => t.Document); - requestContext.SetupProperty(t => t.Result); - - // act - await middleware.InvokeAsync(requestContext.Object); - - // assert - Assert.NotNull(requestContext.Object.Result); - } + .Returns(DocumentValidatorResult.Ok); + + var middleware = new DocumentValidationMiddleware( + _ => throw new Exception("Should not be called."), + new NoopExecutionDiagnosticEvents(), + validator.Object); + + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); + + var requestContext = new Mock(); + requestContext.SetupGet(t => t.Request).Returns(request); + requestContext.SetupGet(t => t.Schema).Returns(default(ISchema)); + requestContext.SetupProperty(t => t.Document); + requestContext.SetupProperty(t => t.Result); + + // act + await middleware.InvokeAsync(requestContext.Object); + + // assert + Assert.NotNull(requestContext.Object.Result); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ExceptionMiddlewareTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ExceptionMiddlewareTests.cs index c31326dd88e..6c7d0299a8a 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ExceptionMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/ExceptionMiddlewareTests.cs @@ -6,62 +6,61 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class ExceptionMiddlewareTests { - public class ExceptionMiddlewareTests + [Fact] + public async Task Unexpected_Error() { - [Fact] - public async Task Unexpected_Error() - { - // arrange - var errorHandler = new DefaultErrorHandler( - Array.Empty(), - new RequestExecutorOptions()); + // arrange + var errorHandler = new DefaultErrorHandler( + Array.Empty(), + new RequestExecutorOptions()); - var middleware = new ExceptionMiddleware( - context => throw new Exception("Something is wrong."), - errorHandler); + var middleware = new ExceptionMiddleware( + context => throw new Exception("Something is wrong."), + errorHandler); - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); - var requestContext = new Mock(); - requestContext.SetupProperty(t => t.Result); + var requestContext = new Mock(); + requestContext.SetupProperty(t => t.Result); - // act - await middleware.InvokeAsync(requestContext.Object); + // act + await middleware.InvokeAsync(requestContext.Object); - // assert - requestContext.Object.Result.ToJson().MatchSnapshot(); - } + // assert + requestContext.Object.Result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task GraphQL_Error() - { - // arrange - var errorHandler = new DefaultErrorHandler( - Array.Empty(), - new RequestExecutorOptions()); + [Fact] + public async Task GraphQL_Error() + { + // arrange + var errorHandler = new DefaultErrorHandler( + Array.Empty(), + new RequestExecutorOptions()); - var middleware = new ExceptionMiddleware( - context => throw new GraphQLException("Something is wrong."), - errorHandler); + var middleware = new ExceptionMiddleware( + context => throw new GraphQLException("Something is wrong."), + errorHandler); - var request = QueryRequestBuilder.New() - .SetQuery("{ a }") - .SetQueryId("a") - .Create(); + var request = QueryRequestBuilder.New() + .SetQuery("{ a }") + .SetQueryId("a") + .Create(); - var requestContext = new Mock(); - requestContext.SetupProperty(t => t.Result); + var requestContext = new Mock(); + requestContext.SetupProperty(t => t.Result); - // act - await middleware.InvokeAsync(requestContext.Object); + // act + await middleware.InvokeAsync(requestContext.Object); - // assert - requestContext.Object.Result.ToJson().MatchSnapshot(); - } + // assert + requestContext.Object.Result.ToJson().MatchSnapshot(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/RequestClassMiddlewareFactoryTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/RequestClassMiddlewareFactoryTests.cs index 1dbe89e8748..d6b3d7f2b48 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/RequestClassMiddlewareFactoryTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/RequestClassMiddlewareFactoryTests.cs @@ -1,102 +1,81 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; using HotChocolate.Execution.Instrumentation; using HotChocolate.Execution.Options; using HotChocolate.Execution.Processing; -using HotChocolate.Language; using HotChocolate.Utilities; -using HotChocolate.Validation; -using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; +using static HotChocolate.Execution.Pipeline.RequestClassMiddlewareFactory; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class RequestClassMiddlewareFactoryTests { - public class RequestClassMiddlewareFactoryTests + [Fact] + public async Task Create_CoreMiddleware_InjectOptimizers() { - [Fact] - public async Task Create_CoreMiddleware_InjectOptimizers() - { - // arrange - RequestCoreMiddleware middleware = RequestClassMiddlewareFactory - .Create>>(); - var applicationServices = new ServiceCollection().BuildServiceProvider(); - ServiceProvider schemaServices = new ServiceCollection() - .AddSingleton() - .BuildServiceProvider(); - var schemaName = "_Default"; - IRequestExecutorOptionsAccessor optionsAccessor = new RequestExecutorOptions(); - var factoryContext = new RequestCoreMiddlewareContext( - schemaName, - applicationServices, - schemaServices, - optionsAccessor); - var context = new RequestContext( - new Mock().Object, - 1, - new Mock().Object, - new Mock().Object, - new Mock().Object, - new Mock().Object); + // arrange + var middleware = Create>>(); + var applicationServices = new ServiceCollection().BuildServiceProvider(); + var schemaServices = new ServiceCollection() + .AddSingleton() + .BuildServiceProvider(); + var schemaName = "_Default"; + IRequestExecutorOptionsAccessor optionsAccessor = new RequestExecutorOptions(); + var factoryContext = new RequestCoreMiddlewareContext( + schemaName, + applicationServices, + schemaServices, + optionsAccessor); + var context = new RequestContext( + new Mock().Object, + 1, + new Mock().Object, + new Mock().Object, + new Mock().Object, + new Mock().Object); - context.Initialize( - new Mock().Object, - new Mock().Object); + context.Initialize( + new Mock().Object, + new Mock().Object); - // act - RequestDelegate compiledMiddleware = middleware(factoryContext, c => default); - await compiledMiddleware(context); + // act + var compiledMiddleware = middleware(factoryContext, _ => default); + await compiledMiddleware(context); - // assert - Assert.Single( - (context.ContextData["result"] as IEnumerable)!); - } - - public class StubMiddleware - { - private readonly RequestDelegate _next; - private readonly T _injectedValue; + // assert + Assert.Single((context.ContextData["result"] as IEnumerable)!); + } - public StubMiddleware( - RequestDelegate next, - T injectedValue) - { - _next = next ?? - throw new ArgumentNullException(nameof(next)); - _injectedValue = injectedValue; - } + private sealed class StubMiddleware + { + private readonly RequestDelegate _next; + private readonly T _injectedValue; - public ValueTask InvokeAsync(IRequestContext context) - { - context.ContextData["result"] = _injectedValue; - return default; - } + public StubMiddleware( + RequestDelegate next, + T injectedValue) + { + _next = next ?? throw new ArgumentNullException(nameof(next)); + _injectedValue = injectedValue; } - public class StubOptimizer : ISelectionOptimizer + public ValueTask InvokeAsync(IRequestContext context) { - public void OptimizeSelectionSet(SelectionOptimizerContext context) - { - throw new NotImplementedException(); - } - - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - InlineFragmentNode fragment) - { - throw new NotImplementedException(); - } + context.ContextData["result"] = _injectedValue; + return _next(context); + } + } - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - FragmentSpreadNode fragmentSpread, - FragmentDefinitionNode fragmentDefinition) - { - throw new NotImplementedException(); - } + private sealed class StubOptimizer : ISelectionSetOptimizer + { + public void OptimizeSelectionSet(SelectionSetOptimizerContext context) + { + throw new NotImplementedException(); } } } diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TimeoutMiddlewareTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TimeoutMiddlewareTests.cs index 3fa5f85f148..9b442659e84 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TimeoutMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TimeoutMiddlewareTests.cs @@ -17,75 +17,74 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class TimeoutMiddlewareTests { - public class TimeoutMiddlewareTests + [Fact] + public async Task TimeoutMiddleware_Is_Integrated_Into_DefaultPipeline() { - [Fact] - public async Task TimeoutMiddleware_Is_Integrated_Into_DefaultPipeline() - { - Snapshot.FullName(); + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ModifyRequestOptions(o => o.ExecutionTimeout = TimeSpan.FromMilliseconds(100)) - .ExecuteRequestAsync("{ timeout }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ModifyRequestOptions(o => o.ExecutionTimeout = TimeSpan.FromMilliseconds(100)) + .ExecuteRequestAsync("{ timeout }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_That_Combined_Token_Is_Not_Disposed_On_Stream() - { - using var cts = new CancellationTokenSource(); + [Fact] + public async Task Ensure_That_Combined_Token_Is_Not_Disposed_On_Stream() + { + using var cts = new CancellationTokenSource(); - IExecutionResult result = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddSubscriptionType() - .ExecuteRequestAsync("subscription { onFoo }", cancellationToken: cts.Token); + var result = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddSubscriptionType() + .ExecuteRequestAsync("subscription { onFoo }", cancellationToken: cts.Token); - ResponseStream responseStream = Assert.IsType(result); + var responseStream = Assert.IsType(result); - IAsyncEnumerable enumerable = responseStream.ReadResultsAsync(); - IAsyncEnumerator enumerator = enumerable.GetAsyncEnumerator( - CancellationToken.None); + var enumerable = responseStream.ReadResultsAsync(); + var enumerator = enumerable.GetAsyncEnumerator( + CancellationToken.None); - // we should get the first result! - await enumerator.MoveNextAsync(); - enumerator.Current.ToJson().MatchSnapshot(); + // we should get the first result! + await enumerator.MoveNextAsync(); + enumerator.Current.ToJson().MatchSnapshot(); - cts.Cancel(); + cts.Cancel(); - Assert.False(await enumerator.MoveNextAsync(), "the stream should be canceled."); - } + Assert.False(await enumerator.MoveNextAsync(), "the stream should be canceled."); + } - public class TimeoutQuery + public class TimeoutQuery + { + public async Task Timeout(CancellationToken cancellationToken) { - public async Task Timeout(CancellationToken cancellationToken) - { - await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken); - return "Hello"; - } + await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken); + return "Hello"; } + } - public class Subscriptions + public class Subscriptions + { + [SubscribeAndResolve] + public async IAsyncEnumerable OnFoo( + [EnumeratorCancellation] CancellationToken cancellationToken) { - [SubscribeAndResolve] - public async IAsyncEnumerable OnFoo( - [EnumeratorCancellation] CancellationToken cancellationToken) + if (!cancellationToken.IsCancellationRequested) { - if (!cancellationToken.IsCancellationRequested) - { - yield return await Task.FromResult("a"); - } + yield return await Task.FromResult("a"); + } - if (!cancellationToken.IsCancellationRequested) - { - yield return "b"; - throw new Exception("we should not get here in this test case."); - } + if (!cancellationToken.IsCancellationRequested) + { + yield return "b"; + throw new Exception("we should not get here in this test case."); } } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TransactionScopeHandlerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TransactionScopeHandlerTests.cs index d395741171d..7bfbe927f1b 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TransactionScopeHandlerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Pipeline/TransactionScopeHandlerTests.cs @@ -6,140 +6,139 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Pipeline +namespace HotChocolate.Execution.Pipeline; + +public class TransactionScopeHandlerTests { - public class TransactionScopeHandlerTests + [Fact] + public async Task Custom_Transaction_Is_Correctly_Completed_and_Disposed() { - [Fact] - public async Task Custom_Transaction_Is_Correctly_Completed_and_Disposed() - { - var completed = false; - var disposed = false; - - void Complete() => completed = true; - void Dispose() => disposed = true; - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .ModifyRequestOptions(o => o.ExecutionTimeout = TimeSpan.FromMilliseconds(100)) - .AddTransactionScopeHandler(_ => new MockTransactionScopeHandler(Complete, Dispose)) - .ExecuteRequestAsync("mutation { doNothing }"); - - Assert.True(completed, "transaction must be completed"); - Assert.True(disposed, "transaction must be disposed"); - } + var completed = false; + var disposed = false; + + void Complete() => completed = true; + void Dispose() => disposed = true; + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .ModifyRequestOptions(o => o.ExecutionTimeout = TimeSpan.FromMilliseconds(100)) + .AddTransactionScopeHandler(_ => new MockTransactionScopeHandler(Complete, Dispose)) + .ExecuteRequestAsync("mutation { doNothing }"); + + Assert.True(completed, "transaction must be completed"); + Assert.True(disposed, "transaction must be disposed"); + } - [Fact] - public async Task Custom_Transaction_Is_Detects_Error_and_Disposes() - { - var completed = false; - var disposed = false; + [Fact] + public async Task Custom_Transaction_Is_Detects_Error_and_Disposes() + { + var completed = false; + var disposed = false; - void Complete() => completed = true; - void Dispose() => disposed = true; + void Complete() => completed = true; + void Dispose() => disposed = true; - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .AddTransactionScopeHandler(_ => new MockTransactionScopeHandler(Complete, Dispose)) - .ExecuteRequestAsync("mutation { doError }"); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .AddTransactionScopeHandler(_ => new MockTransactionScopeHandler(Complete, Dispose)) + .ExecuteRequestAsync("mutation { doError }"); - Assert.False(completed, "transaction was not completed due to error"); - Assert.True(disposed, "transaction must be disposed"); - } + Assert.False(completed, "transaction was not completed due to error"); + Assert.True(disposed, "transaction must be disposed"); + } - [Fact] - public async Task DefaultTransactionScopeHandler_Creates_SystemTransactionScope() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .AddDefaultTransactionScopeHandler() - .ExecuteRequestAsync("mutation { foundTransactionScope }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task DefaultTransactionScopeHandler_Creates_SystemTransactionScope() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .AddDefaultTransactionScopeHandler() + .ExecuteRequestAsync("mutation { foundTransactionScope }") + .MatchSnapshotAsync(); + } + + [Fact] + public async Task By_Default_There_Is_No_TransactionScope() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .ExecuteRequestAsync("mutation { foundTransactionScope }") + .MatchSnapshotAsync(); + } + + public class Query + { + public string DoNothing() => "Hello"; + } + + public class Mutation + { + public string DoNothing() => "Hello"; + + public string DoError() => throw new GraphQLException("I am broken!"); - [Fact] - public async Task By_Default_There_Is_No_TransactionScope() + public bool FoundTransactionScope() => + System.Transactions.Transaction.Current is not null; + } + + public class MockTransactionScopeHandler : ITransactionScopeHandler + { + private readonly Action _complete; + private readonly Action _dispose; + + public MockTransactionScopeHandler( + Action complete, + Action dispose) { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .ExecuteRequestAsync("mutation { foundTransactionScope }") - .MatchSnapshotAsync(); + _complete = complete; + _dispose = dispose; } - public class Query + public ITransactionScope Create(IRequestContext context) { - public string DoNothing() => "Hello"; + return new MockTransactionScope(_complete, _dispose, context); } + } - public class Mutation + public class MockTransactionScope : ITransactionScope + { + private readonly Action _complete; + private readonly Action _dispose; + private readonly IRequestContext _context; + + public MockTransactionScope( + Action complete, + Action dispose, + IRequestContext context) { - public string DoNothing() => "Hello"; - - public string DoError() => throw new GraphQLException("I am broken!"); - - public bool FoundTransactionScope() => - System.Transactions.Transaction.Current is not null; + _complete = complete; + _dispose = dispose; + _context = context; } - public class MockTransactionScopeHandler : ITransactionScopeHandler + public void Complete() { - private readonly Action _complete; - private readonly Action _dispose; - - public MockTransactionScopeHandler( - Action complete, - Action dispose) - { - _complete = complete; - _dispose = dispose; - } - - public ITransactionScope Create(IRequestContext context) + if(_context.Result is IQueryResult { Data: not null, Errors: null or { Count: 0 } }) { - return new MockTransactionScope(_complete, _dispose, context); + _complete(); } } - public class MockTransactionScope : ITransactionScope + public void Dispose() { - private readonly Action _complete; - private readonly Action _dispose; - private readonly IRequestContext _context; - - public MockTransactionScope( - Action complete, - Action dispose, - IRequestContext context) - { - _complete = complete; - _dispose = dispose; - _context = context; - } - - public void Complete() - { - if(_context.Result is IQueryResult { Data: not null, Errors: null or { Count: 0 } }) - { - _complete(); - } - } - - public void Dispose() - { - _dispose(); - } + _dispose(); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/DeferredWorkQueueTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/DeferredWorkQueueTests.cs index ff7facfcc80..a1d6e2bc775 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/DeferredWorkQueueTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/DeferredWorkQueueTests.cs @@ -4,130 +4,129 @@ #nullable enable -namespace HotChocolate.Execution.Processing.Internal +namespace HotChocolate.Execution.Processing.Internal; + +public class DeferredWorkQueueTests { - public class DeferredWorkQueueTests + [Fact] + public void Enqueue_Work() { - [Fact] - public void Enqueue_Work() - { - // arrange - var queue = new DeferredWorkQueue(); + // arrange + var queue = new DeferredWorkQueue(); - // act - var count = queue.Enqueue(new MockTask()); + // act + var count = queue.Enqueue(new MockTask()); - // assert - Assert.Equal(1, queue.Count); - Assert.Equal(1, count); - Assert.False(queue.IsEmpty); - } + // assert + Assert.Equal(1, queue.Count); + Assert.Equal(1, count); + Assert.False(queue.IsEmpty); + } - [Fact] - public void Enqueue_Null() - { - // arrange - var queue = new DeferredWorkQueue(); + [Fact] + public void Enqueue_Null() + { + // arrange + var queue = new DeferredWorkQueue(); - // act - void Error() => queue.Enqueue(null!); + // act + void Error() => queue.Enqueue(null!); - // assert - Assert.Throws(Error); - Assert.Equal(0, queue.Count); - Assert.True(queue.IsEmpty); - } - - [Fact] - public void Enqueue_Multiple() - { - // arrange - var queue = new DeferredWorkQueue(); - - // act - var count1 = queue.Enqueue(new MockTask()); - var count2 = queue.Enqueue(new MockTask()); - - // assert - Assert.Equal(2, queue.Count); - Assert.Equal(1, count1); - Assert.Equal(2, count2); - Assert.False(queue.IsEmpty); - } + // assert + Assert.Throws(Error); + Assert.Equal(0, queue.Count); + Assert.True(queue.IsEmpty); + } - [Fact] - public void Dequeue_Work_InOrder() - { - // arrange - var task1 = new MockTask { Id = 1 }; - var task2 = new MockTask { Id = 2 }; - var task3 = new MockTask { Id = 3 }; + [Fact] + public void Enqueue_Multiple() + { + // arrange + var queue = new DeferredWorkQueue(); + + // act + var count1 = queue.Enqueue(new MockTask()); + var count2 = queue.Enqueue(new MockTask()); + + // assert + Assert.Equal(2, queue.Count); + Assert.Equal(1, count1); + Assert.Equal(2, count2); + Assert.False(queue.IsEmpty); + } - var queue = new DeferredWorkQueue(); - queue.Enqueue(task1); - queue.Enqueue(task2); - queue.Enqueue(task3); + [Fact] + public void Dequeue_Work_InOrder() + { + // arrange + var task1 = new MockTask { Id = 1 }; + var task2 = new MockTask { Id = 2 }; + var task3 = new MockTask { Id = 3 }; - // act - var dequeueSuccess1 = queue.TryDequeue(out IDeferredExecutionTask? dequeuedTask1); - var count1 = queue.Count; + var queue = new DeferredWorkQueue(); + queue.Enqueue(task1); + queue.Enqueue(task2); + queue.Enqueue(task3); - var dequeueSuccess2 = queue.TryDequeue(out IDeferredExecutionTask? dequeuedTask2); - var count2 = queue.Count; + // act + var dequeueSuccess1 = queue.TryDequeue(out var dequeuedTask1); + var count1 = queue.Count; - var dequeueSuccess3 = queue.TryDequeue(out IDeferredExecutionTask? dequeuedTask3); - var count3 = queue.Count; + var dequeueSuccess2 = queue.TryDequeue(out var dequeuedTask2); + var count2 = queue.Count; - // assert - Assert.Equal(0, queue.Count); - Assert.True(queue.IsEmpty); + var dequeueSuccess3 = queue.TryDequeue(out var dequeuedTask3); + var count3 = queue.Count; - Assert.True(dequeueSuccess1); - Assert.Same(task1, dequeuedTask1); - Assert.Equal(2, count1); + // assert + Assert.Equal(0, queue.Count); + Assert.True(queue.IsEmpty); - Assert.True(dequeueSuccess2); - Assert.Same(task2, dequeuedTask2); - Assert.Equal(1, count2); + Assert.True(dequeueSuccess1); + Assert.Same(task1, dequeuedTask1); + Assert.Equal(2, count1); - Assert.True(dequeueSuccess3); - Assert.Same(task3, dequeuedTask3); - Assert.Equal(0, count3); - } + Assert.True(dequeueSuccess2); + Assert.Same(task2, dequeuedTask2); + Assert.Equal(1, count2); - [Fact] - public void Dequeue_Work_When_Empty() - { - // arrange - var queue = new DeferredWorkQueue(); + Assert.True(dequeueSuccess3); + Assert.Same(task3, dequeuedTask3); + Assert.Equal(0, count3); + } - // act - var dequeueSuccess1 = queue.TryDequeue(out IDeferredExecutionTask? dequeuedTask1); + [Fact] + public void Dequeue_Work_When_Empty() + { + // arrange + var queue = new DeferredWorkQueue(); - // assert - Assert.Equal(0, queue.Count); - Assert.True(queue.IsEmpty); + // act + var dequeueSuccess1 = queue.TryDequeue(out var dequeuedTask1); - Assert.False(dequeueSuccess1); - Assert.Null(dequeuedTask1); - } + // assert + Assert.Equal(0, queue.Count); + Assert.True(queue.IsEmpty); - private sealed class MockTask : IDeferredExecutionTask - { - /// - /// For debugging only. - /// - public int Id { get; set; } + Assert.False(dequeueSuccess1); + Assert.Null(dequeuedTask1); + } - public bool IsCompleted => false; + private sealed class MockTask : IDeferredExecutionTask + { + /// + /// For debugging only. + /// + public int Id { get; set; } - public Task ExecuteAsync(IOperationContext operationContext) - { - throw new System.NotImplementedException(); - } + public bool IsCompleted => false; - public IDeferredExecutionTask? Next { get; set; } - public IDeferredExecutionTask? Previous { get; set; } + public Task ExecuteAsync(IOperationContext operationContext) + { + throw new System.NotImplementedException(); } + + public IDeferredExecutionTask? Next { get; set; } + public IDeferredExecutionTask? Previous { get; set; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/SuspendedWorkQueueTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/SuspendedWorkQueueTests.cs deleted file mode 100644 index 93ad677eb03..00000000000 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/SuspendedWorkQueueTests.cs +++ /dev/null @@ -1,77 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using HotChocolate.Execution.Processing.Plan; -using Moq; -using Xunit; - -namespace HotChocolate.Execution.Processing.Internal -{ - public class SuspendedWorkQueueTests - { - [Fact] - public void Enqueue_One() - { - // arrange - var queue = new SuspendedWorkQueue(); - var task = new MockExecutionTask(); - - // act - queue.Enqueue(task); - - // assert - Assert.False(queue.IsEmpty); - Assert.True(queue.HasWork); - } - - [Fact] - public void Enqueue_And_Copy() - { - // arrange - var queue = new SuspendedWorkQueue(); - var task1 = new MockExecutionTask(); - var task2 = new MockExecutionTask(); - - // act - queue.Enqueue(task1); - queue.Enqueue(task2); - - // assert - var work = new WorkQueue(); - var plan = new QueryPlan(new MockQueryPlanStep()); - var state = new Mock(); - var stateMachine = new QueryPlanStateMachine(); - stateMachine.Initialize(state.Object, plan); - queue.CopyTo(work, work, stateMachine); - - Assert.True(work.TryTake(out IExecutionTask task)); - Assert.Same(task1, task); - Assert.True(work.TryTake(out task)); - Assert.Same(task2, task); - } - - internal class MockQueryPlanStep : ExecutionStep - { - } - - public class MockExecutionTask : IExecutionTask - { - public ExecutionTaskKind Kind { get; } - public ExecutionTaskStatus Status { get; } - public IExecutionTask Next { get; set; } - public IExecutionTask Previous { get; set; } - public object State { get; set; } - public bool IsSerial { get; set; } - public bool IsRegistered { get; set; } - - public void BeginExecute(CancellationToken cancellationToken) - { - throw new System.NotImplementedException(); - } - - public Task WaitForCompletionAsync(CancellationToken cancellationToken) - { - throw new System.NotImplementedException(); - } - } - } -} diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/WorkQueueTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/WorkQueueTests.cs index ce2de802b0a..9740e3faf32 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/WorkQueueTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/Internal/WorkQueueTests.cs @@ -4,155 +4,154 @@ #nullable enable -namespace HotChocolate.Execution.Processing.Internal +namespace HotChocolate.Execution.Processing.Internal; + +public class WorkQueueTests { - public class WorkQueueTests + [Fact] + public void Enqueue_One() { - [Fact] - public void Enqueue_One() - { - // arrange - var queue = new WorkQueue(); - var task = new MockExecutionTask(); + // arrange + var queue = new WorkQueue(); + var task = new MockExecutionTask(); - // act - var count = queue.Push(task); + // act + var count = queue.Push(task); - // assert - Assert.Equal(1, count); - Assert.False(queue.HasRunningTasks); - Assert.False(queue.IsEmpty); - } + // assert + Assert.Equal(1, count); + Assert.False(queue.HasRunningTasks); + Assert.False(queue.IsEmpty); + } - [Fact] - public void Enqueue_Two() - { - // arrange - var queue = new WorkQueue(); - var task1 = new MockExecutionTask(); - var task2 = new MockExecutionTask(); - - // act - var count1 = queue.Push(task1); - var count2 = queue.Push(task2); - - // assert - Assert.Equal(1, count1); - Assert.Equal(2, count2); - Assert.False(queue.HasRunningTasks); - Assert.False(queue.IsEmpty); - } + [Fact] + public void Enqueue_Two() + { + // arrange + var queue = new WorkQueue(); + var task1 = new MockExecutionTask(); + var task2 = new MockExecutionTask(); + + // act + var count1 = queue.Push(task1); + var count2 = queue.Push(task2); + + // assert + Assert.Equal(1, count1); + Assert.Equal(2, count2); + Assert.False(queue.HasRunningTasks); + Assert.False(queue.IsEmpty); + } - [Fact] - public void Take_One() - { - // arrange - var queue = new WorkQueue(); - var task1 = new MockExecutionTask(); - var task2 = new MockExecutionTask(); - queue.Push(task1); - queue.Push(task2); - - // act - var success = queue.TryTake(out var task); - - // assert - Assert.Same(task2, task); - Assert.True(success); - Assert.True(queue.HasRunningTasks); - Assert.False(queue.IsEmpty); - } + [Fact] + public void Take_One() + { + // arrange + var queue = new WorkQueue(); + var task1 = new MockExecutionTask(); + var task2 = new MockExecutionTask(); + queue.Push(task1); + queue.Push(task2); + + // act + var success = queue.TryTake(out var task); + + // assert + Assert.Same(task2, task); + Assert.True(success); + Assert.True(queue.HasRunningTasks); + Assert.False(queue.IsEmpty); + } - [Fact] - public void Take_All() - { - // arrange - var queue = new WorkQueue(); - var task1 = new MockExecutionTask(); - var task2 = new MockExecutionTask(); - queue.Push(task1); - queue.Push(task2); - - // act - queue.TryTake(out var task); - var success = queue.TryTake(out task); - - // assert - Assert.Same(task1, task); - Assert.True(success); - Assert.True(queue.HasRunningTasks); - Assert.True(queue.IsEmpty); - } + [Fact] + public void Take_All() + { + // arrange + var queue = new WorkQueue(); + var task1 = new MockExecutionTask(); + var task2 = new MockExecutionTask(); + queue.Push(task1); + queue.Push(task2); + + // act + queue.TryTake(out var task); + var success = queue.TryTake(out task); + + // assert + Assert.Same(task1, task); + Assert.True(success); + Assert.True(queue.HasRunningTasks); + Assert.True(queue.IsEmpty); + } - [Fact] - public void Complete_All() - { - // arrange - var queue = new WorkQueue(); - var task1 = new MockExecutionTask(); - var task2 = new MockExecutionTask(); - queue.Push(task1); - queue.Push(task2); - - // act - queue.TryTake(out var task); - queue.Complete(); - queue.TryTake(out task); - queue.Complete(); - - // assert - Assert.Same(task1, task); - Assert.False(queue.HasRunningTasks); - Assert.True(queue.IsEmpty); - } + [Fact] + public void Complete_All() + { + // arrange + var queue = new WorkQueue(); + var task1 = new MockExecutionTask(); + var task2 = new MockExecutionTask(); + queue.Push(task1); + queue.Push(task2); + + // act + queue.TryTake(out var task); + queue.Complete(); + queue.TryTake(out task); + queue.Complete(); + + // assert + Assert.Same(task1, task); + Assert.False(queue.HasRunningTasks); + Assert.True(queue.IsEmpty); + } - [Fact] - public void Clear() - { - // arrange - var queue = new WorkQueue(); - var task1 = new MockExecutionTask(); - var task2 = new MockExecutionTask(); - queue.Push(task1); - queue.Push(task2); - - // act - queue.Clear(); - - // assert - Assert.Equal(0, queue.Count); - Assert.False(queue.HasRunningTasks); - Assert.True(queue.IsEmpty); - } + [Fact] + public void Clear() + { + // arrange + var queue = new WorkQueue(); + var task1 = new MockExecutionTask(); + var task2 = new MockExecutionTask(); + queue.Push(task1); + queue.Push(task2); + + // act + queue.Clear(); + + // assert + Assert.Equal(0, queue.Count); + Assert.False(queue.HasRunningTasks); + Assert.True(queue.IsEmpty); + } - [Fact] - public void New() + [Fact] + public void New() + { + var queue = new WorkQueue(); + Assert.Equal(0, queue.Count); + Assert.False(queue.HasRunningTasks); + Assert.True(queue.IsEmpty); + } + + public class MockExecutionTask : IExecutionTask + { + public ExecutionTaskKind Kind { get; } + public ExecutionTaskStatus Status { get; } + public IExecutionTask? Next { get; set; } + public IExecutionTask? Previous { get; set; } + public object? State { get; set; } + public bool IsSerial { get; set; } + public bool IsRegistered { get; set; } + + public void BeginExecute(CancellationToken cancellationToken) { - var queue = new WorkQueue(); - Assert.Equal(0, queue.Count); - Assert.False(queue.HasRunningTasks); - Assert.True(queue.IsEmpty); + throw new System.NotImplementedException(); } - public class MockExecutionTask : IExecutionTask + public Task WaitForCompletionAsync(CancellationToken cancellationToken) { - public ExecutionTaskKind Kind { get; } - public ExecutionTaskStatus Status { get; } - public IExecutionTask? Next { get; set; } - public IExecutionTask? Previous { get; set; } - public object? State { get; set; } - public bool IsSerial { get; set; } - public bool IsRegistered { get; set; } - - public void BeginExecute(CancellationToken cancellationToken) - { - throw new System.NotImplementedException(); - } - - public Task WaitForCompletionAsync(CancellationToken cancellationToken) - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/OperationCompilerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/OperationCompilerTests.cs index 7d492dcb42a..0b48a328178 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/OperationCompilerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/OperationCompilerTests.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using ChilliCream.Testing; using HotChocolate.Language; -using HotChocolate.Resolvers; using HotChocolate.StarWars; using HotChocolate.Types; using Microsoft.Extensions.DependencyInjection; @@ -255,8 +254,6 @@ public void Field_Is_Visible_When_One_Selection_Is_Visible_1() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean){ hero(episode: EMPIRE) { @@ -296,8 +293,6 @@ public void Field_Is_Visible_When_One_Selection_Is_Visible_2() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean){ hero(episode: EMPIRE) { @@ -338,8 +333,6 @@ public void Field_Is_Visible_When_One_Selection_Is_Visible_3() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean, $q: Boolean){ hero(episode: EMPIRE) { @@ -379,8 +372,6 @@ public void Field_Is_Visible_When_One_Selection_Is_Visible_4() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean){ hero(episode: EMPIRE) { @@ -426,8 +417,6 @@ public void Object_Field_Visibility_Is_Correctly_Inherited() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean) { hero(episode: EMPIRE) @include(if: $v) { @@ -551,8 +540,6 @@ public void Object_Field_Visibility_Is_Correctly_Inherited_2() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean, $q: Boolean) { hero(episode: EMPIRE) @include(if: $v) { @@ -598,8 +585,6 @@ public void Object_Field_Visibility_Is_Correctly_Inherited_3() .AddStarWarsTypes() .Create(); - var droid = schema.GetType("Droid"); - var document = Utf8GraphQLParser.Parse( @"query foo($v: Boolean, $q: Boolean) { hero(episode: EMPIRE) @include(if: $v) { @@ -972,7 +957,7 @@ public async Task Crypto_List_Test() MatchSnapshot(document, operation); } - private static void MatchSnapshot(DocumentNode original, IPreparedOperation compiled) + private static void MatchSnapshot(DocumentNode original, IOperation compiled) { var sb = new StringBuilder(); sb.AppendLine(original.ToString()); @@ -1000,34 +985,16 @@ public class Baz public string Text => "Baz"; } - public class NoopOptimizer : ISelectionOptimizer + public class NoopOptimizer : ISelectionSetOptimizer { - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - InlineFragmentNode fragment) => true; - - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - FragmentSpreadNode fragmentSpread, - FragmentDefinitionNode fragmentDefinition) => true; - - public void OptimizeSelectionSet(SelectionOptimizerContext context) + public void OptimizeSelectionSet(SelectionSetOptimizerContext context) { } } - public class SimpleOptimizer : ISelectionOptimizer + public class SimpleOptimizer : ISelectionSetOptimizer { - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - InlineFragmentNode fragment) => true; - - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - FragmentSpreadNode fragmentSpread, - FragmentDefinitionNode fragmentDefinition) => true; - - public void OptimizeSelectionSet(SelectionOptimizerContext context) + public void OptimizeSelectionSet(SelectionSetOptimizerContext context) { /* if (!context.Path.IsEmpty && context.Path.Peek() is { Name.Value: "bar" }) diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultHelperTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultHelperTests.cs index fa0f5d52d84..e329a683416 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultHelperTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultHelperTests.cs @@ -1,33 +1,32 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Processing +namespace HotChocolate.Execution.Processing; + +public class ResultHelperTests { - public class ResultHelperTests + [Fact] + public void BuildResult_SimpleResultSet_SnapshotMatches() { - [Fact] - public void BuildResult_SimpleResultSet_SnapshotMatches() - { - // arrange - var helper = new ResultHelper(CreatePool()); - ResultMap map = helper.RentResultMap(1); - map.SetValue(0, "abc", "def", false); - helper.SetData(map); + // arrange + var helper = new ResultHelper(CreatePool()); + var map = helper.RentResultMap(1); + map.SetValue(0, "abc", "def", false); + helper.SetData(map); - // act - IQueryResult result = helper.BuildResult(); + // act + var result = helper.BuildResult(); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - private ResultPool CreatePool() - { - return new ResultPool( - new ResultMapPool(16), - new ResultMapListPool(16), - new ResultListPool(16)); - } + private ResultPool CreatePool() + { + return new ResultPool( + new ResultMapPool(16), + new ResultMapListPool(16), + new ResultListPool(16)); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultMapTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultMapTests.cs index 700d065dc55..1e674f54f91 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultMapTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/ResultMapTests.cs @@ -1,191 +1,190 @@ using System.Collections.Generic; using Xunit; -namespace HotChocolate.Execution.Processing +namespace HotChocolate.Execution.Processing; + +public class ResultMapTests { - public class ResultMapTests + [InlineData(8)] + [InlineData(4)] + [InlineData(2)] + [Theory] + public void EnsureCapacity(int size) + { + // arrange + var resultMap = new ResultMap(); + + // act + resultMap.EnsureCapacity(size); + + // assert + Assert.Equal(size, resultMap.Count); + } + + [Fact] + public void SetValue() + { + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(1); + + // act + resultMap.SetValue(0, "abc", "def"); + + // assert + Assert.Collection( + (IEnumerable)resultMap, + t => + { + Assert.Equal("abc", t.Name); + Assert.Equal("def", t.Value); + }); + } + + [InlineData(9)] + [InlineData(8)] + [InlineData(7)] + [InlineData(5)] + [InlineData(4)] + [InlineData(3)] + [Theory] + public void GetValue_ValueIsFound(int capacity) + { + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(capacity); + resultMap.SetValue(0, "abc", "def"); + resultMap.SetValue(capacity / 2, "def", "def"); + resultMap.SetValue(capacity - 1, "ghi", "def"); + + // act + var value = resultMap.GetValue("def", out var index); + + // assert + Assert.Equal("def", value.Name); + Assert.Equal(capacity / 2, index); + } + + [InlineData(9)] + [InlineData(8)] + [InlineData(7)] + [InlineData(5)] + [InlineData(4)] + [InlineData(3)] + [Theory] + public void TryGetValue_ValueIsFound(int capacity) + { + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(capacity); + resultMap.SetValue(0, "abc", "def"); + resultMap.SetValue(capacity / 2, "def", "def"); + resultMap.SetValue(capacity - 1, "ghi", "def"); + + IReadOnlyDictionary dict = resultMap; + + // act + var found = dict.TryGetValue("def", out var value); + + // assert + Assert.True(found); + Assert.Equal("def", value); + } + + [InlineData(9)] + [InlineData(8)] + [InlineData(7)] + [InlineData(5)] + [InlineData(4)] + [InlineData(3)] + [Theory] + public void ContainsKey(int capacity) + { + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(capacity); + resultMap.SetValue(0, "abc", "def"); + resultMap.SetValue(capacity / 2, "def", "def"); + resultMap.SetValue(capacity - 1, "ghi", "def"); + + IReadOnlyDictionary dict = resultMap; + + // act + var found = dict.ContainsKey("def"); + + // assert + Assert.True(found); + } + + [Fact] + public void EnumerateResultValue() + { + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(5); + + // act + resultMap.SetValue(0, "abc1", "def"); + resultMap.SetValue(2, "abc2", "def"); + resultMap.SetValue(4, "abc3", "def"); + + // assert + Assert.Collection( + (IEnumerable)resultMap, + t => + { + Assert.Equal("abc1", t.Name); + Assert.Equal("def", t.Value); + }, + t => + { + Assert.Equal("abc2", t.Name); + Assert.Equal("def", t.Value); + }, + t => + { + Assert.Equal("abc3", t.Name); + Assert.Equal("def", t.Value); + }); + } + + [Fact] + public void EnumerateKeys() + { + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(5); + + // act + resultMap.SetValue(0, "abc1", "def"); + resultMap.SetValue(2, "abc2", "def"); + resultMap.SetValue(4, "abc3", "def"); + + // assert + Assert.Collection( + ((IReadOnlyDictionary)resultMap).Keys, + t => Assert.Equal("abc1", t), + t => Assert.Equal("abc2", t), + t => Assert.Equal("abc3", t)); + } + + [Fact] + public void EnumerateValues() { - [InlineData(8)] - [InlineData(4)] - [InlineData(2)] - [Theory] - public void EnsureCapacity(int size) - { - // arrange - var resultMap = new ResultMap(); - - // act - resultMap.EnsureCapacity(size); - - // assert - Assert.Equal(size, resultMap.Count); - } - - [Fact] - public void SetValue() - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(1); - - // act - resultMap.SetValue(0, "abc", "def"); - - // assert - Assert.Collection( - (IEnumerable)resultMap, - t => - { - Assert.Equal("abc", t.Name); - Assert.Equal("def", t.Value); - }); - } - - [InlineData(9)] - [InlineData(8)] - [InlineData(7)] - [InlineData(5)] - [InlineData(4)] - [InlineData(3)] - [Theory] - public void GetValue_ValueIsFound(int capacity) - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(capacity); - resultMap.SetValue(0, "abc", "def"); - resultMap.SetValue(capacity / 2, "def", "def"); - resultMap.SetValue(capacity - 1, "ghi", "def"); - - // act - ResultValue value = resultMap.GetValue("def", out var index); - - // assert - Assert.Equal("def", value.Name); - Assert.Equal(capacity / 2, index); - } - - [InlineData(9)] - [InlineData(8)] - [InlineData(7)] - [InlineData(5)] - [InlineData(4)] - [InlineData(3)] - [Theory] - public void TryGetValue_ValueIsFound(int capacity) - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(capacity); - resultMap.SetValue(0, "abc", "def"); - resultMap.SetValue(capacity / 2, "def", "def"); - resultMap.SetValue(capacity - 1, "ghi", "def"); - - IReadOnlyDictionary dict = resultMap; - - // act - var found = dict.TryGetValue("def", out var value); - - // assert - Assert.True(found); - Assert.Equal("def", value); - } - - [InlineData(9)] - [InlineData(8)] - [InlineData(7)] - [InlineData(5)] - [InlineData(4)] - [InlineData(3)] - [Theory] - public void ContainsKey(int capacity) - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(capacity); - resultMap.SetValue(0, "abc", "def"); - resultMap.SetValue(capacity / 2, "def", "def"); - resultMap.SetValue(capacity - 1, "ghi", "def"); - - IReadOnlyDictionary dict = resultMap; - - // act - var found = dict.ContainsKey("def"); - - // assert - Assert.True(found); - } - - [Fact] - public void EnumerateResultValue() - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(5); - - // act - resultMap.SetValue(0, "abc1", "def"); - resultMap.SetValue(2, "abc2", "def"); - resultMap.SetValue(4, "abc3", "def"); - - // assert - Assert.Collection( - (IEnumerable)resultMap, - t => - { - Assert.Equal("abc1", t.Name); - Assert.Equal("def", t.Value); - }, - t => - { - Assert.Equal("abc2", t.Name); - Assert.Equal("def", t.Value); - }, - t => - { - Assert.Equal("abc3", t.Name); - Assert.Equal("def", t.Value); - }); - } - - [Fact] - public void EnumerateKeys() - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(5); - - // act - resultMap.SetValue(0, "abc1", "def"); - resultMap.SetValue(2, "abc2", "def"); - resultMap.SetValue(4, "abc3", "def"); - - // assert - Assert.Collection( - ((IReadOnlyDictionary)resultMap).Keys, - t => Assert.Equal("abc1", t), - t => Assert.Equal("abc2", t), - t => Assert.Equal("abc3", t)); - } - - [Fact] - public void EnumerateValues() - { - // arrange - var resultMap = new ResultMap(); - resultMap.EnsureCapacity(5); - - // act - resultMap.SetValue(0, "abc1", "def"); - resultMap.SetValue(2, "abc2", "def"); - resultMap.SetValue(4, "abc3", "def"); - - // assert - Assert.Collection( - ((IReadOnlyDictionary)resultMap).Values, - t => Assert.Equal("def", t), - t => Assert.Equal("def", t), - t => Assert.Equal("def", t)); - } + // arrange + var resultMap = new ResultMap(); + resultMap.EnsureCapacity(5); + + // act + resultMap.SetValue(0, "abc1", "def"); + resultMap.SetValue(2, "abc2", "def"); + resultMap.SetValue(4, "abc3", "def"); + + // assert + Assert.Collection( + ((IReadOnlyDictionary)resultMap).Values, + t => Assert.Equal("def", t), + t => Assert.Equal("def", t), + t => Assert.Equal("def", t)); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/SelectionIncludeConditionTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/SelectionIncludeConditionTests.cs index a1cd9327826..a9e95172f0f 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/SelectionIncludeConditionTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/SelectionIncludeConditionTests.cs @@ -3,273 +3,272 @@ using Moq; using Xunit; -namespace HotChocolate.Execution.Processing +namespace HotChocolate.Execution.Processing; + +public class SelectionIncludeConditionTests { - public class SelectionIncludeConditionTests + [Fact] + public void Skip_True_Is_Visible_False() + { + // arrange + var variableValues = new Mock(); + var visibility = new SelectionIncludeCondition(skip: new BooleanValueNode(true)); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.False(visible); + } + + [Fact] + public void Skip_Var_True_Is_Visible_False() + { + // arrange + var variableValues = new Mock(); + variableValues.Setup(t => t.GetVariable("b")).Returns(true); + var visibility = new SelectionIncludeCondition(skip: new VariableNode("b")); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.False(visible); + } + + [Fact] + public void Skip_False_Is_Visible_True() + { + // arrange + var variableValues = new Mock(); + var visibility = new SelectionIncludeCondition(skip: new BooleanValueNode(false)); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.True(visible); + } + + [Fact] + public void Skip_Var_False_Is_Visible_True() + { + // arrange + var variableValues = new Mock(); + variableValues.Setup(t => t.GetVariable("b")).Returns(false); + var visibility = new SelectionIncludeCondition(skip: new VariableNode("b")); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.True(visible); + } + + [Fact] + public void Include_True_Is_Visible_True() + { + // arrange + var variableValues = new Mock(); + var visibility = new SelectionIncludeCondition(include: new BooleanValueNode(true)); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.True(visible); + } + + [Fact] + public void Include_Var_True_Is_Visible_True() + { + // arrange + var variableValues = new Mock(); + variableValues.Setup(t => t.GetVariable("b")).Returns(true); + var visibility = new SelectionIncludeCondition(include: new VariableNode("b")); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.True(visible); + } + + [Fact] + public void Include_False_Is_Visible_False() + { + // arrange + var variableValues = new Mock(); + var visibility = new SelectionIncludeCondition(include: new BooleanValueNode(false)); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.False(visible); + } + + [Fact] + public void Include_Var_False_Is_Visible_False() + { + // arrange + var variableValues = new Mock(); + variableValues.Setup(t => t.GetVariable("b")).Returns(false); + var visibility = new SelectionIncludeCondition(include: new VariableNode("b")); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.False(visible); + } + + [Fact] + public void Parent_Visible_True() + { + // arrange + var variableValues = new Mock(); + + var parent = new SelectionIncludeCondition( + include: new BooleanValueNode(true)); + + var visibility = new SelectionIncludeCondition( + include: new BooleanValueNode(true), + parent: parent); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.True(visible); + } + + [Fact] + public void Parent_Visible_False() + { + // arrange + var variableValues = new Mock(); + + var parent = new SelectionIncludeCondition( + include: new BooleanValueNode(false)); + + var visibility = new SelectionIncludeCondition( + include: new BooleanValueNode(true), + parent: parent); + + // act + var visible = visibility.IsTrue(variableValues.Object); + + // assert + Assert.False(visible); + } + + [Fact] + public void Include_Is_String_GraphQLException() { - [Fact] - public void Skip_True_Is_Visible_False() - { - // arrange - var variableValues = new Mock(); - var visibility = new SelectionIncludeCondition(skip: new BooleanValueNode(true)); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.False(visible); - } - - [Fact] - public void Skip_Var_True_Is_Visible_False() - { - // arrange - var variableValues = new Mock(); - variableValues.Setup(t => t.GetVariable("b")).Returns(true); - var visibility = new SelectionIncludeCondition(skip: new VariableNode("b")); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.False(visible); - } - - [Fact] - public void Skip_False_Is_Visible_True() - { - // arrange - var variableValues = new Mock(); - var visibility = new SelectionIncludeCondition(skip: new BooleanValueNode(false)); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.True(visible); - } - - [Fact] - public void Skip_Var_False_Is_Visible_True() - { - // arrange - var variableValues = new Mock(); - variableValues.Setup(t => t.GetVariable("b")).Returns(false); - var visibility = new SelectionIncludeCondition(skip: new VariableNode("b")); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.True(visible); - } - - [Fact] - public void Include_True_Is_Visible_True() - { - // arrange - var variableValues = new Mock(); - var visibility = new SelectionIncludeCondition(include: new BooleanValueNode(true)); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.True(visible); - } - - [Fact] - public void Include_Var_True_Is_Visible_True() - { - // arrange - var variableValues = new Mock(); - variableValues.Setup(t => t.GetVariable("b")).Returns(true); - var visibility = new SelectionIncludeCondition(include: new VariableNode("b")); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.True(visible); - } - - [Fact] - public void Include_False_Is_Visible_False() - { - // arrange - var variableValues = new Mock(); - var visibility = new SelectionIncludeCondition(include: new BooleanValueNode(false)); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.False(visible); - } - - [Fact] - public void Include_Var_False_Is_Visible_False() - { - // arrange - var variableValues = new Mock(); - variableValues.Setup(t => t.GetVariable("b")).Returns(false); - var visibility = new SelectionIncludeCondition(include: new VariableNode("b")); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.False(visible); - } - - [Fact] - public void Parent_Visible_True() - { - // arrange - var variableValues = new Mock(); - - var parent = new SelectionIncludeCondition( - include: new BooleanValueNode(true)); - - var visibility = new SelectionIncludeCondition( - include: new BooleanValueNode(true), - parent: parent); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.True(visible); - } - - [Fact] - public void Parent_Visible_False() - { - // arrange - var variableValues = new Mock(); - - var parent = new SelectionIncludeCondition( - include: new BooleanValueNode(false)); - - var visibility = new SelectionIncludeCondition( - include: new BooleanValueNode(true), - parent: parent); - - // act - var visible = visibility.IsTrue(variableValues.Object); - - // assert - Assert.False(visible); - } - - [Fact] - public void Include_Is_String_GraphQLException() - { - // arrange - // act - Action action = () => new SelectionIncludeCondition( - include: new StringValueNode("abc")); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Skip_Is_String_GraphQLException() - { - // arrange - // act - Action action = () => new SelectionIncludeCondition( - skip: new StringValueNode("abc")); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Equals_Include_True_vs_True() - { - // arrange - var a = new SelectionIncludeCondition( - include: new BooleanValueNode(true)); - - var b = new SelectionIncludeCondition( - include: new BooleanValueNode(true)); - - // act - var equals = a.Equals(b); - - // assert - Assert.True(equals); - } - - [Fact] - public void Equals_Include_True_vs_False() - { - // arrange - var a = new SelectionIncludeCondition( - include: new BooleanValueNode(true)); - - var b = new SelectionIncludeCondition( - include: new BooleanValueNode(false)); - - // act - var equals = a.Equals(b); - - // assert - Assert.False(equals); - } - - [Fact] - public void Equals_Include_True_vs_Variable() - { - // arrange - var a = new SelectionIncludeCondition( - include: new BooleanValueNode(true)); - - var b = new SelectionIncludeCondition( - include: new VariableNode("b")); - - // act - var equals = a.Equals(b); - - // assert - Assert.False(equals); - } - - [Fact] - public void Equals_Include_Variable_A_vs_Variable_B() - { - // arrange - var a = new SelectionIncludeCondition( - include: new VariableNode("a")); - - var b = new SelectionIncludeCondition( - include: new VariableNode("b")); - - // act - var equals = a.Equals(b); - - // assert - Assert.False(equals); - } - - [Fact] - public void Equals_Include_Variable_A_vs_Variable_A() - { - // arrange - var a = new SelectionIncludeCondition( - include: new VariableNode("a")); - - var b = new SelectionIncludeCondition( - include: new VariableNode("a")); - - // act - var equals = a.Equals(b); - - // assert - Assert.True(equals); - } + // arrange + // act + Action action = () => new SelectionIncludeCondition( + include: new StringValueNode("abc")); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Skip_Is_String_GraphQLException() + { + // arrange + // act + Action action = () => new SelectionIncludeCondition( + skip: new StringValueNode("abc")); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Equals_Include_True_vs_True() + { + // arrange + var a = new SelectionIncludeCondition( + include: new BooleanValueNode(true)); + + var b = new SelectionIncludeCondition( + include: new BooleanValueNode(true)); + + // act + var equals = a.Equals(b); + + // assert + Assert.True(equals); + } + + [Fact] + public void Equals_Include_True_vs_False() + { + // arrange + var a = new SelectionIncludeCondition( + include: new BooleanValueNode(true)); + + var b = new SelectionIncludeCondition( + include: new BooleanValueNode(false)); + + // act + var equals = a.Equals(b); + + // assert + Assert.False(equals); + } + + [Fact] + public void Equals_Include_True_vs_Variable() + { + // arrange + var a = new SelectionIncludeCondition( + include: new BooleanValueNode(true)); + + var b = new SelectionIncludeCondition( + include: new VariableNode("b")); + + // act + var equals = a.Equals(b); + + // assert + Assert.False(equals); + } + + [Fact] + public void Equals_Include_Variable_A_vs_Variable_B() + { + // arrange + var a = new SelectionIncludeCondition( + include: new VariableNode("a")); + + var b = new SelectionIncludeCondition( + include: new VariableNode("b")); + + // act + var equals = a.Equals(b); + + // assert + Assert.False(equals); + } + + [Fact] + public void Equals_Include_Variable_A_vs_Variable_A() + { + // arrange + var a = new SelectionIncludeCondition( + include: new VariableNode("a")); + + var b = new SelectionIncludeCondition( + include: new VariableNode("a")); + + // act + var equals = a.Equals(b); + + // assert + Assert.True(equals); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/VariableCoercionHelperTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/VariableCoercionHelperTests.cs index 0be8e90cd1f..2be164cddfa 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/VariableCoercionHelperTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/VariableCoercionHelperTests.cs @@ -10,641 +10,641 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Processing +namespace HotChocolate.Execution.Processing; + +public class VariableCoercionHelperTests { - public class VariableCoercionHelperTests + [Fact] + public void VariableCoercionHelper_Schema_Is_Null() { - [Fact] - public void VariableCoercionHelper_Schema_Is_Null() + // arrange + var variableDefinitions = new List { - // arrange - var variableDefinitions = new List - { - new(null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; + new(null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; - var variableValues = new Dictionary(); - var coercedValues = new Dictionary(); + var variableValues = new Dictionary(); + var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - // act - void Action() => helper.CoerceVariableValues( - null!, variableDefinitions, variableValues, coercedValues); + // act + void Action() => helper.CoerceVariableValues( + null!, variableDefinitions, variableValues, coercedValues); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void VariableCoercionHelper_VariableDefinitions_Is_Null() - { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - var variableValues = new Dictionary(); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - void Action() - => helper.CoerceVariableValues(schema, null!, variableValues, coercedValues); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void VariableCoercionHelper_VariableValues_Is_Null() + [Fact] + public void VariableCoercionHelper_VariableDefinitions_Is_Null() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + var variableValues = new Dictionary(); + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + void Action() + => helper.CoerceVariableValues(schema, null!, variableValues, coercedValues); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void VariableCoercionHelper_VariableValues_Is_Null() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, null!, coercedValues); + + // assert + Assert.Throws(Action); + } - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, null!, coercedValues); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void VariableCoercionHelper_CoercedValues_Is_Null() + [Fact] + public void VariableCoercionHelper_CoercedValues_Is_Null() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; + var variableValues = new Dictionary(); - var variableValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, null!); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, null!); + // assert + Assert.Throws(Action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void Coerce_Nullable_String_Variable_With_Default_Where_Value_Is_Not_Provided() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Coerce_Nullable_String_Variable_With_Default_Where_Value_Is_Not_Provided() + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; - var variableDefinitions = new List + var variableValues = new Dictionary(); + var coercedValues = new Dictionary(); + + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary(); - var coercedValues = new Dictionary(); - - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("String", Assert.IsType(t.Value.Type).Name); - Assert.Equal("def", t.Value.Value); - Assert.Equal("def", Assert.IsType(t.Value.ValueLiteral).Value); - }); - } - - [Fact] - public void Coerce_Nullable_String_Variable_Where_Value_Is_Not_Provided() - { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - null, - Array.Empty()) - }; - - var variableValues = new Dictionary(); - var coercedValues = new Dictionary(); - - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Empty(coercedValues); - } - - [Fact] - public void Coerce_Nullable_String_Variable_With_Default_Where_Value_Is_Provided() + Assert.Equal("abc", t.Key); + Assert.Equal("String", Assert.IsType(t.Value.Type).Name); + Assert.Equal("def", t.Value.Value); + Assert.Equal("def", Assert.IsType(t.Value.ValueLiteral).Value); + }); + } + + [Fact] + public void Coerce_Nullable_String_Variable_Where_Value_Is_Not_Provided() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + null, + Array.Empty()) + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - {"abc", new StringValueNode("xyz")} - }; + var variableValues = new Dictionary(); + var coercedValues = new Dictionary(); - var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Empty(coercedValues); + } - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("String", Assert.IsType(t.Value.Type).Name); - Assert.Equal("xyz", t.Value.Value); - Assert.Equal("xyz", Assert.IsType(t.Value.ValueLiteral).Value); - }); - } + [Fact] + public void Coerce_Nullable_String_Variable_With_Default_Where_Value_Is_Provided() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Coerce_Nullable_String_Variable_With_Default_Where_Plain_Value_Is_Provided() + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + {"abc", new StringValueNode("xyz")} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - {"abc", "xyz"} - }; + var coercedValues = new Dictionary(); - var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Collection(coercedValues, + t => + { + Assert.Equal("abc", t.Key); + Assert.Equal("String", Assert.IsType(t.Value.Type).Name); + Assert.Equal("xyz", t.Value.Value); + Assert.Equal("xyz", Assert.IsType(t.Value.ValueLiteral).Value); + }); + } - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("String", Assert.IsType(t.Value.Type).Name); - Assert.Equal("xyz", t.Value.Value); - t.Value.ValueLiteral!.ToString().MatchSnapshot(); - }); - } + [Fact] + public void Coerce_Nullable_String_Variable_With_Default_Where_Plain_Value_Is_Provided() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Coerce_Nullable_String_Variable_With_Default_Where_Null_Is_Provided() + var variableDefinitions = new List + { + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + {"abc", "xyz"} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary + var coercedValues = new Dictionary(); + + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - {"abc", NullValueNode.Default} - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("String", Assert.IsType(t.Value.Type).Name); - Assert.Null(t.Value.Value); - Assert.IsType(t.Value.ValueLiteral); - }); - } - - [Fact] - public void Coerce_Nullable_String_Variable_With_Default_Where_Plain_Null_Is_Provided() + Assert.Equal("abc", t.Key); + Assert.Equal("String", Assert.IsType(t.Value.Type).Name); + Assert.Equal("xyz", t.Value.Value); + t.Value.ValueLiteral!.ToString().MatchSnapshot(); + }); + } + + [Fact] + public void Coerce_Nullable_String_Variable_With_Default_Where_Null_Is_Provided() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + {"abc", NullValueNode.Default} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - {"abc", null} - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("String", Assert.IsType(t.Value.Type).Name); - Assert.Null(t.Value.Value); - Assert.IsType(t.Value.ValueLiteral); - }); - } - - [Fact] - public void Coerce_Nullable_ReviewInput_Variable_With_Object_Literal() + Assert.Equal("abc", t.Key); + Assert.Equal("String", Assert.IsType(t.Value.Type).Name); + Assert.Null(t.Value.Value); + Assert.IsType(t.Value.ValueLiteral); + }); + } + + [Fact] + public void Coerce_Nullable_String_Variable_With_Default_Where_Plain_Null_Is_Provided() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List + { + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + {"abc", null} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("ReviewInput"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - {"abc", new ObjectValueNode(new ObjectFieldNode("stars", 5))} - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("ReviewInput", Assert.IsType(t.Value.Type).Name); - Assert.Equal(5, Assert.IsType(t.Value.Value).Stars); - Assert.IsType(t.Value.ValueLiteral); - }); - } - - [Fact] - public void Coerce_Nullable_ReviewInput_Variable_With_Dictionary() + Assert.Equal("abc", t.Key); + Assert.Equal("String", Assert.IsType(t.Value.Type).Name); + Assert.Null(t.Value.Value); + Assert.IsType(t.Value.ValueLiteral); + }); + } + + [Fact] + public void Coerce_Nullable_ReviewInput_Variable_With_Object_Literal() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("ReviewInput"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + {"abc", new ObjectValueNode(new ObjectFieldNode("stars", 5))} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("ReviewInput"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - {"abc", new Dictionary { {"stars", 5} }} - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("ReviewInput", Assert.IsType(t.Value.Type).Name); - Assert.Equal(5, Assert.IsType(t.Value.Value).Stars); - t.Value.ValueLiteral!.ToString().MatchSnapshot(); - }); - } - - [Fact] - public void Coerce_Nullable_ReviewInput_Variable_With_Review_Object() + Assert.Equal("abc", t.Key); + Assert.Equal("ReviewInput", Assert.IsType(t.Value.Type).Name); + Assert.Equal(5, Assert.IsType(t.Value.Value).Stars); + Assert.IsType(t.Value.ValueLiteral); + }); + } + + [Fact] + public void Coerce_Nullable_ReviewInput_Variable_With_Dictionary() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("ReviewInput"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + {"abc", new Dictionary { {"stars", 5} }} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("ReviewInput"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - { "abc", new Review { Stars = 5 } } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("ReviewInput", Assert.IsType(t.Value.Type).Name); - Assert.Equal(5, Assert.IsType(t.Value.Value).Stars); - t.Value.ValueLiteral!.ToString().MatchSnapshot(); - }); - } - - [Fact] - public void Error_When_Value_Is_Null_On_Non_Null_Variable() + Assert.Equal("abc", t.Key); + Assert.Equal("ReviewInput", Assert.IsType(t.Value.Type).Name); + Assert.Equal(5, Assert.IsType(t.Value.Value).Stars); + t.Value.ValueLiteral!.ToString().MatchSnapshot(); + }); + } + + [Fact] + public void Coerce_Nullable_ReviewInput_Variable_With_Review_Object() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("ReviewInput"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + { "abc", new Review { Stars = 5 } } + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NonNullTypeNode(new NamedTypeNode("String")), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - {"abc", NullValueNode.Default} - }; + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Collection(coercedValues, + t => + { + Assert.Equal("abc", t.Key); + Assert.Equal("ReviewInput", Assert.IsType(t.Value.Type).Name); + Assert.Equal(5, Assert.IsType(t.Value.Value).Stars); + t.Value.ValueLiteral!.ToString().MatchSnapshot(); + }); + } - // assert - Assert.Throws(Action).Errors.MatchSnapshot(); - } + [Fact] + public void Error_When_Value_Is_Null_On_Non_Null_Variable() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Error_When_PlainValue_Is_Null_On_Non_Null_Variable() + var variableDefinitions = new List + { + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NonNullTypeNode(new NamedTypeNode("String")), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + {"abc", NullValueNode.Default} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NonNullTypeNode(new NamedTypeNode("String")), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - {"abc", null} - }; + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Throws(Action).Errors.MatchSnapshot(); + } - // assert - Assert.Throws(Action).Errors.MatchSnapshot(); - } + [Fact] + public void Error_When_PlainValue_Is_Null_On_Non_Null_Variable() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Error_When_Value_Type_Does_Not_Match_Variable_Type() + var variableDefinitions = new List + { + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NonNullTypeNode(new NamedTypeNode("String")), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + {"abc", null} + }; - var variableDefinitions = new List - { - new VariableDefinitionNode( - null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - {"abc", new IntValueNode(1)} - }; + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Throws(Action).Errors.MatchSnapshot(); + } - // assert - Assert.Throws(Action) - .Errors.Select(t => t.RemoveException()) - .ToList() - .MatchSnapshot(); - } + [Fact] + public void Error_When_Value_Type_Does_Not_Match_Variable_Type() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Error_When_PlainValue_Type_Does_Not_Match_Variable_Type() + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new VariableDefinitionNode( + null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + {"abc", new IntValueNode(1)} + }; - var variableDefinitions = new List - { - new(null, - new VariableNode("abc"), - new NamedTypeNode("String"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - { "abc", 1 } - }; + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Throws(Action) + .Errors.Select(t => t.RemoveException()) + .ToList() + .MatchSnapshot(); + } - // assert - Assert.Throws(Action).Errors.MatchSnapshot(); - } + [Fact] + public void Error_When_PlainValue_Type_Does_Not_Match_Variable_Type() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Variable_Type_Is_Not_An_Input_Type() + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new(null, + new VariableNode("abc"), + new NamedTypeNode("String"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + { "abc", 1 } + }; - var variableDefinitions = new List - { - new(null, - new VariableNode("abc"), - new NamedTypeNode("Human"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - { "abc", 1 } - }; + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Throws(Action).Errors.MatchSnapshot(); + } - // assert - Assert.Throws(Action).Errors.MatchSnapshot(); - } + [Fact] + public void Variable_Type_Is_Not_An_Input_Type() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void Error_When_Input_Field_Has_Different_Properties_Than_Defined() + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + new(null, + new VariableNode("abc"), + new NamedTypeNode("Human"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + { "abc", 1 } + }; - var variableDefinitions = new List - { - new(null, - new VariableNode("abc"), - new NamedTypeNode("ReviewInput"), - new StringValueNode("def"), - Array.Empty()) - }; - - var variableValues = new Dictionary - { - { "abc", new ObjectValueNode(new ObjectFieldNode("abc", "def")) } - }; + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); - // act - void Action() => helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); + // assert + Assert.Throws(Action).Errors.MatchSnapshot(); + } - // assert - Assert.Throws(Action) - .Errors.Select(t => t.RemoveException()) - .ToList() - .MatchSnapshot(); - } + [Fact] + public void Error_When_Input_Field_Has_Different_Properties_Than_Defined() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); - [Fact] - public void StringValues_Representing_EnumValues_In_Lists_ShouldBe_Rewritten() + var variableDefinitions = new List { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + new(null, + new VariableNode("abc"), + new NamedTypeNode("ReviewInput"), + new StringValueNode("def"), + Array.Empty()) + }; + + var variableValues = new Dictionary + { + { "abc", new ObjectValueNode(new ObjectFieldNode("abc", "def")) } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + void Action() => helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Throws(Action) + .Errors.Select(t => t.RemoveException()) + .ToList() + .MatchSnapshot(); + } + + [Fact] + public void StringValues_Representing_EnumValues_In_Lists_ShouldBe_Rewritten() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { test(list: [FooInput]): String } @@ -657,55 +657,55 @@ enum TestEnum { Foo Bar }") - .Use(_ => _ => default) - .Create(); + .Use(_ => _ => default) + .Create(); - var variableDefinitions = new List + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new ListTypeNode(new NamedTypeNode("FooInput")), + null, + Array.Empty()) + }; + + var variableValues = new Dictionary + { { - new(null, - new VariableNode("abc"), - new ListTypeNode(new NamedTypeNode("FooInput")), - null, - Array.Empty()) - }; - - var variableValues = new Dictionary + "abc", + new ListValueNode( + new ObjectValueNode( + new ObjectFieldNode("enum", "Foo")), + new ObjectValueNode( + new ObjectFieldNode("enum", "Bar"))) + } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - { - "abc", - new ListValueNode( - new ObjectValueNode( - new ObjectFieldNode("enum", "Foo")), - new ObjectValueNode( - new ObjectFieldNode("enum", "Bar"))) - } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal( - "[ { enum: Foo }, { enum: Bar } ]", - t.Value.ValueLiteral!.ToString()); - }); - } - - [Fact] - public void StringValues_Representing_NonNullEnumValues_In_Lists_ShouldBe_Rewritten() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + Assert.Equal("abc", t.Key); + Assert.Equal( + "[ { enum: Foo }, { enum: Bar } ]", + t.Value.ValueLiteral!.ToString()); + }); + } + + [Fact] + public void StringValues_Representing_NonNullEnumValues_In_Lists_ShouldBe_Rewritten() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { test(list: [FooInput]): String } @@ -718,55 +718,55 @@ enum TestEnum { Foo Bar }") - .Use(_ => _ => default) - .Create(); + .Use(_ => _ => default) + .Create(); - var variableDefinitions = new List + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new ListTypeNode(new NamedTypeNode("FooInput")), + null, + Array.Empty()) + }; + + var variableValues = new Dictionary + { { - new(null, - new VariableNode("abc"), - new ListTypeNode(new NamedTypeNode("FooInput")), - null, - Array.Empty()) - }; - - var variableValues = new Dictionary + "abc", + new ListValueNode( + new ObjectValueNode( + new ObjectFieldNode("enum", "Foo")), + new ObjectValueNode( + new ObjectFieldNode("enum", "Bar"))) + } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - { - "abc", - new ListValueNode( - new ObjectValueNode( - new ObjectFieldNode("enum", "Foo")), - new ObjectValueNode( - new ObjectFieldNode("enum", "Bar"))) - } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal( - "[ { enum: Foo }, { enum: Bar } ]", - t.Value.ValueLiteral!.ToString()); - }); - } - - [Fact] - public void StringValues_Representing_EnumValues_In_Objects_ShouldBe_Rewritten() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + Assert.Equal("abc", t.Key); + Assert.Equal( + "[ { enum: Foo }, { enum: Bar } ]", + t.Value.ValueLiteral!.ToString()); + }); + } + + [Fact] + public void StringValues_Representing_EnumValues_In_Objects_ShouldBe_Rewritten() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { test(list: FooInput): String } @@ -780,51 +780,51 @@ enum TestEnum { Foo Bar }") - .Use(_ => _ => default) - .Create(); + .Use(_ => _ => default) + .Create(); - var variableDefinitions = new List + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new NamedTypeNode("FooInput"), + null, + Array.Empty()) + }; + + var variableValues = new Dictionary + { { - new(null, - new VariableNode("abc"), - new NamedTypeNode("FooInput"), - null, - Array.Empty()) - }; - - var variableValues = new Dictionary + "abc", + new ObjectValueNode( + new ObjectFieldNode("enum", "Foo"), + new ObjectFieldNode("enum2", "Bar")) + } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - { - "abc", - new ObjectValueNode( - new ObjectFieldNode("enum", "Foo"), - new ObjectFieldNode("enum2", "Bar")) - } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("{ enum: Foo, enum2: Bar }", t.Value.ValueLiteral!.ToString()); - }); - } - - [Fact] - public void StringValues_Representing_NonNullEnumValues_In_Objects_ShouldBe_Rewritten() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + Assert.Equal("abc", t.Key); + Assert.Equal("{ enum: Foo, enum2: Bar }", t.Value.ValueLiteral!.ToString()); + }); + } + + [Fact] + public void StringValues_Representing_NonNullEnumValues_In_Objects_ShouldBe_Rewritten() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { test(list: FooInput): String } @@ -838,51 +838,51 @@ enum TestEnum { Foo Bar }") - .Use(_ => _ => default) - .Create(); + .Use(_ => _ => default) + .Create(); - var variableDefinitions = new List + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new NamedTypeNode("FooInput"), + null, + Array.Empty()) + }; + + var variableValues = new Dictionary + { { - new(null, - new VariableNode("abc"), - new NamedTypeNode("FooInput"), - null, - Array.Empty()) - }; - - var variableValues = new Dictionary + "abc", + new ObjectValueNode( + new ObjectFieldNode("enum", "Foo"), + new ObjectFieldNode("enum2", "Bar")) + } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => { - { - "abc", - new ObjectValueNode( - new ObjectFieldNode("enum", "Foo"), - new ObjectFieldNode("enum2", "Bar")) - } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal("{ enum: Foo, enum2: Bar }", t.Value.ValueLiteral!.ToString()); - }); - } - - [Fact] - public void If_Second_Item_In_Object_Is_Rewritten_The_Previous_Values_Are_Correctly_Copied() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + Assert.Equal("abc", t.Key); + Assert.Equal("{ enum: Foo, enum2: Bar }", t.Value.ValueLiteral!.ToString()); + }); + } + + [Fact] + public void If_Second_Item_In_Object_Is_Rewritten_The_Previous_Values_Are_Correctly_Copied() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { test(list: FooInput): String } @@ -896,60 +896,60 @@ enum TestEnum { Foo Bar }") - .Use(_ => _ => default) - .Create(); + .Use(_ => _ => default) + .Create(); - var variableDefinitions = new List - { - new(null, - new VariableNode("abc"), - new NamedTypeNode("FooInput"), - null, - Array.Empty()) - }; + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new NamedTypeNode("FooInput"), + null, + Array.Empty()) + }; - var expectToBeUnchanged = new ObjectFieldNode("value_a", "Foo"); - var expectToBeRewritten = new ObjectFieldNode("value_b", "Bar"); + var expectToBeUnchanged = new ObjectFieldNode("value_a", "Foo"); + var expectToBeRewritten = new ObjectFieldNode("value_b", "Bar"); - var variableValues = new Dictionary - { - { - "abc", - new ObjectValueNode( - expectToBeUnchanged, - expectToBeRewritten) - } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal( - @"{ value_a: ""Foo"", value_b: Bar }", - t.Value.ValueLiteral.ToString()); - - ObjectValueNode obj = Assert.IsType(t.Value.ValueLiteral); - Assert.Same(expectToBeUnchanged, obj.Fields[0]); - Assert.NotSame(expectToBeRewritten, obj.Fields[1]); - }); - } - - [Fact] - public void If_Second_Item_In_List_Is_Rewritten_The_Previous_Values_Are_Correctly_Copied() + var variableValues = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + { + "abc", + new ObjectValueNode( + expectToBeUnchanged, + expectToBeRewritten) + } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); + + // assert + Assert.Collection(coercedValues, + t => + { + Assert.Equal("abc", t.Key); + Assert.Equal( + @"{ value_a: ""Foo"", value_b: Bar }", + t.Value.ValueLiteral.ToString()); + + var obj = Assert.IsType(t.Value.ValueLiteral); + Assert.Same(expectToBeUnchanged, obj.Fields[0]); + Assert.NotSame(expectToBeRewritten, obj.Fields[1]); + }); + } + + [Fact] + public void If_Second_Item_In_List_Is_Rewritten_The_Previous_Values_Are_Correctly_Copied() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { test(list: [FooInput]): String } @@ -963,76 +963,75 @@ enum TestEnum { Foo Bar }") - .Use(_ => _ => default) - .Create(); + .Use(_ => _ => default) + .Create(); - var variableDefinitions = new List - { - new(null, - new VariableNode("abc"), - new ListTypeNode(new NamedTypeNode("FooInput")), - null, - Array.Empty()) - }; + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new ListTypeNode(new NamedTypeNode("FooInput")), + null, + Array.Empty()) + }; - var expectToBeUnchanged = new ObjectValueNode(new ObjectFieldNode("value_a", "Foo")); - var expectToBeRewritten = new ObjectValueNode(new ObjectFieldNode("value_b", "Bar")); + var expectToBeUnchanged = new ObjectValueNode(new ObjectFieldNode("value_a", "Foo")); + var expectToBeRewritten = new ObjectValueNode(new ObjectFieldNode("value_b", "Bar")); - var variableValues = new Dictionary - { - { - "abc", - new ListValueNode(expectToBeUnchanged, expectToBeRewritten) - } - }; - - var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - - // act - helper.CoerceVariableValues( - schema, variableDefinitions, variableValues, coercedValues); - - // assert - Assert.Collection(coercedValues, - t => - { - Assert.Equal("abc", t.Key); - Assert.Equal( - @"[ { value_a: ""Foo"" }, { value_b: Bar } ]", - t.Value.ValueLiteral.ToString()); - - ListValueNode list = Assert.IsType(t.Value.ValueLiteral); - Assert.Same(expectToBeUnchanged, list.Items[0]); - Assert.NotSame(expectToBeRewritten, list.Items[1]); - }); - } - - [Fact] - public void Variable_Is_Nullable_And_Not_Set() + var variableValues = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + { + "abc", + new ListValueNode(expectToBeUnchanged, expectToBeRewritten) + } + }; + + var coercedValues = new Dictionary(); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + + // act + helper.CoerceVariableValues( + schema, variableDefinitions, variableValues, coercedValues); - var variableDefinitions = new List + // assert + Assert.Collection(coercedValues, + t => { - new(null, - new VariableNode("abc"), - new NamedTypeNode("String"), - null, - Array.Empty()) - }; + Assert.Equal("abc", t.Key); + Assert.Equal( + @"[ { value_a: ""Foo"" }, { value_b: Bar } ]", + t.Value.ValueLiteral.ToString()); + + var list = Assert.IsType(t.Value.ValueLiteral); + Assert.Same(expectToBeUnchanged, list.Items[0]); + Assert.NotSame(expectToBeRewritten, list.Items[1]); + }); + } + + [Fact] + public void Variable_Is_Nullable_And_Not_Set() + { + // arrange + var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); + + var variableDefinitions = new List + { + new(null, + new VariableNode("abc"), + new NamedTypeNode("String"), + null, + Array.Empty()) + }; - var variableValues = new Dictionary(); - var coercedValues = new Dictionary(); + var variableValues = new Dictionary(); + var coercedValues = new Dictionary(); - var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); + var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); - // act - helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); + // act + helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); - // assert - Assert.Empty(coercedValues); - } + // assert + Assert.Empty(coercedValues); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Processing/VisibilityTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Processing/VisibilityTests.cs index c270a8691fc..a4819152c0b 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Processing/VisibilityTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Processing/VisibilityTests.cs @@ -11,7 +11,7 @@ public void TryExtract_Skip_With_Literal() { // arrange var variables = new Mock(); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field @skip(if: true)"); + var field = Utf8GraphQLParser.Syntax.ParseField("field @skip(if: true)"); // act var includeCondition = IncludeCondition.FromSelection(field); @@ -24,8 +24,8 @@ public void TryExtract_Skip_With_Literal() public void Equals_Skip_With_Literal_True() { // arrange - FieldNode fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); - FieldNode fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: true)"); + var fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); + var fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: true)"); // act var includeConditionA = IncludeCondition.FromSelection(fieldA); @@ -39,8 +39,8 @@ public void Equals_Skip_With_Literal_True() public void Equals_Skip_With_Variable_True() { // arrange - FieldNode fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: $a)"); - FieldNode fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: $a)"); + var fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: $a)"); + var fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: $a)"); // act var includeConditionA = IncludeCondition.FromSelection(fieldA); @@ -54,8 +54,8 @@ public void Equals_Skip_With_Variable_True() public void Equals_Skip_With_Literal_False() { // arrange - FieldNode fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); - FieldNode fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: false)"); + var fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); + var fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: false)"); // act var includeConditionA = IncludeCondition.FromSelection(fieldA); @@ -69,8 +69,8 @@ public void Equals_Skip_With_Literal_False() public void Equals_Skip_With_Variable_False() { // arrange - FieldNode fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); - FieldNode fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: $a)"); + var fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); + var fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: $a)"); // act var includeConditionA = IncludeCondition.FromSelection(fieldA); @@ -85,7 +85,7 @@ public void TryExtract_False() { // arrange var variables = new Mock(); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field @test(test: true)"); + var field = Utf8GraphQLParser.Syntax.ParseField("field @test(test: true)"); // act var includeCondition = IncludeCondition.FromSelection(field); @@ -99,7 +99,7 @@ public void TryExtract_False_2() { // arrange var variables = new Mock(); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field"); + var field = Utf8GraphQLParser.Syntax.ParseField("field"); // act var includeCondition = IncludeCondition.FromSelection(field); @@ -113,7 +113,7 @@ public void TryExtract_True() { // arrange var variables = new Mock(); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field @skip(if: true)"); + var field = Utf8GraphQLParser.Syntax.ParseField("field @skip(if: true)"); // act var includeCondition = IncludeCondition.FromSelection(field); @@ -126,8 +126,8 @@ public void TryExtract_True() public void GetHashCode_Skip_With_Literal_Equal() { // arrange - FieldNode fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); - FieldNode fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: true)"); + var fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); + var fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: true)"); var includeConditionA = IncludeCondition.FromSelection(fieldA); var includeConditionB = IncludeCondition.FromSelection(fieldB); @@ -144,8 +144,8 @@ public void GetHashCode_Skip_With_Literal_Equal() public void GetHashCode_Skip_With_Literal_NotEqual() { // arrange - FieldNode fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); - FieldNode fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: false)"); + var fieldA = Utf8GraphQLParser.Syntax.ParseField("fieldA @skip(if: true)"); + var fieldB = Utf8GraphQLParser.Syntax.ParseField("fieldB @skip(if: false)"); var includeConditionA = IncludeCondition.FromSelection(fieldA); var includeConditionB = IncludeCondition.FromSelection(fieldB); @@ -164,7 +164,7 @@ public void IsVisible_Skip_Variables_True() // arrange var variables = new Mock(); variables.Setup(t => t.GetVariable(It.IsAny())).Returns(false); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field @skip(if: $a)"); + var field = Utf8GraphQLParser.Syntax.ParseField("field @skip(if: $a)"); var includeCondition = IncludeCondition.FromSelection(field); // act @@ -180,7 +180,7 @@ public void IsVisible_Include_Variables_True() // arrange var variables = new Mock(); variables.Setup(t => t.GetVariable(It.IsAny())).Returns(true); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field @include(if: $a)"); + var field = Utf8GraphQLParser.Syntax.ParseField("field @include(if: $a)"); var includeCondition = IncludeCondition.FromSelection(field); // act @@ -195,7 +195,7 @@ public void IsVisible_Include_Literal_True() { // arrange var variables = new Mock(); - FieldNode field = Utf8GraphQLParser.Syntax.ParseField("field @include(if: true)"); + var field = Utf8GraphQLParser.Syntax.ParseField("field @include(if: true)"); var includeCondition = IncludeCondition.FromSelection(field); // act diff --git a/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorProxyTests.cs b/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorProxyTests.cs index 384b3daaea9..441856f9804 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorProxyTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorProxyTests.cs @@ -4,64 +4,63 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class RequestExecutorProxyTests { - public class RequestExecutorProxyTests + [Fact] + public async Task Ensure_Executor_Is_Cached() { - [Fact] - public async Task Ensure_Executor_Is_Cached() - { - // arrange - IRequestExecutorResolver resolver = - new ServiceCollection() - .AddGraphQL() - .AddStarWarsRepositories() - .AddStarWarsTypes() - .Services - .BuildServiceProvider() - .GetRequiredService(); + // arrange + var resolver = + new ServiceCollection() + .AddGraphQL() + .AddStarWarsRepositories() + .AddStarWarsTypes() + .Services + .BuildServiceProvider() + .GetRequiredService(); + + // act + var proxy = new RequestExecutorProxy(resolver, Schema.DefaultName); + var a = await proxy.GetRequestExecutorAsync(CancellationToken.None); + var b = await proxy.GetRequestExecutorAsync(CancellationToken.None); - // act - var proxy = new RequestExecutorProxy(resolver, Schema.DefaultName); - IRequestExecutor a = await proxy.GetRequestExecutorAsync(CancellationToken.None); - IRequestExecutor b = await proxy.GetRequestExecutorAsync(CancellationToken.None); + // assert + Assert.Same(a, b); + } - // assert - Assert.Same(a, b); - } + [Fact] + public async Task Ensure_Executor_Is_Correctly_Swapped_When_Evicted() + { + // arrange + var resolver = + new ServiceCollection() + .AddGraphQL() + .AddStarWarsRepositories() + .AddStarWarsTypes() + .Services + .BuildServiceProvider() + .GetRequiredService(); + var evicted = false; + var updated = false; - [Fact] - public async Task Ensure_Executor_Is_Correctly_Swapped_When_Evicted() + var proxy = new RequestExecutorProxy(resolver, Schema.DefaultName); + proxy.ExecutorEvicted += (sender, args) => { - // arrange - IRequestExecutorResolver resolver = - new ServiceCollection() - .AddGraphQL() - .AddStarWarsRepositories() - .AddStarWarsTypes() - .Services - .BuildServiceProvider() - .GetRequiredService(); - var evicted = false; - var updated = false; - - var proxy = new RequestExecutorProxy(resolver, Schema.DefaultName); - proxy.ExecutorEvicted += (sender, args) => - { - evicted = true; - updated = false; - }; - proxy.ExecutorUpdated += (sender, args) => updated = true; + evicted = true; + updated = false; + }; + proxy.ExecutorUpdated += (sender, args) => updated = true; - // act - IRequestExecutor a = await proxy.GetRequestExecutorAsync(CancellationToken.None); - resolver.EvictRequestExecutor(); - IRequestExecutor b = await proxy.GetRequestExecutorAsync(CancellationToken.None); + // act + var a = await proxy.GetRequestExecutorAsync(CancellationToken.None); + resolver.EvictRequestExecutor(); + var b = await proxy.GetRequestExecutorAsync(CancellationToken.None); - // assert - Assert.NotSame(a, b); - Assert.True(evicted); - Assert.True(updated); - } + // assert + Assert.NotSame(a, b); + Assert.True(evicted); + Assert.True(updated); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorTests.cs b/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorTests.cs index bec3d18227e..e119a2759ab 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/RequestExecutorTests.cs @@ -8,110 +8,110 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class RequestExecutorTests { - public class RequestExecutorTests + [Fact] + public async Task Request_Is_Null_ArgumentNullException() { - [Fact] - public async Task Request_Is_Null_ArgumentNullException() - { - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")) - .Create(); + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - // act - Task Action() => executor.ExecuteAsync(null!, default); + // act + Task Action() => executor.ExecuteAsync(null!, default); - // assert - ArgumentException exception = await Assert.ThrowsAsync(Action); - Assert.Equal("request", exception.ParamName); - } - - [Fact] - public void Schema_Property_IsCorrectly_Set() - { - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")) - .Create(); - - // act - IRequestExecutor executor = schema.MakeExecutable(); - - // assert - Assert.Equal(schema, executor.Schema); - } - - [Fact] - public async Task CancellationToken_Is_Passed_Correctly() - { - // arrange - var tokenWasCorrectlyPassedToResolver = false; + // assert + ArgumentException exception = await Assert.ThrowsAsync(Action); + Assert.Equal("request", exception.ParamName); + } - var cts = new CancellationTokenSource(); - void Cancel() => cts.Cancel(); + [Fact] + public void Schema_Property_IsCorrectly_Set() + { + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // act + var executor = schema.MakeExecutable(); + + // assert + Assert.Equal(schema, executor.Schema); + } - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("foo") - .Resolve(ctx => + [Fact] + public async Task CancellationToken_Is_Passed_Correctly() + { + // arrange + var tokenWasCorrectlyPassedToResolver = false; + + var cts = new CancellationTokenSource(); + void Cancel() => cts.Cancel(); + + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("foo") + .Resolve(ctx => + { + // we cancel the cts in the resolver so we are sure + // that we reach this point and the passed in ct was correctly + // passed. + Cancel(); + + try { - // we cancel the cts in the resolver so we are sure - // that we reach this point and the passed in ct was correctly - // passed. - Cancel(); - - try - { - ctx.RequestAborted.ThrowIfCancellationRequested(); - return "bar"; - } - catch (OperationCanceledException) - { - tokenWasCorrectlyPassedToResolver = true; - throw new QueryException("CancellationRaised"); - } - })) - .Create(); + ctx.RequestAborted.ThrowIfCancellationRequested(); + return "bar"; + } + catch (OperationCanceledException) + { + tokenWasCorrectlyPassedToResolver = true; + throw new QueryException("CancellationRaised"); + } + })) + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - IReadOnlyQueryRequest request = QueryRequestBuilder.New() - .SetQuery("{ foo }") - .Create(); + var request = QueryRequestBuilder.New() + .SetQuery("{ foo }") + .Create(); - // act - IExecutionResult result = await executor.ExecuteAsync(request, cts.Token); + // act + var result = await executor.ExecuteAsync(request, cts.Token); - // assert - // match snapshot ... in case of a cancellation the whole result is canceled - // and we return there error result without any data. - result.MatchSnapshot(); + // assert + // match snapshot ... in case of a cancellation the whole result is canceled + // and we return there error result without any data. + result.MatchSnapshot(); - // the cancellation token was correctly passed to the resolver. - Assert.True(tokenWasCorrectlyPassedToResolver); - } + // the cancellation token was correctly passed to the resolver. + Assert.True(tokenWasCorrectlyPassedToResolver); + } - [Fact] - public async Task Ensure_Errors_Do_Not_Result_In_Timeouts() - { - Snapshot.FullName(); + [Fact] + public async Task Ensure_Errors_Do_Not_Result_In_Timeouts() + { + Snapshot.FullName(); - using var cts = new CancellationTokenSource(1000); + using var cts = new CancellationTokenSource(1000); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Name("abc").Field("a").Resolve("a")) - .AddMutationType() - .ExecuteRequestAsync(@" + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Name("abc").Field("a").Resolve("a")) + .AddMutationType() + .ExecuteRequestAsync(@" mutation { test @@ -124,27 +124,26 @@ public async Task Ensure_Errors_Do_Not_Result_In_Timeouts() __typename } }", - cancellationToken: cts.Token) - .MatchSnapshotAsync(); - } + cancellationToken: cts.Token) + .MatchSnapshotAsync(); + } - public class Mutation + public class Mutation + { + public TestMutationPayload Test() { - public TestMutationPayload Test() - { - throw new Exception("Error"); - } + throw new Exception("Error"); } + } - public class TestMutationPayload - { - public Test Test { get; set; } - } + public class TestMutationPayload + { + public Test Test { get; set; } + } - public class Test - { - public string Foo { get; set; } = "Foo"; - public string Bar { get; set; } = "Bar"; - } + public class Test + { + public string Foo { get; set; } = "Foo"; + public string Bar { get; set; } = "Bar"; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/ScalarExecutionErrorTests.cs b/src/HotChocolate/Core/test/Execution.Tests/ScalarExecutionErrorTests.cs index 5f6b19a4851..e470c5f42d6 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/ScalarExecutionErrorTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/ScalarExecutionErrorTests.cs @@ -8,230 +8,229 @@ #nullable enable -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class ScalarExecutionErrorTests { - public class ScalarExecutionErrorTests + [Fact] + public async Task OutputType_ClrValue_CannotBeConverted() { - [Fact] - public async Task OutputType_ClrValue_CannotBeConverted() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ stringToName(name: \" \") }"); + // act + var result = await executor.ExecuteAsync( + "{ stringToName(name: \" \") }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); + } - [Fact] - public async Task OutputType_ClrValue_CannotBeParsed() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public async Task OutputType_ClrValue_CannotBeParsed() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ stringToFoo(name: \" \") }"); + // act + var result = await executor.ExecuteAsync( + "{ stringToFoo(name: \" \") }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); + } - [Fact] - public async Task InputType_Literal_CannotBeParsed() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public async Task InputType_Literal_CannotBeParsed() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ nameToString(name: \" \") }"); + // act + var result = await executor.ExecuteAsync( + "{ nameToString(name: \" \") }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); + } - [Fact] - public async Task InputType_Variable_CannotBeDeserialized() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "query a($a: Foo) { fooToString(name: $a) }", - new Dictionary - { - {"a", " "} - }); - - // assert - result.MatchSnapshot(); - } + [Fact] + public async Task InputType_Variable_CannotBeDeserialized() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - public class Query + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "query a($a: Foo) { fooToString(name: $a) }", + new Dictionary + { + {"a", " "} + }); + + // assert + result.MatchSnapshot(); + } + + public class Query + { + public string StringToName(string name) => name; + + public string NameToString(string name) => name; + + public string StringToFoo(string name) => name; + + public string FooToString(string name) => name; + } + + public class QueryType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public string StringToName(string name) => name; + descriptor.Field(t => t.StringToName(default!)) + .Argument("name", a => a.Type()) + .Type(); - public string NameToString(string name) => name; + descriptor.Field(t => t.NameToString(default!)) + .Argument("name", a => a.Type()) + .Type(); - public string StringToFoo(string name) => name; + descriptor.Field(t => t.StringToFoo(default!)) + .Argument("name", a => a.Type()) + .Type(); - public string FooToString(string name) => name; + descriptor.Field(t => t.FooToString(default!)) + .Argument("name", a => a.Type()) + .Type(); } + } - public class QueryType : ObjectType + public class FooType : ScalarType + { + public FooType() : base("Foo") { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.StringToName(default!)) - .Argument("name", a => a.Type()) - .Type(); + } - descriptor.Field(t => t.NameToString(default!)) - .Argument("name", a => a.Type()) - .Type(); + public override Type RuntimeType => typeof(string); - descriptor.Field(t => t.StringToFoo(default!)) - .Argument("name", a => a.Type()) - .Type(); + public override bool IsInstanceOfType(IValueNode literal) + { + if (literal is null) + { + throw new ArgumentNullException(nameof(literal)); + } - descriptor.Field(t => t.FooToString(default!)) - .Argument("name", a => a.Type()) - .Type(); + if (literal is NullValueNode) + { + return true; } + + return literal is StringValueNode { Value: "a" }; } - public class FooType : ScalarType + public override bool IsInstanceOfType(object? value) { - public FooType() : base("Foo") + if (value is null) { + return true; } - public override Type RuntimeType => typeof(string); + return value is "a"; + } - public override bool IsInstanceOfType(IValueNode literal) + public override object? ParseLiteral(IValueNode literal) + { + if (literal is null) { - if (literal is null) - { - throw new ArgumentNullException(nameof(literal)); - } - - if (literal is NullValueNode) - { - return true; - } - - return literal is StringValueNode { Value: "a" }; + throw new ArgumentNullException(nameof(literal)); } - public override bool IsInstanceOfType(object? value) + if (literal is NullValueNode) { - if (value is null) - { - return true; - } - - return value is "a"; + return null; } - public override object? ParseLiteral(IValueNode literal) + if (literal is StringValueNode { Value: "a" }) { - if (literal is null) - { - throw new ArgumentNullException(nameof(literal)); - } - - if (literal is NullValueNode) - { - return null; - } - - if (literal is StringValueNode { Value: "a" }) - { - return "a"; - } - - throw new SerializationException("StringValue is not a.", this); + return "a"; } - public override IValueNode ParseValue(object? value) - { - if (value is null) - { - return NullValueNode.Default; - } + throw new SerializationException("StringValue is not a.", this); + } - if (value is "a") - { - return new StringValueNode("a"); - } + public override IValueNode ParseValue(object? value) + { + if (value is null) + { + return NullValueNode.Default; + } - throw new SerializationException("String is not a.", this); + if (value is "a") + { + return new StringValueNode("a"); } - public override IValueNode ParseResult(object? resultValue) - => ParseValue(resultValue); + throw new SerializationException("String is not a.", this); + } - public override bool TrySerialize( - object? runtimeValue, - out object? resultValue) - { - if (runtimeValue is null) - { - resultValue = null; - return true; - } - - if (runtimeValue is string and "a") - { - resultValue = new StringValueNode("a"); - return true; - } + public override IValueNode ParseResult(object? resultValue) + => ParseValue(resultValue); + public override bool TrySerialize( + object? runtimeValue, + out object? resultValue) + { + if (runtimeValue is null) + { resultValue = null; - return false; + return true; } - public override bool TryDeserialize( - object? resultValue, - out object?runtimeValue) + if (runtimeValue is string and "a") { - if (resultValue is null) - { - runtimeValue = null; - return true; - } - - if (resultValue is "a") - { - runtimeValue = "a"; - return true; - } + resultValue = new StringValueNode("a"); + return true; + } + resultValue = null; + return false; + } + + public override bool TryDeserialize( + object? resultValue, + out object?runtimeValue) + { + if (resultValue is null) + { runtimeValue = null; - return false; + return true; } + + if (resultValue is "a") + { + runtimeValue = "a"; + return true; + } + + runtimeValue = null; + return false; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/SchemaDirectiveTests.cs b/src/HotChocolate/Core/test/Execution.Tests/SchemaDirectiveTests.cs index e2a3bca7f20..ee4a625db98 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/SchemaDirectiveTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/SchemaDirectiveTests.cs @@ -2,246 +2,245 @@ using HotChocolate.Tests; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class SchemaDirectiveTests { - public class SchemaDirectiveTests + [Fact] + public void DirectivesOnObjectType() { - [Fact] - public void DirectivesOnObjectType() - { - // arrange - ISchema schema = CreateSchema(); + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - schema.MakeExecutable().Execute("{ person { phone } }"); + // act + var result = + schema.MakeExecutable().Execute("{ person { phone } }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); + } - [Fact] - public void DirectivesOnFieldDefinition() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public void DirectivesOnFieldDefinition() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - schema.MakeExecutable().Execute("{ person { name } }"); + // act + var result = + schema.MakeExecutable().Execute("{ person { name } }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); + } - [Fact] - public void DirectivesOnFieldSelection() - { - // arrange - ISchema schema = CreateSchema(); + [Fact] + public void DirectivesOnFieldSelection() + { + // arrange + var schema = CreateSchema(); - // act - IExecutionResult result = - schema.MakeExecutable().Execute( - "{ person { name @c(append:\"Baz\") } }"); + // act + var result = + schema.MakeExecutable().Execute( + "{ person { name @c(append:\"Baz\") } }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); + } - [Fact] - public void ExecDirectiveOrderIsSignificant() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String }") - .AddDirectiveType() - .AddDirectiveType() - .AddResolver("Query", "a", () => "hello") - .Create(); - - // act - IExecutionResult result = - schema.MakeExecutable().Execute( - "{ a @lower @upper b: a @upper @lower }"); - - // assert - result.MatchSnapshot(); - } + [Fact] + public void ExecDirectiveOrderIsSignificant() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String }") + .AddDirectiveType() + .AddDirectiveType() + .AddResolver("Query", "a", () => "hello") + .Create(); + + // act + var result = + schema.MakeExecutable().Execute( + "{ a @lower @upper b: a @upper @lower }"); + + // assert + result.MatchSnapshot(); + } - public static ISchema CreateSchema() - => SchemaBuilder.New() - .AddDirectiveType() - .AddDirectiveType() - .AddDirectiveType() - .AddDirectiveType() - .AddDirectiveType() - .AddType() - .AddType() - .Create(); - - public class Query - { - public Person GetPerson() => new Person(); - } + public static ISchema CreateSchema() + => SchemaBuilder.New() + .AddDirectiveType() + .AddDirectiveType() + .AddDirectiveType() + .AddDirectiveType() + .AddDirectiveType() + .AddType() + .AddType() + .Create(); + + public class Query + { + public Person GetPerson() => new Person(); + } - public class Person - { - public string Name { get; set; } = "Name"; - public string Phone { get; set; } = "Phone"; - public string ZipCode { get; set; } = "ZipCode"; - public string Country { get; set; } = "Country"; - } + public class Person + { + public string Name { get; set; } = "Name"; + public string Phone { get; set; } = "Phone"; + public string ZipCode { get; set; } = "ZipCode"; + public string Country { get; set; } = "Country"; + } - public class PersonType : ObjectType + public class PersonType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Directive(new Resolve()); - descriptor.Directive(new ADirective { Append = "Foo" }); - descriptor.Field(t => t.Name) - .Directive(new BDirective { Append = "Bar" }); - } + descriptor.Directive(new Resolve()); + descriptor.Directive(new ADirective { Append = "Foo" }); + descriptor.Field(t => t.Name) + .Directive(new BDirective { Append = "Bar" }); } + } - public class ADirectiveType : DirectiveType + public class ADirectiveType : DirectiveType + { + protected override void Configure(IDirectiveTypeDescriptor descriptor) { - protected override void Configure(IDirectiveTypeDescriptor descriptor) + descriptor.Name("a"); + descriptor.Location(DirectiveLocation.Object); + descriptor.Location(DirectiveLocation.Interface); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Use(next => context => { - descriptor.Name("a"); - descriptor.Location(DirectiveLocation.Object); - descriptor.Location(DirectiveLocation.Interface); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Use(next => context => - { - var s = context.Directive.ToObject().Append; - context.Result = context.Result + s; - return next.Invoke(context); - }); - } + var s = context.Directive.ToObject().Append; + context.Result = context.Result + s; + return next.Invoke(context); + }); } + } - public class BDirectiveType - : DirectiveType - { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) + public class BDirectiveType + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) + { + descriptor.Name("b"); + descriptor.Location(DirectiveLocation.Object); + descriptor.Location(DirectiveLocation.Interface); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Use(next => context => { - descriptor.Name("b"); - descriptor.Location(DirectiveLocation.Object); - descriptor.Location(DirectiveLocation.Interface); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Use(next => context => - { - var s = context.Directive.ToObject().Append; - context.Result = context.Result + s; - return next.Invoke(context); - }); - } + var s = context.Directive.ToObject().Append; + context.Result = context.Result + s; + return next.Invoke(context); + }); } + } - public class CDirectiveType - : DirectiveType + public class CDirectiveType + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) + descriptor.Name("c"); + descriptor.Location(DirectiveLocation.Field); + descriptor.Use(_ => context => { - descriptor.Name("c"); - descriptor.Location(DirectiveLocation.Field); - descriptor.Use(_ => context => - { - var s = context.Directive.ToObject().Append; - context.Result += s; - return default; - }); - } + var s = context.Directive.ToObject().Append; + context.Result += s; + return default; + }); } + } - public class UpperCaseDirectiveType : DirectiveType + public class UpperCaseDirectiveType : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) + descriptor.Name("upper"); + descriptor.Location(DirectiveLocation.Field | DirectiveLocation.FieldDefinition); + descriptor.Use(next => async context => { - descriptor.Name("upper"); - descriptor.Location(DirectiveLocation.Field | DirectiveLocation.FieldDefinition); - descriptor.Use(next => async context => + await next(context); + + if (context.Directive.Name != "upper") + { + throw new QueryException("Not the upper directive."); + } + + if (context.Result is string s) { - await next(context); - - if (context.Directive.Name != "upper") - { - throw new QueryException("Not the upper directive."); - } - - if (context.Result is string s) - { - context.Result = s.ToUpperInvariant(); - } - }); - } + context.Result = s.ToUpperInvariant(); + } + }); } + } - public class LowerCaseDirectiveType : DirectiveType + public class LowerCaseDirectiveType : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) + descriptor.Name("lower"); + descriptor.Location(DirectiveLocation.Field + | DirectiveLocation.FieldDefinition); + descriptor.Use(next => async context => { - descriptor.Name("lower"); - descriptor.Location(DirectiveLocation.Field - | DirectiveLocation.FieldDefinition); - descriptor.Use(next => async context => + await next(context); + + if (context.Directive.Name != "lower") { - await next(context); - - if (context.Directive.Name != "lower") - { - throw new QueryException("Not the lower directive."); - } - - if (context.Result is string s) - { - context.Result = s.ToLowerInvariant(); - } - }); - } - } + throw new QueryException("Not the lower directive."); + } - public class ADirective - { - public string Append { get; set; } + if (context.Result is string s) + { + context.Result = s.ToLowerInvariant(); + } + }); } + } - public class BDirective : ADirective - { - } + public class ADirective + { + public string Append { get; set; } + } - public class CDirective : ADirective - { - } + public class BDirective : ADirective + { + } + + public class CDirective : ADirective + { + } - public sealed class ResolveDirective : DirectiveType + public sealed class ResolveDirective : DirectiveType + { + protected override void Configure(IDirectiveTypeDescriptor descriptor) { - protected override void Configure(IDirectiveTypeDescriptor descriptor) + descriptor.Name("resolve"); + descriptor.Use(next => async context => { - descriptor.Name("resolve"); - descriptor.Use(next => async context => - { - context.Result = await context.ResolveAsync() - .ConfigureAwait(false); - - await next.Invoke(context).ConfigureAwait(false); - }); - - descriptor.Location(DirectiveLocation.Schema) - .Location(DirectiveLocation.Object) - .Location(DirectiveLocation.Interface) - .Location(DirectiveLocation.FieldDefinition) - .Location(DirectiveLocation.Field); - } - } + context.Result = await context.ResolveAsync() + .ConfigureAwait(false); + + await next.Invoke(context).ConfigureAwait(false); + }); - public sealed class Resolve { } + descriptor.Location(DirectiveLocation.Schema) + .Location(DirectiveLocation.Object) + .Location(DirectiveLocation.Interface) + .Location(DirectiveLocation.FieldDefinition) + .Location(DirectiveLocation.Field); + } } -} + + public sealed class Resolve { } +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/SchemaFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/SchemaFirstTests.cs index 143d72f0b2a..41b89d028f1 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/SchemaFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/SchemaFirstTests.cs @@ -4,40 +4,40 @@ using HotChocolate.Types; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class SchemaFirstTests { - public class SchemaFirstTests + [Fact] + public async Task BindObjectTypeImplicit() { - [Fact] - public async Task BindObjectTypeImplicit() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { test: String testProp: String }") - .AddResolver() - .Create(); + .AddResolver() + .Create(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ test testProp }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ test testProp }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task BindInputTypeImplicit() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"schema { + [Fact] + public async Task BindInputTypeImplicit() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"schema { query: FooQuery } @@ -49,27 +49,27 @@ input Bar { baz: String }") - .AddResolver() - .AddResolver() - .Create(); - - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ foo(bar: { baz: \"hello\"}) }"); - - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + .AddResolver() + .AddResolver() + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ foo(bar: { baz: \"hello\"}) }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task EnumAsOutputType() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + [Fact] + public async Task EnumAsOutputType() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { enumValue: FooEnum } @@ -77,26 +77,26 @@ enum FooEnum { BAR BAZ }") - .AddResolver("Query") - .Create(); + .AddResolver("Query") + .Create(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ enumValue }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ enumValue }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task EnumAsInputType() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + [Fact] + public async Task EnumAsInputType() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { setEnumValue(value:FooEnum) : String } @@ -104,26 +104,26 @@ enum FooEnum { BAR BAZ_BAR }") - .AddResolver("Query") - .Create(); + .AddResolver("Query") + .Create(); - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ setEnumValue(value:BAZ_BAR) }"); + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ setEnumValue(value:BAZ_BAR) }"); - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - [Fact] - public async Task InputObjectWithEnum() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + [Fact] + public async Task InputObjectWithEnum() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { enumInInputObject(payload:Payload) : String } @@ -135,71 +135,70 @@ enum FooEnum { BAR BAZ }") - .AddResolver("Query") - .AddResolver() - .Create(); - - // act - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync( - "{ enumInInputObject(payload: { value:BAZ } ) }"); - - // assert - Assert.Null(Assert.IsType(result).Errors); - result.MatchSnapshot(); - } + .AddResolver("Query") + .AddResolver() + .Create(); + + // act + var result = + await schema.MakeExecutable().ExecuteAsync( + "{ enumInInputObject(payload: { value:BAZ } ) }"); + + // assert + Assert.Null(Assert.IsType(result).Errors); + result.MatchSnapshot(); + } - public class Query + public class Query + { + public string GetTest() { - public string GetTest() - { - return "Hello World 1!"; - } - - public string TestProp => "Hello World 2!"; + return "Hello World 1!"; } - public class FooQuery - { - public string GetFoo(Bar bar) - { - return bar.Baz; - } - } + public string TestProp => "Hello World 2!"; + } - public class Bar + public class FooQuery + { + public string GetFoo(Bar bar) { - public string Baz { get; set; } + return bar.Baz; } + } + + public class Bar + { + public string Baz { get; set; } + } - public class EnumQuery + public class EnumQuery + { + public FooEnum GetEnumValue() { - public FooEnum GetEnumValue() - { - return FooEnum.Bar; - } - - public string SetEnumValue(FooEnum value) - { - return value.ToString(); - } - - public string EnumInInputObject(Payload payload) - { - return payload.Value.ToString(); - } + return FooEnum.Bar; } - public class Payload + public string SetEnumValue(FooEnum value) { - public FooEnum Value { get; set; } + return value.ToString(); } - public enum FooEnum + public string EnumInInputObject(Payload payload) { - Bar, - Baz, - BazBar + return payload.Value.ToString(); } } -} + + public class Payload + { + public FooEnum Value { get; set; } + } + + public enum FooEnum + { + Bar, + Baz, + BazBar + } +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/ScopedContextDataTests.cs b/src/HotChocolate/Core/test/Execution.Tests/ScopedContextDataTests.cs index df946b14cf1..2a1614093f4 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/ScopedContextDataTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/ScopedContextDataTests.cs @@ -2,17 +2,17 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class ScopedContextDataTests { - public class ScopedContextDataTests + [Fact] + public async Task ScopedContextDataIsPassedAlongCorrectly() { - [Fact] - public async Task ScopedContextDataIsPassedAlongCorrectly() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { root: Level1 } @@ -25,35 +25,34 @@ type Level2 { foo: String }") - .Use(_ => context => + .Use(_ => context => + { + if (context.ScopedContextData.TryGetValue("field", out var o) && + o is string s) { - if (context.ScopedContextData.TryGetValue("field", out var o) && - o is string s) - { - s += "/" + context.Selection.Field.Name; - } - else - { - s = "./" + context.Selection.Field.Name; - } + s += "/" + context.Selection.Field.Name; + } + else + { + s = "./" + context.Selection.Field.Name; + } - context.ScopedContextData = context.ScopedContextData - .SetItem("field", s); + context.ScopedContextData = context.ScopedContextData + .SetItem("field", s); - context.Result = s; + context.Result = s; - return default; - }) - .Create(); + return default; + }) + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ root { a { foo } b { foo } } }"); + // act + var result = await executor.ExecuteAsync( + "{ root { a { foo } b { foo } } }"); - // assert - result.MatchSnapshot(); - } + // assert + result.MatchSnapshot(); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Serialization/JsonArrayResponseStreamSerializerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Serialization/JsonArrayResponseStreamSerializerTests.cs index 8ee67840db2..76ad3ff01ea 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Serialization/JsonArrayResponseStreamSerializerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Serialization/JsonArrayResponseStreamSerializerTests.cs @@ -8,21 +8,21 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Serialization +namespace HotChocolate.Execution.Serialization; + +public class JsonArrayResponseStreamSerializerTests { - public class JsonArrayResponseStreamSerializerTests + [Fact] + public async Task Serialize_Response_Stream() { - [Fact] - public async Task Serialize_Response_Stream() - { - // arrange - IExecutionResult result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + // arrange + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { @@ -38,47 +38,46 @@ ... @defer { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var memoryStream = new MemoryStream(); - var serializer = new JsonArrayResponseStreamFormatter(); + var memoryStream = new MemoryStream(); + var serializer = new JsonArrayResponseStreamFormatter(); - // act - await serializer.FormatAsync(stream, memoryStream, CancellationToken.None); + // act + await serializer.FormatAsync(stream, memoryStream, CancellationToken.None); - // assert - memoryStream.Seek(0, SeekOrigin.Begin); - new StreamReader(memoryStream).ReadToEnd().MatchSnapshot(); - } + // assert + memoryStream.Seek(0, SeekOrigin.Begin); + new StreamReader(memoryStream).ReadToEnd().MatchSnapshot(); + } - [Fact] - public async Task Serialize_ResponseStream_Is_Null() - { - // arrange - var serializer = new JsonArrayResponseStreamFormatter(); - var stream = new Mock(); + [Fact] + public async Task Serialize_ResponseStream_Is_Null() + { + // arrange + var serializer = new JsonArrayResponseStreamFormatter(); + var stream = new Mock(); - // act - Task Action() => - serializer.FormatAsync(null!, stream.Object, CancellationToken.None); + // act + Task Action() => + serializer.FormatAsync(null!, stream.Object, CancellationToken.None); - // assert - await Assert.ThrowsAsync(Action); - } + // assert + await Assert.ThrowsAsync(Action); + } - [Fact] - public async Task Serialize_OutputStream_Is_Null() - { - // arrange - var serializer = new JsonArrayResponseStreamFormatter(); - var stream = new Mock(); + [Fact] + public async Task Serialize_OutputStream_Is_Null() + { + // arrange + var serializer = new JsonArrayResponseStreamFormatter(); + var stream = new Mock(); - // act - Task Action() => - serializer.FormatAsync(stream.Object, null!, CancellationToken.None); + // act + Task Action() => + serializer.FormatAsync(stream.Object, null!, CancellationToken.None); - // assert - await Assert.ThrowsAsync(Action); - } + // assert + await Assert.ThrowsAsync(Action); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/Serialization/MultiPartResponseStreamSerializerTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Serialization/MultiPartResponseStreamSerializerTests.cs index cf51ab005b9..f26c2daa351 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Serialization/MultiPartResponseStreamSerializerTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Serialization/MultiPartResponseStreamSerializerTests.cs @@ -8,21 +8,21 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution.Serialization +namespace HotChocolate.Execution.Serialization; + +public class MultiPartResponseStreamSerializerTests { - public class MultiPartResponseStreamSerializerTests + [Fact] + public async Task Serialize_Response_Stream() { - [Fact] - public async Task Serialize_Response_Stream() - { - // arrange - IExecutionResult result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + // arrange + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { @@ -38,47 +38,46 @@ ... @defer { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var memoryStream = new MemoryStream(); - var serializer = new MultiPartResponseStreamFormatter(); + var memoryStream = new MemoryStream(); + var serializer = new MultiPartResponseStreamFormatter(); - // act - await serializer.FormatAsync(stream, memoryStream, CancellationToken.None); + // act + await serializer.FormatAsync(stream, memoryStream, CancellationToken.None); - // assert - memoryStream.Seek(0, SeekOrigin.Begin); - new StreamReader(memoryStream).ReadToEnd().MatchSnapshot(); - } + // assert + memoryStream.Seek(0, SeekOrigin.Begin); + new StreamReader(memoryStream).ReadToEnd().MatchSnapshot(); + } - [Fact] - public async Task Serialize_ResponseStream_Is_Null() - { - // arrange - var serializer = new MultiPartResponseStreamFormatter(); - var stream = new Mock(); + [Fact] + public async Task Serialize_ResponseStream_Is_Null() + { + // arrange + var serializer = new MultiPartResponseStreamFormatter(); + var stream = new Mock(); - // act - Task Action() => - serializer.FormatAsync(null!, stream.Object, CancellationToken.None); + // act + Task Action() => + serializer.FormatAsync(null!, stream.Object, CancellationToken.None); - // assert - await Assert.ThrowsAsync(Action); - } + // assert + await Assert.ThrowsAsync(Action); + } - [Fact] - public async Task Serialize_OutputStream_Is_Null() - { - // arrange - var serializer = new MultiPartResponseStreamFormatter(); - var stream = new Mock(); + [Fact] + public async Task Serialize_OutputStream_Is_Null() + { + // arrange + var serializer = new MultiPartResponseStreamFormatter(); + var stream = new Mock(); - // act - Task Action() => - serializer.FormatAsync(stream.Object, null!, CancellationToken.None); + // act + Task Action() => + serializer.FormatAsync(stream.Object, null!, CancellationToken.None); - // assert - await Assert.ThrowsAsync(Action); - } + // assert + await Assert.ThrowsAsync(Action); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/SourceObjectConversionTests.cs b/src/HotChocolate/Core/test/Execution.Tests/SourceObjectConversionTests.cs index cea6e86d607..ac890930407 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/SourceObjectConversionTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/SourceObjectConversionTests.cs @@ -4,91 +4,90 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class SourceObjectConversionTests { - public class SourceObjectConversionTests + [Fact] + public async Task ConvertSourceObject() { - [Fact] - public async Task ConvertSourceObject() - { - // arrange - var conversionTriggered = false; + // arrange + var conversionTriggered = false; - IRequestExecutor executor = new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeConverter(input => - { - conversionTriggered = true; - return new Baz { Qux = input.Bar }; - }) - .Services - .BuildServiceProvider() - .GetRequiredService() - .GetRequestExecutorAsync() - .Result; + var executor = new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeConverter(input => + { + conversionTriggered = true; + return new Baz { Qux = input.Bar }; + }) + .Services + .BuildServiceProvider() + .GetRequiredService() + .GetRequestExecutorAsync() + .Result; - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo { qux } }"); + // act + var result = await executor.ExecuteAsync("{ foo { qux } }"); - // assert - Assert.True( - Assert.IsType(result).Errors is null, - "There should be no errors."); - Assert.True( - conversionTriggered, - "The custom converter should have been hit."); - result.MatchSnapshot(); - } + // assert + Assert.True( + Assert.IsType(result).Errors is null, + "There should be no errors."); + Assert.True( + conversionTriggered, + "The custom converter should have been hit."); + result.MatchSnapshot(); + } - [Fact] - public async Task NoConverter_Specified() - { - // arrange - ISchema schema = - SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public async Task NoConverter_Specified() + { + // arrange + var schema = + SchemaBuilder.New() + .AddQueryType() + .Create(); - // act - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery("{ foo { qux } }") - .Create(); + // act + var request = + QueryRequestBuilder.New() + .SetQuery("{ foo { qux } }") + .Create(); - IExecutionResult result = - await schema.MakeExecutable().ExecuteAsync(request); + var result = + await schema.MakeExecutable().ExecuteAsync(request); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - public class Query - { - public Foo Foo { get; } = new Foo { Bar = "bar" }; - } + public class Query + { + public Foo Foo { get; } = new Foo { Bar = "bar" }; + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Foo).Type(); - } + descriptor.Field(t => t.Foo).Type(); } + } - public class Foo - { - public string Bar { get; set; } - } + public class Foo + { + public string Bar { get; set; } + } - public class Baz - { - public string Qux { get; set; } - } + public class Baz + { + public string Qux { get; set; } + } - public class BazType : ObjectType - { - } + public class BazType : ObjectType + { } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Execution.Tests/StreamTests.cs b/src/HotChocolate/Core/test/Execution.Tests/StreamTests.cs index 068c2734136..b32d5119efe 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/StreamTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/StreamTests.cs @@ -10,20 +10,20 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Execution +namespace HotChocolate.Execution; + +public class StreamTests { - public class StreamTests + [Fact] + public async Task Stream_Nodes() { - [Fact] - public async Task Stream_Nodes() - { - IExecutionResult result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { @@ -37,31 +37,31 @@ nodes @stream(initialCount: 1) { } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); - - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } + var results = new StringBuilder(); - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task Do_Not_Stream_Nodes() - { - IExecutionResult result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query($stream: Boolean) { + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Do_Not_Stream_Nodes() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query($stream: Boolean) { hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { @@ -74,32 +74,32 @@ nodes @stream(initialCount: 1, if: $stream) { } } }") - .SetVariableValue("stream", false) - .Create()); - - IResponseStream stream = Assert.IsType(result); + .SetVariableValue("stream", false) + .Create()); - var results = new StringBuilder(); + IResponseStream stream = Assert.IsType(result); - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } + var results = new StringBuilder(); - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task Stream_Nested_Nodes() - { - IExecutionResult result = - await new ServiceCollection() - .AddStarWarsRepositories() - .AddGraphQL() - .AddStarWarsTypes() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Stream_Nested_Nodes() + { + var result = + await new ServiceCollection() + .AddStarWarsRepositories() + .AddGraphQL() + .AddStarWarsTypes() + .ExecuteRequestAsync( + @"{ hero(episode: NEW_HOPE) { id ... @defer(label: ""friends"") { @@ -119,206 +119,205 @@ nodes @stream(initialCount: 1) { } }"); - IResponseStream stream = Assert.IsType(result); - - var results = new StringBuilder(); + IResponseStream stream = Assert.IsType(result); - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } + var results = new StringBuilder(); - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task Stream_With_AsyncEnumerable_Schema() - { + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Stream_With_AsyncEnumerable_Schema() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + [Fact] + public async Task List_With_AsyncEnumerable() + { + var result = await new ServiceCollection() .AddGraphQL() .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task List_With_AsyncEnumerable() - { - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync( - @"{ + .ExecuteRequestAsync( + @"{ persons { name } }"); - Assert.IsType(result).MatchSnapshot(); - } + Assert.IsType(result).MatchSnapshot(); + } - [Fact] - public async Task Stream_With_AsyncEnumerable() - { - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync( - @"{ + [Fact] + public async Task Stream_With_AsyncEnumerable() + { + var result = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync( + @"{ persons @stream(initialCount: 0) { name } }"); - IResponseStream stream = Assert.IsType(result); - - var results = new StringBuilder(); + IResponseStream stream = Assert.IsType(result); - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } + var results = new StringBuilder(); - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task Stream_With_AsyncEnumerable_InitialCount_1() - { - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Stream_With_AsyncEnumerable_InitialCount_1() + { + var result = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync( + @"{ persons @stream(initialCount: 1) { name } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); + var results = new StringBuilder(); - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } - - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task Stream_With_DataLoader() - { - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddDataLoader() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Stream_With_DataLoader() + { + var result = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddDataLoader() + .ExecuteRequestAsync( + @"{ persons @stream(initialCount: 0) { name } }"); - IResponseStream stream = Assert.IsType(result); + IResponseStream stream = Assert.IsType(result); - var results = new StringBuilder(); - - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } + var results = new StringBuilder(); - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - [Fact] - public async Task Stream_With_DataLoader_InitialCount_1() - { - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddDataLoader() - .ExecuteRequestAsync( - @"{ + results.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Stream_With_DataLoader_InitialCount_1() + { + var result = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddDataLoader() + .ExecuteRequestAsync( + @"{ persons @stream(initialCount: 1) { name } }"); - IResponseStream stream = Assert.IsType(result); - - var results = new StringBuilder(); + IResponseStream stream = Assert.IsType(result); - await foreach (IQueryResult payload in stream.ReadResultsAsync()) - { - results.AppendLine(payload.ToJson()); - results.AppendLine(); - } + var results = new StringBuilder(); - results.ToString().MatchSnapshot(); + await foreach (var payload in stream.ReadResultsAsync()) + { + results.AppendLine(payload.ToJson()); + results.AppendLine(); } - public class Query + results.ToString().MatchSnapshot(); + } + + public class Query + { + public async IAsyncEnumerable GetPersonsAsync() { - public async IAsyncEnumerable GetPersonsAsync() - { - await Task.Delay(1); - yield return new Person { Name = "Foo" }; - await Task.Delay(1); - yield return new Person { Name = "Bar" }; - } + await Task.Delay(1); + yield return new Person { Name = "Foo" }; + await Task.Delay(1); + yield return new Person { Name = "Bar" }; } + } - public class QueryWithDataLoader + public class QueryWithDataLoader + { + public async IAsyncEnumerable GetPersonsAsync(PersonsGroupDataLoader dl) { - public async IAsyncEnumerable GetPersonsAsync(PersonsGroupDataLoader dl) - { - Person[] persons = await dl.LoadAsync("abc"); + var persons = await dl.LoadAsync("abc"); - foreach (Person person in persons) - { - yield return person; - } + foreach (var person in persons) + { + yield return person; } } + } - public class PersonsGroupDataLoader : GroupedDataLoader + public class PersonsGroupDataLoader : GroupedDataLoader + { + public PersonsGroupDataLoader( + IBatchScheduler batchScheduler, + DataLoaderOptions options = null) + : base(batchScheduler, options) { - public PersonsGroupDataLoader( - IBatchScheduler batchScheduler, - DataLoaderOptions options = null) - : base(batchScheduler, options) - { - } + } - protected override Task> LoadGroupedBatchAsync( - IReadOnlyList keys, - CancellationToken cancellationToken) + protected override Task> LoadGroupedBatchAsync( + IReadOnlyList keys, + CancellationToken cancellationToken) + { + return Task.FromResult(new List { - return Task.FromResult(new List - { - new() { GroupId = keys[0], Name = "Foo" }, - new() { GroupId = keys[0], Name = "Bar" } - }.ToLookup(t => t.GroupId)); - } + new() { GroupId = keys[0], Name = "Foo" }, + new() { GroupId = keys[0], Name = "Bar" } + }.ToLookup(t => t.GroupId)); } + } - public class Person - { - public string GroupId { get; set; } + public class Person + { + public string GroupId { get; set; } - public string Name { get; set; } - } + public string Name { get; set; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/ConnectionTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/ConnectionTests.cs index d5793e53314..62c84fcfa2c 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/ConnectionTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/ConnectionTests.cs @@ -3,86 +3,85 @@ using System.Threading.Tasks; using Xunit; -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class ConnectionTests { - public class ConnectionTests + [Fact] + public void CreateConnection_PageInfoAndEdges_PassedCorrectly() + { + // arrange + var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); + var edges = new List>(); + + // act + var connection = new Connection( + edges, + pageInfo, + _ => throw new NotSupportedException()); + + // assert + Assert.Equal(pageInfo, connection.Info); + Assert.Equal(edges, connection.Edges); + } + + [Fact] + public void CreateConnection_PageInfoNull_ArgumentNullException() { - [Fact] - public void CreateConnection_PageInfoAndEdges_PassedCorrectly() - { - // arrange - var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); - var edges = new List>(); - - // act - var connection = new Connection( - edges, - pageInfo, - _ => throw new NotSupportedException()); - - // assert - Assert.Equal(pageInfo, connection.Info); - Assert.Equal(edges, connection.Edges); - } - - [Fact] - public void CreateConnection_PageInfoNull_ArgumentNullException() - { - // arrange - var edges = new List>(); - - // act - void Action() => new Connection( - edges, - null!, - _ => throw new NotSupportedException()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void CreateConnection_EdgesNull_ArgumentNullException() - { - // arrange - var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); - - // act - void Action() => new Connection( - null!, - pageInfo, - _ => throw new NotSupportedException()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public async Task GetTotalCountAsync_Delegate_ReturnTotalCount() - { - // arrange - var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); - var edges = new List>(); - - // act - var connection = new Connection(edges, pageInfo, _ => new(2)); - - // assert - Assert.Equal(2, await connection.GetTotalCountAsync(default)); - } - - [Fact] - public async Task GetTotalCountAsync_Value_ReturnTotalCount() - { - // arrange - var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); - var edges = new List>(); - - // act - var connection = new Connection(edges, pageInfo, 2); - - // assert - Assert.Equal(2, await connection.GetTotalCountAsync(default)); - } + // arrange + var edges = new List>(); + + // act + void Action() => new Connection( + edges, + null!, + _ => throw new NotSupportedException()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void CreateConnection_EdgesNull_ArgumentNullException() + { + // arrange + var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); + + // act + void Action() => new Connection( + null!, + pageInfo, + _ => throw new NotSupportedException()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public async Task GetTotalCountAsync_Delegate_ReturnTotalCount() + { + // arrange + var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); + var edges = new List>(); + + // act + var connection = new Connection(edges, pageInfo, _ => new(2)); + + // assert + Assert.Equal(2, await connection.GetTotalCountAsync(default)); + } + + [Fact] + public async Task GetTotalCountAsync_Value_ReturnTotalCount() + { + // arrange + var pageInfo = new ConnectionPageInfo(true, true, "a", "b"); + var edges = new List>(); + + // act + var connection = new Connection(edges, pageInfo, 2); + + // assert + Assert.Equal(2, await connection.GetTotalCountAsync(default)); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingHandlerTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingHandlerTests.cs index 3371a7da846..69d9cdfcf4b 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingHandlerTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingHandlerTests.cs @@ -8,906 +8,905 @@ #nullable enable -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class CursorPagingHandlerTests { - public class CursorPagingHandlerTests + [Fact] + public void Range_Count_0() { - [Fact] - public void Range_Count_0() - { - // arrange - var range = new CursorPagingRange(0, 0); + // arrange + var range = new CursorPagingRange(0, 0); - // act - var count = range.Count(); + // act + var count = range.Count(); - // assert - Assert.Equal(0, count); - } + // assert + Assert.Equal(0, count); + } - [Fact] - public void Range_Count_1() - { - // arrange - var range = new CursorPagingRange(0, 1); + [Fact] + public void Range_Count_1() + { + // arrange + var range = new CursorPagingRange(0, 1); - // act - var count = range.Count(); + // act + var count = range.Count(); - // assert - Assert.Equal(1, count); - } + // assert + Assert.Equal(1, count); + } - [Fact] - public void Range_Count_2() - { - // arrange - var range = new CursorPagingRange(2, 4); + [Fact] + public void Range_Count_2() + { + // arrange + var range = new CursorPagingRange(2, 4); - // act - var count = range.Count(); + // act + var count = range.Count(); - // assert - Assert.Equal(2, count); - } + // assert + Assert.Equal(2, count); + } - [Fact] - public async Task ApplyPagination_EmptyList() - { - // arrange - var data = Array.Empty(); - - // act - Connection result = await Apply(data); - - // assert - Assert.Empty(result.Edges); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList() + { + // arrange + var data = Array.Empty(); + + // act + var result = await Apply(data); + + // assert + Assert.Empty(result.Edges); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Default() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Default() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_First_10() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, first: 10); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_First_10() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, first: 10); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_First_2() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, first: 2); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(1, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(1), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_First_2() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, first: 2); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(1, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(1), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_First_20() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, first: 20); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_First_20() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, first: 20); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_After_2_Default() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, ToBase64(1)); - - // assert - Assert.Equal(2, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(2), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_After_2_Default() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, ToBase64(1)); + + // assert + Assert.Equal(2, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(2), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_After_2_First_10() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, ToBase64(1), first: 10); - - // assert - Assert.Equal(2, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(2), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_After_2_First_10() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, ToBase64(1), first: 10); + + // assert + Assert.Equal(2, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(2), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_After_2_First_2() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - Foo.Create(4), - }; - - // act - Connection result = await Apply(data, ToBase64(1), first: 2); - - // assert - Assert.Equal(2, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(2), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(5, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_After_2_First_2() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + Foo.Create(4), + }; + + // act + var result = await Apply(data, ToBase64(1), first: 2); + + // assert + Assert.Equal(2, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(2), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(5, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_After_2_First_20() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, ToBase64(1), first: 20); - - // assert - Assert.Equal(2, ToFoo(result).First().Index); - Assert.Equal(3, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(2), result.Info.StartCursor); - Assert.Equal(ToBase64(3), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_After_2_First_20() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, ToBase64(1), first: 20); + + // assert + Assert.Equal(2, ToFoo(result).First().Index); + Assert.Equal(3, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(2), result.Info.StartCursor); + Assert.Equal(ToBase64(3), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_Default() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(3)); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_Default() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(3)); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_Last_10() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(3), last: 10); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_Last_10() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(3), last: 10); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_Last_2() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(3), last: 2); - - // assert - Assert.Equal(1, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(1), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_Last_2() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(3), last: 2); + + // assert + Assert.Equal(1, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(1), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_Last_20() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(3), last: 20); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_Last_20() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(3), last: 20); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_2_Default() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(2)); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(1, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(1), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_2_Default() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(2)); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(1, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(1), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_2_Last_10() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(2), last: 10); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(1, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(1), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_2_Last_10() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(2), last: 10); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(1, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(1), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_3_Last_2() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - Foo.Create(4), - }; - - // act - Connection result = await Apply(data, before: ToBase64(3), last: 2); - - // assert - Assert.Equal(1, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(1), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(5, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_3_Last_2() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + Foo.Create(4), + }; + + // act + var result = await Apply(data, before: ToBase64(3), last: 2); + + // assert + Assert.Equal(1, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(1), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(5, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Before_2_Last_20() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, before: ToBase64(2), last: 20); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(1, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(1), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Before_2_Last_20() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, before: ToBase64(2), last: 20); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(1, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(1), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice() - { - // arrange - Foo[] data = - { - Foo.Create(0), - Foo.Create(1), - Foo.Create(2), - Foo.Create(3), - }; - - // act - Connection result = await Apply(data, after: ToBase64(0), before: ToBase64(3)); - - // assert - Assert.Equal(1, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(1), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(4, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice() + { + // arrange + Foo[] data = + { + Foo.Create(0), + Foo.Create(1), + Foo.Create(2), + Foo.Create(3), + }; + + // act + var result = await Apply(data, after: ToBase64(0), before: ToBase64(3)); + + // assert + Assert.Equal(1, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(1), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(4, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_WithFirst() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = - await Apply(data, after: ToBase64(0), before: ToBase64(10), first: 2); - - // assert - Assert.Equal(1, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(1), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_WithFirst() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = + await Apply(data, after: ToBase64(0), before: ToBase64(10), first: 2); + + // assert + Assert.Equal(1, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(1), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_WithLast() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = - await Apply(data, after: ToBase64(0), before: ToBase64(10), last: 2); - - // assert - Assert.Equal(8, ToFoo(result).First().Index); - Assert.Equal(9, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(8), result.Info.StartCursor); - Assert.Equal(ToBase64(9), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_WithLast() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = + await Apply(data, after: ToBase64(0), before: ToBase64(10), last: 2); + + // assert + Assert.Equal(8, ToFoo(result).First().Index); + Assert.Equal(9, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(8), result.Info.StartCursor); + Assert.Equal(ToBase64(9), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_After_Last_2() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, after: ToBase64(0), last: 2); - - // assert - Assert.Equal(8, ToFoo(result).First().Index); - Assert.Equal(9, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(8), result.Info.StartCursor); - Assert.Equal(ToBase64(9), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_After_Last_2() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, after: ToBase64(0), last: 2); + + // assert + Assert.Equal(8, ToFoo(result).First().Index); + Assert.Equal(9, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(8), result.Info.StartCursor); + Assert.Equal(ToBase64(9), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_Before_First_2() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, before: ToBase64(8), first: 2); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(1, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(1), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_Before_First_2() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, before: ToBase64(8), first: 2); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(1, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(1), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_Before_OutOfBounds_RangeInReach() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, before: ToBase64(12), last: 4); - - // assert - Assert.Equal(8, ToFoo(result).First().Index); - Assert.Equal(9, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(8), result.Info.StartCursor); - Assert.Equal(ToBase64(9), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_Before_OutOfBounds_RangeInReach() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, before: ToBase64(12), last: 4); + + // assert + Assert.Equal(8, ToFoo(result).First().Index); + Assert.Equal(9, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(8), result.Info.StartCursor); + Assert.Equal(ToBase64(9), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_Before_OutOfBounds_RangeOutOfReach() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, before: ToBase64(20), last: 4); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_Before_OutOfBounds_RangeOutOfReach() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, before: ToBase64(20), last: 4); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_After_OutOfBounds_RangeInReach() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, after: ToBase64(-2), first: 4); - - // assert - Assert.Equal(0, ToFoo(result).First().Index); - Assert.Equal(2, ToFoo(result).Last().Index); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(0), result.Info.StartCursor); - Assert.Equal(ToBase64(2), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_After_OutOfBounds_RangeInReach() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, after: ToBase64(-2), first: 4); + + // assert + Assert.Equal(0, ToFoo(result).First().Index); + Assert.Equal(2, ToFoo(result).Last().Index); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(0), result.Info.StartCursor); + Assert.Equal(ToBase64(2), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Slice_After_OutOfBounds_RangeOutOfReach() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, after: ToBase64(-20), first: 4); - - // assert - Assert.Empty(ToFoo(result)); - Assert.True(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Slice_After_OutOfBounds_RangeOutOfReach() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, after: ToBase64(-20), first: 4); + + // assert + Assert.Empty(ToFoo(result)); + Assert.True(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_Last_2() - { - // arrange - Foo[] data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); - - // act - Connection result = await Apply(data, last: 2); - - // assert - Assert.Equal(8, ToFoo(result).First().Index); - Assert.Equal(9, ToFoo(result).Last().Index); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Equal(ToBase64(8), result.Info.StartCursor); - Assert.Equal(ToBase64(9), result.Info.EndCursor); - Assert.Equal(10, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_Last_2() + { + // arrange + var data = Enumerable.Range(0, 10).Select(Foo.Create).ToArray(); + + // act + var result = await Apply(data, last: 2); + + // assert + Assert.Equal(8, ToFoo(result).First().Index); + Assert.Equal(9, ToFoo(result).Last().Index); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Equal(ToBase64(8), result.Info.StartCursor); + Assert.Equal(ToBase64(9), result.Info.EndCursor); + Assert.Equal(10, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_Default() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_Default() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_First2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, first: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_First2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, first: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_Last2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, last: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_Last2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, last: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_After_2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, after: ToBase64(2)); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_After_2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, after: ToBase64(2)); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_Before_2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, before: ToBase64(2)); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_Before_2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, before: ToBase64(2)); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_After_Minut2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, after: ToBase64(-2)); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_After_Minut2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, after: ToBase64(-2)); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_After_2_First2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, after: ToBase64(2), first: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_After_2_First2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, after: ToBase64(2), first: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_Before_2_First2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, before: ToBase64(2), first: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_Before_2_First2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, before: ToBase64(2), first: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_After_Minus2_First2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, after: ToBase64(-2), first: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_After_Minus2_First2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, after: ToBase64(-2), first: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_After_2_Last2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, after: ToBase64(2), last: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.True(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_After_2_Last2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, after: ToBase64(2), last: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.True(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_Before_2_Last2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, before: ToBase64(2), last: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_Before_2_Last2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, before: ToBase64(2), last: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - [Fact] - public async Task ApplyPagination_EmptyList_After_Minus2_Last2() - { - // arrange - IEnumerable data = Enumerable.Empty(); - - // act - Connection result = await Apply(data, after: ToBase64(-2), last: 2); - - // assert - Assert.Empty(ToFoo(result)); - Assert.False(result.Info.HasNextPage); - Assert.False(result.Info.HasPreviousPage); - Assert.Null(result.Info.StartCursor); - Assert.Null(result.Info.EndCursor); - Assert.Equal(0, await result.GetTotalCountAsync(default)); - } + [Fact] + public async Task ApplyPagination_EmptyList_After_Minus2_Last2() + { + // arrange + var data = Enumerable.Empty(); + + // act + var result = await Apply(data, after: ToBase64(-2), last: 2); + + // assert + Assert.Empty(ToFoo(result)); + Assert.False(result.Info.HasNextPage); + Assert.False(result.Info.HasPreviousPage); + Assert.Null(result.Info.StartCursor); + Assert.Null(result.Info.EndCursor); + Assert.Equal(0, await result.GetTotalCountAsync(default)); + } - private static string ToBase64(int i) - => Convert.ToBase64String(Encoding.UTF8.GetBytes(i.ToString())); + private static string ToBase64(int i) + => Convert.ToBase64String(Encoding.UTF8.GetBytes(i.ToString())); - private static IEnumerable ToFoo(Connection connection) - => connection.Edges.Select(x => x.Node).OfType(); + private static IEnumerable ToFoo(Connection connection) + => connection.Edges.Select(x => x.Node).OfType(); - public class Foo + public class Foo + { + public Foo(int index) { - public Foo(int index) - { - Index = index; - } - - public int Index { get; } - - public static Foo Create(int index) => new(index); + Index = index; } - private static async ValueTask Apply( - IEnumerable foos, - string? after = default, - string? before = default, - int? first = default, - int? last = default) - => await foos.AsQueryable().ApplyCursorPaginationAsync( - first, last, after, before); + public int Index { get; } + + public static Foo Create(int index) => new(index); } -} + + private static async ValueTask Apply( + IEnumerable foos, + string? after = default, + string? before = default, + int? first = default, + int? last = default) + => await foos.AsQueryable().ApplyCursorPaginationAsync( + first, last, after, before); +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingQueryableExtensionsTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingQueryableExtensionsTests.cs index 3615d765708..506e646a353 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingQueryableExtensionsTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CursorPagingQueryableExtensionsTests.cs @@ -12,151 +12,150 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class CursorPagingQueryableExtensionsTests { - public class CursorPagingQueryableExtensionsTests + [Fact] + public async Task Queryable_Query_Is_Null() { - [Fact] - public async Task Queryable_Query_Is_Null() - { - var mock = new Mock(); + var mock = new Mock(); - async Task Fail() - => await default(IQueryable)!.ApplyCursorPaginationAsync(mock.Object); + async Task Fail() + => await default(IQueryable)!.ApplyCursorPaginationAsync(mock.Object); - await Assert.ThrowsAsync(Fail); - } + await Assert.ThrowsAsync(Fail); + } - [Fact] - public async Task Queryable_Context_Is_Null() - { - var mock = new Mock>(); + [Fact] + public async Task Queryable_Context_Is_Null() + { + var mock = new Mock>(); - async Task Fail() - => await mock.Object.ApplyCursorPaginationAsync(default(IResolverContext)!); + async Task Fail() + => await mock.Object.ApplyCursorPaginationAsync(default(IResolverContext)!); - await Assert.ThrowsAsync(Fail); - } + await Assert.ThrowsAsync(Fail); + } - [Fact] - public async Task Queryable_ApplyCursorPaginationAsync_No_Boundaries() - { - Snapshot.FullName(); + [Fact] + public async Task Queryable_ApplyCursorPaginationAsync_No_Boundaries() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ persons { nodes { name } } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ persons { nodes { name } } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Queryable_ApplyCursorPaginationAsync_First_1() - { - Snapshot.FullName(); + [Fact] + public async Task Queryable_ApplyCursorPaginationAsync_First_1() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ persons(first: 1) { nodes { name } } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ persons(first: 1) { nodes { name } } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Enumerable_Query_Is_Null() - { - var mock = new Mock(); + [Fact] + public async Task Enumerable_Query_Is_Null() + { + var mock = new Mock(); - async Task Fail() - => await default(IEnumerable)!.ApplyCursorPaginationAsync(mock.Object); + async Task Fail() + => await default(IEnumerable)!.ApplyCursorPaginationAsync(mock.Object); - await Assert.ThrowsAsync(Fail); - } + await Assert.ThrowsAsync(Fail); + } - [Fact] - public async Task Enumerable_Context_Is_Null() - { - var mock = new Mock>(); + [Fact] + public async Task Enumerable_Context_Is_Null() + { + var mock = new Mock>(); - async Task Fail() - => await mock.Object.ApplyCursorPaginationAsync(default(IResolverContext)!); + async Task Fail() + => await mock.Object.ApplyCursorPaginationAsync(default(IResolverContext)!); - await Assert.ThrowsAsync(Fail); - } + await Assert.ThrowsAsync(Fail); + } - [Fact] - public async Task Enumerable_ApplyCursorPaginationAsync_No_Boundaries() - { - Snapshot.FullName(); + [Fact] + public async Task Enumerable_ApplyCursorPaginationAsync_No_Boundaries() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ persons { nodes { name } } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ persons { nodes { name } } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Enumerable_ApplyCursorPaginationAsync_First_1() - { - Snapshot.FullName(); + [Fact] + public async Task Enumerable_ApplyCursorPaginationAsync_First_1() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ persons(first: 1) { nodes { name } } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ persons(first: 1) { nodes { name } } }") + .MatchSnapshotAsync(); + } - public class Query + public class Query + { + [UsePaging] + public async Task> GetPersons( + IResolverContext context, + CancellationToken cancellationToken) { - [UsePaging] - public async Task> GetPersons( - IResolverContext context, - CancellationToken cancellationToken) + var list = new Person[] { - var list = new Person[] - { - new() { Name = "Foo" }, - new() { Name = "Bar" }, - new() { Name = "Baz" }, - new() { Name = "Qux" } - }; - - return await list.AsQueryable().ApplyCursorPaginationAsync( - context, - defaultPageSize: 2, - totalCount: list.Length, - cancellationToken: cancellationToken); - } + new() { Name = "Foo" }, + new() { Name = "Bar" }, + new() { Name = "Baz" }, + new() { Name = "Qux" } + }; + + return await list.AsQueryable().ApplyCursorPaginationAsync( + context, + defaultPageSize: 2, + totalCount: list.Length, + cancellationToken: cancellationToken); } + } - public class QueryEnumerable + public class QueryEnumerable + { + [UsePaging] + public async Task> GetPersons( + IResolverContext context, + CancellationToken cancellationToken) { - [UsePaging] - public async Task> GetPersons( - IResolverContext context, - CancellationToken cancellationToken) + var list = new Person[] { - var list = new Person[] - { - new() { Name = "Foo" }, - new() { Name = "Bar" }, - new() { Name = "Baz" }, - new() { Name = "Qux" } - }; - - return await list.ApplyCursorPaginationAsync( - context, - defaultPageSize: 2, - totalCount: list.Length, - cancellationToken: cancellationToken); - } + new() { Name = "Foo" }, + new() { Name = "Bar" }, + new() { Name = "Baz" }, + new() { Name = "Qux" } + }; + + return await list.ApplyCursorPaginationAsync( + context, + defaultPageSize: 2, + totalCount: list.Length, + cancellationToken: cancellationToken); } + } - public class Person - { - public string Name { get; set; } - } + public class Person + { + public string Name { get; set; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CustomCursorHandlerTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CustomCursorHandlerTests.cs index d6c87f67a86..ba51e80b34e 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CustomCursorHandlerTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/CustomCursorHandlerTests.cs @@ -7,55 +7,54 @@ #nullable enable -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class CustomCursorHandlerTests { - public class CustomCursorHandlerTests + [Fact] + public void Infer_Schema_Correctly_When_Connection_IsUsed() { - [Fact] - public void Infer_Schema_Correctly_When_Connection_IsUsed() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .Print() - .MatchSnapshot(); - } + SchemaBuilder.New() + .AddQueryType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public async Task Use_Resolver_Result_If_It_Is_A_Page() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task Use_Resolver_Result_If_It_Is_A_Page() + { + // arrange + Snapshot.FullName(); - IReadOnlyQueryRequest request = - QueryRequestBuilder.New() - .SetQuery("{ items { nodes } }") - .Create(); + var request = + QueryRequestBuilder.New() + .SetQuery("{ items { nodes } }") + .Create(); - // act - // assert - await SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .ExecuteAsync(request) - .MatchSnapshotAsync(); - } + // act + // assert + await SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .ExecuteAsync(request) + .MatchSnapshotAsync(); + } - public class Query + public class Query + { + [UsePaging] + public Connection GetItems( + int first = 10, + string? after = null, + int? last = null, + string? before = null) { - [UsePaging] - public Connection GetItems( - int first = 10, - string? after = null, - int? last = null, - string? before = null) - { - return new( - new[] { new Edge("hello", "abc") }, - new ConnectionPageInfo(false, false, "abc", "abc"), - 2000); - } + return new( + new[] { new Edge("hello", "abc") }, + new ConnectionPageInfo(false, false, "abc", "abc"), + 2000); } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/EdgeTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/EdgeTests.cs index 01d12c00a80..e59390f71eb 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/EdgeTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/EdgeTests.cs @@ -8,91 +8,90 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class EdgeTests { - public class EdgeTests + [InlineData("abc", "cde")] + [InlineData("cde", null)] + [Theory] + public void CreateEdge_ArgumentsArePassedCorrectly( + string cursor, string node) { - [InlineData("abc", "cde")] - [InlineData("cde", null)] - [Theory] - public void CreateEdge_ArgumentsArePassedCorrectly( - string cursor, string node) - { - // arrange - // act - var edge = new Edge(node, cursor); + // arrange + // act + var edge = new Edge(node, cursor); - // assert - Assert.Equal(cursor, edge.Cursor); - Assert.Equal(node, edge.Node); - } + // assert + Assert.Equal(cursor, edge.Cursor); + Assert.Equal(node, edge.Node); + } - [Fact] - public void CreateEdge_CursorIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => new Edge("abc", null!); + [Fact] + public void CreateEdge_CursorIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => new Edge("abc", null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void CreateEdge_CursorIsEmpty_ArgumentNullException() - { - // arrange - // act - void Action() => new Edge("abc", string.Empty); + [Fact] + public void CreateEdge_CursorIsEmpty_ArgumentNullException() + { + // arrange + // act + void Action() => new Edge("abc", string.Empty); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public async Task Extend_Edge_Type_And_Inject_Edge_Value_Schema() - { - Snapshot.FullName(); + [Fact] + public async Task Extend_Edge_Type_And_Inject_Edge_Value_Schema() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Extend_Edge_Type_And_Inject_Edge_Value_Request() - { - Snapshot.FullName(); + [Fact] + public async Task Extend_Edge_Type_And_Inject_Edge_Value_Request() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .ExecuteRequestAsync("{ users { edges { test } } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .ExecuteRequestAsync("{ users { edges { test } } }") + .MatchSnapshotAsync(); + } - public class Query - { - [UsePaging] - public IEnumerable GetUsers() => new[] { new User { Name = "Hello" } }; - } + public class Query + { + [UsePaging] + public IEnumerable GetUsers() => new[] { new User { Name = "Hello" } }; + } - [ExtendObjectType("UsersEdge")] - public class UsersEdgeExtensions + [ExtendObjectType("UsersEdge")] + public class UsersEdgeExtensions + { + public string Test([Parent] Edge edge) { - public string Test([Parent] Edge edge) - { - return edge.Node.Name; - } + return edge.Node.Name; } + } - public class User - { - public string Name { get; set; } - } + public class User + { + public string Name { get; set; } } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/IntegrationTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/IntegrationTests.cs index 2b0f86563a0..48dd42a1588 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/IntegrationTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/IntegrationTests.cs @@ -14,53 +14,53 @@ #nullable enable -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class IntegrationTests { - public class IntegrationTests + [Fact] + public async Task Simple_StringList_Schema() { - [Fact] - public async Task Simple_StringList_Schema() - { - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - executor.Schema.Print().MatchSnapshot(); - } + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); - [Fact] - public async Task Attribute_Simple_StringList_Schema() - { - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - executor.Schema.Print().MatchSnapshot(); - } + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task Simple_StringList_Default_Items() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Simple_StringList_Schema() + { + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + executor.Schema.Print().MatchSnapshot(); + } + + [Fact] + public async Task Simple_StringList_Default_Items() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters { edges { @@ -76,25 +76,25 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task No_Boundaries_Set() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { RequirePagingBoundaries = true }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task No_Boundaries_Set() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { RequirePagingBoundaries = true }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters { edges { @@ -110,24 +110,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Simple_StringList_Default_Items() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Simple_StringList_Default_Items() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters { edges { @@ -143,24 +143,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Simple_StringList_First_2() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Simple_StringList_First_2() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters(first: 2) { edges { @@ -176,25 +176,25 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task MaxPageSizeReached_First() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { MaxPageSize = 2 }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task MaxPageSizeReached_First() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { MaxPageSize = 2 }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters(first: 3) { edges { @@ -210,25 +210,25 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task MaxPageSizeReached_Last() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { MaxPageSize = 2 }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task MaxPageSizeReached_Last() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { MaxPageSize = 2 }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters(last: 3) { edges { @@ -244,24 +244,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Simple_StringList_First_2() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Simple_StringList_First_2() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters(first: 2) { edges { @@ -277,24 +277,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Simple_StringList_First_2_After() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Simple_StringList_First_2_After() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters(first: 2 after: ""MQ=="") { edges { @@ -310,24 +310,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Simple_StringList_First_2_After() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Simple_StringList_First_2_After() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters(first: 2 after: ""MQ=="") { edges { @@ -343,25 +343,25 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Simple_StringList_Global_DefaultItem_2() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { DefaultPageSize = 2 }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Simple_StringList_Global_DefaultItem_2() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { DefaultPageSize = 2 }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters { edges { @@ -377,25 +377,25 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Simple_StringList_Global_DefaultItem_2() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { DefaultPageSize = 2 }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Simple_StringList_Global_DefaultItem_2() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { DefaultPageSize = 2 }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { letters { edges { @@ -411,24 +411,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Schema_Type_Is_Explicitly_Specified() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Schema_Type_Is_Explicitly_Specified() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { explicitType(first: 2) { edges { @@ -444,24 +444,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Schema_Type_Is_Explicitly_Specified() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Schema_Type_Is_Explicitly_Specified() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { explicitType(first: 2) { edges { @@ -477,24 +477,24 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Nested_List_With_Field_Settings() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Nested_List_With_Field_Settings() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { nestedObjectList { edges { @@ -515,24 +515,24 @@ await executor totalCount } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Executable_With_Field_Settings() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Executable_With_Field_Settings() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { fooExecutable { edges { @@ -553,24 +553,24 @@ await executor totalCount } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Nested_List_With_Field_Settings() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Nested_List_With_Field_Settings() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { nestedObjectList { edges { @@ -591,24 +591,24 @@ await executor totalCount } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Nested_List_With_Field_Settings_Skip_2() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Nested_List_With_Field_Settings_Skip_2() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { nestedObjectList(first: 2) { edges { @@ -629,24 +629,24 @@ await executor totalCount } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Attribute_Nested_List_With_Field_Settings_Skip_2() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task Attribute_Nested_List_With_Field_Settings_Skip_2() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { nestedObjectList(first: 2) { edges { @@ -667,242 +667,242 @@ await executor totalCount } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Interface_With_Paging_Field() - { - Snapshot.FullName(); - - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddInterfaceType(d => d - .Field(t => t.ExplicitType()) - .UsePaging()) - .ModifyOptions(o => - { - o.RemoveUnreachableTypes = false; - o.StrictValidation = false; - }) - .Services - .BuildServiceProvider() - .GetSchemaAsync(); - - schema.Print().MatchSnapshot(); - } + [Fact] + public async Task Interface_With_Paging_Field() + { + Snapshot.FullName(); - [Fact] - public async Task Attribute_Interface_With_Paging_Field() - { - Snapshot.FullName(); - - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddInterfaceType() - .ModifyOptions(o => - { - o.RemoveUnreachableTypes = false; - o.StrictValidation = false; - }) - .Services - .BuildServiceProvider() - .GetSchemaAsync(); - - schema.Print().MatchSnapshot(); - } + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddInterfaceType(d => d + .Field(t => t.ExplicitType()) + .UsePaging()) + .ModifyOptions(o => + { + o.RemoveUnreachableTypes = false; + o.StrictValidation = false; + }) + .Services + .BuildServiceProvider() + .GetSchemaAsync(); + + schema.Print().MatchSnapshot(); + } - [Fact] - public async Task Deactivate_BackwardPagination() - { - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { AllowBackwardPagination = false }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - executor.Schema.Print().MatchSnapshot(); - } + [Fact] + public async Task Attribute_Interface_With_Paging_Field() + { + Snapshot.FullName(); - [Fact] - public async Task Deactivate_BackwardPagination_Interface() - { - Snapshot.FullName(); - - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { AllowBackwardPagination = false }) - .AddInterfaceType(d => d.Field(t => t.ExplicitType()).UsePaging()) - .Services - .BuildServiceProvider() - .GetSchemaAsync(); - - schema.Print().MatchSnapshot(); - } + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddInterfaceType() + .ModifyOptions(o => + { + o.RemoveUnreachableTypes = false; + o.StrictValidation = false; + }) + .Services + .BuildServiceProvider() + .GetSchemaAsync(); + + schema.Print().MatchSnapshot(); + } - [Fact] - public async Task Infer_ConnectionName_From_Field() - { - Snapshot.FullName(); + [Fact] + public async Task Deactivate_BackwardPagination() + { + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { AllowBackwardPagination = false }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetSchemaAsync(); + executor.Schema.Print().MatchSnapshot(); + } - schema.Print().MatchSnapshot(); - } + [Fact] + public async Task Deactivate_BackwardPagination_Interface() + { + Snapshot.FullName(); - [Fact] - public async Task Explicit_ConnectionName() - { - Snapshot.FullName(); + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { AllowBackwardPagination = false }) + .AddInterfaceType(d => d.Field(t => t.ExplicitType()).UsePaging()) + .Services + .BuildServiceProvider() + .GetSchemaAsync(); + + schema.Print().MatchSnapshot(); + } - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetSchemaAsync(); + [Fact] + public async Task Infer_ConnectionName_From_Field() + { + Snapshot.FullName(); - schema.Print().MatchSnapshot(); - } + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetSchemaAsync(); - [Fact] - public async Task SelectProviderByName() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddCursorPagingProvider(providerName: "Abc") - .SetPagingOptions(new PagingOptions { InferConnectionNameFromField = false }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + schema.Print().MatchSnapshot(); + } + + [Fact] + public async Task Explicit_ConnectionName() + { + Snapshot.FullName(); + + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetSchemaAsync(); + + schema.Print().MatchSnapshot(); + } + + [Fact] + public async Task SelectProviderByName() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddCursorPagingProvider(providerName: "Abc") + .SetPagingOptions(new PagingOptions { InferConnectionNameFromField = false }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { abc { nodes } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task FluentPagingTests() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task FluentPagingTests() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { items { nodes } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task SelectDefaultProvider() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddCursorPagingProvider() - .AddCursorPagingProvider(defaultProvider: true) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + [Fact] + public async Task SelectDefaultProvider() + { + Snapshot.FullName(); + + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddCursorPagingProvider() + .AddCursorPagingProvider(defaultProvider: true) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); + + await executor + .ExecuteAsync(@" { abc { nodes } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_That_Explicit_Backward_Paging_Fields_Work() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Ensure_That_Explicit_Backward_Paging_Fields_Work() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_That_Explicit_Backward_Paging_Fields_Work_Execute() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ foos { nodes } }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Ensure_That_Explicit_Backward_Paging_Fields_Work_Execute() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ foos { nodes } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task LegacySupport_Schema() - { - Snapshot.FullName(); + [Fact] + public async Task LegacySupport_Schema() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { LegacySupport = true }) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + [Fact] + public async Task LegacySupport_Query() + { + Snapshot.FullName(); + + var executor = await new ServiceCollection() .AddGraphQL() .AddQueryType() .SetPagingOptions(new PagingOptions { LegacySupport = true }) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(); - [Fact] - public async Task LegacySupport_Query() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { LegacySupport = true }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(); - - await executor - .ExecuteAsync(@" + await executor + .ExecuteAsync(@" query($first: PaginationAmount = 2){ letters(first: $first) { edges { @@ -918,22 +918,22 @@ await executor } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - [Fact] - public async Task TotalCountWithCustomConnection() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task TotalCountWithCustomConnection() + { + // arrange + Snapshot.FullName(); - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); - // act - const string query = @" + // act + const string query = @" { foos { totalCount @@ -941,265 +941,264 @@ public async Task TotalCountWithCustomConnection() } "; - IExecutionResult result = await executor.ExecuteAsync(query); + var result = await executor.ExecuteAsync(query); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(t => t.Letters) - .UsePaging(); - - descriptor - .Field("explicitType") - .ResolveWith(t => t.Letters) - .UsePaging>(); - - descriptor - .Field(t => t.Foos()) - .Name("nestedObjectList") - .UsePaging( - options: new PagingOptions - { - MaxPageSize = 2, - IncludeTotalCount = true - }); - } + descriptor + .Field(t => t.Letters) + .UsePaging(); + + descriptor + .Field("explicitType") + .ResolveWith(t => t.Letters) + .UsePaging>(); + + descriptor + .Field(t => t.Foos()) + .Name("nestedObjectList") + .UsePaging( + options: new PagingOptions + { + MaxPageSize = 2, + IncludeTotalCount = true + }); } + } - public class ExecutableQueryType : ObjectType + public class ExecutableQueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(t => t.FoosExecutable()) - .Name("fooExecutable") - .UsePaging( - options: new PagingOptions - { - MaxPageSize = 2, - IncludeTotalCount = true - }); - } + descriptor + .Field(t => t.FoosExecutable()) + .Name("fooExecutable") + .UsePaging( + options: new PagingOptions + { + MaxPageSize = 2, + IncludeTotalCount = true + }); } + } - public class Query + public class Query + { + public string[] Letters => new[] { - public string[] Letters => new[] - { - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l" - }; - - public List> Foos() => new() + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l" + }; + + public List> Foos() => new() + { + new List { new() { Bar = "a" } }, + new List { new() { Bar = "b" }, new() { Bar = "c" } }, + new List { new() { Bar = "d" } }, + new List { new() { Bar = "e" } }, + new List { new() { Bar = "f" } } + }; + } + + public class ExecutableQuery + { + public IExecutable FoosExecutable() => new MockExecutable( + new List { - new List { new() { Bar = "a" } }, - new List { new() { Bar = "b" }, new() { Bar = "c" } }, - new List { new() { Bar = "d" } }, - new List { new() { Bar = "e" } }, - new List { new() { Bar = "f" } } - }; - } + new() { Bar = "a" }, + new() { Bar = "b" }, + new() { Bar = "c" } , + new() { Bar = "d" }, + new() { Bar = "e" }, + new() { Bar = "f" } + }.AsQueryable()); + } - public class ExecutableQuery - { - public IExecutable FoosExecutable() => new MockExecutable( - new List - { - new() { Bar = "a" }, - new() { Bar = "b" }, - new() { Bar = "c" } , - new() { Bar = "d" }, - new() { Bar = "e" }, - new() { Bar = "f" } - }.AsQueryable()); - } + public class Foo + { + public string Bar { get; set; } = default!; + } - public class Foo + public class QueryAttr + { + [UsePaging] + public string[] Letters => new[] { - public string Bar { get; set; } = default!; - } - - public class QueryAttr + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l" + }; + + [UsePaging(typeof(NonNullType))] + public string[] ExplicitType => Letters; + + [GraphQLName("nestedObjectList")] + [UsePaging( + MaxPageSize = 2, + IncludeTotalCount = true)] + public List> Foos() => new() { - [UsePaging] - public string[] Letters => new[] - { - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l" - }; - - [UsePaging(typeof(NonNullType))] - public string[] ExplicitType => Letters; - - [GraphQLName("nestedObjectList")] - [UsePaging( - MaxPageSize = 2, - IncludeTotalCount = true)] - public List> Foos() => new() - { - new List { new() { Bar = "a" } }, - new List { new() { Bar = "b" }, new() { Bar = "c" } }, - new List { new() { Bar = "d" } }, - new List { new() { Bar = "e" } }, - new List { new() { Bar = "f" } } - }; - } + new List { new() { Bar = "a" } }, + new List { new() { Bar = "b" }, new() { Bar = "c" } }, + new List { new() { Bar = "d" } }, + new List { new() { Bar = "e" } }, + new List { new() { Bar = "f" } } + }; + } - public interface ISome - { - public string[] ExplicitType(); - } + public interface ISome + { + public string[] ExplicitType(); + } - public interface ISome2 - { - [UsePaging(typeof(NonNullType))] - public string[] ExplicitType(); - } + public interface ISome2 + { + [UsePaging(typeof(NonNullType))] + public string[] ExplicitType(); + } - public class InferConnectionNameFromFieldType : ObjectType + public class InferConnectionNameFromFieldType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor - .Field(t => t.Names()) - .UsePaging(options: new() { InferConnectionNameFromField = true }); + descriptor + .Field(t => t.Names()) + .UsePaging(options: new() { InferConnectionNameFromField = true }); - } } + } - public class InferConnectionNameFromField - { - public string[] Names() => new[] { "a", "b" }; - } + public class InferConnectionNameFromField + { + public string[] Names() => new[] { "a", "b" }; + } - public class ExplicitConnectionName - { - [UsePaging(ConnectionName = "Connection1")] - public string[] Abc => throw new NotImplementedException(); + public class ExplicitConnectionName + { + [UsePaging(ConnectionName = "Connection1")] + public string[] Abc => throw new NotImplementedException(); - [UsePaging(ConnectionName = "Connection2")] - public string[] Def => throw new NotImplementedException(); + [UsePaging(ConnectionName = "Connection2")] + public string[] Def => throw new NotImplementedException(); - [UsePaging] - public string[] Ghi => throw new NotImplementedException(); - } + [UsePaging] + public string[] Ghi => throw new NotImplementedException(); + } - public class ProviderByName - { - [UsePaging(ProviderName = "Abc")] - public string[] Abc => Array.Empty(); - } + public class ProviderByName + { + [UsePaging(ProviderName = "Abc")] + public string[] Abc => Array.Empty(); + } - public class FluentPaging - { - [UsePaging(ProviderName = "Items")] - public async Task> GetItems( - int? first, - int? last, - string? before, - string? after, - CancellationToken cancellationToken) - => await new[] { "a", "b", "c", "d" } - .AsQueryable() - .ApplyCursorPaginationAsync(first, last, before, after, cancellationToken); - } + public class FluentPaging + { + [UsePaging(ProviderName = "Items")] + public async Task> GetItems( + int? first, + int? last, + string? before, + string? after, + CancellationToken cancellationToken) + => await new[] { "a", "b", "c", "d" } + .AsQueryable() + .ApplyCursorPaginationAsync(first, last, before, after, cancellationToken); + } - public class DummyProvider : CursorPagingProvider - { - public override bool CanHandle(IExtendedType source) => false; + public class DummyProvider : CursorPagingProvider + { + public override bool CanHandle(IExtendedType source) => false; - protected override CursorPagingHandler CreateHandler( - IExtendedType source, - PagingOptions options) - => new DummyHandler(options); - } + protected override CursorPagingHandler CreateHandler( + IExtendedType source, + PagingOptions options) + => new DummyHandler(options); + } - public class DummyHandler : CursorPagingHandler + public class DummyHandler : CursorPagingHandler + { + public DummyHandler(PagingOptions options) : base(options) { - public DummyHandler(PagingOptions options) : base(options) - { - } - - protected override ValueTask SliceAsync( - IResolverContext context, - object source, - CursorPagingArguments arguments) - => new(new Connection( - new[] { new Edge("a", "b") }, - new ConnectionPageInfo(false, false, null, null), - _ => new(1))); } - public class Dummy2Provider : CursorPagingProvider - { - public override bool CanHandle(IExtendedType source) => false; - - protected override CursorPagingHandler CreateHandler( - IExtendedType source, - PagingOptions options) - => new Dummy2Handler(options); - } + protected override ValueTask SliceAsync( + IResolverContext context, + object source, + CursorPagingArguments arguments) + => new(new Connection( + new[] { new Edge("a", "b") }, + new ConnectionPageInfo(false, false, null, null), + _ => new(1))); + } - public class Dummy2Handler : CursorPagingHandler - { - public Dummy2Handler(PagingOptions options) : base(options) - { - } + public class Dummy2Provider : CursorPagingProvider + { + public override bool CanHandle(IExtendedType source) => false; - protected override ValueTask SliceAsync( - IResolverContext context, - object source, - CursorPagingArguments arguments) - => new(new Connection( - new[] { new Edge("d", "e") }, - new ConnectionPageInfo(false, false, null, null), - _ => new(1))); - } + protected override CursorPagingHandler CreateHandler( + IExtendedType source, + PagingOptions options) + => new Dummy2Handler(options); + } - public class BackwardQuery + public class Dummy2Handler : CursorPagingHandler + { + public Dummy2Handler(PagingOptions options) : base(options) { - [UsePaging(AllowBackwardPagination = false)] - public Connection GetFoos(int? first, string? after) - => new Connection( - new[] { new Edge("abc", "def") }, - new ConnectionPageInfo(false, false, null, null), - _ => new(1)); } - public class CustomConnectionQuery - { - [UsePaging(IncludeTotalCount = true)] - public Connection GetFoos(int? first, string? after) - => new Connection( - new[] {new Edge("abc", "def"), new Edge("abc", "def")}, - new ConnectionPageInfo(false, false, null, null), 2); - } + protected override ValueTask SliceAsync( + IResolverContext context, + object source, + CursorPagingArguments arguments) + => new(new Connection( + new[] { new Edge("d", "e") }, + new ConnectionPageInfo(false, false, null, null), + _ => new(1))); + } + + public class BackwardQuery + { + [UsePaging(AllowBackwardPagination = false)] + public Connection GetFoos(int? first, string? after) + => new Connection( + new[] { new Edge("abc", "def") }, + new ConnectionPageInfo(false, false, null, null), + _ => new(1)); + } + + public class CustomConnectionQuery + { + [UsePaging(IncludeTotalCount = true)] + public Connection GetFoos(int? first, string? after) + => new Connection( + new[] {new Edge("abc", "def"), new Edge("abc", "def")}, + new ConnectionPageInfo(false, false, null, null), 2); } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/MockExecutable.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/MockExecutable.cs index bc01c34e7dc..3b8461621a4 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/MockExecutable.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/MockExecutable.cs @@ -3,37 +3,36 @@ using System.Threading; using System.Threading.Tasks; -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class MockExecutable : IExecutable { - public class MockExecutable : IExecutable + private readonly IQueryable _source; + + public MockExecutable(IQueryable source) + { + _source = source; + } + + public object Source => _source; + + public ValueTask ToListAsync(CancellationToken cancellationToken) + { + return new(_source.ToList()); + } + + public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken) + { + return new(_source.FirstOrDefault()); + } + + public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) + { + return new(_source.SingleOrDefault()); + } + + public string Print() { - private readonly IQueryable _source; - - public MockExecutable(IQueryable source) - { - _source = source; - } - - public object Source => _source; - - public ValueTask ToListAsync(CancellationToken cancellationToken) - { - return new(_source.ToList()); - } - - public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken) - { - return new(_source.FirstOrDefault()); - } - - public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) - { - return new(_source.SingleOrDefault()); - } - - public string Print() - { - return _source.ToString()!; - } + return _source.ToString()!; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/PagingObjectFieldDescriptorExtensions.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/PagingObjectFieldDescriptorExtensions.cs index f843c510af8..d116e53a0f4 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/PagingObjectFieldDescriptorExtensions.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/PagingObjectFieldDescriptorExtensions.cs @@ -3,40 +3,39 @@ #nullable enable -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class PagingObjectFieldDescriptorExtensionsTests { - public class PagingObjectFieldDescriptorExtensionsTests + [Fact] + public static void ObjectFieldDescriptor_UseOffsetPaging_Descriptor_Is_Null() { - [Fact] - public static void ObjectFieldDescriptor_UseOffsetPaging_Descriptor_Is_Null() - { - Assert.Throws( - () => PagingObjectFieldDescriptorExtensions.UsePaging( - default(IObjectFieldDescriptor)!)); - } + Assert.Throws( + () => PagingObjectFieldDescriptorExtensions.UsePaging( + default(IObjectFieldDescriptor)!)); + } - [Fact] - public static void ObjectFieldDescriptor_AddOffsetPagingArguments_Descriptor_Is_Null() - { - Assert.Throws( - () => PagingObjectFieldDescriptorExtensions.AddPagingArguments( - default(IObjectFieldDescriptor)!)); - } + [Fact] + public static void ObjectFieldDescriptor_AddOffsetPagingArguments_Descriptor_Is_Null() + { + Assert.Throws( + () => PagingObjectFieldDescriptorExtensions.AddPagingArguments( + default(IObjectFieldDescriptor)!)); + } - [Fact] - public static void InterfaceFieldDescriptor_UseOffsetPaging_Descriptor_Is_Null() - { - Assert.Throws( - () => PagingObjectFieldDescriptorExtensions.UsePaging( - default(IInterfaceFieldDescriptor)!)); - } + [Fact] + public static void InterfaceFieldDescriptor_UseOffsetPaging_Descriptor_Is_Null() + { + Assert.Throws( + () => PagingObjectFieldDescriptorExtensions.UsePaging( + default(IInterfaceFieldDescriptor)!)); + } - [Fact] - public static void InterfaceFieldDescriptor_AddOffsetPagingArguments_Descriptor_Is_Null() - { - Assert.Throws( - () => PagingObjectFieldDescriptorExtensions.AddPagingArguments( - default(IInterfaceFieldDescriptor)!)); - } + [Fact] + public static void InterfaceFieldDescriptor_AddOffsetPagingArguments_Descriptor_Is_Null() + { + Assert.Throws( + () => PagingObjectFieldDescriptorExtensions.AddPagingArguments( + default(IInterfaceFieldDescriptor)!)); } } \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/QueryableCursorPagingProviderTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/QueryableCursorPagingProviderTests.cs index 32a00f68af6..1b2010cf909 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/QueryableCursorPagingProviderTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/QueryableCursorPagingProviderTests.cs @@ -7,7 +7,7 @@ using System.Threading; using System.Threading.Tasks; using HotChocolate.Execution; -using HotChocolate.Internal; +using HotChocolate.Execution.Processing; using HotChocolate.Language; using HotChocolate.Resolvers; using HotChocolate.Types.Descriptors; @@ -15,613 +15,599 @@ #nullable enable -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class QueryableCursorPagingProviderTests { - public class QueryableCursorPagingProviderTests + [Fact] + public async Task TakeFirst() { - [Fact] - public async Task TakeFirst() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); - - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); - - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - - var pagingDetails = new CursorPagingArguments(2); - var context = new MockContext(pagingDetails); - - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); - - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("a", t.Node); - Assert.Equal(0, GetPositionFromCursor(t.Cursor)); - }, - t => - { - Assert.Equal("b", t.Node); - Assert.Equal(1, GetPositionFromCursor(t.Cursor)); - }); - - Assert.False( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - - Assert.True( - connection.Info.HasNextPage, - "HasNextPage"); - } + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - [Fact] - public async Task TakeLastSingle() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + var pagingDetails = new CursorPagingArguments(2); + var context = new MockContext(pagingDetails); - var list = new List { "f", "g" }; + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - var pagingDetails = new CursorPagingArguments(last: 1); - var context = new MockContext(pagingDetails); + // assert + Assert.Collection(connection.Edges, + t => + { + Assert.Equal("a", t.Node); + Assert.Equal(0, GetPositionFromCursor(t.Cursor)); + }, + t => + { + Assert.Equal("b", t.Node); + Assert.Equal(1, GetPositionFromCursor(t.Cursor)); + }); - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); + Assert.False( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("g", t.Node); - Assert.Equal(1, GetPositionFromCursor(t.Cursor)); - }); + Assert.True( + connection.Info.HasNextPage, + "HasNextPage"); + } - Assert.True( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - Assert.False( - connection.Info.HasNextPage, - "HasNextPage"); - } + [Fact] + public async Task TakeLastSingle() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - [Fact] - public async Task TakeLast() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); - - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); - - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - - var pagingDetails = new CursorPagingArguments(last: 2); - var context = new MockContext(pagingDetails); - - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); - - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("f", t.Node); - Assert.Equal(5, GetPositionFromCursor(t.Cursor)); - }, - t => - { - Assert.Equal("g", t.Node); - Assert.Equal(6, GetPositionFromCursor(t.Cursor)); - }); - - Assert.True( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - - Assert.False( - connection.Info.HasNextPage, - "HasNextPage"); - } + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - [Fact] - public async Task TakeFirstAfter() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); - - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); - - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - - var pagingDetails = new CursorPagingArguments(); - var context = new MockContext(pagingDetails); - var connection = (Connection)await pagingHandler.SliceAsync(context, list); - - pagingDetails = new CursorPagingArguments(after: connection.Info.StartCursor, first: 2); - context = new MockContext(pagingDetails); - - // act - connection = (Connection)await pagingHandler.SliceAsync(context, list); - - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("b", t.Node); - Assert.Equal(1, GetPositionFromCursor(t.Cursor)); - }, - t => - { - Assert.Equal("c", t.Node); - Assert.Equal(2, GetPositionFromCursor(t.Cursor)); - }); - - Assert.True( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - - Assert.True( - connection.Info.HasNextPage, - "HasNextPage"); - } + var list = new List { "f", "g" }; - [Fact] - public async Task TakeLastBefore() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); - - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); - - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - - var pagingDetails = new CursorPagingArguments(first: 5); - var context = new MockContext(pagingDetails); - var connection = (Connection)await pagingHandler.SliceAsync(context, list); - - pagingDetails = new CursorPagingArguments(before: connection.Info.EndCursor, last: 2); - context = new MockContext(pagingDetails); - - // act - connection = (Connection)await pagingHandler.SliceAsync(context, list); - - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("c", t.Node); - Assert.Equal(2, GetPositionFromCursor(t.Cursor)); - }, - t => - { - Assert.Equal("d", t.Node); - Assert.Equal(3, GetPositionFromCursor(t.Cursor)); - }); - - Assert.True( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - - Assert.True( - connection.Info.HasNextPage, - "HasNextPage"); - } + var pagingDetails = new CursorPagingArguments(last: 1); + var context = new MockContext(pagingDetails); - [Fact] - public async Task HasNextPage_True() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + // assert + Assert.Collection(connection.Edges, + t => + { + Assert.Equal("g", t.Node); + Assert.Equal(1, GetPositionFromCursor(t.Cursor)); + }); - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; + Assert.True( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - var pagingDetails = new CursorPagingArguments(first: 5); - var context = new MockContext(pagingDetails); + Assert.False( + connection.Info.HasNextPage, + "HasNextPage"); + } - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); + [Fact] + public async Task TakeLast() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - // assert - Assert.True(connection.Info.HasNextPage); - } + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - [Fact] - public async Task HasNextPage_False() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + var pagingDetails = new CursorPagingArguments(last: 2); + var context = new MockContext(pagingDetails); - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - var pagingDetails = new CursorPagingArguments(first: 7); - var context = new MockContext(pagingDetails); + // assert + Assert.Collection(connection.Edges, + t => + { + Assert.Equal("f", t.Node); + Assert.Equal(5, GetPositionFromCursor(t.Cursor)); + }, + t => + { + Assert.Equal("g", t.Node); + Assert.Equal(6, GetPositionFromCursor(t.Cursor)); + }); - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); + Assert.True( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - // assert - Assert.False(connection.Info.HasNextPage); - } + Assert.False( + connection.Info.HasNextPage, + "HasNextPage"); + } - [Fact] - public async Task HasPrevious_True() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + [Fact] + public async Task TakeFirstAfter() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - var pagingDetails = new CursorPagingArguments(first: 1); - var context = new MockContext(pagingDetails); - var connection = (Connection)await pagingHandler.SliceAsync(context, list); + var pagingDetails = new CursorPagingArguments(); + var context = new MockContext(pagingDetails); + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - pagingDetails = new CursorPagingArguments(after: connection.Info.EndCursor, first: 2); - context = new MockContext(pagingDetails); + pagingDetails = new CursorPagingArguments(after: connection.Info.StartCursor, first: 2); + context = new MockContext(pagingDetails); - // act - connection = (Connection)await pagingHandler.SliceAsync(context, list); + // act + connection = (Connection)await pagingHandler.SliceAsync(context, list); - // assert - Assert.True(connection.Info.HasPreviousPage); - } + // assert + Assert.Collection(connection.Edges, + t => + { + Assert.Equal("b", t.Node); + Assert.Equal(1, GetPositionFromCursor(t.Cursor)); + }, + t => + { + Assert.Equal("c", t.Node); + Assert.Equal(2, GetPositionFromCursor(t.Cursor)); + }); - [Fact] - public async Task HasPrevious_False() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + Assert.True( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + Assert.True( + connection.Info.HasNextPage, + "HasNextPage"); + } - var list = new List { "a", "b", "c", "d", "e", "f", "g" }; + [Fact] + public async Task TakeLastBefore() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - var pagingDetails = new CursorPagingArguments(first: 1); - var context = new MockContext(pagingDetails); + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - // assert - Assert.False(connection.Info.HasPreviousPage); - } + var pagingDetails = new CursorPagingArguments(first: 5); + var context = new MockContext(pagingDetails); + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - [Fact] - public async Task Executable() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + pagingDetails = new CursorPagingArguments(before: connection.Info.EndCursor, last: 2); + context = new MockContext(pagingDetails); - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + // act + connection = (Connection)await pagingHandler.SliceAsync(context, list); - var list = new MockExecutable(new [] + // assert + Assert.Collection(connection.Edges, + t => + { + Assert.Equal("c", t.Node); + Assert.Equal(2, GetPositionFromCursor(t.Cursor)); + }, + t => { - "a", - "b", - "c", - "d", - "e", - "f", - "g" + Assert.Equal("d", t.Node); + Assert.Equal(3, GetPositionFromCursor(t.Cursor)); }); - var pagingDetails = new CursorPagingArguments(2); - var context = new MockContext(pagingDetails); - - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); - - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("a", t.Node); - Assert.Equal(0, GetPositionFromCursor(t.Cursor)); - }, - t => - { - Assert.Equal("b", t.Node); - Assert.Equal(1, GetPositionFromCursor(t.Cursor)); - }); - - Assert.False( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - - Assert.True( - connection.Info.HasNextPage, - "HasNextPage"); - } + Assert.True( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - [Fact] - public async Task Executable_Queryable() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType sourceType = typeInspector.GetType(typeof(List)); + Assert.True( + connection.Info.HasNextPage, + "HasNextPage"); + } - IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); - IPagingHandler pagingHandler = pagingProvider.CreateHandler(sourceType, default); + [Fact] + public async Task HasNextPage_True() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - var list = new MockExecutable(new [] - { - "a", - "b", - "c", - "d", - "e", - "f", - "g" - }.AsQueryable()); - - var pagingDetails = new CursorPagingArguments(2); - var context = new MockContext(pagingDetails); - - // act - var connection = (Connection)await pagingHandler.SliceAsync(context, list); - - // assert - Assert.Collection(connection.Edges, - t => - { - Assert.Equal("a", t.Node); - Assert.Equal(0, GetPositionFromCursor(t.Cursor)); - }, - t => - { - Assert.Equal("b", t.Node); - Assert.Equal(1, GetPositionFromCursor(t.Cursor)); - }); - - Assert.False( - connection.Info.HasPreviousPage, - "HasPreviousPage"); - - Assert.True( - connection.Info.HasNextPage, - "HasNextPage"); - } + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - private int GetPositionFromCursor(string cursor) - { - return int.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(cursor))); - } + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - public class MockContext : IResolverContext - { - private readonly CursorPagingArguments _arguments; + var pagingDetails = new CursorPagingArguments(first: 5); + var context = new MockContext(pagingDetails); - public MockContext(CursorPagingArguments arguments) - { - _arguments = arguments; - } + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - public IServiceProvider Services - { - get => throw new NotImplementedException(); - set => throw new NotImplementedException(); - } + // assert + Assert.True(connection.Info.HasNextPage); + } + + [Fact] + public async Task HasNextPage_False() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - public ISchema Schema => throw new NotImplementedException(); + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - public IObjectType RootType => throw new NotImplementedException(); + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - public IObjectType ObjectType => throw new NotImplementedException(); + var pagingDetails = new CursorPagingArguments(first: 7); + var context = new MockContext(pagingDetails); - public IObjectField Field => throw new NotImplementedException(); + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - public DocumentNode Document => throw new NotImplementedException(); + // assert + Assert.False(connection.Info.HasNextPage); + } - public OperationDefinitionNode Operation => throw new NotImplementedException(); + [Fact] + public async Task HasPrevious_True() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - public FieldNode FieldSelection => throw new NotImplementedException(); + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - public IFieldSelection Selection => throw new NotImplementedException(); + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; - public NameString ResponseName => throw new NotImplementedException(); + var pagingDetails = new CursorPagingArguments(first: 1); + var context = new MockContext(pagingDetails); + var connection = (Connection)await pagingHandler.SliceAsync(context, list); - public Path Path => throw new NotImplementedException(); + pagingDetails = new CursorPagingArguments(after: connection.Info.EndCursor, first: 2); + context = new MockContext(pagingDetails); - public bool HasErrors => throw new NotImplementedException(); + // act + connection = (Connection)await pagingHandler.SliceAsync(context, list); - public IImmutableDictionary ScopedContextData + // assert + Assert.True(connection.Info.HasPreviousPage); + } + + [Fact] + public async Task HasPrevious_False() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); + + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); + + var list = new List { "a", "b", "c", "d", "e", "f", "g" }; + + var pagingDetails = new CursorPagingArguments(first: 1); + var context = new MockContext(pagingDetails); + + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); + + // assert + Assert.False(connection.Info.HasPreviousPage); + } + + [Fact] + public async Task Executable() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); + + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); + + var list = new MockExecutable(new [] + { + "a", + "b", + "c", + "d", + "e", + "f", + "g" + }); + + var pagingDetails = new CursorPagingArguments(2); + var context = new MockContext(pagingDetails); + + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); + + // assert + Assert.Collection(connection.Edges, + t => { - get => throw new NotImplementedException(); - set => throw new NotImplementedException(); - } - public IImmutableDictionary LocalContextData + Assert.Equal("a", t.Node); + Assert.Equal(0, GetPositionFromCursor(t.Cursor)); + }, + t => { - get => throw new NotImplementedException(); - set => throw new NotImplementedException(); - } + Assert.Equal("b", t.Node); + Assert.Equal(1, GetPositionFromCursor(t.Cursor)); + }); - public IVariableValueCollection Variables => throw new NotImplementedException(); + Assert.False( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - public CancellationToken RequestAborted => default; + Assert.True( + connection.Info.HasNextPage, + "HasNextPage"); + } - public IDictionary ContextData => throw new NotImplementedException(); + [Fact] + public async Task Executable_Queryable() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var sourceType = typeInspector.GetType(typeof(List)); - public T Argument(NameString name) - { - throw new NotImplementedException(); - } + IPagingProvider pagingProvider = new QueryableCursorPagingProvider(); + var pagingHandler = pagingProvider.CreateHandler(sourceType, default); - public ValueKind ArgumentKind(NameString name) + var list = new MockExecutable(new [] + { + "a", + "b", + "c", + "d", + "e", + "f", + "g" + }.AsQueryable()); + + var pagingDetails = new CursorPagingArguments(2); + var context = new MockContext(pagingDetails); + + // act + var connection = (Connection)await pagingHandler.SliceAsync(context, list); + + // assert + Assert.Collection(connection.Edges, + t => { - throw new NotImplementedException(); - } - - public TValueNode ArgumentLiteral(NameString name) - where TValueNode : IValueNode + Assert.Equal("a", t.Node); + Assert.Equal(0, GetPositionFromCursor(t.Cursor)); + }, + t => { - throw new NotImplementedException(); - } + Assert.Equal("b", t.Node); + Assert.Equal(1, GetPositionFromCursor(t.Cursor)); + }); - public Optional ArgumentOptional(NameString name) - { - throw new NotImplementedException(); - } + Assert.False( + connection.Info.HasPreviousPage, + "HasPreviousPage"); - public T ArgumentValue(NameString name) - { - switch (name.Value) - { - case "first": - if (_arguments.First is null) - { - return default!; - } - if (_arguments.First is T first) - { - return first; - } - break; - case "last": - if (_arguments.Last is null) - { - return default!; - } - if (_arguments.Last is T last) - { - return last; - } - break; - case "after": - if (_arguments.After is null) - { - return default!; - } - if (_arguments.After is T after) - { - return after; - } - break; - case "before": - if (_arguments.Before is null) - { - return default!; - } - if (_arguments.Before is T before) - { - return before; - } - break; - } - - throw new NotSupportedException(); - } + Assert.True( + connection.Info.HasNextPage, + "HasNextPage"); + } - public void ReportError(Exception exception, Action? configure = null) - { - throw new NotImplementedException(); - } + private int GetPositionFromCursor(string cursor) + { + return int.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(cursor))); + } - public IReadOnlyList GetSelections( - ObjectType typeContext, - IFieldSelection? selection = null, - bool allowInternals = false) - { - throw new NotImplementedException(); - } + private sealed class MockContext : IResolverContext + { + private readonly CursorPagingArguments _arguments; - public T GetQueryRoot() - { - throw new NotImplementedException(); - } + public MockContext(CursorPagingArguments arguments) + { + _arguments = arguments; + } - public T Parent() - { - throw new NotImplementedException(); - } + public IServiceProvider Services + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } - public void ReportError(string errorMessage) - { - throw new NotImplementedException(); - } + public NameString ResponseName => throw new NotImplementedException(); - public void ReportError(IError error) - { - throw new NotImplementedException(); - } + public bool HasErrors => throw new NotImplementedException(); - public T Resolver() - { - throw new NotImplementedException(); - } + public IImmutableDictionary ScopedContextData + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } - public T Service() - { - throw new NotImplementedException(); - } + public IImmutableDictionary LocalContextData + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } - public object Service(Type service) - { - throw new NotImplementedException(); - } + public CancellationToken RequestAborted => default; + + public object Service(Type service) + { + throw new NotImplementedException(); } - public class MockExecutable : IExecutable - where T : class + public void ReportError(string errorMessage) { - private readonly IEnumerable _source; + throw new NotImplementedException(); + } - public MockExecutable(IEnumerable source) - { - _source = source; - } + public void ReportError(IError error) + { + throw new NotImplementedException(); + } - public object Source => _source; + public void ReportError(Exception exception, Action? configure = null) + { + throw new NotImplementedException(); + } - public ValueTask ToListAsync(CancellationToken cancellationToken) - { - return new(_source.ToList()); - } + public IReadOnlyList GetSelections( + IObjectType typeContext, + ISelection? selection = null, + bool allowInternals = false) + { + throw new NotImplementedException(); + } - public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken) - { - return new(_source.FirstOrDefault()); - } + public T GetQueryRoot() + { + throw new NotImplementedException(); + } - public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) - { - return new(_source.SingleOrDefault()); - } + public ISchema Schema => throw new NotImplementedException(); - public string Print() + public IObjectType ObjectType => throw new NotImplementedException(); + + public IOperation Operation => throw new NotImplementedException(); + + public ISelection Selection => throw new NotImplementedException(); + + public IVariableValueCollection Variables => throw new NotImplementedException(); + + public Path Path => throw new NotImplementedException(); + + public T Parent() + { + throw new NotImplementedException(); + } + + public T ArgumentValue(NameString name) + { + switch (name.Value) { - return _source.ToString()!; + case "first": + if (_arguments.First is null) + { + return default!; + } + if (_arguments.First is T first) + { + return first; + } + break; + case "last": + if (_arguments.Last is null) + { + return default!; + } + if (_arguments.Last is T last) + { + return last; + } + break; + case "after": + if (_arguments.After is null) + { + return default!; + } + if (_arguments.After is T after) + { + return after; + } + break; + case "before": + if (_arguments.Before is null) + { + return default!; + } + if (_arguments.Before is T before) + { + return before; + } + break; } + + throw new InvalidOperationException(); + } + + public TValueNode ArgumentLiteral(NameString name) where TValueNode : IValueNode + { + throw new NotImplementedException(); + } + + public Optional ArgumentOptional(NameString name) + { + throw new NotImplementedException(); + } + + public ValueKind ArgumentKind(NameString name) + { + throw new NotImplementedException(); + } + + public T Service() + { + throw new NotImplementedException(); + } + + public T Resolver() + { + throw new NotImplementedException(); + } + + public IDictionary ContextData => throw new NotImplementedException(); + } + + private sealed class MockExecutable : IExecutable + where T : class + { + private readonly IEnumerable _source; + + public MockExecutable(IEnumerable source) + { + _source = source; + } + + public object Source => _source; + + public ValueTask ToListAsync(CancellationToken cancellationToken) + { + return new(_source.ToList()); + } + + public ValueTask FirstOrDefaultAsync(CancellationToken cancellationToken) + { + return new(_source.FirstOrDefault()); + } + + public ValueTask SingleOrDefaultAsync(CancellationToken cancellationToken) + { + return new(_source.SingleOrDefault()); + } + + public string Print() + { + return _source.ToString()!; } } } diff --git a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/UsePagingAttributeTests.cs b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/UsePagingAttributeTests.cs index c2b47e6cebd..cb396fa1191 100644 --- a/src/HotChocolate/Core/test/Types.CursorPagination.Tests/UsePagingAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.CursorPagination.Tests/UsePagingAttributeTests.cs @@ -8,218 +8,217 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Pagination +namespace HotChocolate.Types.Pagination; + +public class UsePagingAttributeTests { - public class UsePagingAttributeTests + [Fact] + public async Task UsePagingAttribute_Infer_Types() { - [Fact] - public async Task UsePagingAttribute_Infer_Types() - { - Snapshot.FullName(); + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .GetSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .GetSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task UsePagingAttribute_Execute_Query() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .Services + .BuildServiceProvider() + .ExecuteRequestAsync("{ foos(first: 1) { nodes { bar } } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task UsePagingAttribute_Execute_Query() - { - Snapshot.FullName(); + [Fact] + public async Task UsePagingAttribute_Infer_Types_On_Interface() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddType() + .ModifyOptions(o => o.StrictValidation = false) + .Services + .BuildServiceProvider() + .GetSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .Services - .BuildServiceProvider() - .ExecuteRequestAsync("{ foos(first: 1) { nodes { bar } } }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task UsePagingAttribute_On_Extension_Infer_Types() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .Services + .BuildServiceProvider() + .GetSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task UsePagingAttribute_Infer_Types_On_Interface() - { - Snapshot.FullName(); + [Fact] + public async Task UsePagingAttribute_On_Extension_Execute_Query() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .Services + .BuildServiceProvider() + .ExecuteRequestAsync("{ foos(first: 1) { nodes { bar } } }") + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddType() - .ModifyOptions(o => o.StrictValidation = false) - .Services - .BuildServiceProvider() - .GetSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Ensure_Attributes_Are_Applied_Once() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task UsePagingAttribute_On_Extension_Infer_Types() - { - Snapshot.FullName(); + [Fact] + public async Task Ensure_Attributes_Are_Applied_Once_Execute_Query() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .ExecuteRequestAsync("{ foos(first: 1) { nodes { bar } } }") + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType() - .Services - .BuildServiceProvider() - .GetSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task UnknownNodeType() + { + Snapshot.FullName(); - [Fact] - public async Task UsePagingAttribute_On_Extension_Execute_Query() + try { - Snapshot.FullName(); - await new ServiceCollection() .AddGraphQL() .AddQueryType() - .AddType() - .Services - .BuildServiceProvider() - .ExecuteRequestAsync("{ foos(first: 1) { nodes { bar } } }") - .MatchSnapshotAsync(); + .AddType() + .BuildSchemaAsync(); } - - [Fact] - public async Task Ensure_Attributes_Are_Applied_Once() + catch (SchemaException ex) { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task Ensure_Attributes_Are_Applied_Once_Execute_Query() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType() - .ExecuteRequestAsync("{ foos(first: 1) { nodes { bar } } }") - .MatchSnapshotAsync(); - } - - [Fact] - public async Task UnknownNodeType() - { - Snapshot.FullName(); - - try + new { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType() - .BuildSchemaAsync(); - } - catch (SchemaException ex) - { - new - { - ex.Errors[0].Message, - ex.Errors[0].Code - }.MatchSnapshot(); - } + ex.Errors[0].Message, + ex.Errors[0].Code + }.MatchSnapshot(); } + } - [Fact] - public void UsePagingAttribute_Can_Use_Defaults() - { - var attr = new UsePagingAttribute(); + [Fact] + public void UsePagingAttribute_Can_Use_Defaults() + { + var attr = new UsePagingAttribute(); - Assert.True(attr.AllowBackwardPagination); - Assert.True(attr.InferConnectionNameFromField); - Assert.False(attr.RequirePagingBoundaries); - } + Assert.True(attr.AllowBackwardPagination); + Assert.True(attr.InferConnectionNameFromField); + Assert.False(attr.RequirePagingBoundaries); + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - } + descriptor.Name("Query"); } + } - public class Query + public class Query + { + [UsePaging] + public IQueryable Foos () { - [UsePaging] - public IQueryable Foos () + return new List { - return new List - { - new Foo { Bar = "first" }, - new Foo { Bar = "second" }, - }.AsQueryable(); - } + new Foo { Bar = "first" }, + new Foo { Bar = "second" }, + }.AsQueryable(); } + } - public class Query1 + public class Query1 + { + public IQueryable Foos () { - public IQueryable Foos () + return new List { - return new List - { - new Foo { Bar = "first" }, - new Foo { Bar = "second" }, - }.AsQueryable(); - } + new Foo { Bar = "first" }, + new Foo { Bar = "second" }, + }.AsQueryable(); } + } - [Node] - [ExtendObjectType(typeof(Query1))] - public class Query1Extensions + [Node] + [ExtendObjectType(typeof(Query1))] + public class Query1Extensions + { + [UsePaging] + [BindMember(nameof(Query1.Foos))] + public IQueryable Foos () { - [UsePaging] - [BindMember(nameof(Query1.Foos))] - public IQueryable Foos () + return new List { - return new List - { - new Foo { Bar = "first" }, - new Foo { Bar = "second" }, - }.AsQueryable(); - } - - [NodeResolver] - public Query1 GetQuery() - { - return new Query1(); - } + new Foo { Bar = "first" }, + new Foo { Bar = "second" }, + }.AsQueryable(); } - [ExtendObjectType("Query")] - public class QueryExtension : Query + [NodeResolver] + public Query1 GetQuery() { + return new Query1(); } + } - public class Foo - { - public string Bar { get; set; } - } + [ExtendObjectType("Query")] + public class QueryExtension : Query + { + } - public interface IHasFoos - { - [UsePaging] - IQueryable Foos { get; } - } + public class Foo + { + public string Bar { get; set; } + } - [ExtendObjectType("Query")] - public class NoNodeType - { - [UsePaging] - public int GetSomething() => 1; - } + public interface IHasFoos + { + [UsePaging] + IQueryable Foos { get; } + } + + [ExtendObjectType("Query")] + public class NoNodeType + { + [UsePaging] + public int GetSomething() => 1; } -} +} \ No newline at end of file diff --git a/src/HotChocolate/Core/test/Types.Tests/CodeFirstTests.cs b/src/HotChocolate/Core/test/Types.Tests/CodeFirstTests.cs index e34e3fbf49d..bb6fccbcce7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/CodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/CodeFirstTests.cs @@ -11,278 +11,277 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class CodeFirstTests { - public class CodeFirstTests + [Fact] + public void InferSchemaWithNonNullRefTypes() { - [Fact] - public void InferSchemaWithNonNullRefTypes() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .Create() - .ToString() - .MatchSnapshot(); - } + SchemaBuilder.New() + .AddQueryType() + .AddType() + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void InferSchemaWithNonNullRefTypesAndGenerics() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void InferSchemaWithNonNullRefTypesAndGenerics() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Type_Is_Correctly_Upgraded() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType>() - .AddType() - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void Type_Is_Correctly_Upgraded() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType>() + .AddType() + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Change_DefaultBinding_For_DateTime() - { - SchemaBuilder.New() - .AddQueryType() - .BindClrType() - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void Change_DefaultBinding_For_DateTime() + { + SchemaBuilder.New() + .AddQueryType() + .BindClrType() + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Remove_ClrType_Bindings_That_Are_Not_Used() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .BindClrType() - .BindClrType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); - - // assert - bool exists = schema.TryGetType("Url", out INamedType _); - Assert.False(exists); - } + [Fact] + public void Remove_ClrType_Bindings_That_Are_Not_Used() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .BindClrType() + .BindClrType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); + + // assert + var exists = schema.TryGetType("Url", out INamedType _); + Assert.False(exists); + } - [Fact] - public void Infer_Interface_Usage() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Infer_Interface_Usage() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void Infer_Interface_Usage_With_Interfaces_Implementing_Interfaces() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Infer_Interface_Usage_With_Interfaces_Implementing_Interfaces() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public async Task Default_Type_Resolution_Shall_Be_Exact() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => - { - d.Name("Query"); - d.Field("shouldBeCat").Type>().Resolve(new Cat()); - d.Field("shouldBeDog").Type>().Resolve(new Dog()); - }) - .AddType() - .AddType() - .ExecuteRequestAsync("{ shouldBeCat { __typename } shouldBeDog { __typename } }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Default_Type_Resolution_Shall_Be_Exact() + { + Snapshot.FullName(); - [Fact] - public async Task Default_Type_Resolution_Shall_Be_Exact_Schema() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => - { - d.Name("Query"); - d.Field("shouldBeCat").Type>().Resolve(new Cat()); - d.Field("shouldBeDog").Type>().Resolve(new Dog()); - }) - .AddType() - .AddType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => + { + d.Name("Query"); + d.Field("shouldBeCat").Type>().Resolve(new Cat()); + d.Field("shouldBeDog").Type>().Resolve(new Dog()); + }) + .AddType() + .AddType() + .ExecuteRequestAsync("{ shouldBeCat { __typename } shouldBeDog { __typename } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Structureal_Equality_Is_Ignored() - { - Snapshot.FullName(); + [Fact] + public async Task Default_Type_Resolution_Shall_Be_Exact_Schema() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => + { + d.Name("Query"); + d.Field("shouldBeCat").Type>().Resolve(new Cat()); + d.Field("shouldBeDog").Type>().Resolve(new Dog()); + }) + .AddType() + .AddType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - public class Query - { - public string SayHello(string name) => - throw new NotImplementedException(); + [Fact] + public async Task Structureal_Equality_Is_Ignored() + { + Snapshot.FullName(); - public Greetings GetGreetings(Greetings greetings) => - throw new NotImplementedException(); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - public IPet GetPet() => - throw new NotImplementedException(); + public class Query + { + public string SayHello(string name) => + throw new NotImplementedException(); - public Task GetPetOrNull() => - throw new NotImplementedException(); - } + public Greetings GetGreetings(Greetings greetings) => + throw new NotImplementedException(); - public class QueryWithGenerics - { - public Task GetPet(int id, CancellationToken cancellationToken) => - throw new NotImplementedException(); - - // The arguments are needed to make the compiler apply attributes as expected - // for this use case. It's not entirely clear what combination of arguments - // for this and other fields on the class makes it behave this way - // We want the compiler to apply these attributes to the GetPets method - // [NullableContext(2)] - // [return: Nullable(1)] - public Task> GetPets( - int? arg1, - bool? arg2, - bool? arg3, - string? arg4, - GenericWrapper? arg5, - Greetings? arg6, - CancellationToken cancellationToken) => - throw new NotImplementedException(); - } + public IPet GetPet() => + throw new NotImplementedException(); - public class GenericWrapper - { - public T Value { get; set; } = default!; - } + public Task GetPetOrNull() => + throw new NotImplementedException(); + } - public class Greetings - { - public string Name { get; set; } = "Foo"; - } + public class QueryWithGenerics + { + public Task GetPet(int id, CancellationToken cancellationToken) => + throw new NotImplementedException(); + + // The arguments are needed to make the compiler apply attributes as expected + // for this use case. It's not entirely clear what combination of arguments + // for this and other fields on the class makes it behave this way + // We want the compiler to apply these attributes to the GetPets method + // [NullableContext(2)] + // [return: Nullable(1)] + public Task> GetPets( + int? arg1, + bool? arg2, + bool? arg3, + string? arg4, + GenericWrapper? arg5, + Greetings? arg6, + CancellationToken cancellationToken) => + throw new NotImplementedException(); + } - public interface IPet - { - string? Name { get; } - } + public class GenericWrapper + { + public T Value { get; set; } = default!; + } - public class DogType : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field("isMale").Resolve(true); - } - } + public class Greetings + { + public string Name { get; set; } = "Foo"; + } - public class Dog : IPet - { - public string? Name => - throw new NotImplementedException(); - } + public interface IPet + { + string? Name { get; } + } - public class Cat : Dog + public class DogType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { + descriptor.Field("isMale").Resolve(true); } + } - public class QueryWithDateTimeType : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.GetModel()).Type(); - } - } + public class Dog : IPet + { + public string? Name => + throw new NotImplementedException(); + } + + public class Cat : Dog + { + } - public class QueryWithDateTime + public class QueryWithDateTimeType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - public ModelWithDateTime GetModel() => new ModelWithDateTime(); + descriptor.Field(t => t.GetModel()).Type(); } + } - public class ModelWithDateTimeType : ObjectType + public class QueryWithDateTime + { + public ModelWithDateTime GetModel() => new ModelWithDateTime(); + } + + public class ModelWithDateTimeType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Foo).Type(); - } + descriptor.Field(t => t.Foo).Type(); } + } - public class ModelWithDateTime - { - public DateTime Foo { get; set; } + public class ModelWithDateTime + { + public DateTime Foo { get; set; } - public DateTime Bar { get; set; } - } + public DateTime Bar { get; set; } + } - public class QueryInterfaces - { - public IFoo GetFoo() => new Foo(); - } + public class QueryInterfaces + { + public IFoo GetFoo() => new Foo(); + } - public class Foo : IFoo - { - public string GetBar() => "Bar"; + public class Foo : IFoo + { + public string GetBar() => "Bar"; - public string GetFoo() => "Foo"; - } + public string GetFoo() => "Foo"; + } - public interface IFoo : IBar - { - string GetFoo(); - } + public interface IFoo : IBar + { + string GetFoo(); + } - public interface IBar - { - string GetBar(); - } + public interface IBar + { + string GetBar(); + } - public class QueryStructEquals - { - public Example Foo(Example example) => example; - } + public class QueryStructEquals + { + public Example Foo(Example example) => example; + } - public class Example : IStructuralEquatable - { - public string Some { get; set; } + public class Example : IStructuralEquatable + { + public string Some { get; set; } - public bool Equals(object? other, IEqualityComparer comparer) => throw new NotImplementedException(); + public bool Equals(object? other, IEqualityComparer comparer) => throw new NotImplementedException(); - public int GetHashCode(IEqualityComparer comparer) => throw new NotImplementedException(); - } + public int GetHashCode(IEqualityComparer comparer) => throw new NotImplementedException(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/MiddlewareConfigurationTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/MiddlewareConfigurationTests.cs index a1d45dc15b3..26becbb9d39 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/MiddlewareConfigurationTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/MiddlewareConfigurationTests.cs @@ -5,96 +5,95 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class MiddlewareConfigurationTests { - public class MiddlewareConfigurationTests + [Fact] + public async Task MiddlewareConfig_MapWithDelegate() { - [Fact] - public async Task MiddlewareConfig_MapWithDelegate() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String b: String }") - .Map(new FieldReference("Query", "a"), - _ => context => - { - context.Result = "123"; - return default; - }) - .Map(new FieldReference("Query", "b"), - _ => context => - { - context.Result = "456"; - return default; - }) - .Create(); + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String b: String }") + .Map(new FieldReference("Query", "a"), + _ => context => + { + context.Result = "123"; + return default; + }) + .Map(new FieldReference("Query", "b"), + _ => context => + { + context.Result = "456"; + return default; + }) + .Create(); - // act - IExecutionResult result = await schema.MakeExecutable().ExecuteAsync("{ a b }"); + // act + var result = await schema.MakeExecutable().ExecuteAsync("{ a b }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task MiddlewareConfig_MapWithClass() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String b: String }") - .Map(new FieldReference("Query", "a")) - .Map(new FieldReference("Query", "b"), - _ => context => - { - context.Result = "456"; - return default; - }) - .Create(); + [Fact] + public async Task MiddlewareConfig_MapWithClass() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String b: String }") + .Map(new FieldReference("Query", "a")) + .Map(new FieldReference("Query", "b"), + _ => context => + { + context.Result = "456"; + return default; + }) + .Create(); - // act - IExecutionResult result = await schema.MakeExecutable().ExecuteAsync("{ a b }"); + // act + var result = await schema.MakeExecutable().ExecuteAsync("{ a b }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task MiddlewareConfig_MapWithClassFactory() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String b: String }") - .Map(new FieldReference("Query", "a"), - (_, next) => new TestFieldMiddleware(next)) - .Map(new FieldReference("Query", "b"), - _ => context => - { - context.Result = "456"; - return default; - }) - .Create(); + [Fact] + public async Task MiddlewareConfig_MapWithClassFactory() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String b: String }") + .Map(new FieldReference("Query", "a"), + (_, next) => new TestFieldMiddleware(next)) + .Map(new FieldReference("Query", "b"), + _ => context => + { + context.Result = "456"; + return default; + }) + .Create(); - // act - IExecutionResult result = await schema.MakeExecutable().ExecuteAsync("{ a b }"); + // act + var result = await schema.MakeExecutable().ExecuteAsync("{ a b }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - public class TestFieldMiddleware - { - private readonly FieldDelegate _next; + public class TestFieldMiddleware + { + private readonly FieldDelegate _next; - public TestFieldMiddleware(FieldDelegate next) - { - _next = next ?? throw new ArgumentNullException(nameof(next)); - } + public TestFieldMiddleware(FieldDelegate next) + { + _next = next ?? throw new ArgumentNullException(nameof(next)); + } - public ValueTask InvokeAsync(IMiddlewareContext context) - { - context.Result = "123456789"; - return _next(context); - } + public ValueTask InvokeAsync(IMiddlewareContext context) + { + context.Result = "123456789"; + return _next(context); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/ReadOnlySchemaOptionsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/ReadOnlySchemaOptionsTests.cs index 12f40701e4e..ef596a37b54 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/ReadOnlySchemaOptionsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/ReadOnlySchemaOptionsTests.cs @@ -3,120 +3,119 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class ReadOnlySchemaOptionsTests { - public class ReadOnlySchemaOptionsTests + [Fact] + public void Copy_Options() { - [Fact] - public void Copy_Options() - { - // arrange - var options = new SchemaOptions - { - QueryTypeName = "A", - MutationTypeName = "B", - SubscriptionTypeName = "C", - StrictValidation = false, - SortFieldsByName = true, - UseXmlDocumentation = false, - DefaultBindingBehavior = BindingBehavior.Explicit, - FieldMiddleware = FieldMiddlewareApplication.AllFields, - PreserveSyntaxNodes = true - }; - - // act - var copied = new ReadOnlySchemaOptions(options); - var writableCopy = SchemaOptions.FromOptions(copied); - - // assert - copied.MatchSnapshot(); - writableCopy.MatchSnapshot(); - } - - [Fact] - public void Copy_Options_EnableOneOf_EnableDirectiveIntrospection() - { - // arrange - var options = new SchemaOptions - { - QueryTypeName = "A", - MutationTypeName = "B", - SubscriptionTypeName = "C", - StrictValidation = false, - SortFieldsByName = true, - UseXmlDocumentation = false, - DefaultBindingBehavior = BindingBehavior.Explicit, - FieldMiddleware = FieldMiddlewareApplication.AllFields, - PreserveSyntaxNodes = true, - EnableOneOf = true, - EnableDirectiveIntrospection = true - }; - - // act - var copied = new ReadOnlySchemaOptions(options); - var writableCopy = SchemaOptions.FromOptions(copied); - - // assert - copied.MatchSnapshot(); - writableCopy.MatchSnapshot(); - } - - [Fact] - public void Copy_Options_ResolveXmlDocumentationFileName() + // arrange + var options = new SchemaOptions { - // arrange - var options = new SchemaOptions - { - QueryTypeName = "A", - MutationTypeName = "B", - SubscriptionTypeName = "C", - StrictValidation = false, - SortFieldsByName = true, - UseXmlDocumentation = false, - ResolveXmlDocumentationFileName = assembly => "docs.xml", - DefaultBindingBehavior = BindingBehavior.Explicit, - FieldMiddleware = FieldMiddlewareApplication.AllFields, - PreserveSyntaxNodes = true - }; - - // act - var copied = new ReadOnlySchemaOptions(options); - var writableCopy = SchemaOptions.FromOptions(copied); - - // assert - Assert.Same( - options.ResolveXmlDocumentationFileName, - copied.ResolveXmlDocumentationFileName); - - Assert.Same( - copied.ResolveXmlDocumentationFileName, - writableCopy.ResolveXmlDocumentationFileName); - } - - [Fact] - public void Copy_Options_Defaults() + QueryTypeName = "A", + MutationTypeName = "B", + SubscriptionTypeName = "C", + StrictValidation = false, + SortFieldsByName = true, + UseXmlDocumentation = false, + DefaultBindingBehavior = BindingBehavior.Explicit, + FieldMiddleware = FieldMiddlewareApplication.AllFields, + PreserveSyntaxNodes = true + }; + + // act + var copied = new ReadOnlySchemaOptions(options); + var writableCopy = SchemaOptions.FromOptions(copied); + + // assert + copied.MatchSnapshot(); + writableCopy.MatchSnapshot(); + } + + [Fact] + public void Copy_Options_EnableOneOf_EnableDirectiveIntrospection() + { + // arrange + var options = new SchemaOptions { - // arrange - var options = new SchemaOptions(); + QueryTypeName = "A", + MutationTypeName = "B", + SubscriptionTypeName = "C", + StrictValidation = false, + SortFieldsByName = true, + UseXmlDocumentation = false, + DefaultBindingBehavior = BindingBehavior.Explicit, + FieldMiddleware = FieldMiddlewareApplication.AllFields, + PreserveSyntaxNodes = true, + EnableOneOf = true, + EnableDirectiveIntrospection = true + }; - // act - var copied = new ReadOnlySchemaOptions(options); - var writableCopy = SchemaOptions.FromOptions(copied); + // act + var copied = new ReadOnlySchemaOptions(options); + var writableCopy = SchemaOptions.FromOptions(copied); - // assert - copied.MatchSnapshot(); - writableCopy.MatchSnapshot(); - } + // assert + copied.MatchSnapshot(); + writableCopy.MatchSnapshot(); + } - [Fact] - public void Create_Options_Null() + [Fact] + public void Copy_Options_ResolveXmlDocumentationFileName() + { + // arrange + var options = new SchemaOptions { - // arrange - // act - Action action = () => new ReadOnlySchemaOptions(null); + QueryTypeName = "A", + MutationTypeName = "B", + SubscriptionTypeName = "C", + StrictValidation = false, + SortFieldsByName = true, + UseXmlDocumentation = false, + ResolveXmlDocumentationFileName = assembly => "docs.xml", + DefaultBindingBehavior = BindingBehavior.Explicit, + FieldMiddleware = FieldMiddlewareApplication.AllFields, + PreserveSyntaxNodes = true + }; + + // act + var copied = new ReadOnlySchemaOptions(options); + var writableCopy = SchemaOptions.FromOptions(copied); + + // assert + Assert.Same( + options.ResolveXmlDocumentationFileName, + copied.ResolveXmlDocumentationFileName); + + Assert.Same( + copied.ResolveXmlDocumentationFileName, + writableCopy.ResolveXmlDocumentationFileName); + } + + [Fact] + public void Copy_Options_Defaults() + { + // arrange + var options = new SchemaOptions(); + + // act + var copied = new ReadOnlySchemaOptions(options); + var writableCopy = SchemaOptions.FromOptions(copied); + + // assert + copied.MatchSnapshot(); + writableCopy.MatchSnapshot(); + } + + [Fact] + public void Create_Options_Null() + { + // arrange + // act + Action action = () => new ReadOnlySchemaOptions(null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaConfigurationTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaConfigurationTests.cs index 1bbb01417f6..ee1720aa75e 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaConfigurationTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaConfigurationTests.cs @@ -5,101 +5,100 @@ using Moq; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class SchemaConfigurationTests { - public class SchemaConfigurationTests + [Fact] + public void BindResolverCollectionToObjectTypeImplicitly() { - [Fact] - public void BindResolverCollectionToObjectTypeImplicitly() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("TestObjectA"); - d.Field("a").Type(); - d.Field("b").Type(); - }) - .AddResolver("TestObjectA") - .Create(); - - // assert - ObjectType type = schema.GetType("TestObjectA"); - Assert.NotNull(type.Fields["a"].Resolver); - Assert.NotNull(type.Fields["b"].Resolver); - } - - [Fact] - public async Task DeriveResolverFromObjectTypeMethod() - { - // arrange - var dummyObjectType = new TestObjectB(); - - var resolverContext = new Mock(); - resolverContext.Setup(t => t.Parent()) - .Returns(dummyObjectType); - - var source = @"type Dummy { bar2: String }"; - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddDocumentFromString(source) - .BindRuntimeType("Dummy") - .Create(); - - // assert - ObjectType dummy = schema.GetType("Dummy"); - FieldResolverDelegate fieldResolver = dummy.Fields["bar2"].Resolver; - var result = await fieldResolver!(resolverContext.Object); - Assert.Equal(dummyObjectType.GetBar2(), result); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("TestObjectA"); + d.Field("a").Type(); + d.Field("b").Type(); + }) + .AddResolver("TestObjectA") + .Create(); + + // assert + var type = schema.GetType("TestObjectA"); + Assert.NotNull(type.Fields["a"].Resolver); + Assert.NotNull(type.Fields["b"].Resolver); } - public class TestResolverCollectionA + [Fact] + public async Task DeriveResolverFromObjectTypeMethod() { - public string GetA(TestObjectA dummy) - { - return "a_dummy"; - } - - public string GetA(TestObjectA dummy, string a) - { - return "a_dummy_a"; - } - - public string GetFoo(TestObjectA dummy) - { - return null; - } - - public string B { get; set; } + // arrange + var dummyObjectType = new TestObjectB(); + + var resolverContext = new Mock(); + resolverContext.Setup(t => t.Parent()) + .Returns(dummyObjectType); + + var source = @"type Dummy { bar2: String }"; + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddDocumentFromString(source) + .BindRuntimeType("Dummy") + .Create(); + + // assert + var dummy = schema.GetType("Dummy"); + var fieldResolver = dummy.Fields["bar2"].Resolver; + var result = await fieldResolver!(resolverContext.Object); + Assert.Equal(dummyObjectType.GetBar2(), result); } +} - public class TestObjectA +public class TestResolverCollectionA +{ + public string GetA(TestObjectA dummy) { - public string A { get; set; } = "a"; - public string B { get; set; } = "b"; + return "a_dummy"; } - public class TestResolverCollectionB + public string GetA(TestObjectA dummy, string a) { - public string GetFooBar(TestObjectB objectType) - { - return objectType.Bar; - } + return "a_dummy_a"; } - public class TestObjectB + public string GetFoo(TestObjectA dummy) { - public string Bar { get; } = "hello"; - - public string GetBar2() => "world"; + return null; } - public class DummyQuery + public string B { get; set; } +} + +public class TestObjectA +{ + public string A { get; set; } = "a"; + public string B { get; set; } = "b"; +} + +public class TestResolverCollectionB +{ + public string GetFooBar(TestObjectB objectType) { - public string Foo { get; set; } + return objectType.Bar; } } + +public class TestObjectB +{ + public string Bar { get; } = "hello"; + + public string GetBar2() => "world"; +} + +public class DummyQuery +{ + public string Foo { get; set; } +} diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeDiscoveryTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeDiscoveryTests.cs index 0cb2544efdd..d9c60da3abd 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeDiscoveryTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeDiscoveryTests.cs @@ -4,229 +4,228 @@ using HotChocolate.Types; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class SchemaTypeDiscoveryTests { - public class SchemaTypeDiscoveryTests + [Fact] + public void DiscoverInputArgumentTypes() { - [Fact] - public void DiscoverInputArgumentTypes() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - Assert.NotNull(schema.GetType("Foo")); - Assert.NotNull(schema.GetType("Bar")); - Assert.NotNull(schema.GetType("FooInput")); - Assert.NotNull(schema.GetType("BarInput")); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + Assert.NotNull(schema.GetType("Foo")); + Assert.NotNull(schema.GetType("Bar")); + Assert.NotNull(schema.GetType("FooInput")); + Assert.NotNull(schema.GetType("BarInput")); + } + + [Fact] + public void DiscoverOutputGraphFromMethod() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + var query = schema.GetType("QueryField"); + Assert.NotNull(query); + Assert.Collection( + query.Fields.Where(t => !t.IsIntrospectionField), + t => Assert.Equal("foo", t.Name)); + Assert.NotNull(schema.GetType("Foo")); + Assert.NotNull(schema.GetType("Bar")); + } + + [Fact] + public void DiscoverOutputGraphFromProperty() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + var query = schema.GetType("QueryProperty"); + Assert.NotNull(query); + Assert.Collection( + query.Fields.Where(t => !t.IsIntrospectionField), + t => Assert.Equal("foo", t.Name)); + Assert.NotNull(schema.GetType("Foo")); + Assert.NotNull(schema.GetType("Bar")); + } - [Fact] - public void DiscoverOutputGraphFromMethod() + [Fact] + public void DiscoverOutputGraphAndIgnoreVoidMethods() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + var query = schema.GetType("QueryMethodVoid"); + Assert.NotNull(query); + Assert.Collection(query.Fields.Where(t => !t.IsIntrospectionField), + t => Assert.Equal("foo", t.Name)); + Assert.NotNull(schema.GetType("Foo")); + Assert.NotNull(schema.GetType("Bar")); + } + + [Fact] + public void InferEnumAsEnumType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var fooBar = schema.GetType("FooBar"); + Assert.NotNull(fooBar); + Assert.Collection(fooBar.Values, + t => Assert.Equal("FOO", t.Name), + t => Assert.Equal("BAR", t.Name)); + } + + [Fact] + public void InferCustomScalarTypes() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .Create(); + + // assert + var fooByte = schema.GetType("FooByte"); + Assert.NotNull(fooByte); + + var field = fooByte.Fields["bar"]; + Assert.Equal("ByteArray", field.Type.NamedType().Name); + } + + public class QueryFieldArgument + { + public Bar Bar { get; } + + public Foo GetFoo(Foo foo) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - ObjectType query = schema.GetType("QueryField"); - Assert.NotNull(query); - Assert.Collection( - query.Fields.Where(t => !t.IsIntrospectionField), - t => Assert.Equal("foo", t.Name)); - Assert.NotNull(schema.GetType("Foo")); - Assert.NotNull(schema.GetType("Bar")); + return foo; } + } - [Fact] - public void DiscoverOutputGraphFromProperty() + public class QueryField + { + public Foo GetFoo() { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - ObjectType query = schema.GetType("QueryProperty"); - Assert.NotNull(query); - Assert.Collection( - query.Fields.Where(t => !t.IsIntrospectionField), - t => Assert.Equal("foo", t.Name)); - Assert.NotNull(schema.GetType("Foo")); - Assert.NotNull(schema.GetType("Bar")); + return null; } + } + + public class QueryProperty + { + public Foo Foo { get; } + } - [Fact] - public void DiscoverOutputGraphAndIgnoreVoidMethods() + public class QueryMethodVoid + { + public Foo GetFoo() { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - ObjectType query = schema.GetType("QueryMethodVoid"); - Assert.NotNull(query); - Assert.Collection(query.Fields.Where(t => !t.IsIntrospectionField), - t => Assert.Equal("foo", t.Name)); - Assert.NotNull(schema.GetType("Foo")); - Assert.NotNull(schema.GetType("Bar")); + return null; } - [Fact] - public void InferEnumAsEnumType() + public void GetBar() { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType fooBar = schema.GetType("FooBar"); - Assert.NotNull(fooBar); - Assert.Collection(fooBar.Values, - t => Assert.Equal("FOO", t.Name), - t => Assert.Equal("BAR", t.Name)); } + } - [Fact] - public void InferCustomScalarTypes() + public class QueryWithCustomScalar + { + public FooByte GetFoo(FooByte foo) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .Create(); - - // assert - ObjectType fooByte = schema.GetType("FooByte"); - Assert.NotNull(fooByte); - - ObjectField field = fooByte.Fields["bar"]; - Assert.Equal("ByteArray", field.Type.NamedType().Name); + return null; } + } - public class QueryFieldArgument - { - public Bar Bar { get; } + public class Foo + { + public Bar Bar { get; set; } + } - public Foo GetFoo(Foo foo) - { - return foo; - } - } + public class FooByte + { + public byte[] Bar { get; set; } + } + + public class Bar + { + public string Baz { get; set; } + } - public class QueryField + public enum FooBar + { + Foo, + Bar + } + + public class ByteArrayType : ScalarType + { + public ByteArrayType() : base("ByteArray", BindingBehavior.Implicit) { - public Foo GetFoo() - { - return null; - } } - public class QueryProperty + public override Type RuntimeType => typeof(byte[]); + + public override bool IsInstanceOfType(IValueNode literal) { - public Foo Foo { get; } + throw new NotSupportedException(); } - public class QueryMethodVoid + public override object ParseLiteral(IValueNode literal) { - public Foo GetFoo() - { - return null; - } - - public void GetBar() - { - } + throw new NotSupportedException(); } - public class QueryWithCustomScalar + public override IValueNode ParseValue(object value) { - public FooByte GetFoo(FooByte foo) - { - return null; - } + throw new NotSupportedException(); } - public class Foo + public override IValueNode ParseResult(object resultValue) { - public Bar Bar { get; set; } + throw new NotSupportedException(); } - public class FooByte + public override object Serialize(object runtimeValue) { - public byte[] Bar { get; set; } + throw new NotSupportedException(); } - public class Bar + public override object Deserialize(object resultValue) { - public string Baz { get; set; } + throw new NotSupportedException(); } - public enum FooBar + public override bool TryDeserialize(object resultValue, out object runtimeValue) { - Foo, - Bar + throw new NotSupportedException(); } - public class ByteArrayType : ScalarType + public override bool TrySerialize(object runtimeValue, out object resultValue) { - public ByteArrayType() : base("ByteArray", BindingBehavior.Implicit) - { - } - - public override Type RuntimeType => typeof(byte[]); - - public override bool IsInstanceOfType(IValueNode literal) - { - throw new NotSupportedException(); - } - - public override object ParseLiteral(IValueNode literal) - { - throw new NotSupportedException(); - } - - public override IValueNode ParseValue(object value) - { - throw new NotSupportedException(); - } - - public override IValueNode ParseResult(object resultValue) - { - throw new NotSupportedException(); - } - - public override object Serialize(object runtimeValue) - { - throw new NotSupportedException(); - } - - public override object Deserialize(object resultValue) - { - throw new NotSupportedException(); - } - - public override bool TryDeserialize(object resultValue, out object runtimeValue) - { - throw new NotSupportedException(); - } - - public override bool TrySerialize(object runtimeValue, out object resultValue) - { - throw new NotSupportedException(); - } + throw new NotSupportedException(); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeResolverTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeResolverTests.cs index c013837cee6..c8b4b5ca1e6 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeResolverTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/SchemaTypeResolverTests.cs @@ -3,108 +3,107 @@ using HotChocolate.Types.Descriptors; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class SchemaTypeResolverTests { - public class SchemaTypeResolverTests + private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); + + private IExtendedType TypeOf() => + _typeInspector.GetType(typeof(T)); + + [InlineData(TypeContext.Output)] + [InlineData(TypeContext.None)] + [Theory] + public void InferObjectType(TypeContext context) + { + // arrange + var typeReference = TypeReference.Create(TypeOf(), context); + + // act + var success = SchemaTypeResolver.TryInferSchemaType( + _typeInspector, + typeReference, + out var schemaType); + + // assert + Assert.True(success); + Assert.Equal(TypeContext.Output, schemaType.Context); + Assert.Equal(typeof(ObjectType), schemaType.Type.Source); + } + + [InlineData(TypeContext.Output)] + [InlineData(TypeContext.None)] + [Theory] + public void InferInterfaceType(TypeContext context) + { + // arrange + var typeReference = TypeReference.Create(TypeOf(), context); + + // act + var success = SchemaTypeResolver.TryInferSchemaType( + _typeInspector, + typeReference, + out var schemaType); + + // assert + Assert.True(success); + Assert.Equal(TypeContext.Output, schemaType.Context); + Assert.Equal(typeof(InterfaceType), schemaType.Type.Source); + } + + [Fact] + public void InferInputObjectType() + { + // arrange + var typeReference = TypeReference.Create(TypeOf(), TypeContext.Input); + + // act + var success = SchemaTypeResolver.TryInferSchemaType( + _typeInspector, + typeReference, + out var schemaType); + + // assert + Assert.True(success); + Assert.Equal(TypeContext.Input, schemaType.Context); + Assert.Equal(typeof(InputObjectType), schemaType.Type.Source); + } + + [InlineData(TypeContext.Output)] + [InlineData(TypeContext.Input)] + [InlineData(TypeContext.None)] + [Theory] + public void InferEnumType(TypeContext context) + { + // arrange + var typeReference = TypeReference.Create(TypeOf(), context); + + // act + var success = SchemaTypeResolver.TryInferSchemaType( + _typeInspector, + typeReference, + out var schemaType); + + // assert + Assert.True(success); + Assert.Equal(TypeContext.None, schemaType.Context); + Assert.Equal(typeof(EnumType), schemaType.Type.Source); + } + + public class Bar + { + public string Baz { get; } + } + + public interface IBar + { + string Baz { get; } + } + + public enum Foo { - private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); - - private IExtendedType TypeOf() => - _typeInspector.GetType(typeof(T)); - - [InlineData(TypeContext.Output)] - [InlineData(TypeContext.None)] - [Theory] - public void InferObjectType(TypeContext context) - { - // arrange - ExtendedTypeReference typeReference = TypeReference.Create(TypeOf(), context); - - // act - var success = SchemaTypeResolver.TryInferSchemaType( - _typeInspector, - typeReference, - out ExtendedTypeReference schemaType); - - // assert - Assert.True(success); - Assert.Equal(TypeContext.Output, schemaType.Context); - Assert.Equal(typeof(ObjectType), schemaType.Type.Source); - } - - [InlineData(TypeContext.Output)] - [InlineData(TypeContext.None)] - [Theory] - public void InferInterfaceType(TypeContext context) - { - // arrange - ExtendedTypeReference typeReference = TypeReference.Create(TypeOf(), context); - - // act - var success = SchemaTypeResolver.TryInferSchemaType( - _typeInspector, - typeReference, - out ExtendedTypeReference schemaType); - - // assert - Assert.True(success); - Assert.Equal(TypeContext.Output, schemaType.Context); - Assert.Equal(typeof(InterfaceType), schemaType.Type.Source); - } - - [Fact] - public void InferInputObjectType() - { - // arrange - ExtendedTypeReference typeReference = TypeReference.Create(TypeOf(), TypeContext.Input); - - // act - var success = SchemaTypeResolver.TryInferSchemaType( - _typeInspector, - typeReference, - out ExtendedTypeReference schemaType); - - // assert - Assert.True(success); - Assert.Equal(TypeContext.Input, schemaType.Context); - Assert.Equal(typeof(InputObjectType), schemaType.Type.Source); - } - - [InlineData(TypeContext.Output)] - [InlineData(TypeContext.Input)] - [InlineData(TypeContext.None)] - [Theory] - public void InferEnumType(TypeContext context) - { - // arrange - ExtendedTypeReference typeReference = TypeReference.Create(TypeOf(), context); - - // act - var success = SchemaTypeResolver.TryInferSchemaType( - _typeInspector, - typeReference, - out ExtendedTypeReference schemaType); - - // assert - Assert.True(success); - Assert.Equal(TypeContext.None, schemaType.Context); - Assert.Equal(typeof(EnumType), schemaType.Type.Source); - } - - public class Bar - { - public string Baz { get; } - } - - public interface IBar - { - string Baz { get; } - } - - public enum Foo - { - Bar, - Baz - } + Bar, + Baz } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscovererTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscovererTests.cs index cd9d258b278..f3b324aa0ab 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscovererTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscovererTests.cs @@ -7,288 +7,287 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration -{ - public class TypeDiscovererTests - { - private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); +namespace HotChocolate.Configuration; - [Fact] - public void Register_SchemaType_ClrTypeExists_NoSystemTypes() - { - // arrange - var context = DescriptorContext.Create(); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); - - var typeDiscoverer = new TypeDiscoverer( - context, - typeRegistry, - typeLookup, - new HashSet - { - _typeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) - }, - new AggregateTypeInterceptor(), - false); +public class TypeDiscovererTests +{ + private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); - // act - IReadOnlyList errors = typeDiscoverer.DiscoverTypes(); + [Fact] + public void Register_SchemaType_ClrTypeExists_NoSystemTypes() + { + // arrange + var context = DescriptorContext.Create(); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); + + var typeDiscoverer = new TypeDiscoverer( + context, + typeRegistry, + typeLookup, + new HashSet + { + _typeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) + }, + new AggregateTypeInterceptor(), + false); - // assert - Assert.Empty(errors); + // act + var errors = typeDiscoverer.DiscoverTypes(); - new - { - registered = typeRegistry.Types - .Select(t => new - { - type = t.Type.GetType().GetTypeName(), - runtimeType = t.Type is IHasRuntimeType hr - ? hr.RuntimeType.GetTypeName() - : null, - references = t.References.Select(t => t.ToString()).ToList() - }).ToList(), - - runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( - t => t.Key.ToString(), - t => t.Value.ToString()) - - }.MatchSnapshot(); - } + // assert + Assert.Empty(errors); - [Fact] - public void Register_SchemaType_ClrTypeExists() + new { - // arrange - var context = DescriptorContext.Create(); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); - - var typeDiscoverer = new TypeDiscoverer( - context, - typeRegistry, - typeLookup, - new HashSet + registered = typeRegistry.Types + .Select(t => new { - _typeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) - }, - new AggregateTypeInterceptor()); - - // act - IReadOnlyList errors = typeDiscoverer.DiscoverTypes(); - - // assert - Assert.Empty(errors); + type = t.Type.GetType().GetTypeName(), + runtimeType = t.Type is IHasRuntimeType hr + ? hr.RuntimeType.GetTypeName() + : null, + references = t.References.Select(t => t.ToString()).ToList() + }).ToList(), + + runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( + t => t.Key.ToString(), + t => t.Value.ToString()) + + }.MatchSnapshot(); + } - new + [Fact] + public void Register_SchemaType_ClrTypeExists() + { + // arrange + var context = DescriptorContext.Create(); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); + + var typeDiscoverer = new TypeDiscoverer( + context, + typeRegistry, + typeLookup, + new HashSet { - registered = typeRegistry.Types - .Select(t => new - { - type = t.Type.GetType().GetTypeName(), - runtimeType = t.Type is IHasRuntimeType hr - ? hr.RuntimeType.GetTypeName() - : null, - references = t.References.Select(t => t.ToString()).ToList() - }).ToList(), - - runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( - t => t.Key.ToString(), - t => t.Value.ToString()) - - }.MatchSnapshot(); - } + _typeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) + }, + new AggregateTypeInterceptor()); - [Fact] - public void Register_ClrType_InferSchemaTypes() - { - // arrange - var context = DescriptorContext.Create(); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); + // act + var errors = typeDiscoverer.DiscoverTypes(); - var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); + // assert + Assert.Empty(errors); - var typeDiscoverer = new TypeDiscoverer( - context, - typeRegistry, - typeLookup, - new HashSet + new + { + registered = typeRegistry.Types + .Select(t => new { - _typeInspector.GetTypeRef(typeof(Foo), TypeContext.Output) - }, - new AggregateTypeInterceptor()); + type = t.Type.GetType().GetTypeName(), + runtimeType = t.Type is IHasRuntimeType hr + ? hr.RuntimeType.GetTypeName() + : null, + references = t.References.Select(t => t.ToString()).ToList() + }).ToList(), + + runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( + t => t.Key.ToString(), + t => t.Value.ToString()) + + }.MatchSnapshot(); + } - // act - IReadOnlyList errors = typeDiscoverer.DiscoverTypes(); + [Fact] + public void Register_ClrType_InferSchemaTypes() + { + // arrange + var context = DescriptorContext.Create(); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); - // assert - Assert.Empty(errors); + var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); - new + var typeDiscoverer = new TypeDiscoverer( + context, + typeRegistry, + typeLookup, + new HashSet { - registered = typeRegistry.Types - .Select(t => new - { - type = t.Type.GetType().GetTypeName(), - runtimeType = t.Type is IHasRuntimeType hr - ? hr.RuntimeType.GetTypeName() - : null, - references = t.References.Select(r => r.ToString()).ToList() - }).ToList(), - - runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( - t => t.Key.ToString(), - t => t.Value.ToString()) - - }.MatchSnapshot(); - } + _typeInspector.GetTypeRef(typeof(Foo), TypeContext.Output) + }, + new AggregateTypeInterceptor()); - [Fact] - public void Upgrade_Type_From_GenericType() - { - // arrange - var context = DescriptorContext.Create(); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); + // act + var errors = typeDiscoverer.DiscoverTypes(); - var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); + // assert + Assert.Empty(errors); - var typeDiscoverer = new TypeDiscoverer( - context, - typeRegistry, - typeLookup, - new HashSet + new + { + registered = typeRegistry.Types + .Select(t => new { - _typeInspector.GetTypeRef(typeof(ObjectType), TypeContext.Output), - _typeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) - }, - new AggregateTypeInterceptor()); + type = t.Type.GetType().GetTypeName(), + runtimeType = t.Type is IHasRuntimeType hr + ? hr.RuntimeType.GetTypeName() + : null, + references = t.References.Select(r => r.ToString()).ToList() + }).ToList(), + + runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( + t => t.Key.ToString(), + t => t.Value.ToString()) + + }.MatchSnapshot(); + } - // act - IReadOnlyList errors = typeDiscoverer.DiscoverTypes(); + [Fact] + public void Upgrade_Type_From_GenericType() + { + // arrange + var context = DescriptorContext.Create(); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); - // assert - Assert.Empty(errors); + var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); - new + var typeDiscoverer = new TypeDiscoverer( + context, + typeRegistry, + typeLookup, + new HashSet { - registered = typeRegistry.Types - .Select(t => new - { - type = t.Type.GetType().GetTypeName(), - runtimeType = t.Type is IHasRuntimeType hr - ? hr.RuntimeType.GetTypeName() - : null, - references = t.References.Select(t => t.ToString()).ToList() - }).ToList(), - - runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( - t => t.Key.ToString(), - t => t.Value.ToString()) - - }.MatchSnapshot(); - } + _typeInspector.GetTypeRef(typeof(ObjectType), TypeContext.Output), + _typeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) + }, + new AggregateTypeInterceptor()); - [Fact] - public void Cannot_Infer_Input_Type() + // act + var errors = typeDiscoverer.DiscoverTypes(); + + // assert + Assert.Empty(errors); + + new { - // arrange - var context = DescriptorContext.Create(); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); - - var typeDiscoverer = new TypeDiscoverer( - context, - typeRegistry, - typeLookup, - new HashSet + registered = typeRegistry.Types + .Select(t => new { - _typeInspector.GetTypeRef(typeof(QueryWithInferError), TypeContext.Output), - }, - new AggregateTypeInterceptor()); + type = t.Type.GetType().GetTypeName(), + runtimeType = t.Type is IHasRuntimeType hr + ? hr.RuntimeType.GetTypeName() + : null, + references = t.References.Select(t => t.ToString()).ToList() + }).ToList(), + + runtimeTypeRefs = typeRegistry.RuntimeTypeRefs.ToDictionary( + t => t.Key.ToString(), + t => t.Value.ToString()) + + }.MatchSnapshot(); + } - // act - IReadOnlyList errors = typeDiscoverer.DiscoverTypes(); + [Fact] + public void Cannot_Infer_Input_Type() + { + // arrange + var context = DescriptorContext.Create(); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); + + var typeDiscoverer = new TypeDiscoverer( + context, + typeRegistry, + typeLookup, + new HashSet + { + _typeInspector.GetTypeRef(typeof(QueryWithInferError), TypeContext.Output), + }, + new AggregateTypeInterceptor()); - // assert - Assert.Collection( - errors, - error => - { - Assert.Equal(ErrorCodes.Schema.UnresolvedTypes, error.Code); - Assert.IsType>(error.TypeSystemObject); - Assert.False(error.Extensions.ContainsKey("involvedTypes")); - }); + // act + var errors = typeDiscoverer.DiscoverTypes(); - new SchemaException(errors).Message.MatchSnapshot(); - } + // assert + Assert.Collection( + errors, + error => + { + Assert.Equal(ErrorCodes.Schema.UnresolvedTypes, error.Code); + Assert.IsType>(error.TypeSystemObject); + Assert.False(error.Extensions.ContainsKey("involvedTypes")); + }); - [Fact] - public void Cannot_Infer_Multiple_Input_Type() - { - // arrange - var context = DescriptorContext.Create(); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); - - var typeDiscoverer = new TypeDiscoverer( - context, - typeRegistry, - typeLookup, - new HashSet - { - _typeInspector.GetTypeRef(typeof(QueryWithInferError), TypeContext.Output), - _typeInspector.GetTypeRef(typeof(QueryWithInferError2), TypeContext.Output), - }, - new AggregateTypeInterceptor()); - - // act - IReadOnlyList errors = typeDiscoverer.DiscoverTypes(); - - // assert - Assert.Collection( - errors, - error => - { - Assert.Equal(ErrorCodes.Schema.UnresolvedTypes, error.Code); - Assert.IsType>(error.TypeSystemObject); - Assert.True(error.Extensions.ContainsKey("involvedTypes")); - }); - } + new SchemaException(errors).Message.MatchSnapshot(); + } - public class FooType - : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) + [Fact] + public void Cannot_Infer_Multiple_Input_Type() + { + // arrange + var context = DescriptorContext.Create(); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + var typeLookup = new TypeLookup(context.TypeInspector, typeRegistry); + + var typeDiscoverer = new TypeDiscoverer( + context, + typeRegistry, + typeLookup, + new HashSet { - descriptor.Field(t => t.Bar).Type>(); - } - } + _typeInspector.GetTypeRef(typeof(QueryWithInferError), TypeContext.Output), + _typeInspector.GetTypeRef(typeof(QueryWithInferError2), TypeContext.Output), + }, + new AggregateTypeInterceptor()); + + // act + var errors = typeDiscoverer.DiscoverTypes(); + + // assert + Assert.Collection( + errors, + error => + { + Assert.Equal(ErrorCodes.Schema.UnresolvedTypes, error.Code); + Assert.IsType>(error.TypeSystemObject); + Assert.True(error.Extensions.ContainsKey("involvedTypes")); + }); + } - public class BarType : ObjectType + public class FooType + : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { + descriptor.Field(t => t.Bar).Type>(); } + } - public class Foo - { - public Bar Bar { get; } - } + public class BarType : ObjectType + { + } - public class Bar - { - public string Baz { get; } - } + public class Foo + { + public Bar Bar { get; } + } - public class QueryWithInferError - { - public string Foo(IMyArg o) => throw new NotImplementedException(); - } + public class Bar + { + public string Baz { get; } + } - public class QueryWithInferError2 - { - public string Foo(IMyArg o) => throw new NotImplementedException(); - } + public class QueryWithInferError + { + public string Foo(IMyArg o) => throw new NotImplementedException(); + } - public interface IMyArg { } + public class QueryWithInferError2 + { + public string Foo(IMyArg o) => throw new NotImplementedException(); } + + public interface IMyArg { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscoveryTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscoveryTests.cs index c28f1b8932a..73d560862b4 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscoveryTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeDiscoveryTests.cs @@ -3,71 +3,70 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class TypeDiscoveryTests { - public class TypeDiscoveryTests + [Fact] + public void InferDateTime() { - [Fact] - public void InferDateTime() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .Print() - .MatchSnapshot(); - } + SchemaBuilder.New() + .AddQueryType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void InferDateTimeFromModel() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void InferDateTimeFromModel() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .Print() + .MatchSnapshot(); + } - public class QueryWithDateTime - { - public DateTimeOffset DateTimeOffset(DateTimeOffset time) => time; - public DateTime DateTime(DateTime time) => time; - } + public class QueryWithDateTime + { + public DateTimeOffset DateTimeOffset(DateTimeOffset time) => time; + public DateTime DateTime(DateTime time) => time; + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("items") - .Type>() - .Resolve(string.Empty); + descriptor.Name("Query"); + descriptor.Field("items") + .Type>() + .Resolve(string.Empty); - descriptor.Field("paging") - .UsePaging() - .Resolve(string.Empty); - } + descriptor.Field("paging") + .UsePaging() + .Resolve(string.Empty); } + } - public class ModelType : ObjectType + public class ModelType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Time) - .Type>(); + descriptor.Field(t => t.Time) + .Type>(); - descriptor.Field(t => t.Date) - .Type>(); - } + descriptor.Field(t => t.Date) + .Type>(); } + } - public class Model - { - public string Foo { get; set; } - public int Bar { get; set; } - public bool Baz { get; set; } - public DateTime Time { get; set; } - public DateTime Date { get; set; } - } + public class Model + { + public string Foo { get; set; } + public int Bar { get; set; } + public bool Baz { get; set; } + public DateTime Time { get; set; } + public DateTime Date { get; set; } } -} \ No newline at end of file +} diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializationOrderTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializationOrderTests.cs index 9487ffc7d29..af94abca6eb 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializationOrderTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializationOrderTests.cs @@ -6,83 +6,82 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class TypeInitializationOrderTests { - public class TypeInitializationOrderTests + [Fact] + public void Merge_Type_Extensions_AB_KeepOrder() { - [Fact] - public void Merge_Type_Extensions_AB_KeepOrder() - { - // the field order will change depending on the extension order. - SchemaBuilder.New() - .AddQueryType(c => c.Name("Query")) - .AddType() - .AddType() + // the field order will change depending on the extension order. + SchemaBuilder.New() + .AddQueryType(c => c.Name("Query")) + .AddType() + .AddType() .Create() .Print() .MatchSnapshot(); - } + } - [Fact] - public void Merge_Type_Extensions_BA_KeepOrder() - { - SchemaBuilder.New() - .AddQueryType(c => c.Name("Query")) - .AddType() - .AddType() + [Fact] + public void Merge_Type_Extensions_BA_KeepOrder() + { + SchemaBuilder.New() + .AddQueryType(c => c.Name("Query")) + .AddType() + .AddType() .Create() .Print() .MatchSnapshot(new SnapshotNameExtension("BA")); - } + } - public class QueryExtensionType_A : ObjectTypeExtension + public class QueryExtensionType_A : ObjectTypeExtension + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query") - .Field("words") - .Type>>() - .Resolve( - new Word[] { new() { Value = "Hello" }, new() { Value = "World" } }) - .Extend() - .OnBeforeCreate((c,d) => - { - ExtendedTypeReference reference = - c.TypeInspector.GetTypeRef(typeof(Word), TypeContext.Output); + descriptor.Name("Query") + .Field("words") + .Type>>() + .Resolve( + new Word[] { new() { Value = "Hello" }, new() { Value = "World" } }) + .Extend() + .OnBeforeCreate((c,d) => + { + var reference = + c.TypeInspector.GetTypeRef(typeof(Word), TypeContext.Output); - d.Configurations.Add( - new CompleteConfiguration( - (context, _) => - { - ObjectType type = context.GetType(reference); + d.Configurations.Add( + new CompleteConfiguration( + (context, _) => + { + var type = context.GetType(reference); - if (!type.IsCompleted) - { - throw new Exception("Order should not matter"); - } - }, - d, - ApplyConfigurationOn.Completion, - reference, - TypeDependencyKind.Completed)); - }); - } + if (!type.IsCompleted) + { + throw new Exception("Order should not matter"); + } + }, + d, + ApplyConfigurationOn.Completion, + reference, + TypeDependencyKind.Completed)); + }); } + } - public class QueryExtensionType_B : ObjectTypeExtension + public class QueryExtensionType_B : ObjectTypeExtension + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query") - .Field("greeting") - .Type() - .Resolve("Hello world!"); - } + descriptor.Name("Query") + .Field("greeting") + .Type() + .Resolve("Hello world!"); } + } - public class Word - { - public string Value { get; set; } - } + public class Word + { + public string Value { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializerTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializerTests.cs index bf46a572a48..92fe29c22ec 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializerTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeInitializerTests.cs @@ -7,278 +7,277 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class TypeInitializerTests { - public class TypeInitializerTests + [Fact] + public void Register_SchemaType_ClrTypeExists() { - [Fact] - public void Register_SchemaType_ClrTypeExists() - { - // arrange - var typeInterceptor = new AggregateTypeInterceptor(); - typeInterceptor.SetInterceptors(new[] { new IntrospectionTypeInterceptor() }); - IDescriptorContext context = DescriptorContext.Create( - typeInterceptor: typeInterceptor); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - - var typeInitializer = new TypeInitializer( - context, - typeRegistry, - new List - { - context.TypeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) - }, - null, - t => t is FooType ? RootTypeKind.Query : RootTypeKind.None, - new SchemaOptions()); - - // act - typeInitializer.Initialize(); - - // assert - var exists = typeRegistry.TryGetType( - context.TypeInspector.GetTypeRef(typeof(FooType), TypeContext.Output), - out RegisteredType type); - - Assert.True(exists); - var fooType = - Assert.IsType(type.Type).Fields.ToDictionary( - t => t.Name.ToString(), - t => t.Type.Print()); - - exists = typeRegistry.TryGetType( - context.TypeInspector.GetTypeRef(typeof(BarType), TypeContext.Output), - out type); - - Assert.True(exists); - var barType = - Assert.IsType(type.Type).Fields.ToDictionary( - t => t.Name.ToString(), - t => t.Type.Print()); - - new { fooType, barType }.MatchSnapshot(); - } + // arrange + var typeInterceptor = new AggregateTypeInterceptor(); + typeInterceptor.SetInterceptors(new[] { new IntrospectionTypeInterceptor() }); + IDescriptorContext context = DescriptorContext.Create( + typeInterceptor: typeInterceptor); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + + var typeInitializer = new TypeInitializer( + context, + typeRegistry, + new List + { + context.TypeInspector.GetTypeRef(typeof(FooType), TypeContext.Output) + }, + null, + t => t is FooType ? RootTypeKind.Query : RootTypeKind.None, + new SchemaOptions()); + + // act + typeInitializer.Initialize(); + + // assert + var exists = typeRegistry.TryGetType( + context.TypeInspector.GetTypeRef(typeof(FooType), TypeContext.Output), + out var type); + + Assert.True(exists); + var fooType = + Assert.IsType(type.Type).Fields.ToDictionary( + t => t.Name.ToString(), + t => t.Type.Print()); - [Fact] - public void Register_ClrType_InferSchemaTypes() - { - // arrange - var typeInterceptor = new AggregateTypeInterceptor(); - typeInterceptor.SetInterceptors(new[] { new IntrospectionTypeInterceptor() }); - IDescriptorContext context = DescriptorContext.Create( - typeInterceptor: typeInterceptor); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - - var typeInitializer = new TypeInitializer( - context, - typeRegistry, - new List - { - context.TypeInspector.GetTypeRef(typeof(Foo), TypeContext.Output) - }, - null, - t => + exists = typeRegistry.TryGetType( + context.TypeInspector.GetTypeRef(typeof(BarType), TypeContext.Output), + out type); + + Assert.True(exists); + var barType = + Assert.IsType(type.Type).Fields.ToDictionary( + t => t.Name.ToString(), + t => t.Type.Print()); + + new { fooType, barType }.MatchSnapshot(); + } + + [Fact] + public void Register_ClrType_InferSchemaTypes() + { + // arrange + var typeInterceptor = new AggregateTypeInterceptor(); + typeInterceptor.SetInterceptors(new[] { new IntrospectionTypeInterceptor() }); + IDescriptorContext context = DescriptorContext.Create( + typeInterceptor: typeInterceptor); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + + var typeInitializer = new TypeInitializer( + context, + typeRegistry, + new List + { + context.TypeInspector.GetTypeRef(typeof(Foo), TypeContext.Output) + }, + null, + t => + { + return t switch { - return t switch - { - ObjectType => RootTypeKind.Query, - _ => RootTypeKind.None - }; - }, - new SchemaOptions()); - - // act - typeInitializer.Initialize(); - - // assert - var exists = typeRegistry.TryGetType( - context.TypeInspector.GetTypeRef(typeof(ObjectType), TypeContext.Output), - out RegisteredType type); - - Assert.True(exists); - var fooType = - Assert.IsType>(type.Type).Fields.ToDictionary( + ObjectType => RootTypeKind.Query, + _ => RootTypeKind.None + }; + }, + new SchemaOptions()); + + // act + typeInitializer.Initialize(); + + // assert + var exists = typeRegistry.TryGetType( + context.TypeInspector.GetTypeRef(typeof(ObjectType), TypeContext.Output), + out var type); + + Assert.True(exists); + var fooType = + Assert.IsType>(type.Type).Fields.ToDictionary( t => t.Name.ToString(), t => t.Type.Print()); - exists = typeRegistry.TryGetType( - context.TypeInspector.GetTypeRef(typeof(ObjectType), TypeContext.Output), - out type); + exists = typeRegistry.TryGetType( + context.TypeInspector.GetTypeRef(typeof(ObjectType), TypeContext.Output), + out type); - Assert.True(exists); - var barType = - Assert.IsType>(type.Type).Fields.ToDictionary( - t => t.Name.ToString(), - t => t.Type.Print()); + Assert.True(exists); + var barType = + Assert.IsType>(type.Type).Fields.ToDictionary( + t => t.Name.ToString(), + t => t.Type.Print()); - new { fooType, barType }.MatchSnapshot(); - } + new { fooType, barType }.MatchSnapshot(); + } - [Fact] - public void Initializer_SchemaOptions_Are_Null() - { - // arrange - var typeInterceptor = new AggregateTypeInterceptor(); - typeInterceptor.SetInterceptors(new[] { new IntrospectionTypeInterceptor() }); - IDescriptorContext context = DescriptorContext.Create( - typeInterceptor: typeInterceptor); - var typeRegistry = new TypeRegistry(context.TypeInterceptor); - - // act - void Action() => new TypeInitializer( - context, - typeRegistry, - new List - { - context.TypeInspector.GetTypeRef(typeof(Foo), TypeContext.Output) - }, - null!, - t => + [Fact] + public void Initializer_SchemaOptions_Are_Null() + { + // arrange + var typeInterceptor = new AggregateTypeInterceptor(); + typeInterceptor.SetInterceptors(new[] { new IntrospectionTypeInterceptor() }); + IDescriptorContext context = DescriptorContext.Create( + typeInterceptor: typeInterceptor); + var typeRegistry = new TypeRegistry(context.TypeInterceptor); + + // act + void Action() => new TypeInitializer( + context, + typeRegistry, + new List + { + context.TypeInspector.GetTypeRef(typeof(Foo), TypeContext.Output) + }, + null!, + t => + { + return t switch { - return t switch - { - ObjectType => RootTypeKind.Query, - _ => RootTypeKind.None - }; - }, - null!); - - // assert - Assert.Throws(Action); - } + ObjectType => RootTypeKind.Query, + _ => RootTypeKind.None + }; + }, + null!); + + // assert + Assert.Throws(Action); + } - [Fact] - public void Detect_Duplicate_Types() - { - // arrange - var type = new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi")); + [Fact] + public void Detect_Duplicate_Types() + { + // arrange + var type = new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi")); + + // the interceptor will add multiple types references to type and count + // how many times the type is registered. + var interceptor = new TypeRegInterceptor(type); + + // act + SchemaBuilder.New() + .AddQueryType(type) + .TryAddTypeInterceptor(interceptor) + .Create(); + + // assert + Assert.Equal(1, interceptor.Count); + } - // the interceptor will add multiple types references to type and count - // how many times the type is registered. - var interceptor = new TypeRegInterceptor(type); + [Fact] + public void InitializeFactoryTypeRefOnce() + { + // arrange + var typeRef1 = TypeReference.Parse( + "Abc", + factory: _ => new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi"))); + + var typeRef2 = TypeReference.Parse( + "Abc", + factory: _ => new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi"))); + + var interceptor = new InjectTypes(new[] { typeRef1, typeRef2 }); - // act + // act + var schema = SchemaBuilder.New() - .AddQueryType(type) .TryAddTypeInterceptor(interceptor) + .ModifyOptions(o => o.StrictValidation = false) .Create(); - // assert - Assert.Equal(1, interceptor.Count); - } + // assert + schema.Print().MatchSnapshot(); + } - [Fact] - public void InitializeFactoryTypeRefOnce() - { - // arrange - SyntaxTypeReference typeRef1 = TypeReference.Parse( - "Abc", - factory: _ => new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi"))); - - SyntaxTypeReference typeRef2 = TypeReference.Parse( - "Abc", - factory: _ => new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi"))); - - var interceptor = new InjectTypes(new[] { typeRef1, typeRef2 }); - - // act - ISchema schema = - SchemaBuilder.New() - .TryAddTypeInterceptor(interceptor) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - schema.Print().MatchSnapshot(); - } + [Fact] + public void FactoryAndNameRefsAreRecognizedAsTheSameType() + { + // arrange + var typeRef1 = TypeReference.Parse( + "Abc", + factory: _ => new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi"))); - [Fact] - public void FactoryAndNameRefsAreRecognizedAsTheSameType() - { - // arrange - SyntaxTypeReference typeRef1 = TypeReference.Parse( - "Abc", - factory: _ => new ObjectType(d => d.Name("Abc").Field("def").Resolve("ghi"))); + var typeRef2 = TypeReference.Parse("Abc"); - SyntaxTypeReference typeRef2 = TypeReference.Parse("Abc"); + var interceptor = new InjectTypes(new[] { typeRef1, typeRef2 }); - var interceptor = new InjectTypes(new[] { typeRef1, typeRef2 }); + // act + var schema = + SchemaBuilder.New() + .TryAddTypeInterceptor(interceptor) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // act - ISchema schema = - SchemaBuilder.New() - .TryAddTypeInterceptor(interceptor) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + // assert + schema.Print().MatchSnapshot(); + } - // assert - schema.Print().MatchSnapshot(); - } + public class FooType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) + => descriptor.Field(t => t.Bar).Type>(); + } - public class FooType : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - => descriptor.Field(t => t.Bar).Type>(); - } + public class BarType : ObjectType + { + } - public class BarType : ObjectType - { - } + public class Foo + { + public Bar Bar { get; } + } - public class Foo - { - public Bar Bar { get; } - } + public class Bar + { + public string Baz { get; } + } - public class Bar - { - public string Baz { get; } - } + private sealed class TypeRegInterceptor : TypeInterceptor + { + private readonly IType _watch; - private sealed class TypeRegInterceptor : TypeInterceptor + public TypeRegInterceptor(IType watch) { - private readonly IType _watch; - - public TypeRegInterceptor(IType watch) - { - _watch = watch; - } + _watch = watch; + } - public int Count { get; private set; } + public int Count { get; private set; } - public override void OnBeforeInitialize(ITypeDiscoveryContext discoveryContext) + public override void OnBeforeInitialize(ITypeDiscoveryContext discoveryContext) + { + if (!ReferenceEquals(_watch, discoveryContext.Type)) { - if (!ReferenceEquals(_watch, discoveryContext.Type)) - { - discoveryContext.Dependencies.Add( - new(TypeReference.Create(_watch))); + discoveryContext.Dependencies.Add( + new(TypeReference.Create(_watch))); - discoveryContext.Dependencies.Add( - new(TypeReference.Create(new ListType(_watch)))); - } + discoveryContext.Dependencies.Add( + new(TypeReference.Create(new ListType(_watch)))); } + } - public override void OnTypeRegistered(ITypeDiscoveryContext discoveryContext) + public override void OnTypeRegistered(ITypeDiscoveryContext discoveryContext) + { + if (ReferenceEquals(_watch, discoveryContext.Type)) { - if (ReferenceEquals(_watch, discoveryContext.Type)) - { - Count++; - } + Count++; } } + } - private sealed class InjectTypes : TypeInterceptor - { - private readonly List _typeReferences; + private sealed class InjectTypes : TypeInterceptor + { + private readonly List _typeReferences; - public InjectTypes(IEnumerable typeReferences) - => _typeReferences = typeReferences.ToList(); + public InjectTypes(IEnumerable typeReferences) + => _typeReferences = typeReferences.ToList(); - public override bool TriggerAggregations => true; + public override bool TriggerAggregations => true; - public override IEnumerable RegisterMoreTypes( - IReadOnlyCollection discoveryContexts) - => _typeReferences; - } + public override IEnumerable RegisterMoreTypes( + IReadOnlyCollection discoveryContexts) + => _typeReferences; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeScopeInterceptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeScopeInterceptorTests.cs index 6456b6ee993..2af9afba8a5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeScopeInterceptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeScopeInterceptorTests.cs @@ -7,119 +7,118 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class TypeScopeInterceptorTests { - public class TypeScopeInterceptorTests + [Fact] + public void BranchTypesWithScope() { - [Fact] - public void BranchTypesWithScope() - { - var types = new List(); - - SchemaBuilder.New() - .AddQueryType() - .TryAddTypeInterceptor(new TypeScopeInterceptor(types)) - .Create() - .Print() - .MatchSnapshot(); - - Assert.Collection( - types.OfType().Select(t => t.Name).OrderBy(t => t), - name => Assert.Equal("A_Bar", name), - name => Assert.Equal("B_Bar", name), - name => Assert.Equal("C_Baz", name)); - } + var types = new List(); + + SchemaBuilder.New() + .AddQueryType() + .TryAddTypeInterceptor(new TypeScopeInterceptor(types)) + .Create() + .Print() + .MatchSnapshot(); + + Assert.Collection( + types.OfType().Select(t => t.Name).OrderBy(t => t), + name => Assert.Equal("A_Bar", name), + name => Assert.Equal("B_Bar", name), + name => Assert.Equal("C_Baz", name)); + } - public class Foo - { - [Scope(Scope = "A")] - public Bar Bar1 => new Bar(); + public class Foo + { + [Scope(Scope = "A")] + public Bar Bar1 => new Bar(); - [Scope(Scope = "B")] - public Bar Bar2 => new Bar(); - } + [Scope(Scope = "B")] + public Bar Bar2 => new Bar(); + } - public class Bar - { - [Scope(Scope = "C")] - public Baz Baz => new Baz(); + public class Bar + { + [Scope(Scope = "C")] + public Baz Baz => new Baz(); - [Scope(Scope = "D")] - public string SomeString => "hello"; - } + [Scope(Scope = "D")] + public string SomeString => "hello"; + } - public class Baz - { - public string SomeString => "hello"; - } + public class Baz + { + public string SomeString => "hello"; + } - public class ScopeAttribute : ObjectFieldDescriptorAttribute - { - public string Scope { get; set; } + public class ScopeAttribute : ObjectFieldDescriptorAttribute + { + public string Scope { get; set; } - public override void OnConfigure( - IDescriptorContext context, - IObjectFieldDescriptor descriptor, - MemberInfo member) - { - descriptor - .Extend() - .OnBeforeCreate(d => - { - d.Type = ((ExtendedTypeReference)d.Type).WithScope(Scope); - }); - } + public override void OnConfigure( + IDescriptorContext context, + IObjectFieldDescriptor descriptor, + MemberInfo member) + { + descriptor + .Extend() + .OnBeforeCreate(d => + { + d.Type = ((ExtendedTypeReference)d.Type).WithScope(Scope); + }); } + } - public class TypeScopeInterceptor - : TypeInterceptor + public class TypeScopeInterceptor + : TypeInterceptor , ITypeScopeInterceptor - { - private readonly ICollection _types; + { + private readonly ICollection _types; - public TypeScopeInterceptor(ICollection types) - { - _types = types; - } + public TypeScopeInterceptor(ICollection types) + { + _types = types; + } - public override bool TriggerAggregations => true; + public override bool TriggerAggregations => true; - public override bool CanHandle( - ITypeSystemObjectContext context) => - context is { Scope: { } }; + public override bool CanHandle( + ITypeSystemObjectContext context) => + context is { Scope: { } }; - public override void OnBeforeRegisterDependencies( - ITypeDiscoveryContext discoveryContext, - DefinitionBase definition, - IDictionary contextData) + public override void OnBeforeRegisterDependencies( + ITypeDiscoveryContext discoveryContext, + DefinitionBase definition, + IDictionary contextData) + { + if (definition is ObjectTypeDefinition def) { - if (definition is ObjectTypeDefinition def) + foreach (var field in def.Fields) { - foreach (ObjectFieldDefinition field in def.Fields) + if (field.Type is not null && field.Type.Scope is null) { - if (field.Type is not null && field.Type.Scope is null) - { - field.Type = field.Type.With(scope: discoveryContext.Scope); - } + field.Type = field.Type.With(scope: discoveryContext.Scope); } } } + } - public override void OnBeforeCompleteName( - ITypeCompletionContext completionContext, - DefinitionBase definition, - IDictionary contextData) - { - definition.Name = completionContext.Scope + "_" + definition.Name; - } + public override void OnBeforeCompleteName( + ITypeCompletionContext completionContext, + DefinitionBase definition, + IDictionary contextData) + { + definition.Name = completionContext.Scope + "_" + definition.Name; + } - public override void OnTypesInitialized( - IReadOnlyCollection discoveryContexts) + public override void OnTypesInitialized( + IReadOnlyCollection discoveryContexts) + { + foreach (var context in discoveryContexts) { - foreach (ITypeDiscoveryContext context in discoveryContexts) - { - _types.Add(context.Type); - } + _types.Add(context.Type); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeTrimmerTests.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeTrimmerTests.cs index fc61e78f75f..d0575925cb7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeTrimmerTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/TypeTrimmerTests.cs @@ -4,266 +4,265 @@ using Xunit; using DirectiveLocation = HotChocolate.Types.DirectiveLocation; -namespace HotChocolate.Configuration +namespace HotChocolate.Configuration; + +public class TypeTrimmerTests { - public class TypeTrimmerTests + [Fact] + private void RemoveUnusedTypes() { - [Fact] - private void RemoveUnusedTypes() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type() - .Resolve("test")) - .AddMutationType(c => c - .Name("def") - .Field("field") - .Type() - .Resolve("test")) - .AddSubscriptionType(c => c - .Name("ghi") - .Field("field") - .Type() - .Resolve("test")) - .AddObjectType(c => c - .Name("thisTypeWillBeRemoved") - .Field("field") - .Type() - .Resolve("test")) - .AddInputObjectType(c => c - .Name("thisTypeWillBeRemovedInput") - .Field("field") - .Type()) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type() + .Resolve("test")) + .AddMutationType(c => c + .Name("def") + .Field("field") + .Type() + .Resolve("test")) + .AddSubscriptionType(c => c + .Name("ghi") + .Field("field") + .Type() + .Resolve("test")) + .AddObjectType(c => c + .Name("thisTypeWillBeRemoved") + .Field("field") + .Type() + .Resolve("test")) + .AddInputObjectType(c => c + .Name("thisTypeWillBeRemovedInput") + .Field("field") + .Type()) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Interface_Implementors_Correctly_Detected() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("def")) - .Resolve("test")) - .AddInterfaceType(c => c - .Name("def") - .Field("field") - .Type()) - .AddObjectType(c => c - .Name("ghi") - .Implements(new NamedTypeNode("def")) - .Field("field") - .Type() - .Resolve("test")) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Interface_Implementors_Correctly_Detected() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("def")) + .Resolve("test")) + .AddInterfaceType(c => c + .Name("def") + .Field("field") + .Type()) + .AddObjectType(c => c + .Name("ghi") + .Implements(new NamedTypeNode("def")) + .Field("field") + .Type() + .Resolve("test")) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Interface_Implementors_Correctly_Detected_2() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("ghi")) - .Resolve("test")) - .AddInterfaceType(c => c - .Name("def") - .Field("field") - .Type()) - .AddObjectType(c => c - .Name("ghi") - .Implements(new NamedTypeNode("def")) - .Field("field") - .Type() - .Resolve("test")) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Interface_Implementors_Correctly_Detected_2() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("ghi")) + .Resolve("test")) + .AddInterfaceType(c => c + .Name("def") + .Field("field") + .Type()) + .AddObjectType(c => c + .Name("ghi") + .Implements(new NamedTypeNode("def")) + .Field("field") + .Type() + .Resolve("test")) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Union_Set_Is_Correctly_Detected() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("def")) - .Resolve("test")) - .AddUnionType(c => c - .Name("def") - .Type(new NamedTypeNode("ghi"))) - .AddObjectType(c => c - .Name("ghi") - .Field("field") - .Type() - .Resolve("test")) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Union_Set_Is_Correctly_Detected() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("def")) + .Resolve("test")) + .AddUnionType(c => c + .Name("def") + .Type(new NamedTypeNode("ghi"))) + .AddObjectType(c => c + .Name("ghi") + .Field("field") + .Type() + .Resolve("test")) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Unused_TypeSystem_Directives_Are_Removed() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("def")) - .Resolve("test")) - .AddInterfaceType(c => c - .Name("def") - .Field("field") - .Type()) - .AddObjectType(c => c - .Name("ghi") - .Directive("_abc") - .Implements(new NamedTypeNode("def")) - .Field("field") - .Type() - .Resolve("test")) - .AddDirectiveType(new DirectiveType(d => d - .Name("_abc") - .Location(DirectiveLocation.Object))) - .AddDirectiveType(new DirectiveType(d => d - .Name("_def") - .Location(DirectiveLocation.Object))) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Unused_TypeSystem_Directives_Are_Removed() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("def")) + .Resolve("test")) + .AddInterfaceType(c => c + .Name("def") + .Field("field") + .Type()) + .AddObjectType(c => c + .Name("ghi") + .Directive("_abc") + .Implements(new NamedTypeNode("def")) + .Field("field") + .Type() + .Resolve("test")) + .AddDirectiveType(new DirectiveType(d => d + .Name("_abc") + .Location(DirectiveLocation.Object))) + .AddDirectiveType(new DirectiveType(d => d + .Name("_def") + .Location(DirectiveLocation.Object))) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Executable_Directives_Are_Never_Removed() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("def")) - .Resolve("test")) - .AddInterfaceType(c => c - .Name("def") - .Field("field") - .Type()) - .AddObjectType(c => c - .Name("ghi") - .Implements(new NamedTypeNode("def")) - .Field("field") - .Type() - .Resolve("test")) - .AddDirectiveType(new DirectiveType(d => d - .Name("_abc") - .Location(DirectiveLocation.Query))) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Executable_Directives_Are_Never_Removed() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("def")) + .Resolve("test")) + .AddInterfaceType(c => c + .Name("def") + .Field("field") + .Type()) + .AddObjectType(c => c + .Name("ghi") + .Implements(new NamedTypeNode("def")) + .Field("field") + .Type() + .Resolve("test")) + .AddDirectiveType(new DirectiveType(d => d + .Name("_abc") + .Location(DirectiveLocation.Query))) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Executable_Directives_Are_Never_Removed_2() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("def")) - .Resolve("test")) - .AddInterfaceType(c => c - .Name("def") - .Field("field") - .Type()) - .AddObjectType(c => c - .Name("ghi") - .Implements(new NamedTypeNode("def")) - .Field("field") - .Type() - .Resolve("test")) - .AddDirectiveType(new DirectiveType(d => d - .Name("_abc") - .Location(DirectiveLocation.Object | DirectiveLocation.Query))) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Executable_Directives_Are_Never_Removed_2() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("def")) + .Resolve("test")) + .AddInterfaceType(c => c + .Name("def") + .Field("field") + .Type()) + .AddObjectType(c => c + .Name("ghi") + .Implements(new NamedTypeNode("def")) + .Field("field") + .Type() + .Resolve("test")) + .AddDirectiveType(new DirectiveType(d => d + .Name("_abc") + .Location(DirectiveLocation.Object | DirectiveLocation.Query))) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - private void Executable_Directives_Should_Be_Visited() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("abc") - .Field("field") - .Type(new NamedTypeNode("def")) - .Resolve("test")) - .AddInterfaceType(c => c - .Name("def") - .Field("field") - .Type()) - .AddObjectType(c => c - .Name("ghi") - .Implements(new NamedTypeNode("def")) - .Field("field") - .Type() - .Resolve("test")) - .AddType(new UuidType('D')) - .AddDirectiveType(new DirectiveType(d => d - .Name("_abc") - .Location(DirectiveLocation.Object | DirectiveLocation.Query) - .Argument("arg") - .Type())) - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + private void Executable_Directives_Should_Be_Visited() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("abc") + .Field("field") + .Type(new NamedTypeNode("def")) + .Resolve("test")) + .AddInterfaceType(c => c + .Name("def") + .Field("field") + .Type()) + .AddObjectType(c => c + .Name("ghi") + .Implements(new NamedTypeNode("def")) + .Field("field") + .Type() + .Resolve("test")) + .AddType(new UuidType('D')) + .AddDirectiveType(new DirectiveType(d => d + .Name("_abc") + .Location(DirectiveLocation.Object | DirectiveLocation.Query) + .Argument("arg") + .Type())) + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/InterfaceTypeValidation.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/InterfaceTypeValidation.cs index f876ceacded..691379bf214 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/InterfaceTypeValidation.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/InterfaceTypeValidation.cs @@ -1,13 +1,13 @@ using Xunit; -namespace HotChocolate.Configuration.Validation +namespace HotChocolate.Configuration.Validation; + +public class InterfaceTypeValidation : TypeValidationTestBase { - public class InterfaceTypeValidation : TypeValidationTestBase + [Fact] + public void Fields_With_Two_Underscores_Are_Not_Allowed() { - [Fact] - public void Fields_With_Two_Underscores_Are_Not_Allowed() - { - ExpectError(@" + ExpectError(@" type Query { foo : FooInterface } @@ -20,12 +20,12 @@ type Foo implements FooInterface { __foo : String } "); - } + } - [Fact] - public void Arguments_With_Two_Underscores_Are_Not_Allowed() - { - ExpectError(@" + [Fact] + public void Arguments_With_Two_Underscores_Are_Not_Allowed() + { + ExpectError(@" type Query { foo : FooInterface } @@ -38,12 +38,12 @@ type Foo implements FooInterface { foo(__bar: String) : String } "); - } + } - [Fact] - public void Field_Is_Not_Implemented() - { - ExpectError(@" + [Fact] + public void Field_Is_Not_Implemented() + { + ExpectError(@" type Query { foo: Foo } @@ -68,6 +68,5 @@ type Foo implements A & B & C { cde: String } "); - } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/ObjectTypeValidation.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/ObjectTypeValidation.cs index de939cfb80d..21bbe53b012 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/ObjectTypeValidation.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/ObjectTypeValidation.cs @@ -1,33 +1,33 @@ using Xunit; -namespace HotChocolate.Configuration.Validation +namespace HotChocolate.Configuration.Validation; + +public class ObjectTypeValidation : TypeValidationTestBase { - public class ObjectTypeValidation : TypeValidationTestBase + [Fact] + public void Fields_With_Two_Underscores_Are_Not_Allowed() { - [Fact] - public void Fields_With_Two_Underscores_Are_Not_Allowed() - { - ExpectError(@" + ExpectError(@" type Query { __foo : String } "); - } + } - [Fact] - public void Arguments_With_Two_Underscores_Are_Not_Allowed() - { - ExpectError(@" + [Fact] + public void Arguments_With_Two_Underscores_Are_Not_Allowed() + { + ExpectError(@" type Query { foo(__bar: String) : String } "); - } + } - [Fact] - public void Implemented_Field_Is_UnionType_Field_Is_ObjectType() - { - ExpectValid(@" + [Fact] + public void Implemented_Field_Is_UnionType_Field_Is_ObjectType() + { + ExpectValid(@" type Query { foo: Foo } @@ -50,12 +50,12 @@ type Baz { baz: String } "); - } + } - [Fact] - public void Implemented_Field_Is_Interface_Field_Is_ObjectType() - { - ExpectValid(@" + [Fact] + public void Implemented_Field_Is_Interface_Field_Is_ObjectType() + { + ExpectValid(@" type Query { foo: Foo } @@ -76,12 +76,12 @@ type Bar implements BarInterface { bar: String } "); - } + } - [Fact] - public void Implemented_Field_Is_Interface_List_Field_Is_ObjectType_List() - { - ExpectValid(@" + [Fact] + public void Implemented_Field_Is_Interface_List_Field_Is_ObjectType_List() + { + ExpectValid(@" type Query { foo: Foo } @@ -102,12 +102,12 @@ type Bar implements BarInterface { bar: String } "); - } + } - [Fact] - public void Implemented_Field_Is_Interface_Field_Is_NonNull_ObjectType() - { - ExpectValid(@" + [Fact] + public void Implemented_Field_Is_Interface_Field_Is_NonNull_ObjectType() + { + ExpectValid(@" type Query { foo: Foo } @@ -128,12 +128,12 @@ type Bar implements BarInterface { bar: String } "); - } + } - [Fact] - public void Implemented_Field_Is_Nullable_Field_Is_NonNull() - { - ExpectValid(@" + [Fact] + public void Implemented_Field_Is_Nullable_Field_Is_NonNull() + { + ExpectValid(@" type Query { foo: Foo } @@ -146,12 +146,12 @@ type Foo implements FooInterface { bar: String! } "); - } + } - [Fact] - public void Implemented_Field_Is_NonNull_Field_Is_Nullable() - { - ExpectError(@" + [Fact] + public void Implemented_Field_Is_NonNull_Field_Is_Nullable() + { + ExpectError(@" type Query { foo: Foo } @@ -164,12 +164,12 @@ type Foo implements FooInterface { bar: String } "); - } + } - [Fact] - public void All_Arguments_Are_Implemented() - { - ExpectValid(@" + [Fact] + public void All_Arguments_Are_Implemented() + { + ExpectValid(@" type Query { foo: Foo } @@ -182,12 +182,12 @@ type Foo implements FooInterface { abc(a: String): String } "); - } + } - [Fact] - public void Field_Has_Additional_Arguments() - { - ExpectValid(@" + [Fact] + public void Field_Has_Additional_Arguments() + { + ExpectValid(@" type Query { foo: Foo } @@ -200,12 +200,12 @@ type Foo implements FooInterface { abc(a: String b:String): String } "); - } + } - [Fact] - public void Field_Has_Additional_NonNull_Arguments() - { - ExpectError(@" + [Fact] + public void Field_Has_Additional_NonNull_Arguments() + { + ExpectError(@" type Query { foo: Foo } @@ -218,12 +218,12 @@ type Foo implements FooInterface { abc(a: String b:String!): String } "); - } + } - [Fact] - public void Arguments_Are_Not_Implemented() - { - ExpectError(@" + [Fact] + public void Arguments_Are_Not_Implemented() + { + ExpectError(@" type Query { foo: Foo } @@ -236,12 +236,12 @@ type Foo implements FooInterface { abc: String } "); - } + } - [Fact] - public void Implemented_Argument_Types_Do_Not_Match() - { - ExpectError(@" + [Fact] + public void Implemented_Argument_Types_Do_Not_Match() + { + ExpectError(@" type Query { foo: Foo } @@ -254,12 +254,12 @@ type Foo implements FooInterface { abc(a: String!): String } "); - } + } - [Fact] - public void Object_Implements_All_Interfaces() - { - ExpectValid(@" + [Fact] + public void Object_Implements_All_Interfaces() + { + ExpectValid(@" type Query { foo: Foo } @@ -278,12 +278,12 @@ type Foo implements A & B { cde: String } "); - } + } - [Fact] - public void Object_Implements_Not_The_Interfaces_Of_Its_Interfaces() - { - ExpectError(@" + [Fact] + public void Object_Implements_Not_The_Interfaces_Of_Its_Interfaces() + { + ExpectError(@" type Query { foo: Foo } @@ -300,12 +300,12 @@ type Foo implements A & B { abc(a: String): String } "); - } + } - [Fact] - public void Object_Implements_Not_The_Interfaces_Of_Its_Interfaces_2() - { - ExpectError(@" + [Fact] + public void Object_Implements_Not_The_Interfaces_Of_Its_Interfaces_2() + { + ExpectError(@" type Query { foo: Foo } @@ -322,6 +322,5 @@ type Foo implements A { abc(a: String): String } "); - } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/TypeValidationTestBase.cs b/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/TypeValidationTestBase.cs index ff817334be2..bb39bc0da31 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/TypeValidationTestBase.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Configuration/Validation/TypeValidationTestBase.cs @@ -4,49 +4,48 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Configuration.Validation +namespace HotChocolate.Configuration.Validation; + +public class TypeValidationTestBase { - public class TypeValidationTestBase + public static void ExpectValid(string schema) + { + SchemaBuilder.New() + .AddDocumentFromString(schema) + .Use(_ => _ => default) + .ModifyOptions(o => o.EnableOneOf = true) + .Create(); + } + + public static void ExpectError(string schema, params Action[] errorAssert) { - public static void ExpectValid(string schema) + try { SchemaBuilder.New() .AddDocumentFromString(schema) .Use(_ => _ => default) .ModifyOptions(o => o.EnableOneOf = true) .Create(); + Assert.False(true, "Expected error!"); } - - public static void ExpectError(string schema, params Action[] errorAssert) + catch (SchemaException ex) { - try + Assert.NotEmpty(ex.Errors); + + if (errorAssert.Length > 0) { - SchemaBuilder.New() - .AddDocumentFromString(schema) - .Use(_ => _ => default) - .ModifyOptions(o => o.EnableOneOf = true) - .Create(); - Assert.False(true, "Expected error!"); + Assert.Collection(ex.Errors, errorAssert); } - catch (SchemaException ex) - { - Assert.NotEmpty(ex.Errors); - - if (errorAssert.Length > 0) - { - Assert.Collection(ex.Errors, errorAssert); - } - - var text = new StringBuilder(); - foreach (ISchemaError error in ex.Errors) - { - text.AppendLine(error.ToString()); - text.AppendLine(); - } + var text = new StringBuilder(); - text.ToString().MatchSnapshot(); + foreach (var error in ex.Errors) + { + text.AppendLine(error.ToString()); + text.AppendLine(); } + + text.ToString().MatchSnapshot(); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/DataLoader/DataLoaderResolverContextExtensions.cs b/src/HotChocolate/Core/test/Types.Tests/DataLoader/DataLoaderResolverContextExtensions.cs index b8e596cebe0..320b1b8fac0 100644 --- a/src/HotChocolate/Core/test/Types.Tests/DataLoader/DataLoaderResolverContextExtensions.cs +++ b/src/HotChocolate/Core/test/Types.Tests/DataLoader/DataLoaderResolverContextExtensions.cs @@ -8,364 +8,363 @@ using Moq; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class DataLoaderResolverContextExtensionsTests { - public class DataLoaderResolverContextExtensionsTests + [Fact] + public void BatchDataLoader_1_ContextNull_ArgNullException() + { + // arrange + // act + Action a = () => DataLoaderResolverContextExtensions + .BatchDataLoader( + null!, + new FetchBatch((keys, ct) => Task + .FromResult>( + null)), + dataLoaderName: "abc"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void BatchDataLoader_2_ContextNull_ArgNullException() + { + // arrange + // act + Action a = () => DataLoaderResolverContextExtensions + .BatchDataLoader( + null!, + "abc", + new FetchBatch((keys, ct) => Task + .FromResult>( + null))); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void BatchDataLoader_2_KeyNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .BatchDataLoader( + resolverContext.Object, + null, + new FetchBatch((keys, ct) => Task + .FromResult>( + null))); + + // assert + Assert.Throws(a); + } + + [Fact] + public void BatchDataLoader_1_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .BatchDataLoader( + resolverContext.Object, + default(FetchBatch), + dataLoaderName: "123"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void BatchDataLoader_2_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .BatchDataLoader( + resolverContext.Object, + "123", + default(FetchBatch)); + + // assert + Assert.Throws(a); + } + + [Fact] + public void GroupDataLoader_1_ContextNull_ArgNullException() + { + // arrange + var lookup = new Mock>(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .GroupDataLoader( + null, + new FetchGroup((keys, ct) => + Task.FromResult(lookup.Object)), + dataLoaderName: "abc"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void GroupDataLoader_2_ContextNull_ArgNullException() + { + // arrange + var lookup = new Mock>(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .GroupDataLoader( + null, + "abc", + new FetchGroup((keys, ct) => + Task.FromResult(lookup.Object))); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void GroupDataLoader_2_KeyNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + var lookup = new Mock>(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .GroupDataLoader( + resolverContext.Object, + null, + new FetchGroup((keys, ct) => + Task.FromResult(lookup.Object))); + + // assert + Assert.Throws(a); + } + + [Fact] + public void GroupDataLoader_1_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .GroupDataLoader( + resolverContext.Object, + default(FetchGroup), + dataLoaderName: "123"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void GroupDataLoader_2_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .GroupDataLoader( + resolverContext.Object, + "123", + default(FetchGroup)); + + // assert + Assert.Throws(a); + } + + [Fact] + public void CacheDataLoader_1_ContextNull_ArgNullException() + { + // arrange + // act + Action a = () => DataLoaderResolverContextExtensions + .CacheDataLoader( + null, + new FetchCache((keys, ct) => + Task.FromResult(string.Empty)), + key: "abc"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void CacheDataLoader_2_ContextNull_ArgNullException() + { + // arrange + // act + Action a = () => DataLoaderResolverContextExtensions + .CacheDataLoader( + null, + "abc", + new FetchCache((keys, ct) => + Task.FromResult(string.Empty))); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void CacheDataLoader_2_KeyNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .CacheDataLoader( + resolverContext.Object, + null, + new FetchCache((keys, ct) => + Task.FromResult(string.Empty))); + + // assert + Assert.Throws(a); + } + + [Fact] + public void CacheDataLoader_1_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .CacheDataLoader( + resolverContext.Object, + default(FetchCache), + key: "123"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void CacheDataLoader_2_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .CacheDataLoader( + resolverContext.Object, + "123", + default(FetchCache)); + + // assert + Assert.Throws(a); + } + + [Fact] + public void FetchOnceAsync_1_ContextNull_ArgNullException() + { + // arrange + // assert + Action a = () => DataLoaderResolverContextExtensions + .FetchOnceAsync( + null, + new Func>(ct => + Task.FromResult(string.Empty)), + key: "abc"); + + // act + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void FetchOnceAsync_2_ContextNull_ArgNullException() + { + // arrange + // act + Action a = () => DataLoaderResolverContextExtensions + .FetchOnceAsync( + null, + "abc", + new Func>(ct => + Task.FromResult(string.Empty))); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void FetchOnceAsync_2_KeyNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .FetchOnceAsync( + resolverContext.Object, + null, + new Func>(ct => + Task.FromResult(string.Empty))); + + // assert + Assert.Throws(a); + } + + [Fact] + public void FetchOnceAsync_1_FetchNull_ArgNullException() + { + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .FetchOnceAsync( + resolverContext.Object, + default(Func>), + key: "123"); + + // assert + Assert.Throws(a); + } + + [Fact] + [Obsolete] + public void FetchOnceAsync_2_FetchNull_ArgNullException() { - [Fact] - public void BatchDataLoader_1_ContextNull_ArgNullException() - { - // arrange - // act - Action a = () => DataLoaderResolverContextExtensions - .BatchDataLoader( - null!, - new FetchBatch((keys, ct) => Task - .FromResult>( - null)), - dataLoaderName: "abc"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void BatchDataLoader_2_ContextNull_ArgNullException() - { - // arrange - // act - Action a = () => DataLoaderResolverContextExtensions - .BatchDataLoader( - null!, - "abc", - new FetchBatch((keys, ct) => Task - .FromResult>( - null))); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void BatchDataLoader_2_KeyNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .BatchDataLoader( - resolverContext.Object, - null, - new FetchBatch((keys, ct) => Task - .FromResult>( - null))); - - // assert - Assert.Throws(a); - } - - [Fact] - public void BatchDataLoader_1_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .BatchDataLoader( - resolverContext.Object, - default(FetchBatch), - dataLoaderName: "123"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void BatchDataLoader_2_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .BatchDataLoader( - resolverContext.Object, - "123", - default(FetchBatch)); - - // assert - Assert.Throws(a); - } - - [Fact] - public void GroupDataLoader_1_ContextNull_ArgNullException() - { - // arrange - var lookup = new Mock>(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .GroupDataLoader( - null, - new FetchGroup((keys, ct) => - Task.FromResult(lookup.Object)), - dataLoaderName: "abc"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void GroupDataLoader_2_ContextNull_ArgNullException() - { - // arrange - var lookup = new Mock>(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .GroupDataLoader( - null, - "abc", - new FetchGroup((keys, ct) => - Task.FromResult(lookup.Object))); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void GroupDataLoader_2_KeyNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - var lookup = new Mock>(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .GroupDataLoader( - resolverContext.Object, - null, - new FetchGroup((keys, ct) => - Task.FromResult(lookup.Object))); - - // assert - Assert.Throws(a); - } - - [Fact] - public void GroupDataLoader_1_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .GroupDataLoader( - resolverContext.Object, - default(FetchGroup), - dataLoaderName: "123"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void GroupDataLoader_2_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .GroupDataLoader( - resolverContext.Object, - "123", - default(FetchGroup)); - - // assert - Assert.Throws(a); - } - - [Fact] - public void CacheDataLoader_1_ContextNull_ArgNullException() - { - // arrange - // act - Action a = () => DataLoaderResolverContextExtensions - .CacheDataLoader( - null, - new FetchCache((keys, ct) => - Task.FromResult(string.Empty)), - key: "abc"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void CacheDataLoader_2_ContextNull_ArgNullException() - { - // arrange - // act - Action a = () => DataLoaderResolverContextExtensions - .CacheDataLoader( - null, - "abc", - new FetchCache((keys, ct) => - Task.FromResult(string.Empty))); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void CacheDataLoader_2_KeyNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .CacheDataLoader( - resolverContext.Object, - null, - new FetchCache((keys, ct) => - Task.FromResult(string.Empty))); - - // assert - Assert.Throws(a); - } - - [Fact] - public void CacheDataLoader_1_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .CacheDataLoader( - resolverContext.Object, - default(FetchCache), - key: "123"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void CacheDataLoader_2_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .CacheDataLoader( - resolverContext.Object, - "123", - default(FetchCache)); - - // assert - Assert.Throws(a); - } - - [Fact] - public void FetchOnceAsync_1_ContextNull_ArgNullException() - { - // arrange - // assert - Action a = () => DataLoaderResolverContextExtensions - .FetchOnceAsync( - null, - new Func>(ct => - Task.FromResult(string.Empty)), - key: "abc"); - - // act - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void FetchOnceAsync_2_ContextNull_ArgNullException() - { - // arrange - // act - Action a = () => DataLoaderResolverContextExtensions - .FetchOnceAsync( - null, - "abc", - new Func>(ct => - Task.FromResult(string.Empty))); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void FetchOnceAsync_2_KeyNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .FetchOnceAsync( - resolverContext.Object, - null, - new Func>(ct => - Task.FromResult(string.Empty))); - - // assert - Assert.Throws(a); - } - - [Fact] - public void FetchOnceAsync_1_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .FetchOnceAsync( - resolverContext.Object, - default(Func>), - key: "123"); - - // assert - Assert.Throws(a); - } - - [Fact] - [Obsolete] - public void FetchOnceAsync_2_FetchNull_ArgNullException() - { - // arrange - var resolverContext = new Mock(); - - // act - Action a = () => DataLoaderResolverContextExtensions - .FetchOnceAsync( - resolverContext.Object, - "123", - default(Func>)); - - // assert - Assert.Throws(a); - } + // arrange + var resolverContext = new Mock(); + + // act + Action a = () => DataLoaderResolverContextExtensions + .FetchOnceAsync( + resolverContext.Object, + "123", + default(Func>)); + + // assert + Assert.Throws(a); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Document.Tests.cs b/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Document.Tests.cs index 52a8b4cba33..ddcd145bee7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Document.Tests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Document.Tests.cs @@ -5,69 +5,67 @@ using Snapshooter.Xunit; using IOPath = System.IO.Path; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaBuilderExtensionsDocumentTests { - public class SchemaBuilderExtensionsDocumentTests + [Fact] + public void AddDocumentFromFile_Builder_Is_Null() { - [Fact] - public void AddDocumentFromFile_Builder_Is_Null() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddDocumentFromFile(null, "abc"); + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddDocumentFromFile(null, "abc"); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddDocumentFromFile_File_Is_Null() - { - // arrange - var builder = SchemaBuilder.New(); + [Fact] + public void AddDocumentFromFile_File_Is_Null() + { + // arrange + var builder = SchemaBuilder.New(); - // act - Action action = () => - SchemaBuilderExtensions.AddDocumentFromFile(builder, null); + // act + Action action = () => + SchemaBuilderExtensions.AddDocumentFromFile(builder, null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddDocumentFromFile_File_Is_Empty() - { - // arrange - var builder = SchemaBuilder.New(); + [Fact] + public void AddDocumentFromFile_File_Is_Empty() + { + // arrange + var builder = SchemaBuilder.New(); - // act - Action action = () => - SchemaBuilderExtensions.AddDocumentFromFile( - builder, string.Empty); + // act + Action action = () => + SchemaBuilderExtensions.AddDocumentFromFile( + builder, string.Empty); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public async Task AddDocumentFromFile() - { - // arrange - var builder = SchemaBuilder.New(); - string file = IOPath.GetTempFileName(); - await File.WriteAllTextAsync(file, "type Query { a: String }"); + [Fact] + public async Task AddDocumentFromFile() + { + // arrange + var builder = SchemaBuilder.New(); + var file = IOPath.GetTempFileName(); + await File.WriteAllTextAsync(file, "type Query { a: String }"); - // act - SchemaBuilderExtensions.AddDocumentFromFile(builder, file); + // act + SchemaBuilderExtensions.AddDocumentFromFile(builder, file); - // assert - ISchema schema = builder - .Use(next => context => next.Invoke(context)) - .Create(); + // assert + var schema = builder + .Use(next => context => next.Invoke(context)) + .Create(); - schema.ToString().MatchSnapshot(); - } + schema.ToString().MatchSnapshot(); } } - diff --git a/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Resolvers.Tests.cs b/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Resolvers.Tests.cs index 3fa0573ec64..50959c17762 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Resolvers.Tests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Resolvers.Tests.cs @@ -6,315 +6,313 @@ using HotChocolate.Resolvers; using HotChocolate.Tests; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaBuilderExtensionsResolversTests { - public class SchemaBuilderExtensionsResolversTests + [Fact] + public void AddResolverContextObject_BuilderIsNull_ArgNullExcept() { - [Fact] - public void AddResolverContextObject_BuilderIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - null, - "A", - "B", - new Func(c => new object())); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void AddResolverContextObject_ResolverIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - builder, - "A", - "B", - (Func)null); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task AddResolverContextObject_ResolveField() - { - // arrange - Snapshot.FullName(); - var builder = new SchemaBuilder(); - builder.AddDocumentFromString("type Query { foo: String }"); - - // act - SchemaBuilderExtensions - .AddResolver( - builder, - "Query", - "foo", - new Func(c => "bar")); - - // assert - await builder.Create() - .MakeExecutable() - .ExecuteAsync("{ foo }") - .MatchSnapshotAsync(); - } - - [Fact] - public void AddResolverContextTaskObject_BuilderIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - null, - "A", - "B", - new Func>( - c => Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void AddResolverContextTaskObject_ResolverIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - builder, - "A", - "B", - (Func>)null); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task AddResolverContextTaskObject_ResolveField() - { - // arrange - Snapshot.FullName(); - var builder = new SchemaBuilder(); - builder.AddDocumentFromString("type Query { foo: String }"); - - // act - SchemaBuilderExtensions - .AddResolver( - builder, - "Query", - "foo", - new Func>( - c => new ValueTask("bar"))); - - // assert - await builder.Create() - .MakeExecutable() - .ExecuteAsync("{ foo }") - .MatchSnapshotAsync(); - } - - [Fact] - public void AddResolverContextTResult_BuilderIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - null, - "A", - "B", - new Func( - c => "abc")); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void AddResolverContextTResult_ResolverIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - builder, - "A", - "B", - (Func)null); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task AddResolverContextTResult_ResolveField() - { - // arrange - Snapshot.FullName(); - var builder = new SchemaBuilder(); - builder.AddDocumentFromString("type Query { foo: String }"); - - // act - SchemaBuilderExtensions - .AddResolver( - builder, - "Query", - "foo", - new Func( - c => "bar")); - - // assert - await builder.Create() - .MakeExecutable() - .ExecuteAsync("{ foo }") - .MatchSnapshotAsync(); - } - - [Fact] - public void AddResolverContextTaskTResult_BuilderIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - null, - "A", - "B", - new Func>( - c => Task.FromResult("abc"))); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void AddResolverContextTaskTResult_ResolverIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - builder, - "A", - "B", - (Func>)null); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task AddResolverContextTaskTResult_ResolveField() - { - // arrange - Snapshot.FullName(); - var builder = new SchemaBuilder(); - builder.AddDocumentFromString("type Query { foo: String }"); - - // act - SchemaBuilderExtensions - .AddResolver( - builder, - "Query", - "foo", - new Func>( - c => new ValueTask("bar"))); - - // assert - await builder.Create() - .MakeExecutable() - .ExecuteAsync("{ foo }") - .MatchSnapshotAsync(); - } - - [Fact] - public void AddResolverObject_BuilderIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - null, - "A", - "B", - new Func(() => "abc")); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void AddResolverObject_ResolverIsNull_ArgNullExcept() - { - // arrange - var builder = new SchemaBuilder(); - - // act - Action action = () => SchemaBuilderExtensions - .AddResolver( - builder, - "A", - "B", - (Func)null); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task AddResolverObject_ResolveField() - { - // arrange - Snapshot.FullName(); - var builder = new SchemaBuilder(); - builder.AddDocumentFromString("type Query { foo: String }"); - - // act - SchemaBuilderExtensions - .AddResolver( - builder, - "Query", - "foo", - new Func(() => "bar")); - - // assert - await builder.Create() - .MakeExecutable() - .ExecuteAsync("{ foo }") - .MatchSnapshotAsync(); - } + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + null, + "A", + "B", + new Func(c => new object())); + + // assert + Assert.Throws(action); } -} + + [Fact] + public void AddResolverContextObject_ResolverIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + builder, + "A", + "B", + (Func)null); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task AddResolverContextObject_ResolveField() + { + // arrange + Snapshot.FullName(); + var builder = new SchemaBuilder(); + builder.AddDocumentFromString("type Query { foo: String }"); + + // act + SchemaBuilderExtensions + .AddResolver( + builder, + "Query", + "foo", + new Func(c => "bar")); + + // assert + await builder.Create() + .MakeExecutable() + .ExecuteAsync("{ foo }") + .MatchSnapshotAsync(); + } + + [Fact] + public void AddResolverContextTaskObject_BuilderIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + null, + "A", + "B", + new Func>( + c => Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void AddResolverContextTaskObject_ResolverIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + builder, + "A", + "B", + (Func>)null); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task AddResolverContextTaskObject_ResolveField() + { + // arrange + Snapshot.FullName(); + var builder = new SchemaBuilder(); + builder.AddDocumentFromString("type Query { foo: String }"); + + // act + SchemaBuilderExtensions + .AddResolver( + builder, + "Query", + "foo", + new Func>( + c => new ValueTask("bar"))); + + // assert + await builder.Create() + .MakeExecutable() + .ExecuteAsync("{ foo }") + .MatchSnapshotAsync(); + } + + [Fact] + public void AddResolverContextTResult_BuilderIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + null, + "A", + "B", + new Func( + c => "abc")); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void AddResolverContextTResult_ResolverIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + builder, + "A", + "B", + (Func)null); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task AddResolverContextTResult_ResolveField() + { + // arrange + Snapshot.FullName(); + var builder = new SchemaBuilder(); + builder.AddDocumentFromString("type Query { foo: String }"); + + // act + SchemaBuilderExtensions + .AddResolver( + builder, + "Query", + "foo", + new Func( + c => "bar")); + + // assert + await builder.Create() + .MakeExecutable() + .ExecuteAsync("{ foo }") + .MatchSnapshotAsync(); + } + + [Fact] + public void AddResolverContextTaskTResult_BuilderIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + null, + "A", + "B", + new Func>( + c => Task.FromResult("abc"))); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void AddResolverContextTaskTResult_ResolverIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + builder, + "A", + "B", + (Func>)null); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task AddResolverContextTaskTResult_ResolveField() + { + // arrange + Snapshot.FullName(); + var builder = new SchemaBuilder(); + builder.AddDocumentFromString("type Query { foo: String }"); + + // act + SchemaBuilderExtensions + .AddResolver( + builder, + "Query", + "foo", + new Func>( + c => new ValueTask("bar"))); + + // assert + await builder.Create() + .MakeExecutable() + .ExecuteAsync("{ foo }") + .MatchSnapshotAsync(); + } + + [Fact] + public void AddResolverObject_BuilderIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + null, + "A", + "B", + new Func(() => "abc")); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void AddResolverObject_ResolverIsNull_ArgNullExcept() + { + // arrange + var builder = new SchemaBuilder(); + + // act + Action action = () => SchemaBuilderExtensions + .AddResolver( + builder, + "A", + "B", + (Func)null); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task AddResolverObject_ResolveField() + { + // arrange + Snapshot.FullName(); + var builder = new SchemaBuilder(); + builder.AddDocumentFromString("type Query { foo: String }"); + + // act + SchemaBuilderExtensions + .AddResolver( + builder, + "Query", + "foo", + new Func(() => "bar")); + + // assert + await builder.Create() + .MakeExecutable() + .ExecuteAsync("{ foo }") + .MatchSnapshotAsync(); + } +} diff --git a/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Types.Tests.cs b/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Types.Tests.cs index 73ff047eb4d..374b54d2129 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Types.Tests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Extensions/SchemaBuilderExtensions.Types.Tests.cs @@ -4,1165 +4,1164 @@ using HotChocolate.Types; using HotChocolate.Language; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaBuilderExtensionsTypeTests { - public class SchemaBuilderExtensionsTypeTests + [Fact] + public void AddQueryTypeDesc_ConfigureIsNull_ArgumentNullException() { - [Fact] - public void AddQueryTypeDesc_ConfigureIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(builder, (Action)null); + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(builder, (Action)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeDesc_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(null, t => { }); + [Fact] + public void AddQueryTypeDesc_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(null, t => { }); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeDesc_ConfigureQueryType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeDesc_ConfigureQueryType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); - // act - SchemaBuilderExtensions.AddQueryType(builder, - t => t.Name("Foo").Field("bar").Resolve("result")); + // act + SchemaBuilderExtensions.AddQueryType(builder, + t => t.Name("Foo").Field("bar").Resolve("result")); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationTypeDesc_ConfigureIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddMutationTypeDesc_ConfigureIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, (Action)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, (Action)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeDesc_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, t => { }); + [Fact] + public void AddMutationTypeDesc_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, t => { }); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeDesc_ConfigureQueryType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddMutationTypeDesc_ConfigureQueryType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddMutationType(builder, - t => t.Name("Foo").Field("bar").Resolve("result")); + // act + SchemaBuilderExtensions.AddMutationType(builder, + t => t.Name("Foo").Field("bar").Resolve("result")); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddSubscriptionTypeDesc_ConfigureIsNull_ArgNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddSubscriptionTypeDesc_ConfigureIsNull_ArgNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, (Action)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, (Action)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeDesc_BuilderIsNull_ArgNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, t => { }); + [Fact] + public void AddSubscriptionTypeDesc_BuilderIsNull_ArgNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, t => { }); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeDesc_ConfigureQueryType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddSubscriptionTypeDesc_ConfigureQueryType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddSubscriptionType(builder, - t => t.Name("Foo").Field("bar").Resolve("result")); + // act + SchemaBuilderExtensions.AddSubscriptionType(builder, + t => t.Name("Foo").Field("bar").Resolve("result")); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddQueryTypeDescT_ConfigureIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeDescT_ConfigureIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(builder, - (Action>)null); + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(builder, + (Action>)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeDescT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(null, t => { }); + [Fact] + public void AddQueryTypeDescT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(null, t => { }); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeDescT_ConfigureQueryType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeDescT_ConfigureQueryType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); - // act - SchemaBuilderExtensions.AddQueryType(builder, - t => t.Name("Foo").Field(f => f.Bar).Resolve("result")); + // act + SchemaBuilderExtensions.AddQueryType(builder, + t => t.Name("Foo").Field(f => f.Bar).Resolve("result")); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationTypeDescT_ConfigureIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddMutationTypeDescT_ConfigureIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, - (Action>)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, + (Action>)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeDescT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, t => { }); + [Fact] + public void AddMutationTypeDescT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, t => { }); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeDescT_ConfigureQueryType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddMutationTypeDescT_ConfigureQueryType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddMutationType(builder, - t => t.Name("Foo").Field(f => f.Bar).Resolve("result")); + // act + SchemaBuilderExtensions.AddMutationType(builder, + t => t.Name("Foo").Field(f => f.Bar).Resolve("result")); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddSubscriptionTypeDescT_ConfigureIsNull_ArgNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddSubscriptionTypeDescT_ConfigureIsNull_ArgNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, - (Action>)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, + (Action>)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeDescT_BuilderIsNull_ArgNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, t => { }); + [Fact] + public void AddSubscriptionTypeDescT_BuilderIsNull_ArgNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, t => { }); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeDescT_ConfQueryType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddSubscriptionTypeDescT_ConfQueryType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddSubscriptionType(builder, - t => t.Name("Foo").Field(f => f.Bar).Resolve("result")); + // act + SchemaBuilderExtensions.AddSubscriptionType(builder, + t => t.Name("Foo").Field(f => f.Bar).Resolve("result")); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddQueryTypeType_TypeIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeType_TypeIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(builder, (Type)null); + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(builder, (Type)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(null, typeof(FooType)); + [Fact] + public void AddQueryTypeType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(null, typeof(FooType)); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeType_TypeIsFooType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeType_TypeIsFooType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); - // act - SchemaBuilderExtensions.AddQueryType(builder, typeof(FooType)); + // act + SchemaBuilderExtensions.AddQueryType(builder, typeof(FooType)); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationTypeType_TypeIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddMutationTypeType_TypeIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, (Type)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, (Type)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, typeof(FooType)); + [Fact] + public void AddMutationTypeType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, typeof(FooType)); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeType_TypeIsFooType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddMutationTypeType_TypeIsFooType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddMutationType(builder, typeof(FooType)); + // act + SchemaBuilderExtensions.AddMutationType(builder, typeof(FooType)); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddSubscriptionTypeType_TypeIsNull_ArgNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddSubscriptionTypeType_TypeIsNull_ArgNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, (Type)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, (Type)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeType_BuilderIsNull_ArgNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, typeof(FooType)); + [Fact] + public void AddSubscriptionTypeType_BuilderIsNull_ArgNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, typeof(FooType)); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeType_TypeIsFooType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddSubscriptionTypeType_TypeIsFooType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddSubscriptionType( - builder, typeof(FooType)); + // act + SchemaBuilderExtensions.AddSubscriptionType( + builder, typeof(FooType)); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddQueryTypeObjectType_TypeIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeObjectType_TypeIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(builder, (ObjectType)null); + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(builder, (ObjectType)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeObjectType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddQueryType(null, new FooType()); + [Fact] + public void AddQueryTypeObjectType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddQueryType(null, new FooType()); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddQueryTypeObjectType_TypeIsFooType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddQueryTypeObjectType_TypeIsFooType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); - // act - SchemaBuilderExtensions.AddQueryType(builder, new FooType()); + // act + SchemaBuilderExtensions.AddQueryType(builder, new FooType()); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationTypeObjectType_TypeIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddMutationTypeObjectType_TypeIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, (ObjectType)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, (ObjectType)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeObjectType_BuilderIsNull_ArgNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, new FooType()); + [Fact] + public void AddMutationTypeObjectType_BuilderIsNull_ArgNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, new FooType()); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddMutationTypeObjectType_TypeIsFooType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddMutationTypeObjectType_TypeIsFooType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddMutationType(builder, new FooType()); + // act + SchemaBuilderExtensions.AddMutationType(builder, new FooType()); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddSubscriptionTypeObjectType_TypeIsNull_ArgNullException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void AddSubscriptionTypeObjectType_TypeIsNull_ArgNullException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(builder, (ObjectType)null); + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(builder, (ObjectType)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeObjType_BuilderIsNull_ArgNullException() - { - // arrange - // act - Action action = () => SchemaBuilderExtensions - .AddMutationType(null, new FooType()); + [Fact] + public void AddSubscriptionTypeObjType_BuilderIsNull_ArgNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions + .AddMutationType(null, new FooType()); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddSubscriptionTypeObjType_TypeIsFooType_SchemaIsCreated() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + [Fact] + public void AddSubscriptionTypeObjType_TypeIsFooType_SchemaIsCreated() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // act - SchemaBuilderExtensions.AddSubscriptionType( - builder, new FooType()); + // act + SchemaBuilderExtensions.AddSubscriptionType( + builder, new FooType()); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void SetSchema_BuilderIsNull_ArgumentException() - { - // arrange - var builder = new SchemaBuilder(); + [Fact] + public void SetSchema_BuilderIsNull_ArgumentException() + { + // arrange + var builder = new SchemaBuilder(); - // act - Action action = () => - SchemaBuilderExtensions.SetSchema(null); + // act + Action action = () => + SchemaBuilderExtensions.SetSchema(null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void SetSchema_TypeSchema_SchemaIsCreatedFromType() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); - - // act - ISchema schema = SchemaBuilder.New() - .SetSchema() - .AddType(queryType) - .Create(); - - // assert - Assert.Equal("Description", - Assert.IsType(schema).Description); - } + [Fact] + public void SetSchema_TypeSchema_SchemaIsCreatedFromType() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + // act + var schema = SchemaBuilder.New() + .SetSchema() + .AddType(queryType) + .Create(); + + // assert + Assert.Equal("Description", + Assert.IsType(schema).Description); + } - [Fact] - public void AddObjectType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddObjectType( - null, c => { }); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddObjectType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddObjectType( + null, c => { }); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddObjectType_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddObjectType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddObjectType_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddObjectType( + SchemaBuilder.New(), null); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddObjectTypeT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddObjectType( - null, c => { }); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddObjectTypeT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddObjectType( + null, c => { }); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddObjectTypeT2_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddObjectType(null); + [Fact] + public void AddObjectTypeT2_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddObjectType(null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddObjectTypeT_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddObjectType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddObjectTypeT_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddObjectType( + SchemaBuilder.New(), null); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddDirectiveType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddDirectiveType( - null, typeof(MyDirective)); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddDirectiveType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddDirectiveType( + null, typeof(MyDirective)); - [Fact] - public void AddDirectiveType_TypeIsNull_ArgumentNullException() - { - // arrange - var builder = new SchemaBuilder(); + // assert + Assert.Throws(action); + } - // act - Action action = () => - SchemaBuilderExtensions.AddDirectiveType(builder, (Type)null); + [Fact] + public void AddDirectiveType_TypeIsNull_ArgumentNullException() + { + // arrange + var builder = new SchemaBuilder(); - // assert - Assert.Throws(action); - } + // act + Action action = () => + SchemaBuilderExtensions.AddDirectiveType(builder, (Type)null); - [Fact] - public void AddDirectiveType_TypeIsDirectiveType_ArgumentException() - { - // arrange - var builder = new SchemaBuilder(); + // assert + Assert.Throws(action); + } - // act - Action action = () => - SchemaBuilderExtensions.AddDirectiveType( - builder, typeof(DirectiveType)); + [Fact] + public void AddDirectiveType_TypeIsDirectiveType_ArgumentException() + { + // arrange + var builder = new SchemaBuilder(); - // assert - Assert.Throws(action); - } + // act + Action action = () => + SchemaBuilderExtensions.AddDirectiveType( + builder, typeof(DirectiveType)); - [Fact] - public void AddDirectiveType_TypeIsDirectiveTypeFoo_ArgumentException() - { - // arrange - var builder = new SchemaBuilder(); + // assert + Assert.Throws(action); + } - // act - Action action = () => - SchemaBuilderExtensions.AddDirectiveType( - builder, typeof(DirectiveType)); + [Fact] + public void AddDirectiveType_TypeIsDirectiveTypeFoo_ArgumentException() + { + // arrange + var builder = new SchemaBuilder(); - // assert - Assert.Throws(action); - } + // act + Action action = () => + SchemaBuilderExtensions.AddDirectiveType( + builder, typeof(DirectiveType)); - [Fact] - public void AddDirectiveType_TypeIsMyDirectiveType_SchemaIsValid() - { - // arrange - var builder = new SchemaBuilder(); - builder.AddQueryType(); + // assert + Assert.Throws(action); + } - // act - SchemaBuilderExtensions.AddDirectiveType( - builder, typeof(MyDirective)); + [Fact] + public void AddDirectiveType_TypeIsMyDirectiveType_SchemaIsValid() + { + // arrange + var builder = new SchemaBuilder(); + builder.AddQueryType(); - // assert - builder.Create().ToString().MatchSnapshot(); - } + // act + SchemaBuilderExtensions.AddDirectiveType( + builder, typeof(MyDirective)); - [Fact] - public void AddInterfaceType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInterfaceType( - null, c => { }); - - // assert - Assert.Throws(action); - } + // assert + builder.Create().ToString().MatchSnapshot(); + } - [Fact] - public void AddInterfaceType_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); + [Fact] + public void AddInterfaceType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInterfaceType( + null, c => { }); + + // assert + Assert.Throws(action); + } - // act + [Fact] + public void AddInterfaceType_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + + // act + SchemaBuilderExtensions.AddInterfaceType( + builder, d => d.Name("ABC").Field("abc").Type()); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } + + [Fact] + public void AddInterfaceType_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions.AddInterfaceType( - builder, d => d.Name("ABC").Field("abc").Type()); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + SchemaBuilder.New(), null); - [Fact] - public void AddInterfaceType_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInterfaceType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddInterfaceTypeT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInterfaceType( - null, c => { }); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddInterfaceTypeT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInterfaceType( + null, c => { }); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddInterfaceTypeT2_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInterfaceType(null); + [Fact] + public void AddInterfaceTypeT2_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInterfaceType(null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddInterfaceTypeT_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInterfaceType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddInterfaceTypeT_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInterfaceType( + SchemaBuilder.New(), null); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddInterfaceTypeT_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); - - // act - SchemaBuilderExtensions.AddInterfaceType( - builder, d => d.Field("abc").Type()); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void AddInterfaceTypeT_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + + // act + SchemaBuilderExtensions.AddInterfaceType( + builder, d => d.Field("abc").Type()); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void AddUnionType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddUnionType( - null, c => { }); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddUnionType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddUnionType( + null, c => { }); - [Fact] - public void AddUnionType_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddUnionType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddUnionType_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); - builder.AddObjectType(d => d - .Name("Foo") - .Field("bar") - .Type() - .Resolve("empty")); - - // act + [Fact] + public void AddUnionType_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions.AddUnionType( - builder, d => d.Name("ABC").Type(new NamedTypeNode("Foo"))); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + SchemaBuilder.New(), null); - [Fact] - public void AddUnionTypeT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddUnionType( - null, c => { }); - - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddUnionTypeT2_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddUnionType(null); + [Fact] + public void AddUnionType_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + builder.AddObjectType(d => d + .Name("Foo") + .Field("bar") + .Type() + .Resolve("empty")); + + // act + SchemaBuilderExtensions.AddUnionType( + builder, d => d.Name("ABC").Type(new NamedTypeNode("Foo"))); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddUnionTypeT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddUnionType( + null, c => { }); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddUnionTypeT_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddUnionType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddUnionTypeT2_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddUnionType(null); - [Fact] - public void AddUnionTypeT_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); - builder.AddObjectType(d => d - .Name("Foo") - .Field("bar") - .Type() - .Resolve("empty")); - - // act - SchemaBuilderExtensions.AddUnionType( - builder, d => d.Name("ABC").Type(new NamedTypeNode("Foo"))); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddInputObjectType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInputObjectType( - null, c => { }); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddUnionTypeT_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddUnionType( + SchemaBuilder.New(), null); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddInputObjectType_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInputObjectType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddUnionTypeT_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + builder.AddObjectType(d => d + .Name("Foo") + .Field("bar") + .Type() + .Resolve("empty")); + + // act + SchemaBuilderExtensions.AddUnionType( + builder, d => d.Name("ABC").Type(new NamedTypeNode("Foo"))); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void AddInputObjectType_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); + [Fact] + public void AddInputObjectType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInputObjectType( + null, c => { }); + + // assert + Assert.Throws(action); + } - // act + [Fact] + public void AddInputObjectType_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions.AddInputObjectType( - builder, d => d.Name("Foo").Field("bar").Type()); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + SchemaBuilder.New(), null); - [Fact] - public void AddInputObjectTypeT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInputObjectType( - null, c => { }); - - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddInputObjectTypeT2_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInputObjectType(null); + [Fact] + public void AddInputObjectType_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + + // act + SchemaBuilderExtensions.AddInputObjectType( + builder, d => d.Name("Foo").Field("bar").Type()); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddInputObjectTypeT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInputObjectType( + null, c => { }); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddInputObjectTypeT_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddInputObjectType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddInputObjectTypeT2_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInputObjectType(null); - [Fact] - public void AddInputObjectTypeT_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); - - // act - SchemaBuilderExtensions.AddInputObjectType( - builder, d => d.Field("qux").Type()); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + // assert + Assert.Throws(action); + } + + [Fact] + public void AddInputObjectTypeT_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddInputObjectType( + SchemaBuilder.New(), null); + + // assert + Assert.Throws(action); + } + [Fact] + public void AddInputObjectTypeT_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + + // act + SchemaBuilderExtensions.AddInputObjectType( + builder, d => d.Field("qux").Type()); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void AddEnumType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddEnumType( - null, c => { }); - - // assert - Assert.Throws(action); - } - [Fact] - public void AddEnumType_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddEnumType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddEnumType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddEnumType( + null, c => { }); - [Fact] - public void AddEnumType_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); + // assert + Assert.Throws(action); + } - // act + [Fact] + public void AddEnumType_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilderExtensions.AddEnumType( - builder, d => d.Name("Foo").Value("bar").Name("BAZ")); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + SchemaBuilder.New(), null); - [Fact] - public void AddEnumTypeT_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddEnumType( - null, c => { }); - - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddEnumTypeT2_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddEnumType(null); + [Fact] + public void AddEnumType_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + + // act + SchemaBuilderExtensions.AddEnumType( + builder, d => d.Name("Foo").Value("bar").Name("BAZ")); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddEnumTypeT_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddEnumType( + null, c => { }); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddEnumTypeT_ConfigureIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - SchemaBuilderExtensions.AddObjectType( - SchemaBuilder.New(), null); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddEnumTypeT2_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddEnumType(null); - [Fact] - public void AddEnumTypeT_With_Descriptor() - { - // arrange - SchemaBuilder builder = SchemaBuilder.New(); - - // act - SchemaBuilderExtensions.AddEnumType( - builder, d => d.BindValuesExplicitly().Value(MyEnum.A)); - - // assert - builder - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - public class QueryType - : ObjectType - { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("foo").Type().Resolve("bar"); - } - } + [Fact] + public void AddEnumTypeT_ConfigureIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + SchemaBuilderExtensions.AddObjectType( + SchemaBuilder.New(), null); + + // assert + Assert.Throws(action); + } - public class MutationType - : ObjectType - { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Mutation"); - descriptor.Field("bar").Type().Resolve(123); - } - } + [Fact] + public void AddEnumTypeT_With_Descriptor() + { + // arrange + var builder = SchemaBuilder.New(); + + // act + SchemaBuilderExtensions.AddEnumType( + builder, d => d.BindValuesExplicitly().Value(MyEnum.A)); + + // assert + builder + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - public class SubscriptionType - : ObjectType + public class QueryType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Subscription"); - descriptor.Field("onFoo").Type().Resolve(123); - } + descriptor.Name("Query"); + descriptor.Field("foo").Type().Resolve("bar"); } + } - public class FooType - : ObjectType + public class MutationType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Bar).Type>(); - } + descriptor.Name("Mutation"); + descriptor.Field("bar").Type().Resolve(123); } + } - public class BarType - : ObjectType + public class SubscriptionType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { + descriptor.Name("Subscription"); + descriptor.Field("onFoo").Type().Resolve(123); } + } - public class Foo + public class FooType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public Bar Bar { get; } + descriptor.Field(t => t.Bar).Type>(); } + } - public class Bar - { - public string Baz { get; } - } + public class BarType + : ObjectType + { + } - public class MySchema - : Schema + public class Foo + { + public Bar Bar { get; } + } + + public class Bar + { + public string Baz { get; } + } + + public class MySchema + : Schema + { + protected override void Configure(ISchemaTypeDescriptor descriptor) { - protected override void Configure(ISchemaTypeDescriptor descriptor) - { - descriptor.Description("Description"); - } + descriptor.Description("Description"); } + } - public class MyDirective - : DirectiveType + public class MyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("my"); - descriptor.Location(Types.DirectiveLocation.Field); - } + descriptor.Name("my"); + descriptor.Location(Types.DirectiveLocation.Field); } + } - public interface IMyInterface - { + public interface IMyInterface + { - } + } - public enum MyEnum - { - A, - B - } + public enum MyEnum + { + A, + B } } diff --git a/src/HotChocolate/Core/test/Types.Tests/ForbiddenRuntimeTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/ForbiddenRuntimeTypeTests.cs index b85af819c45..2579e331bc7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/ForbiddenRuntimeTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/ForbiddenRuntimeTypeTests.cs @@ -5,44 +5,43 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class ForbiddenRuntimeTypeTests { - public class ForbiddenRuntimeTypeTests + [Fact] + public async Task Executable_NotAllowed() { - [Fact] - public async Task Executable_NotAllowed() - { - async Task SchemaError() => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync(); + async Task SchemaError() => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync(); - SchemaException exception = await Assert.ThrowsAsync(SchemaError); - exception.Errors[0].Message.MatchSnapshot(); - } + var exception = await Assert.ThrowsAsync(SchemaError); + exception.Errors[0].Message.MatchSnapshot(); + } - [Fact] - public async Task ExecutableList_NotAllowed() - { - async Task SchemaError() => - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync(); + [Fact] + public async Task ExecutableList_NotAllowed() + { + async Task SchemaError() => + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync(); - SchemaException exception = await Assert.ThrowsAsync(SchemaError); - exception.Errors[0].Message.MatchSnapshot(); - } + var exception = await Assert.ThrowsAsync(SchemaError); + exception.Errors[0].Message.MatchSnapshot(); + } - public class Query1 - { - public IExecutable Executable() => throw new InvalidOperationException(); - } + public class Query1 + { + public IExecutable Executable() => throw new InvalidOperationException(); + } - public class Query2 - { - public IExecutable[] Executable() => throw new InvalidOperationException(); - } + public class Query2 + { + public IExecutable[] Executable() => throw new InvalidOperationException(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/GraphQLNonNullTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/GraphQLNonNullTypeTests.cs index b18f09bb4e2..e2899fb3a05 100644 --- a/src/HotChocolate/Core/test/Types.Tests/GraphQLNonNullTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/GraphQLNonNullTypeTests.cs @@ -7,189 +7,188 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class GraphQLNonNullTypeTests { - public class GraphQLNonNullTypeTests + [Fact] + public async Task GraphQLNonNull_Should_RewriteFirstToNonNull_When_NoParametersAreSet() { - [Fact] - public async Task GraphQLNonNull_Should_RewriteFirstToNonNull_When_NoParametersAreSet() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLNonNull_Should_RewriteToNonNull_When_ParametersAreSet() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task GraphQLNonNull_Should_RewriteToNonNull_When_ParametersAreSet() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLNonNull_Should_RewriteToNonNull_When_GraphQLTypeIsUsed() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task GraphQLNonNull_Should_RewriteToNonNull_When_GraphQLTypeIsUsed() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLNonNull_Should_RewriteFirstToNonNull_When_RequiredIsSet() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task GraphQLNonNull_Should_RewriteFirstToNonNull_When_RequiredIsSet() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task GraphQLNonNull_Should_RewriteFirstToNonNull_When_RequiredAndTypeIsSet() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task GraphQLNonNull_Should_RewriteFirstToNonNull_When_RequiredAndTypeIsSet() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - public class Query - { - [GraphQLNonNullType()] - public string? Scalar { get; } + public class Query + { + [GraphQLNonNullType()] + public string? Scalar { get; } - [GraphQLNonNullType] - public string?[]? ScalarArray { get; } + [GraphQLNonNullType] + public string?[]? ScalarArray { get; } - [GraphQLNonNullType] - public string?[]?[]? ScalarNestedArray { get; } + [GraphQLNonNullType] + public string?[]?[]? ScalarNestedArray { get; } - [GraphQLNonNullType] - public Foo? Object { get; } + [GraphQLNonNullType] + public Foo? Object { get; } - [GraphQLNonNullType] - public Foo?[]? ObjectArray { get; } + [GraphQLNonNullType] + public Foo?[]? ObjectArray { get; } - [GraphQLNonNullType] - public Foo?[]?[]? ObjectNestedArray { get; } - } + [GraphQLNonNullType] + public Foo?[]?[]? ObjectNestedArray { get; } + } - public class QueryRequired - { - [Required] - public string? Scalar { get; } + public class QueryRequired + { + [Required] + public string? Scalar { get; } - [Required] - public string?[]? ScalarArray { get; } + [Required] + public string?[]? ScalarArray { get; } - [Required] - public string?[]?[]? ScalarNestedArray { get; } + [Required] + public string?[]?[]? ScalarNestedArray { get; } - [Required] - public Foo? Object { get; } + [Required] + public Foo? Object { get; } - [Required] - public Foo?[]? ObjectArray { get; } + [Required] + public Foo?[]? ObjectArray { get; } - [Required] - public Foo?[]?[]? ObjectNestedArray { get; } - } + [Required] + public Foo?[]?[]? ObjectNestedArray { get; } + } - public class QueryDeep - { - [GraphQLNonNullType()] - public string? Scalar { get; } + public class QueryDeep + { + [GraphQLNonNullType()] + public string? Scalar { get; } - [GraphQLNonNullType(false, false)] - public string?[]? ScalarArray { get; } + [GraphQLNonNullType(false, false)] + public string?[]? ScalarArray { get; } - [GraphQLNonNullType(false, false,false)] - public string?[]?[]? ScalarNestedArray { get; } + [GraphQLNonNullType(false, false,false)] + public string?[]?[]? ScalarNestedArray { get; } - [GraphQLNonNullType] - public Foo? Object { get; } + [GraphQLNonNullType] + public Foo? Object { get; } - [GraphQLNonNullType(false, false)] - public Foo?[]? ObjectArray { get; } + [GraphQLNonNullType(false, false)] + public Foo?[]? ObjectArray { get; } - [GraphQLNonNullType(false, false,false)] - public Foo?[]?[]? ObjectNestedArray { get; } - } + [GraphQLNonNullType(false, false,false)] + public Foo?[]?[]? ObjectNestedArray { get; } + } - public class QueryRequiredWithType - { - [Required] - [GraphQLType(typeof(IdType))] - public string Scalar { get; } = default!; + public class QueryRequiredWithType + { + [Required] + [GraphQLType(typeof(IdType))] + public string Scalar { get; } = default!; - [Required] - [GraphQLType(typeof(ListType))] - public string[] ScalarArray { get; } = default!; + [Required] + [GraphQLType(typeof(ListType))] + public string[] ScalarArray { get; } = default!; - [Required] - [GraphQLType(typeof(ListType>))] - public string[][] ScalarNestedArray { get; } = default!; + [Required] + [GraphQLType(typeof(ListType>))] + public string[][] ScalarNestedArray { get; } = default!; - [Required] - [GraphQLType(typeof(FooType))] - public Foo Object { get; } = default!; + [Required] + [GraphQLType(typeof(FooType))] + public Foo Object { get; } = default!; - [Required] - [GraphQLType(typeof(ListType))] - public Foo[] ObjectArray { get; } = default!; + [Required] + [GraphQLType(typeof(ListType))] + public Foo[] ObjectArray { get; } = default!; - [Required] - [GraphQLType(typeof(ListType>))] - public Foo[][] ObjectNestedArray { get; } = default!; - } + [Required] + [GraphQLType(typeof(ListType>))] + public Foo[][] ObjectNestedArray { get; } = default!; + } - public class QueryDeepWithType - { - [GraphQLNonNullType()] - [GraphQLType(typeof(IdType))] - public string? Scalar { get; } + public class QueryDeepWithType + { + [GraphQLNonNullType()] + [GraphQLType(typeof(IdType))] + public string? Scalar { get; } - [GraphQLNonNullType(false, false)] - [GraphQLType(typeof(ListType))] - public string?[]? ScalarArray { get; } + [GraphQLNonNullType(false, false)] + [GraphQLType(typeof(ListType))] + public string?[]? ScalarArray { get; } - [GraphQLNonNullType(false, false,false)] - [GraphQLType(typeof(ListType>))] - public string?[]?[]? ScalarNestedArray { get; } + [GraphQLNonNullType(false, false,false)] + [GraphQLType(typeof(ListType>))] + public string?[]?[]? ScalarNestedArray { get; } - [GraphQLNonNullType] - [GraphQLType(typeof(FooType))] - public Foo? Object { get; } + [GraphQLNonNullType] + [GraphQLType(typeof(FooType))] + public Foo? Object { get; } - [GraphQLNonNullType(false, false)] - [GraphQLType(typeof(ListType))] - public Foo?[]? ObjectArray { get; } + [GraphQLNonNullType(false, false)] + [GraphQLType(typeof(ListType))] + public Foo?[]? ObjectArray { get; } - [GraphQLNonNullType(false, false,false)] - [GraphQLType(typeof(ListType>))] - public Foo?[]?[]? ObjectNestedArray { get; } - } + [GraphQLNonNullType(false, false,false)] + [GraphQLType(typeof(ListType>))] + public Foo?[]?[]? ObjectNestedArray { get; } + } - public class Foo - { - public string Bar { get; } = default!; - } + public class Foo + { + public string Bar { get; } = default!; + } - public class FooType : ObjectType + public class FooType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("CustomType"); - descriptor.Field("bar").Resolve(10); - } + descriptor.Name("CustomType"); + descriptor.Field("bar").Resolve(10); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/IgnoreTests.cs b/src/HotChocolate/Core/test/Types.Tests/IgnoreTests.cs index bb84c957699..f82ee78c245 100644 --- a/src/HotChocolate/Core/test/Types.Tests/IgnoreTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/IgnoreTests.cs @@ -7,50 +7,49 @@ #nullable enable -namespace HotChocolate +namespace HotChocolate; + +public class IgnoreTests { - public class IgnoreTests + [Fact] + public async Task IgnoreOutputField() { - [Fact] - public async Task IgnoreOutputField() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ignore_By_Name() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Ignore_By_Name() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - public class Query - { - public Bar GetBar() => new(); - } + public class Query + { + public Bar GetBar() => new(); + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field("bar").Ignore(); - descriptor.Field("foo").Resolve("foo"); - } + descriptor.Field("bar").Ignore(); + descriptor.Field("foo").Resolve("foo"); } + } - public class Bar - { - public string Baz { get; set; } = default!; + public class Bar + { + public string Baz { get; set; } = default!; - [GraphQLIgnore] - public (string X, string? Y) IgnoreThis() => default; - } + [GraphQLIgnore] + public (string X, string? Y) IgnoreThis() => default; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeNullabilityTests.cs b/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeNullabilityTests.cs index cbe08c75633..9789cc630d0 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeNullabilityTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeNullabilityTests.cs @@ -6,176 +6,175 @@ #nullable enable -namespace HotChocolate.Internal +namespace HotChocolate.Internal; + +public class ExtendedTypeNullabilityTests { - public class ExtendedTypeNullabilityTests + private readonly TypeCache _typeCache = new TypeCache(); + + [InlineData("Array", "[Byte!]!")] + [InlineData("NullableArray", "[Byte!]")] + [InlineData("ArrayNullableElement", "[Byte]!")] + [InlineData("NullableArrayNullableElement", "[Byte]")] + [InlineData("ObjectArray", "[Object!]!")] + [InlineData("NullableObjectArray", "[Object!]")] + [InlineData("ObjectArrayNullableElement", "[Object]!")] + [InlineData("NullableObjectArrayNullableElement", "[Object]")] + [Theory] + public void DetectNullabilityOnArrays(string methodName, string typeName) { - private readonly TypeCache _typeCache = new TypeCache(); - - [InlineData("Array", "[Byte!]!")] - [InlineData("NullableArray", "[Byte!]")] - [InlineData("ArrayNullableElement", "[Byte]!")] - [InlineData("NullableArrayNullableElement", "[Byte]")] - [InlineData("ObjectArray", "[Object!]!")] - [InlineData("NullableObjectArray", "[Object!]")] - [InlineData("ObjectArrayNullableElement", "[Object]!")] - [InlineData("NullableObjectArrayNullableElement", "[Object]")] - [Theory] - public void DetectNullabilityOnArrays(string methodName, string typeName) - { - // arrange - MethodInfo method = typeof(Arrays).GetMethod(methodName)!; - - // act - ExtendedType extendedType = ExtendedType.FromMember(method, _typeCache); + // arrange + var method = typeof(Arrays).GetMethod(methodName)!; - // assert - Assert.Equal(typeName, extendedType.ToString()); - } - - [InlineData("List", "List!")] - [InlineData("NullableList", "List")] - [InlineData("ListNullableElement", "List!")] - [InlineData("NullableListNullableElement", "List")] - [InlineData("ObjectList", "List!")] - [InlineData("NullableObjectList", "List")] - [InlineData("ObjectListNullableElement", "List!")] - [InlineData("NullableObjectListNullableElement", "List")] - [Theory] - public void DetectNullabilityOnLists(string methodName, string typeName) - { - // arrange - MethodInfo method = typeof(Lists).GetMethod(methodName)!; - - // act - ExtendedType extendedType = ExtendedType.FromMember(method, _typeCache); - - // assert - Assert.Equal(typeName, extendedType.ToString()); - } - - [InlineData("Dict1", "Dictionary!")] - [InlineData("Dict2", "Dictionary")] - [InlineData( - "Tuple", - "Tuple!, Tuple!>!>")] - [InlineData("TaskAsyncEnumerable", "IAsyncEnumerable!")] - [InlineData("ValueTaskAsyncEnumerable", "IAsyncEnumerable!")] - [Theory] - public void DetectNullabilityWithGenerics(string methodName, string typeName) - { - // arrange - MethodInfo method = typeof(Generics).GetMethod(methodName)!; - - // act - ExtendedType extendedType = ExtendedType.FromMember(method, _typeCache); - - // assert - Assert.Equal(typeName, extendedType.ToString()); - } + // act + var extendedType = ExtendedType.FromMember(method, _typeCache); - public class Arrays - { - public byte[] Array() - { - throw new NotImplementedException(); - } + // assert + Assert.Equal(typeName, extendedType.ToString()); + } - public byte[]? NullableArray() - { - throw new NotImplementedException(); - } + [InlineData("List", "List!")] + [InlineData("NullableList", "List")] + [InlineData("ListNullableElement", "List!")] + [InlineData("NullableListNullableElement", "List")] + [InlineData("ObjectList", "List!")] + [InlineData("NullableObjectList", "List")] + [InlineData("ObjectListNullableElement", "List!")] + [InlineData("NullableObjectListNullableElement", "List")] + [Theory] + public void DetectNullabilityOnLists(string methodName, string typeName) + { + // arrange + var method = typeof(Lists).GetMethod(methodName)!; - public byte?[] ArrayNullableElement() - { - throw new NotImplementedException(); - } + // act + var extendedType = ExtendedType.FromMember(method, _typeCache); - public byte?[]? NullableArrayNullableElement() - { - throw new NotImplementedException(); - } + // assert + Assert.Equal(typeName, extendedType.ToString()); + } - public object[] ObjectArray() - { - throw new NotImplementedException(); - } + [InlineData("Dict1", "Dictionary!")] + [InlineData("Dict2", "Dictionary")] + [InlineData( + "Tuple", + "Tuple!, Tuple!>!>")] + [InlineData("TaskAsyncEnumerable", "IAsyncEnumerable!")] + [InlineData("ValueTaskAsyncEnumerable", "IAsyncEnumerable!")] + [Theory] + public void DetectNullabilityWithGenerics(string methodName, string typeName) + { + // arrange + var method = typeof(Generics).GetMethod(methodName)!; - public object[]? NullableObjectArray() - { - throw new NotImplementedException(); - } + // act + var extendedType = ExtendedType.FromMember(method, _typeCache); - public object?[] ObjectArrayNullableElement() - { - throw new NotImplementedException(); - } + // assert + Assert.Equal(typeName, extendedType.ToString()); + } - public object?[]? NullableObjectArrayNullableElement() - { - throw new NotImplementedException(); - } + public class Arrays + { + public byte[] Array() + { + throw new NotImplementedException(); } - public class Lists + public byte[]? NullableArray() { - public List List() - { - throw new NotImplementedException(); - } + throw new NotImplementedException(); + } - public List? NullableList() - { - throw new NotImplementedException(); - } + public byte?[] ArrayNullableElement() + { + throw new NotImplementedException(); + } - public List ListNullableElement() - { - throw new NotImplementedException(); - } + public byte?[]? NullableArrayNullableElement() + { + throw new NotImplementedException(); + } - public List? NullableListNullableElement() - { - throw new NotImplementedException(); - } + public object[] ObjectArray() + { + throw new NotImplementedException(); + } - public List ObjectList() - { - throw new NotImplementedException(); - } + public object[]? NullableObjectArray() + { + throw new NotImplementedException(); + } - public List? NullableObjectList() - { - throw new NotImplementedException(); - } + public object?[] ObjectArrayNullableElement() + { + throw new NotImplementedException(); + } - public List ObjectListNullableElement() - { - throw new NotImplementedException(); - } + public object?[]? NullableObjectArrayNullableElement() + { + throw new NotImplementedException(); + } + } - public List? NullableObjectListNullableElement() - { - throw new NotImplementedException(); - } + public class Lists + { + public List List() + { + throw new NotImplementedException(); } - public class Generics + public List? NullableList() { - public Dictionary Dict1() => - throw new NotImplementedException(); + throw new NotImplementedException(); + } - public Dictionary? Dict2() => - throw new NotImplementedException(); + public List ListNullableElement() + { + throw new NotImplementedException(); + } - public Tuple, Tuple>>? Tuple() => - throw new NotImplementedException(); + public List? NullableListNullableElement() + { + throw new NotImplementedException(); + } - public Task> TaskAsyncEnumerable() => - throw new NotImplementedException(); + public List ObjectList() + { + throw new NotImplementedException(); + } - public ValueTask> ValueTaskAsyncEnumerable() => - throw new NotImplementedException(); + public List? NullableObjectList() + { + throw new NotImplementedException(); } + + public List ObjectListNullableElement() + { + throw new NotImplementedException(); + } + + public List? NullableObjectListNullableElement() + { + throw new NotImplementedException(); + } + } + + public class Generics + { + public Dictionary Dict1() => + throw new NotImplementedException(); + + public Dictionary? Dict2() => + throw new NotImplementedException(); + + public Tuple, Tuple>>? Tuple() => + throw new NotImplementedException(); + + public Task> TaskAsyncEnumerable() => + throw new NotImplementedException(); + + public ValueTask> ValueTaskAsyncEnumerable() => + throw new NotImplementedException(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeTests.cs index af49c6911a6..eaf9d5d174f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Internal/ExtendedTypeTests.cs @@ -10,414 +10,413 @@ #nullable enable -namespace HotChocolate.Internal +namespace HotChocolate.Internal; + +public class ExtendedTypeTests { - public class ExtendedTypeTests + private readonly TypeCache _cache = new TypeCache(); + + [Fact] + public void From_SystemType_Array() + { + // arrange + // act + var extendedType = ExtendedType.FromType(typeof(byte[]), _cache); + + // assert + Assert.True(extendedType.IsArray); + Assert.Collection( + extendedType.TypeArguments.Select(t => t.Type), + t => Assert.Equal(typeof(byte), t)); + } + + [Fact] + public void From_SystemType_List() + { + // arrange + // act + IExtendedType list = ExtendedType.FromType( + typeof(NativeType>), + _cache); + list = ExtendedType.Tools.ChangeNullability( + list, new bool?[] { false }, _cache); + + var nullableList = ExtendedType.FromType( + typeof(List), + _cache); + + // assert + Assert.True(list.IsList); + Assert.True(list.IsArrayOrList); + Assert.False(list.IsNullable); + Assert.True(nullableList.IsList); + Assert.True(nullableList.IsArrayOrList); + Assert.True(nullableList.IsNullable); + } + + [Fact] + public void From_SystemType_Dict() + { + // arrange + // act + var dict = ExtendedType.FromType( + typeof(Dictionary), + _cache); + + // assert + Assert.True(dict.IsList); + Assert.True(dict.IsArrayOrList); + } + + [Fact] + public void From_SchemaType_ListOfString() + { + // arrange + // act + var extendedType = ExtendedType.FromType(typeof(ListType), _cache); + + // assert + Assert.True(extendedType.IsSchemaType); + Assert.True(extendedType.IsGeneric); + Assert.Collection(extendedType.TypeArguments.Select(t => t.Type), + t => Assert.Equal(typeof(StringType), t)); + } + + [Fact] + public void From_SchemaType_NonNullListOfString() + { + // arrange + // act + var extendedType = ExtendedType.FromType( + typeof(NonNullType>), + _cache); + + // assert + Assert.True(extendedType.IsSchemaType); + Assert.True(extendedType.IsGeneric); + Assert.False(extendedType.IsNullable); + } + + [Fact] + public void From_IntType() + { + // arrange + // act + var extendedType = ExtendedType.FromType( + typeof(IntType), + _cache); + + // assert + Assert.True(extendedType.IsSchemaType); + Assert.False(extendedType.IsGeneric); + Assert.True(extendedType.IsNullable); + } + + [Fact] + public void From_InputObjectOfIntType() + { + // arrange + // act + var extendedType = ExtendedType.FromType( + typeof(InputObjectType), + _cache); + + // assert + Assert.True(extendedType.IsSchemaType); + Assert.True(extendedType.IsGeneric); + Assert.True(extendedType.IsNamedType); + Assert.True(extendedType.IsNullable); + + IExtendedType argument = extendedType.TypeArguments[0]; + Assert.True(argument.IsSchemaType); + Assert.False(argument.IsGeneric); + Assert.True(extendedType.IsNamedType); + Assert.True(argument.IsNullable); + } + + [Fact] + public void From_NativeTypeIntType() + { + // arrange + // act + var extendedType = ExtendedType.FromType( + typeof(NativeType), + _cache); + + // assert + Assert.True(extendedType.IsSchemaType); + Assert.False(extendedType.IsGeneric); + Assert.True(extendedType.IsNullable); + } + + [Fact] + public void Schema_Type_Cache_Id_Distinguishes_Between_NonNull_And_Nullable() + { + // arrange + // act + var extendedType1 = ExtendedType.FromType( + typeof(NonNullType>), + _cache); + + var extendedType2 = ExtendedType.FromType( + typeof(NonNullType), + _cache); + + var extendedType3 = ExtendedType.FromType( + typeof(ListType), + _cache); + + var extendedType4 = ExtendedType.FromType( + typeof(StringType), + _cache); + + // assert + Assert.False(extendedType1.IsNullable); + Assert.False(extendedType2.IsNullable); + Assert.True(extendedType3.IsNullable); + Assert.True(extendedType4.IsNullable); + } + + [Fact] + public void IsEqual_Byte_Byte_True() { - private readonly TypeCache _cache = new TypeCache(); - - [Fact] - public void From_SystemType_Array() - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType(typeof(byte[]), _cache); - - // assert - Assert.True(extendedType.IsArray); - Assert.Collection( - extendedType.TypeArguments.Select(t => t.Type), - t => Assert.Equal(typeof(byte), t)); - } - - [Fact] - public void From_SystemType_List() - { - // arrange - // act - IExtendedType list = ExtendedType.FromType( - typeof(NativeType>), - _cache); - list = ExtendedType.Tools.ChangeNullability( - list, new bool?[] { false }, _cache); - - ExtendedType nullableList = ExtendedType.FromType( - typeof(List), - _cache); - - // assert - Assert.True(list.IsList); - Assert.True(list.IsArrayOrList); - Assert.False(list.IsNullable); - Assert.True(nullableList.IsList); - Assert.True(nullableList.IsArrayOrList); - Assert.True(nullableList.IsNullable); - } - - [Fact] - public void From_SystemType_Dict() - { - // arrange - // act - ExtendedType dict = ExtendedType.FromType( - typeof(Dictionary), - _cache); - - // assert - Assert.True(dict.IsList); - Assert.True(dict.IsArrayOrList); - } - - [Fact] - public void From_SchemaType_ListOfString() - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType(typeof(ListType), _cache); - - // assert - Assert.True(extendedType.IsSchemaType); - Assert.True(extendedType.IsGeneric); - Assert.Collection(extendedType.TypeArguments.Select(t => t.Type), - t => Assert.Equal(typeof(StringType), t)); - } - - [Fact] - public void From_SchemaType_NonNullListOfString() - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType( - typeof(NonNullType>), - _cache); - - // assert - Assert.True(extendedType.IsSchemaType); - Assert.True(extendedType.IsGeneric); - Assert.False(extendedType.IsNullable); - } - - [Fact] - public void From_IntType() - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType( - typeof(IntType), - _cache); - - // assert - Assert.True(extendedType.IsSchemaType); - Assert.False(extendedType.IsGeneric); - Assert.True(extendedType.IsNullable); - } - - [Fact] - public void From_InputObjectOfIntType() - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType( - typeof(InputObjectType), - _cache); - - // assert - Assert.True(extendedType.IsSchemaType); - Assert.True(extendedType.IsGeneric); - Assert.True(extendedType.IsNamedType); - Assert.True(extendedType.IsNullable); - - IExtendedType argument = extendedType.TypeArguments[0]; - Assert.True(argument.IsSchemaType); - Assert.False(argument.IsGeneric); - Assert.True(extendedType.IsNamedType); - Assert.True(argument.IsNullable); - } - - [Fact] - public void From_NativeTypeIntType() - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType( - typeof(NativeType), - _cache); - - // assert - Assert.True(extendedType.IsSchemaType); - Assert.False(extendedType.IsGeneric); - Assert.True(extendedType.IsNullable); - } - - [Fact] - public void Schema_Type_Cache_Id_Distinguishes_Between_NonNull_And_Nullable() - { - // arrange - // act - ExtendedType extendedType1 = ExtendedType.FromType( - typeof(NonNullType>), - _cache); - - ExtendedType extendedType2 = ExtendedType.FromType( - typeof(NonNullType), - _cache); - - ExtendedType extendedType3 = ExtendedType.FromType( - typeof(ListType), - _cache); - - ExtendedType extendedType4 = ExtendedType.FromType( - typeof(StringType), - _cache); - - // assert - Assert.False(extendedType1.IsNullable); - Assert.False(extendedType2.IsNullable); - Assert.True(extendedType3.IsNullable); - Assert.True(extendedType4.IsNullable); - } - - [Fact] - public void IsEqual_Byte_Byte_True() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - ExtendedType b = ExtendedType.FromType(typeof(byte), _cache); - - // act - var result = a.Equals(b); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEqual_Object_Byte_Byte_True() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - ExtendedType b = ExtendedType.FromType(typeof(byte), _cache); - - // act - var result = a.Equals((object)b); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEqual_Ref_Byte_Byte_True() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - - // act - var result = a.Equals(a); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEqual_Ref_Object_Byte_Byte_True() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - - // act - var result = a.Equals((object)a); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEqual_Byte_Null_False() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - - // act - var result = a.Equals(default(ExtendedType)); - - // assert - Assert.False(result); - } - - [Fact] - public void IsEqual_Object_Byte_Null_False() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - - // act - var result = a.Equals(default(object)); - - // assert - Assert.False(result); - } - - [Fact] - public void IsEqual_Byte_String_False() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - ExtendedType b = ExtendedType.FromType(typeof(string), _cache); - - // act - var result = a.Equals(b); - - // assert - Assert.False(result); - } - - [Fact] - public void IsEqual_Object_Byte_String_False() - { - // arrange - ExtendedType a = ExtendedType.FromType(typeof(byte), _cache); - ExtendedType b = ExtendedType.FromType(typeof(string), _cache); - - // act - var result = a.Equals((object)b); - - // assert - Assert.False(result); - } - - [InlineData(typeof(CustomStringList1), "CustomStringList1", "String")] - [InlineData(typeof(CustomStringList2), "CustomStringList2", "String")] - [InlineData( - typeof(CustomStringList3), - "CustomStringList3", - "String")] - [InlineData(typeof(List), "List", "String")] - [InlineData(typeof(Collection), "Collection", "String")] - [InlineData(typeof(ReadOnlyCollection), "ReadOnlyCollection", "String")] - [InlineData(typeof(ImmutableList), "ImmutableList", "String")] - [InlineData(typeof(ImmutableArray), "ImmutableArray!", "String")] - [InlineData(typeof(IList), "IList", "String")] - [InlineData(typeof(ICollection), "ICollection", "String")] - [InlineData(typeof(IEnumerable), "IEnumerable", "String")] - [InlineData(typeof(IReadOnlyCollection), "IReadOnlyCollection", "String")] - [InlineData(typeof(IReadOnlyList), "IReadOnlyList", "String")] - [InlineData(typeof(IExecutable), "IExecutable", "String")] - [InlineData(typeof(string[]), "[String]", "String")] - [InlineData( - typeof(Task>), - "IAsyncEnumerable", - "String")] - [InlineData( - typeof(ValueTask>), - "IAsyncEnumerable", - "String")] - [Theory] - public void SupportedListTypes(Type type, string listTypeName, string elementTypeName) - { - // arrange - // act - ExtendedType extendedType = ExtendedType.FromType(type, _cache); - - // assert - Assert.Equal(listTypeName, extendedType.ToString()); - Assert.Equal(elementTypeName, extendedType.ElementType?.ToString()); - } - - [InlineData(typeof(List))] - [InlineData(typeof(IReadOnlyList))] - [InlineData(typeof(IList))] - [InlineData(typeof(CustomStringList2))] - [InlineData(typeof(ImmutableArray))] - [InlineData(typeof(IEnumerable))] - [InlineData(typeof(IExecutable))] - [InlineData(typeof(Task>))] - [InlineData(typeof(ValueTask>))] - [Theory] - public void ChangeNullability_From_ElementType(Type listType) - { - // arrange - // act - IExtendedType list = ExtendedType.FromType(listType, _cache); - list = ExtendedType.Tools.ChangeNullability( - list, new bool?[] { null, false }, _cache); - - // assert - Assert.False(list.ElementType!.IsNullable); - Assert.Same(list.ElementType, list.TypeArguments[0]); - } - - [Fact] - public void NullableOptionalNullableString() - { - // arrange - MethodInfo member = - typeof(Nullability).GetMethod(nameof(Nullability.NullableOptionalNullableString))!; - - // act - ExtendedType type = ExtendedType.FromMember(member, _cache); - - // assert - Assert.Equal("Optional", type.ToString()); - } - - [Fact] - public void OptionalNullableOptionalNullableString() - { - // arrange - MethodInfo member = - typeof(Nullability) - .GetMethod(nameof(Nullability.OptionalNullableOptionalNullableString))!; - - // act - ExtendedType type = ExtendedType.FromMember(member, _cache); - - // assert - Assert.Equal("Optional>!", type.ToString()); - } - - [Fact] - public void From_IExecutableScalar() - { - // arrange - // act - ExtendedType dict = ExtendedType.FromType( - typeof(IExecutable), - _cache); - - // assert - Assert.True(dict.IsList); - Assert.True(dict.IsArrayOrList); - } - - private sealed class CustomStringList1 - : List - { - } - - private sealed class CustomStringList2 - : List - where T : notnull - { - } - - private sealed class CustomStringList3 - : List - where T : notnull - { - public TK Foo { get; set; } = default!; - } + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + var b = ExtendedType.FromType(typeof(byte), _cache); + + // act + var result = a.Equals(b); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEqual_Object_Byte_Byte_True() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + var b = ExtendedType.FromType(typeof(byte), _cache); + + // act + var result = a.Equals((object)b); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEqual_Ref_Byte_Byte_True() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + + // act + var result = a.Equals(a); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEqual_Ref_Object_Byte_Byte_True() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + + // act + var result = a.Equals((object)a); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEqual_Byte_Null_False() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + + // act + var result = a.Equals(default(ExtendedType)); + + // assert + Assert.False(result); + } + + [Fact] + public void IsEqual_Object_Byte_Null_False() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + + // act + var result = a.Equals(default(object)); + + // assert + Assert.False(result); + } + + [Fact] + public void IsEqual_Byte_String_False() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + var b = ExtendedType.FromType(typeof(string), _cache); + + // act + var result = a.Equals(b); + + // assert + Assert.False(result); + } + + [Fact] + public void IsEqual_Object_Byte_String_False() + { + // arrange + var a = ExtendedType.FromType(typeof(byte), _cache); + var b = ExtendedType.FromType(typeof(string), _cache); + + // act + var result = a.Equals((object)b); + + // assert + Assert.False(result); + } + + [InlineData(typeof(CustomStringList1), "CustomStringList1", "String")] + [InlineData(typeof(CustomStringList2), "CustomStringList2", "String")] + [InlineData( + typeof(CustomStringList3), + "CustomStringList3", + "String")] + [InlineData(typeof(List), "List", "String")] + [InlineData(typeof(Collection), "Collection", "String")] + [InlineData(typeof(ReadOnlyCollection), "ReadOnlyCollection", "String")] + [InlineData(typeof(ImmutableList), "ImmutableList", "String")] + [InlineData(typeof(ImmutableArray), "ImmutableArray!", "String")] + [InlineData(typeof(IList), "IList", "String")] + [InlineData(typeof(ICollection), "ICollection", "String")] + [InlineData(typeof(IEnumerable), "IEnumerable", "String")] + [InlineData(typeof(IReadOnlyCollection), "IReadOnlyCollection", "String")] + [InlineData(typeof(IReadOnlyList), "IReadOnlyList", "String")] + [InlineData(typeof(IExecutable), "IExecutable", "String")] + [InlineData(typeof(string[]), "[String]", "String")] + [InlineData( + typeof(Task>), + "IAsyncEnumerable", + "String")] + [InlineData( + typeof(ValueTask>), + "IAsyncEnumerable", + "String")] + [Theory] + public void SupportedListTypes(Type type, string listTypeName, string elementTypeName) + { + // arrange + // act + var extendedType = ExtendedType.FromType(type, _cache); + + // assert + Assert.Equal(listTypeName, extendedType.ToString()); + Assert.Equal(elementTypeName, extendedType.ElementType?.ToString()); + } + + [InlineData(typeof(List))] + [InlineData(typeof(IReadOnlyList))] + [InlineData(typeof(IList))] + [InlineData(typeof(CustomStringList2))] + [InlineData(typeof(ImmutableArray))] + [InlineData(typeof(IEnumerable))] + [InlineData(typeof(IExecutable))] + [InlineData(typeof(Task>))] + [InlineData(typeof(ValueTask>))] + [Theory] + public void ChangeNullability_From_ElementType(Type listType) + { + // arrange + // act + IExtendedType list = ExtendedType.FromType(listType, _cache); + list = ExtendedType.Tools.ChangeNullability( + list, new bool?[] { null, false }, _cache); + + // assert + Assert.False(list.ElementType!.IsNullable); + Assert.Same(list.ElementType, list.TypeArguments[0]); + } + + [Fact] + public void NullableOptionalNullableString() + { + // arrange + var member = + typeof(Nullability).GetMethod(nameof(Nullability.NullableOptionalNullableString))!; + + // act + var type = ExtendedType.FromMember(member, _cache); + + // assert + Assert.Equal("Optional", type.ToString()); + } + + [Fact] + public void OptionalNullableOptionalNullableString() + { + // arrange + var member = + typeof(Nullability) + .GetMethod(nameof(Nullability.OptionalNullableOptionalNullableString))!; + + // act + var type = ExtendedType.FromMember(member, _cache); + + // assert + Assert.Equal("Optional>!", type.ToString()); + } + + [Fact] + public void From_IExecutableScalar() + { + // arrange + // act + var dict = ExtendedType.FromType( + typeof(IExecutable), + _cache); + + // assert + Assert.True(dict.IsList); + Assert.True(dict.IsArrayOrList); + } + + private sealed class CustomStringList1 + : List + { + } + + private sealed class CustomStringList2 + : List + where T : notnull + { + } + + private sealed class CustomStringList3 + : List + where T : notnull + { + public TK Foo { get; set; } = default!; + } #nullable enable - public class Nullability - { - public Nullable> NullableOptionalNullableString() => - throw new NotImplementedException(); + public class Nullability + { + public Nullable> NullableOptionalNullableString() => + throw new NotImplementedException(); - public Optional>> OptionalNullableOptionalNullableString() => - throw new NotImplementedException(); - } + public Optional>> OptionalNullableOptionalNullableString() => + throw new NotImplementedException(); + } #nullable disable - } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Internal/TypeInfoTests.cs b/src/HotChocolate/Core/test/Types.Tests/Internal/TypeInfoTests.cs index 9d451cf7060..ce9c9c1bff5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Internal/TypeInfoTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Internal/TypeInfoTests.cs @@ -9,617 +9,616 @@ using HotChocolate.Types.Descriptors; using Xunit; -namespace HotChocolate.Internal +namespace HotChocolate.Internal; + +public class TypeInfoTests { - public class TypeInfoTests - { - private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); - private readonly TypeCache _cache = new TypeCache(); - - [InlineData(typeof(string), "String")] - [InlineData(typeof(Task), "String")] - [InlineData(typeof(List), "[String]")] - [InlineData(typeof(Task>), "[String]")] - [InlineData(typeof(Task>>), "[[String]]")] - [InlineData(typeof(string[]), "[String]")] - [InlineData(typeof(Task), "[String]")] - [InlineData(typeof(NativeType), "String")] - [InlineData(typeof(NativeType>), "String")] - [InlineData(typeof(NativeType>), "[String]")] - [InlineData(typeof(NativeType>>), "[String]")] - [InlineData(typeof(NativeType), "[String]")] - [InlineData(typeof(NativeType>), "[String]")] - [InlineData(typeof(int), "String!")] - [InlineData(typeof(Task), "String!")] - [InlineData(typeof(List), "[String!]")] - [InlineData(typeof(Task>), "[String!]")] - [InlineData(typeof(Task>>), "[[String!]]")] - [InlineData(typeof(int[]), "[String!]")] - [InlineData(typeof(Task), "[String!]")] - [InlineData(typeof(NativeType), "String!")] - [InlineData(typeof(NativeType>), "String!")] - [InlineData(typeof(NativeType>), "[String!]")] - [InlineData(typeof(NativeType>>), "[String!]")] - [InlineData(typeof(NativeType), "[String!]")] - [InlineData(typeof(NativeType>), "[String!]")] - [InlineData(typeof(int?), "String")] - [InlineData(typeof(Task), "String")] - [InlineData(typeof(List), "[String]")] - [InlineData(typeof(Task>), "[String]")] - [InlineData(typeof(Task>>), "[[String]]")] - [InlineData(typeof(int?[]), "[String]")] - [InlineData(typeof(Task), "[String]")] - [InlineData(typeof(NativeType), "String")] - [InlineData(typeof(NativeType>), "String")] - [InlineData(typeof(NativeType>), "[String]")] - [InlineData(typeof(NativeType>>), "[String]")] - [InlineData(typeof(NativeType), "[String]")] - [InlineData(typeof(NativeType>), "[String]")] - [InlineData(typeof(Optional), "[String]")] - [InlineData(typeof(ValueTask), "[String]")] - [InlineData(typeof(IAsyncEnumerable), "[String]")] - [InlineData(typeof(IEnumerable), "[String]")] - [InlineData(typeof(IQueryable), "[String]")] - [InlineData(typeof(IExecutable), "[String]")] - [InlineData(typeof(IExecutable), "[String!]")] - [InlineData(typeof(IExecutable), "[String]")] - [Theory] - public void CreateTypeInfoFromRuntimeType( - Type clrType, - string expectedTypeName) - { - // arrange - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetType(clrType), _cache); - - // assert - Assert.Equal(expectedTypeName, typeInfo.CreateType(new StringType()).Print()); - } - - [InlineData(typeof(CustomStringList), "[String]")] - [InlineData(typeof(List), "[String]")] - [InlineData(typeof(Collection), "[String]")] - [InlineData(typeof(ReadOnlyCollection), "[String]")] - [InlineData(typeof(ImmutableList), "[String]")] - [InlineData(typeof(ImmutableArray), "[String]!")] - [InlineData(typeof(IList), "[String]")] - [InlineData(typeof(ICollection), "[String]")] - [InlineData(typeof(IEnumerable), "[String]")] - [InlineData(typeof(IReadOnlyCollection), "[String]")] - [InlineData(typeof(IReadOnlyList), "[String]")] - [InlineData(typeof(IExecutable), "[String]")] - [InlineData(typeof(string[]), "[String]")] - [Theory] - public void SupportedListTypes(Type clrType, string expectedTypeName) - { - // arrange - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetType(clrType), _cache); - - // assert - Assert.Equal(expectedTypeName, typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullListNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullListNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullListNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullListNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableListNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableListNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableListNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableListNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullQueryNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullQueryNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullQueryNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullQueryNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableQueryNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableQueryNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableQueryNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableQueryNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); - } - [Fact] - public void NonNullCollectionNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullCollectionNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullCollectionNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullCollectionNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableCollectionNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableCollectionNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableCollectionNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableCollectionNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullArrayNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullArrayNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NonNullArrayNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NonNullArrayNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableArrayNullableElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableArrayNullableElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableArrayNonNullElement() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableArrayNonNullElement)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NestedList() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NestedList)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("[[String]]", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void OptionalNullableString() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.OptionalNullableString)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("String", typeInfo.CreateType(new StringType()).Print()); - } - - [Fact] - public void NullableOptionalNullableString() - { - // arrange - MethodInfo methodInfo = - typeof(Nullability).GetMethod(nameof(Nullability.NullableOptionalNullableString)); - - // act - var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); - - // assert - Assert.Equal("String", typeInfo.CreateType(new StringType()).Print()); - } - - [InlineData(typeof(NativeType>), typeof(string))] - [InlineData(typeof(NativeType), typeof(string))] - [InlineData(typeof(Task), typeof(string))] - [InlineData(typeof(ValueTask), typeof(string[]))] - [InlineData(typeof(ValueTask>), typeof(List))] - [Theory] - public void Unwrap(Type type, Type expectedReducedType) - { - // arrange - // act - IExtendedType reducedType = TypeInfo.RuntimeType.Unwrap( - _typeInspector.GetReturnType(type)); - - // assert - Assert.Equal(expectedReducedType, reducedType.Type); - } - - [InlineData(typeof(List>), 3)] - [InlineData(typeof(List>), 3)] - [Theory] - public void NestedListFromType(Type type, int components) - { - // arrange - // act - ITypeInfo typeInfo = _typeInspector.CreateTypeInfo(type); - - // assert - Assert.Equal(components, typeInfo.Components.Count); - } - - [Fact] - public void Create_TypeInfo_From_RewrittenType() - { - // arrange - IExtendedType extendedType = _typeInspector.GetType(typeof(List), null, false); - - // act - var success = TypeInfo.TryCreate( - extendedType, - _cache, - out TypeInfo typeInfo); - - // assert - Assert.True(success); - - Assert.Collection(typeInfo.Components.Select(t => t.Kind), - t => Assert.Equal(TypeComponentKind.List, t), - t => Assert.Equal(TypeComponentKind.NonNull, t), - t => Assert.Equal(TypeComponentKind.Named, t)); - - IType schemaType = typeInfo.CreateType(new StringType()); - - Assert.IsType( - Assert.IsType( - Assert.IsType(schemaType).ElementType).Type); - } - - [Fact] - public void Case5() - { - // arrange - Type nativeType = - typeof(NonNullType>>>>); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.Equal("[[String!]!]!", type.Print()); - } - - [Fact] - public void Case4() - { - // arrange - Type nativeType = typeof(NonNullType>>); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.IsType(type); - type = ((NonNullType)type).Type as IOutputType; - Assert.IsType(type); - type = ((ListType)type).ElementType as IOutputType; - Assert.IsType(type); - type = ((NonNullType)type).Type as IOutputType; - Assert.IsType(type); - } - - [Fact] - public void Case3_1() - { - // arrange - Type nativeType = typeof(ListType>); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.IsType(type); - type = ((ListType)type).ElementType as IOutputType; - Assert.IsType(type); - type = ((NonNullType)type).Type as IOutputType; - Assert.IsType(type); - } - - [Fact] - public void Case3_2() - { - // arrange - Type nativeType = typeof(NonNullType>); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.IsType(type); - type = ((NonNullType)type).Type as IOutputType; - Assert.IsType(type); - type = ((ListType)type).ElementType as IOutputType; - Assert.IsType(type); - } - - [Fact] - public void Case2_1() - { - // arrange - Type nativeType = typeof(NonNullType); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.IsType(type); - type = ((NonNullType)type).Type as IOutputType; - Assert.IsType(type); - } - - [Fact] - public void Case2_2() - { - // arrange - Type nativeType = typeof(ListType); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.IsType(type); - type = ((ListType)type).ElementType as IOutputType; - Assert.IsType(type); - } - - [Fact] - public void Case1() - { - // arrange - Type nativeType = typeof(StringType); - - // act - var success = TypeInfo.TryCreate( - _typeInspector.GetReturnType(nativeType), - _cache, - out TypeInfo typeInfo); - IType type = typeInfo!.CreateType(new StringType()); - - // assert - Assert.True(success); - Assert.IsType(type); - } - - private sealed class CustomStringList : CustomStringListBase - { - } - - private class CustomStringListBase : List - { - } + private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); + private readonly TypeCache _cache = new TypeCache(); + + [InlineData(typeof(string), "String")] + [InlineData(typeof(Task), "String")] + [InlineData(typeof(List), "[String]")] + [InlineData(typeof(Task>), "[String]")] + [InlineData(typeof(Task>>), "[[String]]")] + [InlineData(typeof(string[]), "[String]")] + [InlineData(typeof(Task), "[String]")] + [InlineData(typeof(NativeType), "String")] + [InlineData(typeof(NativeType>), "String")] + [InlineData(typeof(NativeType>), "[String]")] + [InlineData(typeof(NativeType>>), "[String]")] + [InlineData(typeof(NativeType), "[String]")] + [InlineData(typeof(NativeType>), "[String]")] + [InlineData(typeof(int), "String!")] + [InlineData(typeof(Task), "String!")] + [InlineData(typeof(List), "[String!]")] + [InlineData(typeof(Task>), "[String!]")] + [InlineData(typeof(Task>>), "[[String!]]")] + [InlineData(typeof(int[]), "[String!]")] + [InlineData(typeof(Task), "[String!]")] + [InlineData(typeof(NativeType), "String!")] + [InlineData(typeof(NativeType>), "String!")] + [InlineData(typeof(NativeType>), "[String!]")] + [InlineData(typeof(NativeType>>), "[String!]")] + [InlineData(typeof(NativeType), "[String!]")] + [InlineData(typeof(NativeType>), "[String!]")] + [InlineData(typeof(int?), "String")] + [InlineData(typeof(Task), "String")] + [InlineData(typeof(List), "[String]")] + [InlineData(typeof(Task>), "[String]")] + [InlineData(typeof(Task>>), "[[String]]")] + [InlineData(typeof(int?[]), "[String]")] + [InlineData(typeof(Task), "[String]")] + [InlineData(typeof(NativeType), "String")] + [InlineData(typeof(NativeType>), "String")] + [InlineData(typeof(NativeType>), "[String]")] + [InlineData(typeof(NativeType>>), "[String]")] + [InlineData(typeof(NativeType), "[String]")] + [InlineData(typeof(NativeType>), "[String]")] + [InlineData(typeof(Optional), "[String]")] + [InlineData(typeof(ValueTask), "[String]")] + [InlineData(typeof(IAsyncEnumerable), "[String]")] + [InlineData(typeof(IEnumerable), "[String]")] + [InlineData(typeof(IQueryable), "[String]")] + [InlineData(typeof(IExecutable), "[String]")] + [InlineData(typeof(IExecutable), "[String!]")] + [InlineData(typeof(IExecutable), "[String]")] + [Theory] + public void CreateTypeInfoFromRuntimeType( + Type clrType, + string expectedTypeName) + { + // arrange + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetType(clrType), _cache); + + // assert + Assert.Equal(expectedTypeName, typeInfo.CreateType(new StringType()).Print()); + } + + [InlineData(typeof(CustomStringList), "[String]")] + [InlineData(typeof(List), "[String]")] + [InlineData(typeof(Collection), "[String]")] + [InlineData(typeof(ReadOnlyCollection), "[String]")] + [InlineData(typeof(ImmutableList), "[String]")] + [InlineData(typeof(ImmutableArray), "[String]!")] + [InlineData(typeof(IList), "[String]")] + [InlineData(typeof(ICollection), "[String]")] + [InlineData(typeof(IEnumerable), "[String]")] + [InlineData(typeof(IReadOnlyCollection), "[String]")] + [InlineData(typeof(IReadOnlyList), "[String]")] + [InlineData(typeof(IExecutable), "[String]")] + [InlineData(typeof(string[]), "[String]")] + [Theory] + public void SupportedListTypes(Type clrType, string expectedTypeName) + { + // arrange + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetType(clrType), _cache); + + // assert + Assert.Equal(expectedTypeName, typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullListNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullListNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullListNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullListNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableListNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableListNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableListNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableListNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullQueryNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullQueryNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullQueryNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullQueryNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableQueryNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableQueryNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableQueryNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableQueryNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); + } + [Fact] + public void NonNullCollectionNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullCollectionNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullCollectionNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullCollectionNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableCollectionNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableCollectionNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableCollectionNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableCollectionNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullArrayNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullArrayNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NonNullArrayNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NonNullArrayNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]!", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableArrayNullableElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableArrayNullableElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableArrayNonNullElement() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableArrayNonNullElement)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[String!]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NestedList() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NestedList)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("[[String]]", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void OptionalNullableString() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.OptionalNullableString)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("String", typeInfo.CreateType(new StringType()).Print()); + } + + [Fact] + public void NullableOptionalNullableString() + { + // arrange + var methodInfo = + typeof(Nullability).GetMethod(nameof(Nullability.NullableOptionalNullableString)); + + // act + var typeInfo = TypeInfo.Create(_typeInspector.GetReturnType(methodInfo!), _cache); + + // assert + Assert.Equal("String", typeInfo.CreateType(new StringType()).Print()); + } + + [InlineData(typeof(NativeType>), typeof(string))] + [InlineData(typeof(NativeType), typeof(string))] + [InlineData(typeof(Task), typeof(string))] + [InlineData(typeof(ValueTask), typeof(string[]))] + [InlineData(typeof(ValueTask>), typeof(List))] + [Theory] + public void Unwrap(Type type, Type expectedReducedType) + { + // arrange + // act + var reducedType = TypeInfo.RuntimeType.Unwrap( + _typeInspector.GetReturnType(type)); + + // assert + Assert.Equal(expectedReducedType, reducedType.Type); + } + + [InlineData(typeof(List>), 3)] + [InlineData(typeof(List>), 3)] + [Theory] + public void NestedListFromType(Type type, int components) + { + // arrange + // act + var typeInfo = _typeInspector.CreateTypeInfo(type); + + // assert + Assert.Equal(components, typeInfo.Components.Count); + } + + [Fact] + public void Create_TypeInfo_From_RewrittenType() + { + // arrange + var extendedType = _typeInspector.GetType(typeof(List), null, false); + + // act + var success = TypeInfo.TryCreate( + extendedType, + _cache, + out var typeInfo); + + // assert + Assert.True(success); + + Assert.Collection(typeInfo.Components.Select(t => t.Kind), + t => Assert.Equal(TypeComponentKind.List, t), + t => Assert.Equal(TypeComponentKind.NonNull, t), + t => Assert.Equal(TypeComponentKind.Named, t)); + + var schemaType = typeInfo.CreateType(new StringType()); + + Assert.IsType( + Assert.IsType( + Assert.IsType(schemaType).ElementType).Type); + } + + [Fact] + public void Case5() + { + // arrange + var nativeType = + typeof(NonNullType>>>>); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.Equal("[[String!]!]!", type.Print()); + } + + [Fact] + public void Case4() + { + // arrange + var nativeType = typeof(NonNullType>>); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.IsType(type); + type = ((NonNullType)type).Type as IOutputType; + Assert.IsType(type); + type = ((ListType)type).ElementType as IOutputType; + Assert.IsType(type); + type = ((NonNullType)type).Type as IOutputType; + Assert.IsType(type); + } + + [Fact] + public void Case3_1() + { + // arrange + var nativeType = typeof(ListType>); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.IsType(type); + type = ((ListType)type).ElementType as IOutputType; + Assert.IsType(type); + type = ((NonNullType)type).Type as IOutputType; + Assert.IsType(type); + } + + [Fact] + public void Case3_2() + { + // arrange + var nativeType = typeof(NonNullType>); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.IsType(type); + type = ((NonNullType)type).Type as IOutputType; + Assert.IsType(type); + type = ((ListType)type).ElementType as IOutputType; + Assert.IsType(type); + } + + [Fact] + public void Case2_1() + { + // arrange + var nativeType = typeof(NonNullType); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.IsType(type); + type = ((NonNullType)type).Type as IOutputType; + Assert.IsType(type); + } + + [Fact] + public void Case2_2() + { + // arrange + var nativeType = typeof(ListType); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.IsType(type); + type = ((ListType)type).ElementType as IOutputType; + Assert.IsType(type); + } + + [Fact] + public void Case1() + { + // arrange + var nativeType = typeof(StringType); + + // act + var success = TypeInfo.TryCreate( + _typeInspector.GetReturnType(nativeType), + _cache, + out var typeInfo); + var type = typeInfo!.CreateType(new StringType()); + + // assert + Assert.True(success); + Assert.IsType(type); + } + + private sealed class CustomStringList : CustomStringListBase + { + } + + private class CustomStringListBase : List + { + } #nullable enable - public class Nullability - { - public List NonNullListNonNullElement() => default!; + public class Nullability + { + public List NonNullListNonNullElement() => default!; - public List NonNullListNullableElement() => default!; + public List NonNullListNullableElement() => default!; - public List? NullableListNullableElement() => default; + public List? NullableListNullableElement() => default; - public List? NullableListNonNullElement() => default; + public List? NullableListNonNullElement() => default; - public ICollection NonNullCollectionNonNullElement() => default!; + public ICollection NonNullCollectionNonNullElement() => default!; - public ICollection NonNullCollectionNullableElement() => default!; + public ICollection NonNullCollectionNullableElement() => default!; - public ICollection? NullableCollectionNullableElement() => default; + public ICollection? NullableCollectionNullableElement() => default; - public ICollection? NullableCollectionNonNullElement() => default; + public ICollection? NullableCollectionNonNullElement() => default; - public IExecutable NonNullQueryNonNullElement() => default!; + public IExecutable NonNullQueryNonNullElement() => default!; - public IExecutable NonNullQueryNullableElement() => default!; + public IExecutable NonNullQueryNullableElement() => default!; - public IExecutable? NullableQueryNullableElement() => default; + public IExecutable? NullableQueryNullableElement() => default; - public IExecutable? NullableQueryNonNullElement() => default; + public IExecutable? NullableQueryNonNullElement() => default; - public string[] NonNullArrayNonNullElement() => default!; + public string[] NonNullArrayNonNullElement() => default!; - public string?[] NonNullArrayNullableElement() => default!; + public string?[] NonNullArrayNullableElement() => default!; - public string?[]? NullableArrayNullableElement() => default; + public string?[]? NullableArrayNullableElement() => default; - public string[]? NullableArrayNonNullElement() => default; + public string[]? NullableArrayNonNullElement() => default; - public List?>? NestedList() => default; + public List?>? NestedList() => default; - public Optional OptionalNullableString() => default; + public Optional OptionalNullableString() => default; - public Nullable> NullableOptionalNullableString() => default; - } + public Nullable> NullableOptionalNullableString() => default; + } #nullable disable - public class Foo { } - } + public class Foo { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/NamingConventionTests.cs b/src/HotChocolate/Core/test/Types.Tests/NamingConventionTests.cs index 9fa5ec9ab93..2937cd73b01 100644 --- a/src/HotChocolate/Core/test/Types.Tests/NamingConventionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/NamingConventionTests.cs @@ -9,97 +9,96 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class NamingConventionTests { - public class NamingConventionTests + [Fact] + public void PureCodeFirst_NamingConvention_RenameArgument() + { + SchemaBuilder.New() + .AddQueryType() + .AddMutationType() + .AddConvention() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public async Task PureCodeFirst_NamingConvention_RenameArgument_RequestBuilder() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .AddConvention() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + public class CustomNamingConvention : DefaultNamingConventions { - [Fact] - public void PureCodeFirst_NamingConvention_RenameArgument() + public override NameString GetArgumentName(ParameterInfo parameter) { - SchemaBuilder.New() - .AddQueryType() - .AddMutationType() - .AddConvention() - .Create() - .Print() - .MatchSnapshot(); + var name = base.GetArgumentName(parameter); + return name.Value + "_Named"; } - [Fact] - public async Task PureCodeFirst_NamingConvention_RenameArgument_RequestBuilder() + public override string GetArgumentDescription(ParameterInfo parameter) { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .AddConvention() - .BuildSchemaAsync() - .MatchSnapshotAsync(); + return "GetArgumentDescription"; } - public class CustomNamingConvention : DefaultNamingConventions + public override string GetMemberDescription(MemberInfo member, MemberKind kind) { - public override NameString GetArgumentName(ParameterInfo parameter) - { - NameString name = base.GetArgumentName(parameter); - return name.Value + "_Named"; - } - - public override string GetArgumentDescription(ParameterInfo parameter) - { - return "GetArgumentDescription"; - } - - public override string GetMemberDescription(MemberInfo member, MemberKind kind) - { - return "GetMemberDescription"; - } - - public override NameString GetTypeName(Type type, TypeKind kind) - { - NameString name = base.GetTypeName(type, kind); - return name.Value + "_Named"; - } - - public override string GetEnumValueDescription(object value) - { - return "GetEnumValueDescription"; - } - - public override NameString GetMemberName(MemberInfo member, MemberKind kind) - { - NameString name = base.GetMemberName(member, kind); - return name.Value + "_Named"; - } - - public override string GetTypeDescription(Type type, TypeKind kind) - { - return "GetTypeDescription"; - } + return "GetMemberDescription"; } - public class QueryNamingConvention + public override NameString GetTypeName(Type type, TypeKind kind) { - public ObjectNamingConvention QueryField( - int queryArgument, - InputObjectNamingConvention complexArgument) => default!; + var name = base.GetTypeName(type, kind); + return name.Value + "_Named"; } - public class InputObjectNamingConvention + public override string GetEnumValueDescription(object value) { - public string InputField { get; set; } + return "GetEnumValueDescription"; } - public class ObjectNamingConvention + public override NameString GetMemberName(MemberInfo member, MemberKind kind) { - public string OutputField { get; set; } + var name = base.GetMemberName(member, kind); + return name.Value + "_Named"; } - public class MutationNamingConvention + public override string GetTypeDescription(Type type, TypeKind kind) { - public ObjectNamingConvention MutationField( - int mutationArgument, - InputObjectNamingConvention complexArgumentMutation) => default!; + return "GetTypeDescription"; } } + + public class QueryNamingConvention + { + public ObjectNamingConvention QueryField( + int queryArgument, + InputObjectNamingConvention complexArgument) => default!; + } + + public class InputObjectNamingConvention + { + public string InputField { get; set; } + } + + public class ObjectNamingConvention + { + public string OutputField { get; set; } + } + + public class MutationNamingConvention + { + public ObjectNamingConvention MutationField( + int mutationArgument, + InputObjectNamingConvention complexArgumentMutation) => default!; + } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Regressions/NestedOptionalInt_2114.cs b/src/HotChocolate/Core/test/Types.Tests/Regressions/NestedOptionalInt_2114.cs index a4fefe93133..a8c700e371f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Regressions/NestedOptionalInt_2114.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Regressions/NestedOptionalInt_2114.cs @@ -8,23 +8,23 @@ #nullable enable -namespace HotChocolate.Regressions +namespace HotChocolate.Regressions; + +// Relates to issue https://github.com/ChilliCream/hotchocolate/issues/2114 +public class NestedOptionalInt_2114 { - // Relates to issue https://github.com/ChilliCream/hotchocolate/issues/2114 - public class NestedOptionalInt_2114 + [Fact] + public async Task ShouldNotFailWithExplicitValues() { - [Fact] - public async Task ShouldNotFailWithExplicitValues() + // arrange + ToppingInput? input = null; + var executor = CreateExecutor(value => { - // arrange - ToppingInput? input = null; - IRequestExecutor executor = CreateExecutor(value => - { - input = value; - return true; - }); + input = value; + return true; + }); - const string Query = @" + const string Query = @" mutation { eat(topping: { pickles: [ { @@ -33,26 +33,26 @@ public async Task ShouldNotFailWithExplicitValues() complexAssigned: { value: 3 }, complexAssignedNull: null, complexList: [ { value: 2 } ] } } ] }) }"; - // act - IExecutionResult result = await executor.ExecuteAsync(Query); + // act + var result = await executor.ExecuteAsync(Query); - // assert - Assert.Null(result.ExpectQueryResult().Errors); - Verify(input); - } + // assert + Assert.Null(result.ExpectQueryResult().Errors); + Verify(input); + } - [Fact] - public async Task ShouldNotFailWithVariables() + [Fact] + public async Task ShouldNotFailWithVariables() + { + // arrange + ToppingInput? input = null; + var executor = CreateExecutor(value => { - // arrange - ToppingInput? input = null; - IRequestExecutor executor = CreateExecutor(value => - { - input = value; - return true; - }); + input = value; + return true; + }); - const string Query = @" + const string Query = @" mutation a($input: ButterPickleInput!) { eat(topping: { @@ -61,111 +61,110 @@ mutation a($input: ButterPickleInput!) ] } ) }"; - // act - IExecutionResult result = await executor.ExecuteAsync( - Query, - new Dictionary + // act + var result = await executor.ExecuteAsync( + Query, + new Dictionary + { { + "input", + new Dictionary { - "input", - new Dictionary + { "size", 5 }, { - { "size", 5 }, + "complexAssigned", + new Dictionary { - "complexAssigned", - new Dictionary - { - { "value", 3 } - } - }, - { "complexAssignedNull", null} , + { "value", 3 } + } + }, + { "complexAssignedNull", null} , + { + "complexList", + new List> { - "complexList", - new List> - { - new() { { "value", 2 } } - } + new() { { "value", 2 } } } } } - }); - - // assert - Assert.Null(result.ExpectQueryResult().Errors); - Verify(input); - } - - private static void Verify(ToppingInput? input) - { - Assert.NotNull(input); - ButterPickleInput? pickle = input?.Pickles!.First()?.ButterPickle; - Assert.NotNull(pickle); - Assert.Equal(5, pickle?.Size); - Assert.False(pickle?.Width.HasValue); - Assert.False(pickle?.ComplexUnassigned.HasValue); - Assert.True(pickle?.ComplexAssigned.HasValue); - Assert.Equal(3, pickle?.ComplexAssigned.Value?.Value); - Assert.True(pickle?.ComplexAssignedNull.HasValue); - Assert.Null(pickle?.ComplexAssignedNull.Value); - Assert.True(pickle?.ComplexList.HasValue); - Assert.Equal(2, pickle?.ComplexList.Value?.First().Value); - } + } + }); - private static IRequestExecutor CreateExecutor(Func? onEat = null) - { - return SchemaBuilder.New() - .AddQueryType() - .AddMutationType(new MutationType(onEat)) - .Create() - .MakeExecutable(); - } + // assert + Assert.Null(result.ExpectQueryResult().Errors); + Verify(input); + } - public class Query - { - public string Chocolate => "rain"; - } + private static void Verify(ToppingInput? input) + { + Assert.NotNull(input); + var pickle = input?.Pickles!.First()?.ButterPickle; + Assert.NotNull(pickle); + Assert.Equal(5, pickle?.Size); + Assert.False(pickle?.Width.HasValue); + Assert.False(pickle?.ComplexUnassigned.HasValue); + Assert.True(pickle?.ComplexAssigned.HasValue); + Assert.Equal(3, pickle?.ComplexAssigned.Value?.Value); + Assert.True(pickle?.ComplexAssignedNull.HasValue); + Assert.Null(pickle?.ComplexAssignedNull.Value); + Assert.True(pickle?.ComplexList.HasValue); + Assert.Equal(2, pickle?.ComplexList.Value?.First().Value); + } - public class MutationType : ObjectType - { - private readonly Func _onEat; + private static IRequestExecutor CreateExecutor(Func? onEat = null) + { + return SchemaBuilder.New() + .AddQueryType() + .AddMutationType(new MutationType(onEat)) + .Create() + .MakeExecutable(); + } - public MutationType(Func? onEat = null) - { - _onEat = onEat ?? (_ => true); - } + public class Query + { + public string Chocolate => "rain"; + } - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field("eat") - .Type>() - .Argument("topping", arg => arg.Type(typeof(ToppingInput))) - .Resolve(ctx => _onEat(ctx.ArgumentValue("topping"))); - } - } + public class MutationType : ObjectType + { + private readonly Func _onEat; - public class ToppingInput + public MutationType(Func? onEat = null) { - public IEnumerable? Pickles { get; set; } + _onEat = onEat ?? (_ => true); } - public class PicklesInput + protected override void Configure(IObjectTypeDescriptor descriptor) { - public ButterPickleInput? ButterPickle { get; set; } + descriptor.Field("eat") + .Type>() + .Argument("topping", arg => arg.Type(typeof(ToppingInput))) + .Resolve(ctx => _onEat(ctx.ArgumentValue("topping"))); } + } - public class ButterPickleInput - { - public Optional Size { get; set; } - public Optional Width { get; set; } - public Optional ComplexUnassigned { get; set; } - public Optional ComplexAssigned { get; set; } - public Optional ComplexAssignedNull { get; set; } - public Optional?> ComplexList { get; set; } - } + public class ToppingInput + { + public IEnumerable? Pickles { get; set; } + } - public class SomeComplexInput - { - public int Value { get; set; } - } + public class PicklesInput + { + public ButterPickleInput? ButterPickle { get; set; } + } + + public class ButterPickleInput + { + public Optional Size { get; set; } + public Optional Width { get; set; } + public Optional ComplexUnassigned { get; set; } + public Optional ComplexAssigned { get; set; } + public Optional ComplexAssignedNull { get; set; } + public Optional?> ComplexList { get; set; } + } + + public class SomeComplexInput + { + public int Value { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/ResolverContextStateExtensionTests.cs b/src/HotChocolate/Core/test/Types.Tests/ResolverContextStateExtensionTests.cs index 030e7c4613e..eed07788cb8 100644 --- a/src/HotChocolate/Core/test/Types.Tests/ResolverContextStateExtensionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/ResolverContextStateExtensionTests.cs @@ -52,7 +52,7 @@ public void GetGlobalStateOrDefault_KeyMissing() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetGlobalStateOrDefault("key"); @@ -67,7 +67,7 @@ public void GetGlobalState_KeyMissing() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; Assert.Throws(() => context.GetGlobalState("key")); @@ -81,7 +81,7 @@ public void GetGlobalStateOrDefault_KeyExists_WrongType() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetGlobalStateOrDefault("key"); @@ -96,7 +96,7 @@ public void GetGlobalState_KeyExists_WrongType() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; Assert.Throws(() => context.GetGlobalState("key")); @@ -110,7 +110,7 @@ public void GetGlobalStateOrDefault_KeyExists_CorrectType() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetGlobalStateOrDefault("key"); @@ -125,7 +125,7 @@ public void GetGlobalState_KeyExists_CorrectType() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetGlobalState("key"); @@ -140,7 +140,7 @@ public void SetGlobalState() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; context.SetGlobalState("key", "value"); @@ -155,7 +155,7 @@ public void GetOrSetGlobalState_KeyMissing() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetOrSetGlobalState("key", key => 1); @@ -174,7 +174,7 @@ public void GetOrSetGlobalState_KeyExists_WrongType() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetOrSetGlobalState("key", key => 1); @@ -193,7 +193,7 @@ public void GetOrSetGlobalState_KeyExists_CorrectType() var mock = new Mock(); mock.SetupGet(c => c.ContextData).Returns(dict); - IResolverContext context = mock.Object; + var context = mock.Object; var state = context.GetOrSetGlobalState("key", key => 1); @@ -207,7 +207,7 @@ public void GetScopedStateOrDefault_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = ImmutableDictionary.Empty; var state = context.GetScopedStateOrDefault("key"); @@ -221,7 +221,7 @@ public void GetScopedState_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = ImmutableDictionary.Empty; Assert.Throws(() => @@ -234,7 +234,7 @@ public void GetScopedStateOrDefault_KeyExists_WrongType() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = new Dictionary { { "key", "value" } @@ -251,7 +251,7 @@ public void GetScopedState_KeyExists_WrongType() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = new Dictionary { { "key", "value" } @@ -267,7 +267,7 @@ public void GetScopedStateOrDefault_KeyExists_CorrectType() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = new Dictionary { { "key", 1 } @@ -284,7 +284,7 @@ public void GetScopedState_KeyExists_CorrectType() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = new Dictionary { { "key", 1 } @@ -301,7 +301,7 @@ public void SetScopedState() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = ImmutableDictionary.Empty; context.SetScopedState("key", "value"); @@ -315,7 +315,7 @@ public void GetOrSetScopedState_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = ImmutableDictionary.Empty; var state = context.GetOrSetScopedState("key", key => 1); @@ -330,7 +330,7 @@ public void GetOrSetScopedState_KeyExists_WrongType() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = new Dictionary { {"key", "value"} @@ -348,7 +348,7 @@ public void GetOrSetScopedState_KeyExists_CorrectType() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = new Dictionary { {"key", 2} @@ -366,7 +366,7 @@ public void RemoveScopedState_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = ImmutableDictionary.Empty; context.RemoveScopedState("key"); @@ -380,7 +380,7 @@ public void RemoveScopedState_KeyExists() var mock = new Mock(); mock.SetupProperty(c => c.ScopedContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.ScopedContextData = ImmutableDictionary.Empty; context.SetScopedState("key1", 1); @@ -398,7 +398,7 @@ public void GetLocalStateOrDefault_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = ImmutableDictionary.Empty; var state = context.GetLocalStateOrDefault("key"); @@ -412,7 +412,7 @@ public void GetLocalState_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = ImmutableDictionary.Empty; Assert.Throws(() => @@ -425,7 +425,7 @@ public void GetLocalStateOrDefault_KeyExists_WrongType() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = new Dictionary { { "key", "value" } @@ -442,7 +442,7 @@ public void GetLocalState_KeyExists_WrongType() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = new Dictionary { { "key", "value" } @@ -458,7 +458,7 @@ public void GetLocalStateOrDefault_KeyExists_CorrectType() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = new Dictionary { { "key", 1 } @@ -475,7 +475,7 @@ public void GetLocalState_KeyExists_CorrectType() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = new Dictionary { { "key", 1 } @@ -492,7 +492,7 @@ public void SetLocalState() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = ImmutableDictionary.Empty; context.SetLocalState("key", "value"); @@ -506,7 +506,7 @@ public void GetOrSetLocalState_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = ImmutableDictionary.Empty; var state = context.GetOrSetLocalState("key", key => 1); @@ -521,7 +521,7 @@ public void GetOrSetLocalState_KeyExists_WrongType() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = new Dictionary { { "key", "value" } @@ -539,7 +539,7 @@ public void GetOrSetLocalState_KeyExists_CorrectType() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = new Dictionary { { "key", 2 } @@ -557,7 +557,7 @@ public void RemoveLocalState_KeyMissing() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = ImmutableDictionary.Empty; context.RemoveLocalState("key"); @@ -571,7 +571,7 @@ public void RemoveLocalState_KeyExists() var mock = new Mock(); mock.SetupProperty(c => c.LocalContextData); - IResolverContext context = mock.Object; + var context = mock.Object; context.LocalContextData = ImmutableDictionary.Empty; context.SetLocalState("key1", 1); diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/CustomResolverCompilerTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/CustomResolverCompilerTests.cs index fa11b7e8a40..8e59f202f26 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/CustomResolverCompilerTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/CustomResolverCompilerTests.cs @@ -1,234 +1,233 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.ObjectPool; using HotChocolate.Execution; using HotChocolate.Execution.Configuration; using HotChocolate.Tests; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.ObjectPool; using Moq; using Snapshooter.Xunit; using Xunit; #nullable enable -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class CustomResolverCompilerTests { - public class CustomResolverCompilerTests + [Fact] + public async Task AddDefaultService() { - [Fact] - public async Task AddDefaultService() - { - Snapshot.FullName(); + Snapshot.FullName(); + + await new ServiceCollection() + .AddSingleton() + .AddGraphQL() + .AddQueryType() + .RegisterService() + .ExecuteRequestAsync("{ sayHello }") + .MatchSnapshotAsync(); + } + + [Fact] + public async Task AddPooledService() + { + Snapshot.FullName(); + + var pooledService = new SayHelloServicePool(); + + await new ServiceCollection() + .AddSingleton>(pooledService) + .AddGraphQL() + .AddQueryType() + .RegisterService(ServiceKind.Pooled) + .ExecuteRequestAsync("{ sayHello }") + .MatchSnapshotAsync(); + Assert.True(pooledService.GetService); + Assert.True(pooledService.ReturnService); + } + + [Fact] + public async Task AddSynchronizedService() + { + Snapshot.FullName(); + + var executor = await new ServiceCollection() .AddSingleton() .AddGraphQL() .AddQueryType() - .RegisterService() - .ExecuteRequestAsync("{ sayHello }") - .MatchSnapshotAsync(); - } + .RegisterService(ServiceKind.Synchronized) + .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) + .BuildRequestExecutorAsync(); - [Fact] - public async Task AddPooledService() - { - Snapshot.FullName(); + Assert.False(executor.Schema.QueryType.Fields["sayHello"].IsParallelExecutable); - var pooledService = new SayHelloServicePool(); + await executor.ExecuteAsync("{ sayHello }").MatchSnapshotAsync(); + } + + [Fact] + public async Task AddResolverService() + { + Snapshot.FullName(); + var executor = await new ServiceCollection() - .AddSingleton>(pooledService) + .AddSingleton() .AddGraphQL() .AddQueryType() - .RegisterService(ServiceKind.Pooled) - .ExecuteRequestAsync("{ sayHello }") - .MatchSnapshotAsync(); + .RegisterService(ServiceKind.Resolver) + .MapField( + new FieldReference("Query", "sayHello"), + next => async context => + { + await next(context); + Assert.True( + context.LocalContextData.ContainsKey( + WellKnownMiddleware.ResolverServiceScope)); + }) + .BuildRequestExecutorAsync(); + + await executor.ExecuteAsync("{ sayHello }").MatchSnapshotAsync(); + } - Assert.True(pooledService.GetService); - Assert.True(pooledService.ReturnService); - } + [Fact] + [Obsolete] + public async Task AddWellKnownService() + { + Snapshot.FullName(); - [Fact] - public async Task AddSynchronizedService() - { - Snapshot.FullName(); + await new ServiceCollection() + .AddSingleton() + .AddGraphQL() + .AddQueryType() + .ConfigureResolverCompiler(c => + { + c.AddService(); + }) + .ExecuteRequestAsync("{ sayHello }") + .MatchSnapshotAsync(); + } - IRequestExecutor executor = - await new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddQueryType() - .RegisterService(ServiceKind.Synchronized) - .ModifyRequestOptions(o => o.IncludeExceptionDetails = true) - .BuildRequestExecutorAsync(); + [Fact] + [Obsolete] + public async Task AddWellKnownState() + { + Snapshot.FullName(); - Assert.False(executor.Schema.QueryType.Fields["sayHello"].IsParallelExecutable); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ConfigureResolverCompiler(c => + { + c.AddParameter(ctx => (SayHelloState)ctx.ContextData["someState"]!); + }) + .ExecuteRequestAsync( + QueryRequestBuilder.New() + .SetQuery("{ sayHello }") + .AddGlobalState("someState", new SayHelloState("Hello")) + .Create()) + .MatchSnapshotAsync(); + } - await executor.ExecuteAsync("{ sayHello }").MatchSnapshotAsync(); - } + [Fact] + [Obsolete] + public void AddParameterEnsureBuilderIsNotNull() + { + void Configure() + => default(IResolverCompilerBuilder)! + .AddParameter(ctx => ctx.Operation.Document); - [Fact] - public async Task AddResolverService() - { - Snapshot.FullName(); - - IRequestExecutor executor = - await new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddQueryType() - .RegisterService(ServiceKind.Resolver) - .MapField( - new FieldReference("Query", "sayHello"), - next => async context => - { - await next(context); - Assert.True( - context.LocalContextData.ContainsKey( - WellKnownMiddleware.ResolverServiceScope)); - }) - .BuildRequestExecutorAsync(); - - await executor.ExecuteAsync("{ sayHello }").MatchSnapshotAsync(); - } + Assert.Throws(Configure); + } - [Fact] - [Obsolete] - public async Task AddWellKnownService() - { - Snapshot.FullName(); + [Fact] + [Obsolete] + public void AddParameterEnsureExpressionIsNotNull() + { + var mock = new Mock(); - await new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddQueryType() - .ConfigureResolverCompiler(c => - { - c.AddService(); - }) - .ExecuteRequestAsync("{ sayHello }") - .MatchSnapshotAsync(); - } + void Configure() + => mock.Object.AddParameter(null!); - [Fact] - [Obsolete] - public async Task AddWellKnownState() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ConfigureResolverCompiler(c => - { - c.AddParameter(ctx => (SayHelloState)ctx.ContextData["someState"]!); - }) - .ExecuteRequestAsync( - QueryRequestBuilder.New() - .SetQuery("{ sayHello }") - .AddGlobalState("someState", new SayHelloState("Hello")) - .Create()) - .MatchSnapshotAsync(); - } + Assert.Throws(Configure); + } - [Fact] - [Obsolete] - public void AddParameterEnsureBuilderIsNotNull() - { - void Configure() - => default(IResolverCompilerBuilder)! - .AddParameter(ctx => ctx.Document); + [Fact] + [Obsolete] + public void AddServiceEnsureBuilderIsNotNull() + { + void Configure() + => default(IResolverCompilerBuilder)! + .AddService(); - Assert.Throws(Configure); - } + Assert.Throws(Configure); + } - [Fact] - [Obsolete] - public void AddParameterEnsureExpressionIsNotNull() - { - var mock = new Mock(); + [Fact] + [Obsolete] + public void EnsureRequestExecutorBuilderIsNotNull() + { + void Configure() + => default(IRequestExecutorBuilder)!.ConfigureResolverCompiler(_ => { }); - void Configure() - => mock.Object.AddParameter(null!); + Assert.Throws(Configure); + } - Assert.Throws(Configure); - } + [Fact] + [Obsolete] + public void EnsureConfigureIsNotNull() + { + var mock = new Mock(); - [Fact] - [Obsolete] - public void AddServiceEnsureBuilderIsNotNull() - { - void Configure() - => default(IResolverCompilerBuilder)! - .AddService(); + void Configure() => mock.Object.ConfigureResolverCompiler(null!); - Assert.Throws(Configure); - } + Assert.Throws(Configure); + } - [Fact] - [Obsolete] - public void EnsureRequestExecutorBuilderIsNotNull() - { - void Configure() - => default(IRequestExecutorBuilder)!.ConfigureResolverCompiler(_ => { }); + public class SayHelloService + { + public string SayHello() => "Hello"; + } - Assert.Throws(Configure); - } + public class QueryWellKnownService + { + public string SayHello(SayHelloService service) + => service.SayHello(); + } - [Fact] - [Obsolete] - public void EnsureConfigureIsNotNull() + public class SayHelloState + { + public SayHelloState(string greetings) { - var mock = new Mock(); - - void Configure() => mock.Object.ConfigureResolverCompiler(null!); - - Assert.Throws(Configure); + Greetings = greetings; } - public class SayHelloService - { - public string SayHello() => "Hello"; - } + public string Greetings { get; } + } - public class QueryWellKnownService - { - public string SayHello(SayHelloService service) - => service.SayHello(); - } + public class QueryWellKnownState + { + public string SayHello(SayHelloState state) + => state.Greetings; + } - public class SayHelloState - { - public SayHelloState(string greetings) - { - Greetings = greetings; - } + public class SayHelloServicePool : ObjectPool + { + public bool GetService { get; private set; } - public string Greetings { get; } - } + public bool ReturnService { get; private set; } - public class QueryWellKnownState + public override SayHelloService Get() { - public string SayHello(SayHelloState state) - => state.Greetings; + GetService = true; + return new SayHelloService(); } - public class SayHelloServicePool : ObjectPool + public override void Return(SayHelloService obj) { - public bool GetService { get; private set; } - - public bool ReturnService { get; private set; } - - public override SayHelloService Get() - { - GetService = true; - return new SayHelloService(); - } - - public override void Return(SayHelloService obj) - { - ReturnService = true; - } + ReturnService = true; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMemberTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMemberTests.cs index ecb9c14b54d..9725e252b28 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMemberTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMemberTests.cs @@ -3,341 +3,340 @@ using System.Reflection; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class FieldMemberTests { - public class FieldMemberTests + [Fact] + public void Create() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var member = GetMemberA(); + + // act + var fieldMember = new FieldMember( + typeName, fieldName, member); + + // assert + Assert.Equal(typeName, fieldMember.TypeName); + Assert.Equal(fieldName, fieldMember.FieldName); + Assert.Equal(member, fieldMember.Member); + } + + [Fact] + public void CreateTypeNull() + { + // arrange + var fieldName = TestUtils.CreateFieldName(); + var member = GetMemberA(); + + // act + Action action = () => new FieldMember(null, fieldName, member); + + // assert + Assert.Throws(action); + } + + [Fact] + public void CreateFieldNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var member = GetMemberA(); + + // act + Action action = () => new FieldMember(typeName, null, member); + + // assert + Assert.Throws(action); + } + + [Fact] + public void CreateMemberNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + + // act + Action action = () => new FieldMember(typeName, fieldName, default(MemberInfo)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void CreateExpressionNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + + // act + Action action = () => new FieldMember(typeName, fieldName, default(Expression)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithTypeName() + { + // arrange + var originalTypeName = TestUtils.CreateTypeName(); + var newTypeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var member = GetMemberA(); + + var fieldMember = new FieldMember( + originalTypeName, fieldName, member); + + // act + fieldMember = fieldMember.WithTypeName(newTypeName); + + // assert + Assert.Equal(newTypeName, fieldMember.TypeName); + } + + [Fact] + public void WithTypeNameNull() + { + // arrange + var originalTypeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var member = GetMemberA(); + + var fieldMember = new FieldMember( + originalTypeName, fieldName, member); + + // act + Action action = () => fieldMember.WithTypeName(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithFieldName() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var originalFieldName = TestUtils.CreateFieldName(); + var newFieldName = TestUtils.CreateFieldName(); + var member = GetMemberA(); + + var fieldMember = new FieldMember( + typeName, originalFieldName, member); + + // act + fieldMember = fieldMember.WithFieldName(newFieldName); + + // assert + Assert.Equal(newFieldName, fieldMember.FieldName); + } + + [Fact] + public void WithFieldNameNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var originalFieldName = TestUtils.CreateFieldName(); + var member = GetMemberA(); + + var fieldMember = new FieldMember( + typeName, originalFieldName, member); + + // act + Action action = () => fieldMember.WithFieldName(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithMember() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var originalMember = GetMemberA(); + var newMember = GetMemberB(); + + var fieldMember = new FieldMember( + typeName, fieldName, originalMember); + + // act + fieldMember = fieldMember.WithMember(newMember); + + // assert + Assert.Equal(newMember, fieldMember.Member); + } + + [Fact] + public void WithMemberNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var originalMember = GetMemberA(); + + var fieldMember = new FieldMember( + typeName, fieldName, originalMember); + + // act + Action action = () => fieldMember.WithMember(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void EqualsObjectNull() + { + // arrange + var fieldMember = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + // act + var result = fieldMember.Equals(default(object)); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectReferenceEquals() + { + // arrange + var fieldMember = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + // act + var result = fieldMember.Equals((object)fieldMember); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsObjectFieldsAreEqual() + { + // arrange + var fieldMember_a = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + var fieldMember_b = new FieldMember( + fieldMember_a.TypeName, + fieldMember_a.FieldName, + fieldMember_a.Member); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsObjectWithIncompatibleType() + { + // arrange + var fieldMember = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + // act + var result = fieldMember.Equals(new object()); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectTypeNotEqual() + { + // arrange + var fieldMember_a = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + var fieldMember_b = new FieldMember( + TestUtils.CreateTypeName(), + fieldMember_a.FieldName, + fieldMember_a.Member); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectFieldNotEqual() + { + // arrange + var fieldMember_a = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + var fieldMember_b = new FieldMember( + fieldMember_a.TypeName, + TestUtils.CreateFieldName(), + fieldMember_a.Member); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectMemberNotEqual() + { + // arrange + var fieldMember_a = new FieldMember( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetMemberA()); + + var fieldMember_b = new FieldMember( + fieldMember_a.TypeName, + fieldMember_a.FieldName, + GetMemberB()); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.False(result); + } + + private MemberInfo GetMemberA() + { + return typeof(Foo).GetProperty("BarA"); + } + + private MemberInfo GetMemberB() + { + return typeof(Foo).GetProperty("BarB"); + } + + private sealed class Foo { - [Fact] - public void Create() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - MemberInfo member = GetMemberA(); - - // act - var fieldMember = new FieldMember( - typeName, fieldName, member); - - // assert - Assert.Equal(typeName, fieldMember.TypeName); - Assert.Equal(fieldName, fieldMember.FieldName); - Assert.Equal(member, fieldMember.Member); - } - - [Fact] - public void CreateTypeNull() - { - // arrange - var fieldName = TestUtils.CreateFieldName(); - MemberInfo member = GetMemberA(); - - // act - Action action = () => new FieldMember(null, fieldName, member); - - // assert - Assert.Throws(action); - } - - [Fact] - public void CreateFieldNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - MemberInfo member = GetMemberA(); - - // act - Action action = () => new FieldMember(typeName, null, member); - - // assert - Assert.Throws(action); - } - - [Fact] - public void CreateMemberNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - - // act - Action action = () => new FieldMember(typeName, fieldName, default(MemberInfo)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void CreateExpressionNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - - // act - Action action = () => new FieldMember(typeName, fieldName, default(Expression)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithTypeName() - { - // arrange - var originalTypeName = TestUtils.CreateTypeName(); - var newTypeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - MemberInfo member = GetMemberA(); - - var fieldMember = new FieldMember( - originalTypeName, fieldName, member); - - // act - fieldMember = fieldMember.WithTypeName(newTypeName); - - // assert - Assert.Equal(newTypeName, fieldMember.TypeName); - } - - [Fact] - public void WithTypeNameNull() - { - // arrange - var originalTypeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - MemberInfo member = GetMemberA(); - - var fieldMember = new FieldMember( - originalTypeName, fieldName, member); - - // act - Action action = () => fieldMember.WithTypeName(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithFieldName() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var originalFieldName = TestUtils.CreateFieldName(); - var newFieldName = TestUtils.CreateFieldName(); - MemberInfo member = GetMemberA(); - - var fieldMember = new FieldMember( - typeName, originalFieldName, member); - - // act - fieldMember = fieldMember.WithFieldName(newFieldName); - - // assert - Assert.Equal(newFieldName, fieldMember.FieldName); - } - - [Fact] - public void WithFieldNameNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var originalFieldName = TestUtils.CreateFieldName(); - MemberInfo member = GetMemberA(); - - var fieldMember = new FieldMember( - typeName, originalFieldName, member); - - // act - Action action = () => fieldMember.WithFieldName(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithMember() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - MemberInfo originalMember = GetMemberA(); - MemberInfo newMember = GetMemberB(); - - var fieldMember = new FieldMember( - typeName, fieldName, originalMember); - - // act - fieldMember = fieldMember.WithMember(newMember); - - // assert - Assert.Equal(newMember, fieldMember.Member); - } - - [Fact] - public void WithMemberNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - MemberInfo originalMember = GetMemberA(); - - var fieldMember = new FieldMember( - typeName, fieldName, originalMember); - - // act - Action action = () => fieldMember.WithMember(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void EqualsObjectNull() - { - // arrange - var fieldMember = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - // act - bool result = fieldMember.Equals(default(object)); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectReferenceEquals() - { - // arrange - var fieldMember = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - // act - bool result = fieldMember.Equals((object)fieldMember); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsObjectFieldsAreEqual() - { - // arrange - var fieldMember_a = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - var fieldMember_b = new FieldMember( - fieldMember_a.TypeName, - fieldMember_a.FieldName, - fieldMember_a.Member); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsObjectWithIncompatibleType() - { - // arrange - var fieldMember = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - // act - bool result = fieldMember.Equals(new object()); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectTypeNotEqual() - { - // arrange - var fieldMember_a = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - var fieldMember_b = new FieldMember( - TestUtils.CreateTypeName(), - fieldMember_a.FieldName, - fieldMember_a.Member); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectFieldNotEqual() - { - // arrange - var fieldMember_a = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - var fieldMember_b = new FieldMember( - fieldMember_a.TypeName, - TestUtils.CreateFieldName(), - fieldMember_a.Member); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectMemberNotEqual() - { - // arrange - var fieldMember_a = new FieldMember( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetMemberA()); - - var fieldMember_b = new FieldMember( - fieldMember_a.TypeName, - fieldMember_a.FieldName, - GetMemberB()); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.False(result); - } - - private MemberInfo GetMemberA() - { - return typeof(Foo).GetProperty("BarA"); - } - - private MemberInfo GetMemberB() - { - return typeof(Foo).GetProperty("BarB"); - } - - private sealed class Foo - { - public string BarA { get; } - public string BarB { get; } - } + public string BarA { get; } + public string BarB { get; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMiddlewareTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMiddlewareTests.cs index 89007bf3f1a..bac402b7df0 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldMiddlewareTests.cs @@ -7,59 +7,58 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class FieldMiddlewareTests { - public class FieldMiddlewareTests + [Fact] + public async Task TaskMiddlewareAreCorrectlyConverted() { - [Fact] - public async Task TaskMiddlewareAreCorrectlyConverted() - { - Snapshot.FullName(); + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Use()) - .ExecuteRequestAsync("{ foo }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Use()) + .ExecuteRequestAsync("{ foo }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task ValueTaskMiddlewareAreCorrectlyConverted() - { - Snapshot.FullName(); + [Fact] + public async Task ValueTaskMiddlewareAreCorrectlyConverted() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Use()) - .ExecuteRequestAsync("{ foo }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Use()) + .ExecuteRequestAsync("{ foo }") + .MatchSnapshotAsync(); + } - public class TaskFieldMiddleware + public class TaskFieldMiddleware + { + public Task InvokeAsync(IMiddlewareContext context) { - public Task InvokeAsync(IMiddlewareContext context) - { - context.Result = "worked"; - return Task.CompletedTask; - ; - } + context.Result = "worked"; + return Task.CompletedTask; + ; } + } - public class ValueTaskFieldMiddleware + public class ValueTaskFieldMiddleware + { + public ValueTask InvokeAsync(IMiddlewareContext context) { - public ValueTask InvokeAsync(IMiddlewareContext context) - { - context.Result = "worked"; - return default; - } + context.Result = "worked"; + return default; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldReferenceTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldReferenceTests.cs index d246cb96acd..efba40a1a3d 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldReferenceTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldReferenceTests.cs @@ -1,217 +1,216 @@ using System; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class FieldReferenceTests { - public class FieldReferenceTests + [Fact] + public void Create() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + + // act + var fieldReference = new FieldReference(typeName, fieldName); + + // assert + Assert.Equal(typeName, fieldReference.TypeName); + Assert.Equal(fieldName, fieldReference.FieldName); + } + + [Fact] + public void CreateTypeNull() + { + // arrange + var fieldName = TestUtils.CreateFieldName(); + + // act + Action action = () => new FieldReference(null, fieldName); + + // assert + Assert.Throws(action); + } + + [Fact] + public void CreateFieldNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + + // act + Action action = () => new FieldReference(typeName, null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithTypeName() + { + // arrange + var originalTypeName = TestUtils.CreateTypeName(); + var newTypeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var fieldReference = new FieldReference( + originalTypeName, fieldName); + + // act + fieldReference = fieldReference.WithTypeName(newTypeName); + + // assert + Assert.Equal(newTypeName, fieldReference.TypeName); + } + + [Fact] + public void WithTypeNameNull() + { + // arrange + var originalTypeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var fieldReference = new FieldReference( + originalTypeName, fieldName); + + // act + Action action = () => fieldReference.WithTypeName(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithFieldName() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var originalFieldName = TestUtils.CreateFieldName(); + var newFieldName = TestUtils.CreateFieldName(); + var fieldReference = new FieldReference( + typeName, originalFieldName); + + // act + fieldReference = fieldReference.WithFieldName(newFieldName); + + // assert + Assert.Equal(newFieldName, fieldReference.FieldName); + } + + [Fact] + public void WithFieldNameNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var originalFieldName = TestUtils.CreateFieldName(); + var fieldReference = new FieldReference( + typeName, originalFieldName); + + // act + Action action = () => fieldReference.WithFieldName(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void EqualsObjectNull() + { + // arrange + var fieldReference = new FieldReference( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName()); + + // act + var result = fieldReference.Equals(default(object)); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectReferenceEquals() + { + // arrange + var fieldReference = new FieldReference( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName()); + + // act + var result = fieldReference.Equals((object)fieldReference); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsObjectFieldsAreEqual() { - [Fact] - public void Create() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - - // act - var fieldReference = new FieldReference(typeName, fieldName); - - // assert - Assert.Equal(typeName, fieldReference.TypeName); - Assert.Equal(fieldName, fieldReference.FieldName); - } - - [Fact] - public void CreateTypeNull() - { - // arrange - var fieldName = TestUtils.CreateFieldName(); - - // act - Action action = () => new FieldReference(null, fieldName); - - // assert - Assert.Throws(action); - } - - [Fact] - public void CreateFieldNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - - // act - Action action = () => new FieldReference(typeName, null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithTypeName() - { - // arrange - var originalTypeName = TestUtils.CreateTypeName(); - var newTypeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - var fieldReference = new FieldReference( - originalTypeName, fieldName); - - // act - fieldReference = fieldReference.WithTypeName(newTypeName); - - // assert - Assert.Equal(newTypeName, fieldReference.TypeName); - } - - [Fact] - public void WithTypeNameNull() - { - // arrange - var originalTypeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - var fieldReference = new FieldReference( - originalTypeName, fieldName); - - // act - Action action = () => fieldReference.WithTypeName(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithFieldName() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var originalFieldName = TestUtils.CreateFieldName(); - var newFieldName = TestUtils.CreateFieldName(); - var fieldReference = new FieldReference( - typeName, originalFieldName); - - // act - fieldReference = fieldReference.WithFieldName(newFieldName); - - // assert - Assert.Equal(newFieldName, fieldReference.FieldName); - } - - [Fact] - public void WithFieldNameNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var originalFieldName = TestUtils.CreateFieldName(); - var fieldReference = new FieldReference( - typeName, originalFieldName); - - // act - Action action = () => fieldReference.WithFieldName(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void EqualsObjectNull() - { - // arrange - var fieldReference = new FieldReference( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName()); - - // act - bool result = fieldReference.Equals(default(object)); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectReferenceEquals() - { - // arrange - var fieldReference = new FieldReference( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName()); - - // act - bool result = fieldReference.Equals((object)fieldReference); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsObjectFieldsAreEqual() - { - // arrange - var fieldReference_a = new FieldReference( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName()); - - var fieldReference_b = new FieldReference( - fieldReference_a.TypeName, - fieldReference_a.FieldName); - - // act - bool result = fieldReference_a.Equals((object)fieldReference_b); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsObjectWithIncompatibleType() - { - // arrange - var fieldReference = new FieldReference( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName()); - - // act - bool result = fieldReference.Equals(new object()); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectTypeNotEqual() - { - // arrange - var fieldReference_a = new FieldReference( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName()); - - var fieldReference_b = new FieldReference( - TestUtils.CreateTypeName(), - fieldReference_a.FieldName); - - // act - bool result = fieldReference_a.Equals((object)fieldReference_b); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectFieldNotEqual() - { - // arrange - var fieldReference_a = new FieldReference( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName()); - - var fieldReference_b = new FieldReference( - fieldReference_a.TypeName, - TestUtils.CreateFieldName()); - - // act - bool result = fieldReference_a.Equals((object)fieldReference_b); - - // assert - Assert.False(result); - } + // arrange + var fieldReference_a = new FieldReference( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName()); + + var fieldReference_b = new FieldReference( + fieldReference_a.TypeName, + fieldReference_a.FieldName); + + // act + var result = fieldReference_a.Equals((object)fieldReference_b); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsObjectWithIncompatibleType() + { + // arrange + var fieldReference = new FieldReference( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName()); + + // act + var result = fieldReference.Equals(new object()); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectTypeNotEqual() + { + // arrange + var fieldReference_a = new FieldReference( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName()); + + var fieldReference_b = new FieldReference( + TestUtils.CreateTypeName(), + fieldReference_a.FieldName); + + // act + var result = fieldReference_a.Equals((object)fieldReference_b); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectFieldNotEqual() + { + // arrange + var fieldReference_a = new FieldReference( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName()); + + var fieldReference_b = new FieldReference( + fieldReference_a.TypeName, + TestUtils.CreateFieldName()); + + // act + var result = fieldReference_a.Equals((object)fieldReference_b); + + // assert + Assert.False(result); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldResolverTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldResolverTests.cs index a9d6669042d..c737bc307f9 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldResolverTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/FieldResolverTests.cs @@ -2,329 +2,328 @@ using System.Threading.Tasks; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class FieldResolverTests { - public class FieldResolverTests + [Fact] + public void Create() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var resolver = GetResolverA(); + + // act + var fieldMember = new FieldResolver( + typeName, fieldName, resolver); + + // assert + Assert.Equal(typeName, fieldMember.TypeName); + Assert.Equal(fieldName, fieldMember.FieldName); + Assert.Equal(resolver, fieldMember.Resolver); + } + + [Fact] + public void CreateTypeNull() + { + // arrange + var fieldName = TestUtils.CreateFieldName(); + var resolver = GetResolverA(); + + // act + Action action = () => new FieldResolver(null, fieldName, resolver); + + // assert + Assert.Throws(action); + } + + [Fact] + public void CreateFieldNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var resolver = GetResolverA(); + + // act + Action action = () => new FieldResolver(typeName, null, resolver); + + // assert + Assert.Throws(action); + } + + [Fact] + public void CreateMemberNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + + // act + Action action = () => new FieldResolver(typeName, fieldName, null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithTypeName() + { + // arrange + var originalTypeName = TestUtils.CreateTypeName(); + var newTypeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var resolver = GetResolverA(); + + var fieldMember = new FieldResolver( + originalTypeName, fieldName, resolver); + + // act + fieldMember = fieldMember.WithTypeName(newTypeName); + + // assert + Assert.Equal(newTypeName, fieldMember.TypeName); + } + + [Fact] + public void WithTypeNameNull() + { + // arrange + var originalTypeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var resolver = GetResolverA(); + + var fieldMember = new FieldResolver( + originalTypeName, fieldName, resolver); + + // act + Action action = () => fieldMember.WithTypeName(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithFieldName() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var originalFieldName = TestUtils.CreateFieldName(); + var newFieldName = TestUtils.CreateFieldName(); + var resolver = GetResolverA(); + + var fieldMember = new FieldResolver( + typeName, originalFieldName, resolver); + + // act + fieldMember = fieldMember.WithFieldName(newFieldName); + + // assert + Assert.Equal(newFieldName, fieldMember.FieldName); + } + + [Fact] + public void WithFieldNameNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var originalFieldName = TestUtils.CreateFieldName(); + var resolver = GetResolverA(); + + var fieldMember = new FieldResolver( + typeName, originalFieldName, resolver); + + // act + Action action = () => fieldMember.WithFieldName(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void WithResolver() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var originalResolver = GetResolverA(); + var newResolver = GetResolverB(); + + var fieldMember = new FieldResolver( + typeName, fieldName, originalResolver); + + // act + fieldMember = fieldMember.WithResolver(newResolver); + + // assert + Assert.Equal(newResolver, fieldMember.Resolver); + } + + [Fact] + public void WithResolverNull() + { + // arrange + var typeName = TestUtils.CreateTypeName(); + var fieldName = TestUtils.CreateFieldName(); + var originalResolver = GetResolverA(); + + var fieldMember = new FieldResolver( + typeName, fieldName, originalResolver); + + // act + Action action = () => fieldMember.WithResolver(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void EqualsObjectNull() + { + // arrange + var fieldMember = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + // act + var result = fieldMember.Equals(default(object)); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectReferenceEquals() + { + // arrange + var fieldMember = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + // act + var result = fieldMember.Equals((object)fieldMember); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsObjectFieldsAreEqual() + { + // arrange + var fieldMember_a = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + var fieldMember_b = new FieldResolver( + fieldMember_a.TypeName, + fieldMember_a.FieldName, + fieldMember_a.Resolver); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsObjectWithIncompatibleType() + { + // arrange + var fieldMember = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + // act + var result = fieldMember.Equals(new object()); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectTypeNotEqual() + { + // arrange + var fieldMember_a = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + var fieldMember_b = new FieldResolver( + TestUtils.CreateTypeName(), + fieldMember_a.FieldName, + fieldMember_a.Resolver); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectFieldNotEqual() + { + // arrange + var fieldMember_a = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + var fieldMember_b = new FieldResolver( + fieldMember_a.TypeName, + TestUtils.CreateFieldName(), + fieldMember_a.Resolver); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsObjectMemberNotEqual() + { + // arrange + var fieldMember_a = new FieldResolver( + TestUtils.CreateTypeName(), + TestUtils.CreateFieldName(), + GetResolverA()); + + var fieldMember_b = new FieldResolver( + fieldMember_a.TypeName, + fieldMember_a.FieldName, + GetResolverB()); + + // act + var result = fieldMember_a.Equals((object)fieldMember_b); + + // assert + Assert.False(result); + } + + private FieldResolverDelegate GetResolverA() + { + return new FieldResolverDelegate( + a => new ValueTask(null)); + } + + private FieldResolverDelegate GetResolverB() + { + return new FieldResolverDelegate( + a => new ValueTask(null)); + } + + private sealed class Foo { - [Fact] - public void Create() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate resolver = GetResolverA(); - - // act - var fieldMember = new FieldResolver( - typeName, fieldName, resolver); - - // assert - Assert.Equal(typeName, fieldMember.TypeName); - Assert.Equal(fieldName, fieldMember.FieldName); - Assert.Equal(resolver, fieldMember.Resolver); - } - - [Fact] - public void CreateTypeNull() - { - // arrange - var fieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate resolver = GetResolverA(); - - // act - Action action = () => new FieldResolver(null, fieldName, resolver); - - // assert - Assert.Throws(action); - } - - [Fact] - public void CreateFieldNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - FieldResolverDelegate resolver = GetResolverA(); - - // act - Action action = () => new FieldResolver(typeName, null, resolver); - - // assert - Assert.Throws(action); - } - - [Fact] - public void CreateMemberNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - - // act - Action action = () => new FieldResolver(typeName, fieldName, null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithTypeName() - { - // arrange - var originalTypeName = TestUtils.CreateTypeName(); - var newTypeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate resolver = GetResolverA(); - - var fieldMember = new FieldResolver( - originalTypeName, fieldName, resolver); - - // act - fieldMember = fieldMember.WithTypeName(newTypeName); - - // assert - Assert.Equal(newTypeName, fieldMember.TypeName); - } - - [Fact] - public void WithTypeNameNull() - { - // arrange - var originalTypeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate resolver = GetResolverA(); - - var fieldMember = new FieldResolver( - originalTypeName, fieldName, resolver); - - // act - Action action = () => fieldMember.WithTypeName(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithFieldName() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var originalFieldName = TestUtils.CreateFieldName(); - var newFieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate resolver = GetResolverA(); - - var fieldMember = new FieldResolver( - typeName, originalFieldName, resolver); - - // act - fieldMember = fieldMember.WithFieldName(newFieldName); - - // assert - Assert.Equal(newFieldName, fieldMember.FieldName); - } - - [Fact] - public void WithFieldNameNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var originalFieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate resolver = GetResolverA(); - - var fieldMember = new FieldResolver( - typeName, originalFieldName, resolver); - - // act - Action action = () => fieldMember.WithFieldName(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void WithResolver() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate originalResolver = GetResolverA(); - FieldResolverDelegate newResolver = GetResolverB(); - - var fieldMember = new FieldResolver( - typeName, fieldName, originalResolver); - - // act - fieldMember = fieldMember.WithResolver(newResolver); - - // assert - Assert.Equal(newResolver, fieldMember.Resolver); - } - - [Fact] - public void WithResolverNull() - { - // arrange - var typeName = TestUtils.CreateTypeName(); - var fieldName = TestUtils.CreateFieldName(); - FieldResolverDelegate originalResolver = GetResolverA(); - - var fieldMember = new FieldResolver( - typeName, fieldName, originalResolver); - - // act - Action action = () => fieldMember.WithResolver(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void EqualsObjectNull() - { - // arrange - var fieldMember = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - // act - bool result = fieldMember.Equals(default(object)); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectReferenceEquals() - { - // arrange - var fieldMember = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - // act - bool result = fieldMember.Equals((object)fieldMember); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsObjectFieldsAreEqual() - { - // arrange - var fieldMember_a = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - var fieldMember_b = new FieldResolver( - fieldMember_a.TypeName, - fieldMember_a.FieldName, - fieldMember_a.Resolver); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsObjectWithIncompatibleType() - { - // arrange - var fieldMember = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - // act - bool result = fieldMember.Equals(new object()); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectTypeNotEqual() - { - // arrange - var fieldMember_a = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - var fieldMember_b = new FieldResolver( - TestUtils.CreateTypeName(), - fieldMember_a.FieldName, - fieldMember_a.Resolver); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectFieldNotEqual() - { - // arrange - var fieldMember_a = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - var fieldMember_b = new FieldResolver( - fieldMember_a.TypeName, - TestUtils.CreateFieldName(), - fieldMember_a.Resolver); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsObjectMemberNotEqual() - { - // arrange - var fieldMember_a = new FieldResolver( - TestUtils.CreateTypeName(), - TestUtils.CreateFieldName(), - GetResolverA()); - - var fieldMember_b = new FieldResolver( - fieldMember_a.TypeName, - fieldMember_a.FieldName, - GetResolverB()); - - // act - bool result = fieldMember_a.Equals((object)fieldMember_b); - - // assert - Assert.False(result); - } - - private FieldResolverDelegate GetResolverA() - { - return new FieldResolverDelegate( - a => new ValueTask(null)); - } - - private FieldResolverDelegate GetResolverB() - { - return new FieldResolverDelegate( - a => new ValueTask(null)); - } - - private sealed class Foo - { - public string BarA { get; } - public string BarB { get; } - } + public string BarA { get; } + public string BarB { get; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverCompilerTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverCompilerTests.cs index d60cd69d07f..7937b51f4ef 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverCompilerTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverCompilerTests.cs @@ -19,1485 +19,1491 @@ #nullable enable -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class ResolverCompilerTests { - public class ResolverCompilerTests + private readonly IParameterExpressionBuilder[] _empty = + Array.Empty(); + + [Fact] + public async Task Compile_TaskObjMethod_NoParams_SourceResolver() { - private readonly IParameterExpressionBuilder[] _empty = - Array.Empty(); + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectTaskResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("ObjectResolverResult", result); + } - [Fact] - public async Task Compile_TaskObjMethod_NoParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectTaskResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("ObjectResolverResult", result); - } + [Fact] + public async Task Compile_TaskStringMethod_NoParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringTaskResolver", result); + } - [Fact] - public async Task Compile_TaskStringMethod_NoParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - string result = (string)(await resolver(context.Object))!; - Assert.Equal("StringTaskResolver", result); - } + [Fact] + public async Task Compile_TaskStringMethod_WithParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolverWithArg))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ArgumentValue("a")).Returns("abc"); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("abc", result); + } - [Fact] - public async Task Compile_TaskStringMethod_WithParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolverWithArg))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ArgumentValue("a")).Returns("abc"); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("abc", result); - } + [Fact] + public async Task Compile_ObjMethod_NoParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("ObjectResolverResult", result); + } - [Fact] - public async Task Compile_ObjMethod_NoParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("ObjectResolverResult", result); - } + [Fact] + public async Task Compile_StringMethod_NoParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringTaskResolver", result); + } - [Fact] - public async Task Compile_StringMethod_NoParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringTaskResolver", result); - } + [Fact] + public async Task Compile_StringMethod_WithParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolverWithArg))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ArgumentValue("a")).Returns("abc"); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("abc", result); + } - [Fact] - public async Task Compile_StringMethod_WithParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolverWithArg))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ArgumentValue("a")).Returns("abc"); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("abc", result); - } + [Fact] + public async Task Compile_StringValueNodeMethod_WithParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringValueNodeResolverWithArg))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ArgumentLiteral("a")) + .Returns(new StringValueNode("abc")); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("abc", result); + } - [Fact] - public async Task Compile_StringValueNodeMethod_WithParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringValueNodeResolverWithArg))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ArgumentLiteral("a")) - .Returns(new StringValueNode("abc")); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("abc", result); - } + [Fact] + public async Task Compile_OptionalStringMethod_WithParams_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.OptionalStringResolverWithArg))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ArgumentOptional("a")) + .Returns(new Optional("abc")); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("abc", result); + } - [Fact] - public async Task Compile_OptionalStringMethod_WithParams_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.OptionalStringResolverWithArg))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ArgumentOptional("a")) - .Returns(new Optional("abc")); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("abc", result); - } + [Fact] + public async Task Compile_ObjTaskProperty_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetProperty("ObjectTaskStringProp")!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("ObjectTaskStringProp", result); + } - [Fact] - public async Task Compile_ObjTaskProperty_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetProperty("ObjectTaskStringProp")!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("ObjectTaskStringProp", result); - } + [Fact] + public async Task Compile_StringTaskProperty_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetProperty("StringTaskResolverProp")!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringTaskResolverProp", result); + } - [Fact] - public async Task Compile_StringTaskProperty_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetProperty("StringTaskResolverProp")!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringTaskResolverProp", result); - } + [Fact] + public async Task Compile_StringProperty_SourceResolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetProperty("StringProp")!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringProp", result); + } - [Fact] - public async Task Compile_StringProperty_SourceResolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetProperty("StringProp")!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringProp", result); - } + [Fact] + public async Task Compile_TaskObjMethod_NoParams_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectTaskResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("ObjectResolverResult", result); + } - [Fact] - public async Task Compile_TaskObjMethod_NoParams_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectTaskResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("ObjectResolverResult", result); - } + [Fact] + public async Task Compile_TaskStringMethod_NoParams_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringTaskResolver", result); + } - [Fact] - public async Task Compile_TaskStringMethod_NoParams_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringTaskResolver", result); - } + [Fact] + public async Task Compile_TaskStringMethod_WithParams_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolverWithArg))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + context.Setup(t => t.ArgumentValue("a")).Returns("abc"); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("abc", result); + } - [Fact] - public async Task Compile_TaskStringMethod_WithParams_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringTaskResolverWithArg))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - context.Setup(t => t.ArgumentValue("a")).Returns("abc"); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("abc", result); - } + [Fact] + public async Task Compile_ObjMethod_NoParams_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("ObjectResolverResult", result); + } - [Fact] - public async Task Compile_ObjMethod_NoParams_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ObjectResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("ObjectResolverResult", result); - } + [Fact] + public async Task Compile_StringMethod_NoParams_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolver))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringTaskResolver", result); + } - [Fact] - public async Task Compile_StringMethod_NoParams_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolver))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringTaskResolver", result); - } + [Fact] + public async Task Compile_StringMethod_WithParams_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolverWithArg))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + context.Setup(t => t.ArgumentValue("a")).Returns("abc"); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("abc", result); + } - [Fact] - public async Task Compile_StringMethod_WithParams_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.StringResolverWithArg))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - context.Setup(t => t.ArgumentValue("a")).Returns("abc"); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("abc", result); - } + [Fact] + public async Task Compile_ObjTaskProperty_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetProperty("ObjectTaskStringProp")!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("ObjectTaskStringProp", result); + } - [Fact] - public async Task Compile_ObjTaskProperty_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetProperty("ObjectTaskStringProp")!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("ObjectTaskStringProp", result); - } + [Fact] + public async Task Compile_StringTaskProperty_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetProperty("StringTaskResolverProp")!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringTaskResolverProp", result); + } - [Fact] - public async Task Compile_StringTaskProperty_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetProperty("StringTaskResolverProp")!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringTaskResolverProp", result); - } + [Fact] + public async Task Compile_StringProperty_Resolver() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetProperty("StringProp")!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = + compiler.CompileResolve(member, typeof(Entity), type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Resolver()).Returns(new Resolvers()); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("StringProp", result); + } - [Fact] - public async Task Compile_StringProperty_Resolver() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetProperty("StringProp")!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = - compiler.CompileResolve(member, typeof(Entity), type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Resolver()).Returns(new Resolvers()); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("StringProp", result); - } + [Fact] + public async Task Compile_Arguments_CancellationToken() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithCancellationToken))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.RequestAborted).Returns(CancellationToken.None); + var result = (string)(await resolver(context.Object))!; + Assert.Equal("cancel", result); + } - [Fact] - public async Task Compile_Arguments_CancellationToken() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithCancellationToken))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.RequestAborted).Returns(CancellationToken.None); - var result = (string)(await resolver(context.Object))!; - Assert.Equal("cancel", result); - } + [Fact] + public async Task Compile_Arguments_ResolverContext() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithResolverContext))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - [Fact] - public async Task Compile_Arguments_ResolverContext() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithResolverContext))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + [Fact] + public async Task Compile_Arguments_FieldSelection() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithFieldSelection))!; - [Fact] - public async Task Compile_Arguments_FieldSelection() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithFieldSelection))!; + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + // assert + var selection = new Mock(); - // assert - var selection = new Mock(); + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Selection).Returns(selection.Object); - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Selection).Returns(selection.Object); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + [Fact] + public async Task Compile_Arguments_Selection() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithSelection))!; - [Fact] - public async Task Compile_Arguments_Selection() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithSelection))!; + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + var pure = compiler.CompileResolve(member, type).PureResolver!; - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - PureFieldDelegate pure = compiler.CompileResolve(member, type).PureResolver!; + // assert + var selection = new Mock(); - // assert - var selection = new Mock(); + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Selection).Returns(selection.Object); - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Selection).Returns(selection.Object); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result, "Standard Resolver"); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result, "Standard Resolver"); + result = (bool)pure(context.Object)!; + Assert.True(result, "Pure Resolver"); + } - result = (bool)pure(context.Object)!; - Assert.True(result, "Pure Resolver"); - } + [Fact] + public async Task Compile_Arguments_FieldSyntax() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithFieldSyntax))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + var pure = compiler.CompileResolve(member, type).PureResolver!; + + // assert + var fieldSyntax = new FieldNode( + null, + new NameNode("foo"), + null, + null, + Array.Empty(), + Array.Empty(), + null); + + var selection = new Mock(); + selection.SetupGet(t => t.SyntaxNode).Returns(fieldSyntax); + + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Selection).Returns(selection.Object); + + var result = (bool)(await resolver(context.Object))!; + Assert.True(result, "Standard Resolver"); + + result = (bool)pure(context.Object)!; + Assert.True(result, "Pure Resolver"); + } - [Fact] - public async Task Compile_Arguments_FieldSyntax() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithFieldSyntax))!; + [Fact] + public async Task Compile_Arguments_ObjectType() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithObjectType))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String }") + .Use(next => next) + .Create(); + + var queryType = schema.GetType("Query"); + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.ObjectType).Returns(queryType); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - PureFieldDelegate pure = compiler.CompileResolve(member, type).PureResolver!; + [Fact] + public async Task Compile_Arguments_Operation() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithOperationDefinition))!; - // assert - var fieldSyntax = new FieldNode( - null, - new NameNode("foo"), + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var operationDefinition = + new OperationDefinitionNode( null, null, + OperationType.Query, + Array.Empty(), Array.Empty(), - Array.Empty(), - null); + new SelectionSetNode( + null, + Array.Empty())); - var selection = new Mock(); - selection.SetupGet(t => t.SyntaxNode).Returns(fieldSyntax); + var operation = new Mock(); + operation.Setup(t => t.Definition).Returns(operationDefinition); - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Selection).Returns(selection.Object); + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Operation).Returns(operation.Object); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - var result = (bool)(await resolver(context.Object))!; - Assert.True(result, "Standard Resolver"); + [Fact] + public async Task Compile_Arguments_ObjectField() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithObjectField))!; - result = (bool)pure(context.Object)!; - Assert.True(result, "Pure Resolver"); - } + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - [Fact] - public async Task Compile_Arguments_ObjectType() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithObjectType))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String }") - .Use(next => next) - .Create(); - - ObjectType queryType = schema.GetType("Query"); - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.ObjectType).Returns(queryType); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + // assert + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String }") + .Use(next => next) + .Create(); - [Fact] - public async Task Compile_Arguments_Operation() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithOperationDefinition))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()) - .Returns(new Resolvers()); - context.SetupGet(t => t.Operation) - .Returns(new OperationDefinitionNode( - null, - null, - OperationType.Query, - Array.Empty(), - Array.Empty(), - new SelectionSetNode( - null, - Array.Empty()))); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + var queryType = schema.GetType("Query"); - [Fact] - public async Task Compile_Arguments_ObjectField() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithObjectField))!; + var selection = new Mock(); + selection.SetupGet(t => t.Field).Returns(queryType.Fields.First()); - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Selection).Returns(selection.Object); - // assert - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String }") - .Use(next => next) - .Create(); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - ObjectType queryType = schema.GetType("Query"); + [Fact] + public async Task Compile_Arguments_IOutputField() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithOutputField))!; - var selection = new Mock(); - selection.SetupGet(t => t.Field).Returns(queryType.Fields.First()); + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Selection).Returns(selection.Object); + // assert + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String }") + .Use(next => next) + .Create(); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + var queryType = schema.GetType("Query"); - [Fact] - public async Task Compile_Arguments_IOutputField() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithOutputField))!; + var selection = new Mock(); + selection.SetupGet(t => t.Field).Returns(queryType.Fields.First()); - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Selection).Returns(selection.Object); - // assert - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String }") - .Use(next => next) - .Create(); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - ObjectType queryType = schema.GetType("Query"); + [Fact] + public async Task Compile_Arguments_Document() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithDocument))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var document = new DocumentNode(Array.Empty()); + var operation = new Mock(); + operation.Setup(t => t.Document).Returns(document); + + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Operation).Returns(operation.Object); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - var selection = new Mock(); - selection.SetupGet(t => t.Field).Returns(queryType.Fields.First()); + [Fact] + public async Task Compile_Arguments_Schema() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithSchema))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { a: String }") + .Use(next => next) + .Create(); + + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Schema).Returns(schema); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Selection).Returns(selection.Object); + [Fact] + public async Task Compile_Arguments_Service() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithService))!; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.Service()).Returns(new MyService()); + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + [Fact] + public async Task Compile_GetGlobalState_With_Key() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateWithKey))!; + var contextData = new Dictionary { { "foo", "bar" } }; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + var value = await resolver(context.Object); + Assert.Equal("bar", Assert.IsType(value)); + } - [Fact] - public async Task Compile_Arguments_Document() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithDocument))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var document = new DocumentNode(Array.Empty()); - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Document).Returns(document); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + [Fact] + public async Task Compile_GetGlobalState() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalState))!; + var contextData = new Dictionary { { "foo", "bar" } }; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + var value = await resolver(context.Object); + Assert.Equal("bar", Assert.IsType(value)); + } - [Fact] - public async Task Compile_Arguments_Schema() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithSchema))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { a: String }") - .Use(next => next) - .Create(); - - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Schema).Returns(schema); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + [Fact] + public async Task Compile_GetGlobalState_State_Does_Not_Exist() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalState))!; + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + await Assert.ThrowsAsync( + async () => await resolver(context.Object)); + } - [Fact] - public async Task Compile_Arguments_Service() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.ResolverWithService))!; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.Service()).Returns(new MyService()); - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + [Fact] + public async Task Compile_GetGlobalState_With_Default_Abc() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateWithDefaultAbc))!; + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + var value = await resolver(context.Object); + Assert.Equal("abc", Assert.IsType(value)); + } - [Fact] - public async Task Compile_GetGlobalState_With_Key() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateWithKey))!; - var contextData = new Dictionary { { "foo", "bar" } }; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - var value = await resolver(context.Object); - Assert.Equal("bar", Assert.IsType(value)); - } + [Fact] + public async Task Compile_GetGlobalState_With_Default() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateWithDefault))!; + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + var value = await resolver(context.Object); + Assert.Null(value); + } - [Fact] - public async Task Compile_GetGlobalState() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalState))!; - var contextData = new Dictionary { { "foo", "bar" } }; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - var value = await resolver(context.Object); - Assert.Equal("bar", Assert.IsType(value)); - } + [Fact] + public async Task Compile_GetGlobalState_Nullable() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateNullable))!; + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + var value = await resolver(context.Object); + Assert.Null(value); + } - [Fact] - public async Task Compile_GetGlobalState_State_Does_Not_Exist() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalState))!; - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - await Assert.ThrowsAsync( - async () => await resolver(context.Object)); - } + [Fact] + public async Task Compile_SetGlobalState() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.SetGlobalState))!; + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + await resolver(context.Object); + + Assert.True(contextData.ContainsKey("foo")); + Assert.Equal("abc", contextData["foo"]); + } - [Fact] - public async Task Compile_GetGlobalState_With_Default_Abc() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateWithDefaultAbc))!; - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - var value = await resolver(context.Object); - Assert.Equal("abc", Assert.IsType(value)); - } + [Fact] + public async Task Compile_SetGlobalState_Generic() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.SetGlobalStateGeneric))!; - [Fact] - public async Task Compile_GetGlobalState_With_Default() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateWithDefault))!; - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - var value = await resolver(context.Object); - Assert.Null(value); - } + var contextData = new Dictionary(); - [Fact] - public async Task Compile_GetGlobalState_Nullable() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetGlobalStateNullable))!; - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - var value = await resolver(context.Object); - Assert.Null(value); - } + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - [Fact] - public async Task Compile_SetGlobalState() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.SetGlobalState))!; - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - await resolver(context.Object); - - Assert.True(contextData.ContainsKey("foo")); - Assert.Equal("abc", contextData["foo"]); - } + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + await resolver(context.Object); - [Fact] - public async Task Compile_SetGlobalState_Generic() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.SetGlobalStateGeneric))!; + Assert.True(contextData.ContainsKey("foo")); + Assert.Equal("abc", contextData["foo"]); + } - var contextData = new Dictionary(); + [Fact] + public async Task Compile_GetScopedState_With_Key() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateWithKey))!; + var contextData = new Dictionary { { "foo", "bar" } } + .ToImmutableDictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var value = await resolver(context.Object); + Assert.Equal("bar", Assert.IsType(value)); + } - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + [Fact] + public async Task Compile_GetScopedState() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedState))!; + + var contextData = new Dictionary{ { "foo", "bar" } } + .ToImmutableDictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var value = await resolver(context.Object); + Assert.Equal("bar", Assert.IsType(value)); + } - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - await resolver(context.Object); + [Fact] + public async Task Compile_GetScopedState_State_Does_Not_Exist() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedState))!; + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + await Assert.ThrowsAsync( + async () => await resolver(context.Object)); + } - Assert.True(contextData.ContainsKey("foo")); - Assert.Equal("abc", contextData["foo"]); - } + [Fact] + public async Task Compile_GetScopedState_With_Default_Abc() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateWithDefaultAbc))!; + + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var value = await resolver(context.Object); + Assert.Equal("abc", Assert.IsType(value)); + } - [Fact] - public async Task Compile_GetScopedState_With_Key() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateWithKey))!; - var contextData = new Dictionary { { "foo", "bar" } } - .ToImmutableDictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - var value = await resolver(context.Object); - Assert.Equal("bar", Assert.IsType(value)); - } + [Fact] + public async Task Compile_GetScopedState_With_Default() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateWithDefault))!; + + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var value = await resolver(context.Object); + Assert.Null(value); + } - [Fact] - public async Task Compile_GetScopedState() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedState))!; - - var contextData = new Dictionary{ { "foo", "bar" } } - .ToImmutableDictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - var value = await resolver(context.Object); - Assert.Equal("bar", Assert.IsType(value)); - } + [Fact] + public async Task Compile_GetScopedState_Nullable() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateNullable))!; + + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(() => new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var value = await resolver(context.Object); + Assert.Null(value); + } - [Fact] - public async Task Compile_GetScopedState_State_Does_Not_Exist() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedState))!; - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - await Assert.ThrowsAsync( - async () => await resolver(context.Object)); - } + [Fact] + public async Task Compile_SetScopedState() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.SetScopedState))!; - [Fact] - public async Task Compile_GetScopedState_With_Default_Abc() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateWithDefaultAbc))!; - - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - var value = await resolver(context.Object); - Assert.Equal("abc", Assert.IsType(value)); - } + var contextData = + ImmutableDictionary.Empty; - [Fact] - public async Task Compile_GetScopedState_With_Default() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateWithDefault))!; - - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - var value = await resolver(context.Object); - Assert.Null(value); - } + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - [Fact] - public async Task Compile_GetScopedState_Nullable() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetScopedStateNullable))!; - - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(() => new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - var value = await resolver(context.Object); - Assert.Null(value); - } + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var resolverContext = context.Object; - [Fact] - public async Task Compile_SetScopedState() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.SetScopedState))!; + await resolver(resolverContext); - ImmutableDictionary contextData = - ImmutableDictionary.Empty; + Assert.True(resolverContext.ScopedContextData.ContainsKey("foo")); + Assert.Equal("abc", resolverContext.ScopedContextData["foo"]); + } - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + [Fact] + public async Task Compile_SetScopedState_Generic() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.SetScopedStateGeneric))!; - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - IResolverContext resolverContext = context.Object; + var contextData = + ImmutableDictionary.Empty; - await resolver(resolverContext); + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - Assert.True(resolverContext.ScopedContextData.ContainsKey("foo")); - Assert.Equal("abc", resolverContext.ScopedContextData["foo"]); - } + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.ScopedContextData, contextData); + var resolverContext = context.Object; - [Fact] - public async Task Compile_SetScopedState_Generic() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.SetScopedStateGeneric))!; + await resolver(resolverContext); - ImmutableDictionary contextData = - ImmutableDictionary.Empty; + Assert.True(resolverContext.ScopedContextData.ContainsKey("foo")); + Assert.Equal("abc", resolverContext.ScopedContextData["foo"]); + } - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + [Fact] + public async Task Compile_GetLocalState_With_Key() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalStateWithKey))!; + var contextData = new Dictionary { { "foo", "bar" } } + .ToImmutableDictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + var value = await resolver(context.Object); + Assert.Equal("bar", Assert.IsType(value)); + } - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.ScopedContextData, contextData); - IResolverContext resolverContext = context.Object; + [Fact] + public async Task Compile_GetLocalState() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalState))!; + var contextData = new Dictionary { { "foo", "bar" } } + .ToImmutableDictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + var value = await resolver(context.Object); + Assert.Equal("bar", Assert.IsType(value)); + } - await resolver(resolverContext); + [Fact] + public async Task Compile_GetLocalState_State_Does_Not_Exist() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalState))!; + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + await Assert.ThrowsAsync( + async () => await resolver(context.Object)); + } - Assert.True(resolverContext.ScopedContextData.ContainsKey("foo")); - Assert.Equal("abc", resolverContext.ScopedContextData["foo"]); - } + [Fact] + public async Task Compile_GetLocalState_With_Default_Abc() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalStateWithDefaultAbc))!; + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + var value = await resolver(context.Object); + Assert.Equal("abc", Assert.IsType(value)); + } - [Fact] - public async Task Compile_GetLocalState_With_Key() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalStateWithKey))!; - var contextData = new Dictionary { { "foo", "bar" } } - .ToImmutableDictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - var value = await resolver(context.Object); - Assert.Equal("bar", Assert.IsType(value)); - } + [Fact] + public async Task Compile_GetLocalState_With_Default() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalStateWithDefault))!; + var contextData = + ImmutableDictionary.Empty; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + var value = await resolver(context.Object); + Assert.Null(value); + } - [Fact] - public async Task Compile_GetLocalState() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalState))!; - var contextData = new Dictionary { { "foo", "bar" } } - .ToImmutableDictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - var value = await resolver(context.Object); - Assert.Equal("bar", Assert.IsType(value)); - } + [Fact] + public async Task Compile_SetLocalState() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.SetLocalState))!; - [Fact] - public async Task Compile_GetLocalState_State_Does_Not_Exist() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalState))!; - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - await Assert.ThrowsAsync( - async () => await resolver(context.Object)); - } + var contextData = + ImmutableDictionary.Empty; - [Fact] - public async Task Compile_GetLocalState_With_Default_Abc() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalStateWithDefaultAbc))!; - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - var value = await resolver(context.Object); - Assert.Equal("abc", Assert.IsType(value)); - } + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - [Fact] - public async Task Compile_GetLocalState_With_Default() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetLocalStateWithDefault))!; - ImmutableDictionary contextData = - ImmutableDictionary.Empty; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - var value = await resolver(context.Object); - Assert.Null(value); - } + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + var resolverContext = context.Object; - [Fact] - public async Task Compile_SetLocalState() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.SetLocalState))!; + await resolver(resolverContext); - ImmutableDictionary contextData = - ImmutableDictionary.Empty; + Assert.True(resolverContext.LocalContextData.ContainsKey("foo")); + Assert.Equal("abc", resolverContext.LocalContextData["foo"]); + } + + [Fact] + public async Task Compile_SetLocalState_Generic() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.SetLocalStateGeneric))!; - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + var contextData = + ImmutableDictionary.Empty; - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - IResolverContext resolverContext = context.Object; + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - await resolver(resolverContext); + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupProperty(t => t.LocalContextData, contextData); + var resolverContext = context.Object; - Assert.True(resolverContext.LocalContextData.ContainsKey("foo")); - Assert.Equal("abc", resolverContext.LocalContextData["foo"]); - } + await resolver(resolverContext); - [Fact] - public async Task Compile_SetLocalState_Generic() + Assert.True(resolverContext.LocalContextData.ContainsKey("foo")); + Assert.Equal("abc", resolverContext.LocalContextData["foo"]); + } + + [Fact] + public async Task Compile_GetClaimsPrincipal() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetClaimsPrincipal))!; + + var contextData = new Dictionary { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.SetLocalStateGeneric))!; + { nameof(ClaimsPrincipal), new ClaimsPrincipal() } + }; + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + var value = await resolver(context.Object); + Assert.True(Assert.IsType(value)); + } - ImmutableDictionary contextData = - ImmutableDictionary.Empty; + [Fact] + public async Task Compile_GetClaimsPrincipal_ClaimsNotExists() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetClaimsPrincipal))!; + + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + async Task Execute() => await resolver(context.Object); + Exception ex = await Assert.ThrowsAsync(Execute); + ex.Message.MatchSnapshot(); + } - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + [Fact] + public async Task Compile_GetNullableClaimsPrincipal_ClaimsNotExists() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetNullableClaimsPrincipal))!; + + var contextData = new Dictionary(); + + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; + + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.Setup(t => t.ContextData).Returns(contextData); + async Task Execute() => await resolver(context.Object); + Exception ex = await Assert.ThrowsAsync(Execute); + ex.Message.MatchSnapshot(); + } - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupProperty(t => t.LocalContextData, contextData); - IResolverContext resolverContext = context.Object; + [Fact] + public async Task Compile_Arguments_Path() + { + // arrange + var type = typeof(Resolvers); + MemberInfo member = type.GetMethod(nameof(Resolvers.GetPath))!; - await resolver(resolverContext); + // act + var compiler = new DefaultResolverCompiler(_empty); + var resolver = compiler.CompileResolve(member, type).Resolver!; - Assert.True(resolverContext.LocalContextData.ContainsKey("foo")); - Assert.Equal("abc", resolverContext.LocalContextData["foo"]); - } + // assert + var context = new Mock(); + context.Setup(t => t.Parent()).Returns(new Resolvers()); + context.SetupGet(t => t.Path).Returns(PathFactory.Instance.New("FOO")); - [Fact] - public async Task Compile_GetClaimsPrincipal() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetClaimsPrincipal))!; - - var contextData = new Dictionary - { - { nameof(ClaimsPrincipal), new ClaimsPrincipal() } - }; - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - var value = await resolver(context.Object); - Assert.True(Assert.IsType(value)); - } + var result = (bool)(await resolver(context.Object))!; + Assert.True(result); + } - [Fact] - public async Task Compile_GetClaimsPrincipal_ClaimsNotExists() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetClaimsPrincipal))!; - - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - async Task Execute() => await resolver(context!.Object); - Exception ex = await Assert.ThrowsAsync(Execute); - ex.Message.MatchSnapshot(); - } + [Fact] + public async Task SchemaIntegrationTest() + { + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ModifyOptions(o => o.SortFieldsByName = true) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Compile_GetNullableClaimsPrincipal_ClaimsNotExists() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetNullableClaimsPrincipal))!; - - var contextData = new Dictionary(); - - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; - - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.Setup(t => t.ContextData).Returns(contextData); - async Task Execute() => await resolver(context!.Object); - Exception ex = await Assert.ThrowsAsync(Execute); - ex.Message.MatchSnapshot(); - } + public class Resolvers + { + public Task ObjectTaskResolver() => + Task.FromResult("ObjectResolverResult"); - [Fact] - public async Task Compile_Arguments_Path() - { - // arrange - Type type = typeof(Resolvers); - MemberInfo member = type.GetMethod(nameof(Resolvers.GetPath))!; + public Task StringTaskResolver() => + Task.FromResult("StringTaskResolver"); - // act - var compiler = new DefaultResolverCompiler(_empty); - FieldResolverDelegate resolver = compiler.CompileResolve(member, type).Resolver!; + public Task StringTaskResolverWithArg(string a) => + Task.FromResult(a); - // assert - var context = new Mock(); - context.Setup(t => t.Parent()).Returns(new Resolvers()); - context.SetupGet(t => t.Path).Returns(PathFactory.Instance.New("FOO")); + public object ObjectResolver() => "ObjectResolverResult"; - var result = (bool)(await resolver(context.Object))!; - Assert.True(result); - } + public string StringResolver() => "StringTaskResolver"; - [Fact] - public async Task SchemaIntegrationTest() - { - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ModifyOptions(o => o.SortFieldsByName = true) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + public string StringResolverWithArg(string a) => a; - public class Resolvers - { - public Task ObjectTaskResolver() => - Task.FromResult("ObjectResolverResult"); + [GraphQLIgnore] + public string StringValueNodeResolverWithArg(StringValueNode a) => a.Value; + + public string? OptionalStringResolverWithArg(Optional a) => a.Value; + + public Task ObjectTaskStringProp { get; } = + Task.FromResult("ObjectTaskStringProp"); + + public Task StringTaskResolverProp { get; } = + Task.FromResult("StringTaskResolverProp"); + + public string StringProp { get; } = "StringProp"; + + public string ResolverWithCancellationToken( + CancellationToken cancellationToken) => + "cancel"; + + public bool GetClaimsPrincipal(ClaimsPrincipal claims) + => claims != null!; + + public bool GetNullableClaimsPrincipal(ClaimsPrincipal? claims) + => claims != null!; + + public bool GetPath(Path path) + => path != null!; - public Task StringTaskResolver() => - Task.FromResult("StringTaskResolver"); + public bool ResolverWithResolverContext( + IResolverContext context) => + context != null!; - public Task StringTaskResolverWithArg(string a) => - Task.FromResult(a); + public bool ResolverWithFieldSyntax( + FieldNode fieldSyntax) => + fieldSyntax != null!; - public object ObjectResolver() => "ObjectResolverResult"; + public bool ResolverWithFieldSelection( + ISelection fieldSelection) => + fieldSelection != null!; - public string StringResolver() => "StringTaskResolver"; + public bool ResolverWithSelection( + ISelection fieldSelection) => + fieldSelection != null!; - public string StringResolverWithArg(string a) => a; + public bool ResolverWithObjectType( + ObjectType objectType) => + objectType != null!; - [GraphQLIgnore] - public string StringValueNodeResolverWithArg(StringValueNode a) => a.Value; + public bool ResolverWithOperationDefinition( + OperationDefinitionNode operationDefinition) => + operationDefinition != null!; - public string? OptionalStringResolverWithArg(Optional a) => a.Value; + public bool ResolverWithObjectField( + ObjectField objectField) => + objectField != null!; - public Task ObjectTaskStringProp { get; } = - Task.FromResult("ObjectTaskStringProp"); + public bool ResolverWithOutputField( + IOutputField outputField) => + outputField != null!; - public Task StringTaskResolverProp { get; } = - Task.FromResult("StringTaskResolverProp"); + public bool ResolverWithDocument( + DocumentNode document) => + document != null!; - public string StringProp { get; } = "StringProp"; + public bool ResolverWithSchema( + ISchema schema) => + schema != null!; - public string ResolverWithCancellationToken( - CancellationToken cancellationToken) => - "cancel"; + public bool ResolverWithService( + [Service] MyService service) => + service != null!; - public bool GetClaimsPrincipal(ClaimsPrincipal claims) - => claims != null!; + public string GetGlobalStateWithKey( + [GlobalState("foo")] + string s) => s; - public bool GetNullableClaimsPrincipal(ClaimsPrincipal? claims) - => claims != null!; + public string GetGlobalState( + [GlobalState] + string foo) => foo; - public bool GetPath(Path path) - => path != null!; + public string GetGlobalStateWithDefaultAbc( + [GlobalState] + string foo = "abc") => foo; - public bool ResolverWithResolverContext( - IResolverContext context) => - context != null!; + public string? GetGlobalStateWithDefault( + [GlobalState] + string? foo = default) => foo; - public bool ResolverWithFieldSyntax( - FieldNode fieldSyntax) => - fieldSyntax != null!; + public string GetGlobalStateNullable( + [GlobalState] + string? foo) => foo!; - public bool ResolverWithFieldSelection( - ISelection fieldSelection) => - fieldSelection != null!; + public string SetGlobalStateGeneric( + [GlobalState] + SetState foo) + { + foo("abc"); + return "foo"; + } - public bool ResolverWithSelection( - ISelection fieldSelection) => - fieldSelection != null!; + public string SetGlobalState( + [GlobalState] + SetState foo) + { + foo("abc"); + return "foo"; + } - public bool ResolverWithObjectType( - ObjectType objectType) => - objectType != null!; + public string GetScopedStateWithKey( + [ScopedState("foo")] + string s) => s; - public bool ResolverWithOperationDefinition( - OperationDefinitionNode operationDefinition) => - operationDefinition != null!; + public string GetScopedState( + [ScopedState] + string foo) => foo; - public bool ResolverWithObjectField( - ObjectField objectField) => - objectField != null!; + public string GetScopedStateWithDefaultAbc( + [ScopedState] + string foo = "abc") => foo; - public bool ResolverWithOutputField( - IOutputField outputField) => - outputField != null!; + public string? GetScopedStateWithDefault( + [ScopedState] + string? foo = default) => foo; - public bool ResolverWithDocument( - DocumentNode document) => - document != null!; + public string GetScopedStateNullable( + [ScopedState] + string? foo) => foo!; - public bool ResolverWithSchema( - ISchema schema) => - schema != null!; + public string SetScopedStateGeneric( + [ScopedState] + SetState foo) + { + foo("abc"); + return "foo"; + } - public bool ResolverWithService( - [Service] MyService service) => - service != null!; - - public string GetGlobalStateWithKey( - [GlobalState("foo")] - string s) => s; - - public string GetGlobalState( - [GlobalState] - string foo) => foo; - - public string GetGlobalStateWithDefaultAbc( - [GlobalState] - string foo = "abc") => foo; - - public string? GetGlobalStateWithDefault( - [GlobalState] - string? foo = default) => foo; - - public string GetGlobalStateNullable( - [GlobalState] - string? foo) => foo!; - - public string SetGlobalStateGeneric( - [GlobalState] - SetState foo) - { - foo("abc"); - return "foo"; - } - - public string SetGlobalState( - [GlobalState] - SetState foo) - { - foo("abc"); - return "foo"; - } - - public string GetScopedStateWithKey( - [ScopedState("foo")] - string s) => s; - - public string GetScopedState( - [ScopedState] - string foo) => foo; - - public string GetScopedStateWithDefaultAbc( - [ScopedState] - string foo = "abc") => foo; - - public string? GetScopedStateWithDefault( - [ScopedState] - string? foo = default) => foo; - - public string GetScopedStateNullable( - [ScopedState] - string? foo) => foo!; - - public string SetScopedStateGeneric( - [ScopedState] - SetState foo) - { - foo("abc"); - return "foo"; - } - - public string SetScopedState( - [ScopedState] - SetState foo) - { - foo("abc"); - return "foo"; - } - - public string GetLocalStateWithKey( - [LocalState("foo")] - string s) => s; - - public string GetLocalState( - [LocalState] - string foo) => foo; - - public string GetLocalStateWithDefaultAbc( - [LocalState] - string foo = "abc") => foo; - - public string? GetLocalStateWithDefault( - [LocalState] - string? foo = default) => foo; - - public string SetLocalStateGeneric( - [LocalState] - SetState foo) - { - foo("abc"); - return "foo"; - } - - public string SetLocalState( - [LocalState] - SetState foo) - { - foo("abc"); - return "foo"; - } + public string SetScopedState( + [ScopedState] + SetState foo) + { + foo("abc"); + return "foo"; } - public class Entity { } + public string GetLocalStateWithKey( + [LocalState("foo")] + string s) => s; + + public string GetLocalState( + [LocalState] + string foo) => foo; + + public string GetLocalStateWithDefaultAbc( + [LocalState] + string foo = "abc") => foo; - public class MyService { } + public string? GetLocalStateWithDefault( + [LocalState] + string? foo = default) => foo; + + public string SetLocalStateGeneric( + [LocalState] + SetState foo) + { + foo("abc"); + return "foo"; + } + + public string SetLocalState( + [LocalState] + SetState foo) + { + foo("abc"); + return "foo"; + } } + + public class Entity { } + + public class MyService { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverDescriptorTests.cs index 4549f292f2b..bdda2efbdbd 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverDescriptorTests.cs @@ -2,52 +2,51 @@ using HotChocolate.Resolvers.Expressions; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class ResolverDescriptorTests { - public class ResolverDescriptorTests + [Fact] + public void Create_With_ResolverType_Object() { - [Fact] - public void Create_With_ResolverType_Object() - { - var descriptor = new ResolverDescriptor( - typeof(string), - new FieldMember("a", "b", typeof(object).GetMembers().First()), - resolverType: typeof(object)); + var descriptor = new ResolverDescriptor( + typeof(string), + new FieldMember("a", "b", typeof(object).GetMembers().First()), + resolverType: typeof(object)); - Assert.Equal(typeof(string), descriptor.SourceType); - Assert.Null(descriptor.ResolverType); - Assert.NotNull(descriptor.Field.Member); - Assert.Equal("a", descriptor.Field.TypeName.Value); - Assert.Equal("b", descriptor.Field.FieldName.Value); - } + Assert.Equal(typeof(string), descriptor.SourceType); + Assert.Null(descriptor.ResolverType); + Assert.NotNull(descriptor.Field.Member); + Assert.Equal("a", descriptor.Field.TypeName.Value); + Assert.Equal("b", descriptor.Field.FieldName.Value); + } - [Fact] - public void Create_With_ResolverType_Null() - { - var descriptor = new ResolverDescriptor( - typeof(string), - new FieldMember("a", "b", typeof(object).GetMembers().First())); + [Fact] + public void Create_With_ResolverType_Null() + { + var descriptor = new ResolverDescriptor( + typeof(string), + new FieldMember("a", "b", typeof(object).GetMembers().First())); - Assert.Equal(typeof(string), descriptor.SourceType); - Assert.Null(descriptor.ResolverType); - Assert.NotNull(descriptor.Field.Member); - Assert.Equal("a", descriptor.Field.TypeName.Value); - Assert.Equal("b", descriptor.Field.FieldName.Value); - } + Assert.Equal(typeof(string), descriptor.SourceType); + Assert.Null(descriptor.ResolverType); + Assert.NotNull(descriptor.Field.Member); + Assert.Equal("a", descriptor.Field.TypeName.Value); + Assert.Equal("b", descriptor.Field.FieldName.Value); + } - [Fact] - public void Create_With_ResolverType_Int() - { - var descriptor = new ResolverDescriptor( - typeof(string), - new FieldMember("a", "b", typeof(object).GetMembers().First()), - resolverType: typeof(int)); + [Fact] + public void Create_With_ResolverType_Int() + { + var descriptor = new ResolverDescriptor( + typeof(string), + new FieldMember("a", "b", typeof(object).GetMembers().First()), + resolverType: typeof(int)); - Assert.Equal(typeof(string), descriptor.SourceType); - Assert.Equal(typeof(int), descriptor.ResolverType); - Assert.NotNull(descriptor.Field.Member); - Assert.Equal("a", descriptor.Field.TypeName.Value); - Assert.Equal("b", descriptor.Field.FieldName.Value); - } + Assert.Equal(typeof(string), descriptor.SourceType); + Assert.Equal(typeof(int), descriptor.ResolverType); + Assert.NotNull(descriptor.Field.Member); + Assert.Equal("a", descriptor.Field.TypeName.Value); + Assert.Equal("b", descriptor.Field.FieldName.Value); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverServiceTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverServiceTests.cs index eca5ae4d843..3dc3590ae7b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverServiceTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverServiceTests.cs @@ -47,7 +47,7 @@ public async Task AddSynchronizedService() { Snapshot.FullName(); - IRequestExecutor executor = + var executor = await new ServiceCollection() .AddSingleton() .AddGraphQL() @@ -64,7 +64,7 @@ public async Task AddResolverService() { Snapshot.FullName(); - IRequestExecutor executor = + var executor = await new ServiceCollection() .AddSingleton() .AddGraphQL() diff --git a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverTaskNullTests.cs b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverTaskNullTests.cs index 52dffe0a8a6..d285cdf6825 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverTaskNullTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Resolvers/ResolverTaskNullTests.cs @@ -5,87 +5,86 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Resolvers +namespace HotChocolate.Resolvers; + +public class ResolverTaskNullTests { - public class ResolverTaskNullTests + [InlineData("case1", "abc")] + [InlineData("case1", null)] + [InlineData("case2", "abc")] + [InlineData("case2", null)] + [InlineData("case3", "abc")] + [InlineData("case3", null)] + [InlineData("case4", "abc")] + [InlineData("case4", null)] + [Theory] + public async Task HandleNullResolverTask(string field, string argument) { - [InlineData("case1", "abc")] - [InlineData("case1", null)] - [InlineData("case2", "abc")] - [InlineData("case2", null)] - [InlineData("case3", "abc")] - [InlineData("case3", null)] - [InlineData("case4", "abc")] - [InlineData("case4", null)] - [Theory] - public async Task HandleNullResolverTask(string field, string argument) - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddType() - .Create() - .MakeExecutable(); + // arrange + var executor = SchemaBuilder.New() + .AddType() + .Create() + .MakeExecutable(); - // act - var arg = argument is null ? "null" : $"\"{argument}\""; - IExecutionResult result = await executor.ExecuteAsync( - $"{{ {field}(name: {arg}) }}"); + // act + var arg = argument is null ? "null" : $"\"{argument}\""; + var result = await executor.ExecuteAsync( + $"{{ {field}(name: {arg}) }}"); - // assert - result.ToJson().MatchSnapshot(SnapshotNameExtension.Create( - field, argument ?? "null")); - } + // assert + result.ToJson().MatchSnapshot(SnapshotNameExtension.Create( + field, argument ?? "null")); + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Case2(default)); - descriptor.Field("case3") - .Argument("name", a => a.Type()) - .Type() - .Resolve(ctx => - { - var name = ctx.ArgumentValue("name"); - return name is null - ? new ValueTask(default(object)) - : new ValueTask(name); - }); + descriptor.Field(t => t.Case2(default)); + descriptor.Field("case3") + .Argument("name", a => a.Type()) + .Type() + .Resolve(ctx => + { + var name = ctx.ArgumentValue("name"); + return name is null + ? new ValueTask(default(object)) + : new ValueTask(name); + }); - descriptor.Field("case4") - .Argument("name", a => a.Type()) - .Type() - .Resolve(ctx => - { - var name = ctx.ArgumentValue("name"); - return name is null ? null : Task.FromResult(name); - }); - } + descriptor.Field("case4") + .Argument("name", a => a.Type()) + .Type() + .Resolve(ctx => + { + var name = ctx.ArgumentValue("name"); + return name is null ? null : Task.FromResult(name); + }); } + } - public class Query + public class Query + { + public Task Case1(string name) { - public Task Case1(string name) + if (name is null) { - if (name is null) - { - return null; - } - return Task.FromResult(name); + return null; } + return Task.FromResult(name); } + } - public class QueryResolver + public class QueryResolver + { + public Task Case2(string name) { - public Task Case2(string name) + if (name is null) { - if (name is null) - { - return null; - } - return Task.FromResult(name); + return null; } + return Task.FromResult(name); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/SchemaBuilderTests.cs b/src/HotChocolate/Core/test/Types.Tests/SchemaBuilderTests.cs index 71c568e00e5..90dfc59697b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/SchemaBuilderTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/SchemaBuilderTests.cs @@ -14,2310 +14,2309 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaBuilderTests { - public class SchemaBuilderTests + [Fact] + public void Create_SingleType() { - [Fact] - public void Create_SingleType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddRootType(typeof(FooType), OperationType.Query) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddRootType(typeof(FooType), OperationType.Query) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddRootType_ValueTypeAsQueryType_ArgumentNullException() - { - // arrange - // act - void Action() - => SchemaBuilder.New().AddRootType(((Type)null)!, OperationType.Query); + [Fact] + public void AddRootType_ValueTypeAsQueryType_ArgumentNullException() + { + // arrange + // act + void Action() + => SchemaBuilder.New().AddRootType(((Type)null)!, OperationType.Query); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void AddRootType_ValueTypeAsQueryType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddRootType(typeof(int), OperationType.Query); + [Fact] + public void AddRootType_ValueTypeAsQueryType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddRootType(typeof(int), OperationType.Query); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddRootType_TypeIsNonGenericBaseType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddRootType(typeof(ObjectType), OperationType.Query); + [Fact] + public void AddRootType_TypeIsNonGenericBaseType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddRootType(typeof(ObjectType), OperationType.Query); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddRootType_TypeIsNotObjectType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddRootType(typeof(MyEnumType), OperationType.Query); + [Fact] + public void AddRootType_TypeIsNotObjectType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddRootType(typeof(MyEnumType), OperationType.Query); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddRootType_DuplicateQueryType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddRootType(typeof(FooType), OperationType.Query) - .AddRootType(typeof(FooType), OperationType.Query); - - // assert - Assert.Throws(action); - } + [Fact] + public void AddRootType_DuplicateQueryType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddRootType(typeof(FooType), OperationType.Query) + .AddRootType(typeof(FooType), OperationType.Query); + + // assert + Assert.Throws(action); + } - [Fact] - public void AddRootType_TypeIsObjectType_SchemaIsCreated() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddRootType(typeof(FooType), OperationType.Query) - .Create(); - - // assert - ObjectType queryType = schema.GetType("Foo"); - Assert.NotNull(queryType); - Assert.Equal(queryType, schema.QueryType); - } + [Fact] + public void AddRootType_TypeIsObjectType_SchemaIsCreated() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddRootType(typeof(FooType), OperationType.Query) + .Create(); + + // assert + var queryType = schema.GetType("Foo"); + Assert.NotNull(queryType); + Assert.Equal(queryType, schema.QueryType); + } - [Fact] - public void AddRootType_MutationType_SchemaIsCreated() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddRootType(typeof(FooType), OperationType.Query) - .AddRootType(typeof(BarType), OperationType.Mutation) - .Create(); - - // assert - ObjectType queryType = schema.GetType("Bar"); - Assert.NotNull(queryType); - Assert.Equal(queryType, schema.MutationType); - } + [Fact] + public void AddRootType_MutationType_SchemaIsCreated() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddRootType(typeof(FooType), OperationType.Query) + .AddRootType(typeof(BarType), OperationType.Mutation) + .Create(); + + // assert + var queryType = schema.GetType("Bar"); + Assert.NotNull(queryType); + Assert.Equal(queryType, schema.MutationType); + } - [Fact] - public void AddRootType_SubscriptionType_SchemaIsCreated() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddRootType(typeof(FooType), OperationType.Query) - .AddRootType(typeof(BarType), OperationType.Subscription) - .Create(); - - // assert - ObjectType queryType = schema.GetType("Bar"); - Assert.NotNull(queryType); - Assert.Equal(queryType, schema.SubscriptionType); - } + [Fact] + public void AddRootType_SubscriptionType_SchemaIsCreated() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddRootType(typeof(FooType), OperationType.Query) + .AddRootType(typeof(BarType), OperationType.Subscription) + .Create(); + + // assert + var queryType = schema.GetType("Bar"); + Assert.NotNull(queryType); + Assert.Equal(queryType, schema.SubscriptionType); + } - [Fact] - public void AddRootType_ObjectTypeIsNull_ArgumentNullException() - { - // arrange - // act - void Action() - => SchemaBuilder.New().AddRootType(((ObjectType)null)!, OperationType.Query); + [Fact] + public void AddRootType_ObjectTypeIsNull_ArgumentNullException() + { + // arrange + // act + void Action() + => SchemaBuilder.New().AddRootType(((ObjectType)null)!, OperationType.Query); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void AddRootType_ObjTypeQueryType_SchemaIsCreated() - { - // arrange - var fooType = new FooType(); + [Fact] + public void AddRootType_ObjTypeQueryType_SchemaIsCreated() + { + // arrange + var fooType = new FooType(); + + // act + var schema = SchemaBuilder.New() + .AddRootType(fooType, OperationType.Query) + .Create(); + + // assert + var queryType = schema.GetType("Foo"); + Assert.NotNull(queryType); + Assert.Equal(queryType, schema.QueryType); + Assert.Equal(fooType, schema.QueryType); + } - // act - ISchema schema = SchemaBuilder.New() - .AddRootType(fooType, OperationType.Query) - .Create(); + [Fact] + public void AddRootType_ObjTypeMutationType_SchemaIsCreated() + { + // arrange + var fooType = new FooType(); + var barType = new BarType(); + + // act + var schema = SchemaBuilder.New() + .AddRootType(fooType, OperationType.Query) + .AddRootType(barType, OperationType.Mutation) + .Create(); + + // assert + var mutationType = schema.GetType("Bar"); + Assert.NotNull(mutationType); + Assert.Equal(mutationType, schema.MutationType); + Assert.Equal(barType, schema.MutationType); + } - // assert - ObjectType queryType = schema.GetType("Foo"); - Assert.NotNull(queryType); - Assert.Equal(queryType, schema.QueryType); - Assert.Equal(fooType, schema.QueryType); - } + [Fact] + public void AddRootType_ObjTypeSubscriptionType_SchemaIsCreated() + { + // arrange + var fooType = new FooType(); + var barType = new BarType(); + + // act + var schema = SchemaBuilder.New() + .AddRootType(fooType, OperationType.Query) + .AddRootType(barType, OperationType.Subscription) + .Create(); + + // assert + var subscriptionType = schema.GetType("Bar"); + Assert.NotNull(subscriptionType); + Assert.Equal(subscriptionType, schema.SubscriptionType); + Assert.Equal(barType, schema.SubscriptionType); + } - [Fact] - public void AddRootType_ObjTypeMutationType_SchemaIsCreated() - { - // arrange - var fooType = new FooType(); - var barType = new BarType(); + [Fact] + public void AddRootType_ObjTypeDuplicateQueryType_ArgumentException() + { + // arrange + var fooType = new FooType(); - // act - ISchema schema = SchemaBuilder.New() + // act + void Action() + => SchemaBuilder.New() .AddRootType(fooType, OperationType.Query) - .AddRootType(barType, OperationType.Mutation) - .Create(); - - // assert - ObjectType mutationType = schema.GetType("Bar"); - Assert.NotNull(mutationType); - Assert.Equal(mutationType, schema.MutationType); - Assert.Equal(barType, schema.MutationType); - } + .AddRootType(fooType, OperationType.Query); - [Fact] - public void AddRootType_ObjTypeSubscriptionType_SchemaIsCreated() - { - // arrange - var fooType = new FooType(); - var barType = new BarType(); + // assert + Assert.Throws(Action); + } - // act - ISchema schema = SchemaBuilder.New() - .AddRootType(fooType, OperationType.Query) - .AddRootType(barType, OperationType.Subscription) - .Create(); - - // assert - ObjectType subscriptionType = schema.GetType("Bar"); - Assert.NotNull(subscriptionType); - Assert.Equal(subscriptionType, schema.SubscriptionType); - Assert.Equal(barType, schema.SubscriptionType); - } + [Fact] + public void AddQueryType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(FooType)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddRootType_ObjTypeDuplicateQueryType_ArgumentException() - { - // arrange - var fooType = new FooType(); + [Fact] + public void AddQueryType_Generic() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // act - void Action() - => SchemaBuilder.New() - .AddRootType(fooType, OperationType.Query) - .AddRootType(fooType, OperationType.Query); + [Fact] + public void AddQueryType_GenericClr() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void InferQueryType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddQueryType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(FooType)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddMutationType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(QueryType)) + .AddMutationType(typeof(FooType)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddQueryType_Generic() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddMutationType_Generic() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(QueryType)) + .AddMutationType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddQueryType_GenericClr() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddMutationType_GenericClr() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(QueryType)) + .AddMutationType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void InferQueryType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void InferMutationType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddType() + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(QueryType)) - .AddMutationType(typeof(FooType)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddSubscriptionType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(QueryType)) + .AddSubscriptionType(typeof(FooType)) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationType_Generic() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(QueryType)) - .AddMutationType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddSubscriptionType_Generic() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(QueryType)) + .AddSubscriptionType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddMutationType_GenericClr() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(QueryType)) - .AddMutationType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddSubscriptionType_GenericClr() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(typeof(QueryType)) + .AddSubscriptionType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void InferMutationType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .AddType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void InferSubscriptionType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddType() + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AddSubscriptionType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(QueryType)) - .AddSubscriptionType(typeof(FooType)) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Use_MiddlewareNull_ArgumentNullException() + { + // arrange + // act + void Action() + => SchemaBuilder.New().Use(((FieldMiddleware)null)!); - [Fact] - public void AddSubscriptionType_Generic() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(QueryType)) - .AddSubscriptionType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void AddSubscriptionType_GenericClr() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(typeof(QueryType)) - .AddSubscriptionType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Use_MiddlewareDelegate() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddDocument(_ => Utf8GraphQLParser.Parse("type Query { a: String }")) + .Use(_ => context => + { + context.Result = "foo"; + return default; + }) + .Create(); - [Fact] - public void InferSubscriptionType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .AddType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - [Fact] - public void Use_MiddlewareNull_ArgumentNullException() - { - // arrange - // act - void Action() - => SchemaBuilder.New().Use(((FieldMiddleware)null)!); + // assert + schema.MakeExecutable().Execute("{ a }").MatchSnapshot(); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void AddDocument_DocumentIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddDocument((LoadSchemaDocument)null); - [Fact] - public void Use_MiddlewareDelegate() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddDocument(_ => Utf8GraphQLParser.Parse("type Query { a: String }")) - .Use(_ => context => - { - context.Result = "foo"; - return default; - }) - .Create(); + // assert + Assert.Throws(action); + } + [Fact] + public void AddDocument_MultipleDocuments_Are_Merged() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddDocument(_ => + Utf8GraphQLParser.Parse("type Query { a: Foo }")) + .AddDocument(_ => + Utf8GraphQLParser.Parse("type Foo { a: String }")) + .Use(_ => context => + { + context.Result = "foo"; + return default; + }) + .Create(); - // assert - schema.MakeExecutable().Execute("{ a }").MatchSnapshot(); - } - [Fact] - public void AddDocument_DocumentIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddDocument((LoadSchemaDocument)null); + // assert + schema.MakeExecutable().Execute("{ a { a } }").MatchSnapshot(); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddType_TypeIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddType((Type)null); - [Fact] - public void AddDocument_MultipleDocuments_Are_Merged() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddDocument(_ => - Utf8GraphQLParser.Parse("type Query { a: Foo }")) - .AddDocument(_ => - Utf8GraphQLParser.Parse("type Foo { a: String }")) - .Use(_ => context => - { - context.Result = "foo"; - return default; - }) - .Create(); + // assert + Assert.Throws(action); + } + [Fact] + public void AddType_NamedTypeIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddType((INamedType)null); - // assert - schema.MakeExecutable().Execute("{ a { a } }").MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddType_TypeIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddType((Type)null); + [Fact] + public void AddType_QueryIsAdded_SchemaIsCreated() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + // act + var schema = SchemaBuilder.New() + .AddType(queryType) + .Create(); + + // assert + var type = schema.GetType("Query"); + Assert.Equal(queryType, type); + Assert.Equal(queryType, schema.QueryType); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddType_NamedTypeExtensionIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddType((INamedTypeExtension)null); - [Fact] - public void AddType_NamedTypeIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddType((INamedType)null); + // assert + Assert.Throws(action); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddType_QueryAndExtensionAreAdded_SchemaIsCreated() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + var queryTypeExtension = new ObjectTypeExtension(t => t + .Name("Query") + .Field("bar") + .Resolve("foo")); + + // act + var schema = SchemaBuilder.New() + .AddType(queryType) + .AddType(queryTypeExtension) + .Create(); + + // assert + var type = schema.GetType("Query"); + Assert.True(type.Fields.ContainsField("bar")); + } - [Fact] - public void AddType_QueryIsAdded_SchemaIsCreated() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); + [Fact] + public void AddDirectiveType_DirectiveTypeIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddDirectiveType((DirectiveType)null); - // act - ISchema schema = SchemaBuilder.New() - .AddType(queryType) - .Create(); + // assert + Assert.Throws(action); + } - // assert - ObjectType type = schema.GetType("Query"); - Assert.Equal(queryType, type); - Assert.Equal(queryType, schema.QueryType); - } + [Fact] + public void AddDirectiveType_DirectiveTypeIsAdded_SchemaIsCreated() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + var directiveType = new DirectiveType(t => t + .Name("foo") + .Location(Types.DirectiveLocation.Field)); + + // act + var schema = SchemaBuilder.New() + .AddType(queryType) + .AddDirectiveType(directiveType) + .Create(); + + // assert + var type = schema.GetDirectiveType("foo"); + Assert.Equal(directiveType, type); + } - [Fact] - public void AddType_NamedTypeExtensionIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddType((INamedTypeExtension)null); + [Fact] + public void SetSchema_TypeIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .SetSchema((Type)null); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddType_QueryAndExtensionAreAdded_SchemaIsCreated() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); + [Fact] + public void SetSchema_TypeIsNotSchema_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .SetSchema(typeof(SchemaBuilderTests)); - var queryTypeExtension = new ObjectTypeExtension(t => t - .Name("Query") - .Field("bar") - .Resolve("foo")); - - // act - ISchema schema = SchemaBuilder.New() - .AddType(queryType) - .AddType(queryTypeExtension) - .Create(); - - // assert - ObjectType type = schema.GetType("Query"); - Assert.True(type.Fields.ContainsField("bar")); - } + // assert + Assert.Throws(action); + } - [Fact] - public void AddDirectiveType_DirectiveTypeIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddDirectiveType((DirectiveType)null); + [Fact] + public void SetSchema_TypeSchema_SchemaIsCreatedFromType() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + // act + var schema = SchemaBuilder.New() + .SetSchema(typeof(MySchema)) + .AddType(queryType) + .Create(); + + // assert + Assert.Equal("Description", + Assert.IsType(schema).Description); + } - // assert - Assert.Throws(action); - } + [Fact] + public void SetSchema_SetName() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + var schemaDef = new Schema(t => t + .Name("FooBar")); + + // act + var schema = SchemaBuilder.New() + .SetSchema(schemaDef) + .AddQueryType(queryType) + .Create(); + + // assert + Assert.Equal(schemaDef, schema); + Assert.Equal("FooBar", schema.Name); + } - [Fact] - public void AddDirectiveType_DirectiveTypeIsAdded_SchemaIsCreated() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); + [Fact] + public void SetSchema_SetDescription() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Resolve("bar")); + + var schemaDef = new Schema(t => t + .Description("TestMe")); + + // act + var schema = SchemaBuilder.New() + .SetSchema(schemaDef) + .AddQueryType(queryType) + .Create(); + + // assert + Assert.Equal(schemaDef, schema); + Assert.Equal("TestMe", schema.Description); + } - var directiveType = new DirectiveType(t => t - .Name("foo") - .Location(Types.DirectiveLocation.Field)); + [Fact] + public void SetSchema_NameDoesNotCollideWithTypeName() + { + // arrange + var queryType = new ObjectType(t => t + .Name("TestMe") + .Field("foo") + .Resolve("bar")); + + var schemaDef = new Schema(t => t + .Name("TestMe")); + + // act + var schema = SchemaBuilder.New() + .SetSchema(schemaDef) + .AddQueryType(queryType) + .Create(); + + // assert + Assert.Equal(schemaDef, schema); + Assert.Equal("TestMe", schema.Name); + Assert.NotNull(schema.GetType("TestMe")); + } - // act - ISchema schema = SchemaBuilder.New() - .AddType(queryType) - .AddDirectiveType(directiveType) - .Create(); + [Fact] + public void SetSchema_SchemaIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .SetSchema((ISchema)null); - // assert - DirectiveType type = schema.GetDirectiveType("foo"); - Assert.Equal(directiveType, type); - } + // assert + Assert.Throws(action); + } - [Fact] - public void SetSchema_TypeIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .SetSchema((Type)null); + [Fact] + public void SetSchema_SchemaIsNotTypeSystemObject_ArgumentException() + { + // arrange + var schemaMock = new Mock(); - // assert - Assert.Throws(action); - } + // act + Action action = () => SchemaBuilder.New() + .SetSchema(schemaMock.Object); - [Fact] - public void SetSchema_TypeIsNotSchema_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .SetSchema(typeof(SchemaBuilderTests)); + // assert + Assert.Throws(action); + } - // assert - Assert.Throws(action); - } + [Fact] + public void SetSchema_ConfigureIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .SetSchema((Action)null); - [Fact] - public void SetSchema_TypeSchema_SchemaIsCreatedFromType() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); + // assert + Assert.Throws(action); + } - // act - ISchema schema = SchemaBuilder.New() - .SetSchema(typeof(MySchema)) - .AddType(queryType) - .Create(); + [Fact] + public void SetSchema_ConfigureInline_DescriptionIsSet() + { + // arrange + var queryType = new ObjectType(t => t + .Name("TestMe") + .Field("foo") + .Resolve("bar")); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(queryType) + .SetSchema(c => c.Description("Some Description.")) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - Assert.Equal("Description", - Assert.IsType(schema).Description); - } + [Fact] + public void ModifyOptions_Configure_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .ModifyOptions(null); - [Fact] - public void SetSchema_SetName() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); + // assert + Assert.Throws(action); + } - var schemaDef = new Schema(t => t - .Name("FooBar")); + [Fact] + public void ModifyOptions_SetQueryTypeName_SpecifTypeBecomesQueryType() + { + // arrange + var queryType = new ObjectType(t => t + .Name("TestMe") + .Field("foo") + .Resolve("bar")); + + // act + var schema = SchemaBuilder.New() + .ModifyOptions(o => o.QueryTypeName = "TestMe") + .AddType(queryType) + .Create(); + + // assert + Assert.Equal("TestMe", schema.QueryType.Name); + } - // act - ISchema schema = SchemaBuilder.New() - .SetSchema(schemaDef) - .AddQueryType(queryType) - .Create(); + [Fact] + public void AddResolver_ResolverIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddRootResolver((FieldResolver)null); - // assert - Assert.Equal(schemaDef, schema); - Assert.Equal("FooBar", schema.Name); - } + // assert + Assert.Throws(action); + } - [Fact] - public void SetSchema_SetDescription() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Resolve("bar")); + [Fact] + public async Task AddResolver_Resolver_ResolverIsSet() + { + // arrange + var queryType = new ObjectType(t => t + .Name("TestMe") + .Field("foo") + .Type()); + + ValueTask ResolverDelegate(IResolverContext c) => new("test"); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(queryType) + .AddResolver("TestMe", "foo", ResolverDelegate) + .Create(); + + // assert + var type = schema.GetType("TestMe"); + Assert.NotNull(type); + + var context = new Mock(); + Assert.Equal("test", await type.Fields["foo"].Resolver!(context.Object)); + } - var schemaDef = new Schema(t => t - .Description("TestMe")); + [Fact] + public void BindClrType_IntToString_IntFieldIsStringField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .BindClrType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // act - ISchema schema = SchemaBuilder.New() - .SetSchema(schemaDef) - .AddQueryType(queryType) - .Create(); + [Fact] + public void BindClrType_BuilderIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => SchemaBuilderExtensions.BindClrType(null); - // assert - Assert.Equal(schemaDef, schema); - Assert.Equal("TestMe", schema.Description); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void SetSchema_NameDoesNotCollideWithTypeName() - { - // arrange - var queryType = new ObjectType(t => t - .Name("TestMe") - .Field("foo") - .Resolve("bar")); + [Fact] + public void BindClrType_ClrTypeIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => SchemaBuilder.New().BindRuntimeType(null, typeof(StringType)); - var schemaDef = new Schema(t => t - .Name("TestMe")); + // assert + Assert.Throws(Action); + } - // act - ISchema schema = SchemaBuilder.New() - .SetSchema(schemaDef) - .AddQueryType(queryType) - .Create(); + [Fact] + public void BindClrType_SchemaTypeIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => SchemaBuilder.New().BindRuntimeType(typeof(string), null); - // assert - Assert.Equal(schemaDef, schema); - Assert.Equal("TestMe", schema.Name); - Assert.NotNull(schema.GetType("TestMe")); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void SetSchema_SchemaIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .SetSchema((ISchema)null); + [Fact] + public void BindClrType_SchemaTypeIsNotTso_ArgumentNullException() + { + // arrange + // act + void Action() => SchemaBuilder.New().BindRuntimeType(typeof(string), typeof(string)); - // assert - Assert.Throws(action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void SetSchema_SchemaIsNotTypeSystemObject_ArgumentException() - { - // arrange - var schemaMock = new Mock(); + [Fact] + public void Dynamic_Types_Are_Integrated() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Type(new DynamicFooType("MyFoo")) + .Resolve(new object())); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(queryType) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // act - Action action = () => SchemaBuilder.New() - .SetSchema(schemaMock.Object); + [Fact] + public void DuplicateName() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Type(new DynamicFooType("MyFoo")) + .Resolve(new object())); + + // act + Action action = () => SchemaBuilder.New() + .AddQueryType(queryType) + .AddType(new DynamicFooType("MyFoo")) + .AddType(new DynamicFooType("MyBar")) + .Create(); + + // assert + Assert.Throws(action).Message.MatchSnapshot(); + } - // assert - Assert.Throws(action); - } + [Fact] + public void UseFirstRegisteredDynamicType() + { + // arrange + var queryType = new ObjectType(t => t + .Name("Query") + .Field("foo") + .Type() + .Resolve(new object())); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(queryType) + .AddType(new DynamicFooType("MyFoo")) + .AddType(new DynamicFooType("MyBar")) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void SetSchema_ConfigureIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .SetSchema((Action)null); + [Fact] + public void Could_Not_Resolve_Type() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddDocumentFromString("type Query { foo : Bar } scalar Bar") + .AddResolver("Query", "foo", "bar") + .Create(); + + // assert + Assert.Throws(action).Message.MatchSnapshot(); + } - // assert - Assert.Throws(action); - } + [Fact] + public void Interface_Without_Implementation() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddDocumentFromString(@" + type Query { + foo : Bar + } + interface Bar { + baz: String + }") + .AddResolver("Query", "foo", "bar") + .Create(); - [Fact] - public void SetSchema_ConfigureInline_DescriptionIsSet() - { - // arrange - var queryType = new ObjectType(t => t - .Name("TestMe") - .Field("foo") - .Resolve("bar")); + // assert + Assert.Throws(action).Message.MatchSnapshot(); + } - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(queryType) - .SetSchema(c => c.Description("Some Description.")) - .Create(); + [Fact] + public void Interface_Without_Implementation_But_Not_Used() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(@" + type Query { + foo : Baz + } - // assert - schema.ToString().MatchSnapshot(); - } + type Baz { + baz: String + } - [Fact] - public void ModifyOptions_Configure_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .ModifyOptions(null); + interface Bar { + baz: String + }") + .AddResolver("Query", "foo", "bar") + .AddResolver("Baz", "baz", "baz") + .Create(); - // assert - Assert.Throws(action); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void ModifyOptions_SetQueryTypeName_SpecifTypeBecomesQueryType() - { - // arrange - var queryType = new ObjectType(t => t - .Name("TestMe") - .Field("foo") - .Resolve("bar")); + [Fact] + public void Interface_Without_Implementation_Not_Strict() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(@" + type Query { + foo : Bar + } + interface Bar { + baz: String + }") + .AddResolver("Query", "foo", "bar") + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // act - ISchema schema = SchemaBuilder.New() - .ModifyOptions(o => o.QueryTypeName = "TestMe") - .AddType(queryType) - .Create(); + // assert + Assert.NotNull(schema); + } - // assert - Assert.Equal("TestMe", schema.QueryType.Name); - } + [Fact] + public async Task Execute_Against_Interface_Without_Impl_Field() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(@" + type Query { + foo : Bar + } + interface Bar { + baz: String + }") + .AddResolver("Query", "foo", "bar") + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public void AddResolver_ResolverIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddRootResolver((FieldResolver)null); + var executor = schema.MakeExecutable(); - // assert - Assert.Throws(action); - } + // act + var result = + await executor.ExecuteAsync("{ foo { baz } }"); - [Fact] - public async Task AddResolver_Resolver_ResolverIsSet() - { - // arrange - var queryType = new ObjectType(t => t - .Name("TestMe") - .Field("foo") - .Type()); + // assert + result.ToJson().MatchSnapshot(); + } - ValueTask ResolverDelegate(IResolverContext c) => new("test"); + [Fact] + public void Abstract_Classes_Are_Allowed_As_Object_Types() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(queryType) - .AddResolver("TestMe", "foo", ResolverDelegate) - .Create(); + [Fact] + public void AddInterceptor_TypeIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .TryAddTypeInterceptor((Type)null); - // assert - ObjectType type = schema.GetType("TestMe"); - Assert.NotNull(type); + // assert + Assert.Throws(action); + } - var context = new Mock(); - Assert.Equal("test", await type.Fields["foo"].Resolver!(context.Object)); - } + [Fact] + public void AddInterceptor_InterceptorIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .TryAddTypeInterceptor((ITypeInitializationInterceptor)null); - [Fact] - public void BindClrType_IntToString_IntFieldIsStringField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .BindClrType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void BindClrType_BuilderIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => SchemaBuilderExtensions.BindClrType(null); + [Fact] + public void AddInterceptor_TypeIsNotAnInterceptorType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .TryAddTypeInterceptor(typeof(string)); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(action); + } - [Fact] - public void BindClrType_ClrTypeIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => SchemaBuilder.New().BindRuntimeType(null, typeof(StringType)); + [Fact] + public void AddInterceptor_TypeIsInterceptor_TypesAreTouched() + { + // arrange + // act + var schema = SchemaBuilder.New() + .TryAddTypeInterceptor(typeof(MyInterceptor)) + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); - // assert - Assert.Throws(Action); - } + // assert + Assert.Collection(schema.GetType("Query").ContextData, + item => Assert.Equal("touched", item.Key)); - [Fact] - public void BindClrType_SchemaTypeIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => SchemaBuilder.New().BindRuntimeType(typeof(string), null); + Assert.Collection(schema.GetType("String").ContextData, + item => Assert.Equal("touched", item.Key)); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void AddInterceptor_Generic_TypesAreTouched() + { + // arrange + // act + var schema = SchemaBuilder.New() + .TryAddTypeInterceptor() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); - [Fact] - public void BindClrType_SchemaTypeIsNotTso_ArgumentNullException() - { - // arrange - // act - void Action() => SchemaBuilder.New().BindRuntimeType(typeof(string), typeof(string)); + // assert + Assert.Collection(schema.GetType("Query").ContextData, + item => Assert.Equal("touched", item.Key)); - // assert - Assert.Throws(Action); - } + Assert.Collection(schema.GetType("String").ContextData, + item => Assert.Equal("touched", item.Key)); + } - [Fact] - public void Dynamic_Types_Are_Integrated() - { - // arrange - var queryType = new ObjectType(t => t + [Fact] + public void AddInterceptor_AsService_TypesAreTouched() + { + // arrange + var services = new ServiceCollection(); + services.AddSingleton(); + + // act + var schema = SchemaBuilder.New() + .AddServices(services.BuildServiceProvider()) + .AddQueryType(d => d .Name("Query") .Field("foo") - .Type(new DynamicFooType("MyFoo")) - .Resolve(new object())); + .Resolve("bar")) + .Create(); - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(queryType) - .Create(); + // assert + Assert.Collection(schema.GetType("Query").ContextData, + item => Assert.Equal("touched", item.Key)); - // assert - schema.ToString().MatchSnapshot(); - } + Assert.Collection(schema.GetType("String").ContextData, + item => Assert.Equal("touched", item.Key)); + } - [Fact] - public void DuplicateName() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Type(new DynamicFooType("MyFoo")) - .Resolve(new object())); - - // act - Action action = () => SchemaBuilder.New() - .AddQueryType(queryType) - .AddType(new DynamicFooType("MyFoo")) - .AddType(new DynamicFooType("MyBar")) - .Create(); - - // assert - Assert.Throws(action).Message.MatchSnapshot(); - } - [Fact] - public void UseFirstRegisteredDynamicType() - { - // arrange - var queryType = new ObjectType(t => t - .Name("Query") - .Field("foo") - .Type() - .Resolve(new object())); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(queryType) - .AddType(new DynamicFooType("MyFoo")) - .AddType(new DynamicFooType("MyBar")) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddConvention_TypeIsNullConcreteIsSet_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(null, new TestConvention()); - [Fact] - public void Could_Not_Resolve_Type() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddDocumentFromString("type Query { foo : Bar } scalar Bar") - .AddResolver("Query", "foo", "bar") - .Create(); - - // assert - Assert.Throws(action).Message.MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void Interface_Without_Implementation() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddDocumentFromString(@" - type Query { - foo : Bar - } - interface Bar { - baz: String - }") - .AddResolver("Query", "foo", "bar") - .Create(); + [Fact] + public void AddConvention_ConventionIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(typeof(IConvention), default(TestConvention)); - // assert - Assert.Throws(action).Message.MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void Interface_Without_Implementation_But_Not_Used() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(@" - type Query { - foo : Baz - } + [Fact] + public void AddConvention_ConventionTypeIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(null, typeof(IConvention)); - type Baz { - baz: String - } + // assert + Assert.Throws(action); + } - interface Bar { - baz: String - }") - .AddResolver("Query", "foo", "bar") - .AddResolver("Baz", "baz", "baz") - .Create(); + [Fact] + public void AddConvention_ConcreteConventionTypeIsNull_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(typeof(IConvention), default(Type)); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void Interface_Without_Implementation_Not_Strict() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(@" - type Query { - foo : Bar - } - interface Bar { - baz: String - }") - .AddResolver("Query", "foo", "bar") - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - // assert - Assert.NotNull(schema); - } - [Fact] - public async Task Execute_Against_Interface_Without_Impl_Field() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(@" - type Query { - foo : Bar - } - interface Bar { - baz: String - }") - .AddResolver("Query", "foo", "bar") - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void AddConvention_ConventionHasInvalidTypeConcrete_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(typeof(IInvalidTestConvention), new TestConvention()); - IRequestExecutor executor = schema.MakeExecutable(); + // assert + Assert.Throws(action); + } - // act - IExecutionResult result = - await executor.ExecuteAsync("{ foo { baz } }"); + [Fact] + public void AddConvention_ConventionTypeHasInvalidType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(typeof(IInvalidTestConvention), typeof(IConvention)); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + Assert.Throws(action); + } - [Fact] - public void Abstract_Classes_Are_Allowed_As_Object_Types() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void AddConvention_ConventionHasInvalidType_ArgumentException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddConvention(typeof(IConvention), typeof(IInvalidTestConvention)); - [Fact] - public void AddInterceptor_TypeIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .TryAddTypeInterceptor((Type)null); + // assert + Assert.Throws(action); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddConvention_WithImplementation_Generic() + { + // arrange + var convention = TestConvention.New(); + + // act + var schema = SchemaBuilder.New() + .AddConvention(convention) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var retrieved = testType.Context.GetConventionOrDefault( + new TestConvention()); + Assert.Equal(convention, retrieved); + } - [Fact] - public void AddInterceptor_InterceptorIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .TryAddTypeInterceptor((ITypeInitializationInterceptor)null); + [Fact] + public void AddConvention_WithImplementation() + { + // arrange + var convention = TestConvention.New(); + + // act + var schema = SchemaBuilder.New() + .AddConvention(typeof(ITestConvention), convention) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var retrieved = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.NotNull(convention); + Assert.Equal(convention, retrieved); + } - // assert - Assert.Throws(action); - } + [Fact] + public void AddConvention_NoImplementation_Generic() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddConvention() + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.NotNull(convention); + Assert.IsType(convention); + } - [Fact] - public void AddInterceptor_TypeIsNotAnInterceptorType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .TryAddTypeInterceptor(typeof(string)); + [Fact] + public void AddConvention_NoImplementation() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddConvention(typeof(ITestConvention), typeof(TestConvention)) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.NotNull(convention); + Assert.IsType(convention); + } - // assert - Assert.Throws(action); - } - [Fact] - public void AddInterceptor_TypeIsInterceptor_TypesAreTouched() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .TryAddTypeInterceptor(typeof(MyInterceptor)) - .AddQueryType(d => d + [Fact] + public void AddConvention_ServiceDependency() + { + // arrange + var services = new ServiceCollection(); + var provider = services.AddSingleton() + .BuildServiceProvider(); + var dependencyOfConvention = provider.GetService(); + + // act + var schema = SchemaBuilder.New() + .AddServices(provider) + .AddConvention( + typeof(ITestConvention), + typeof(TestConventionServiceDependency)) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention()); + Assert.IsType(convention); + Assert.Equal( + dependencyOfConvention, + ((TestConventionServiceDependency)convention).Dependency); + } + + [Fact] + public void AddConvention_Through_ServiceCollection() + { + // arrange + var services = new ServiceCollection(); + services.AddTransient(); + var provider = services.BuildServiceProvider(); + + // act + var schema = SchemaBuilder.New() + .AddServices(provider) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.IsType(convention); + } + + [Fact] + public void AddConvention_Through_ServiceCollection_ProvideImplementation() + { + // arrange + var services = new ServiceCollection(); + var conventionImpl = new TestConvention(); + services.AddSingleton(conventionImpl); + var provider = services.BuildServiceProvider(); + + // act + var schema = SchemaBuilder.New() + .AddServices(provider) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.IsType(convention); + Assert.Equal(convention, conventionImpl); + } + + [Fact] + public void AddConvention_Through_ServiceCollection_And_SchemaBuilderOverrides() + { + // arrange + var services = new ServiceCollection(); + services.AddSingleton(); + var provider = services.BuildServiceProvider(); + + // act + var schema = SchemaBuilder.New() + .AddServices(provider) + .AddConvention(typeof(IConvention), typeof(TestConvention2)) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.IsType(convention); + } + + [Fact] + public void AddConvention_NamingConvention() + { + // arrange + var myNamingConvention = new DefaultNamingConventions(); + + // act + var schema = SchemaBuilder.New() + .AddConvention(myNamingConvention) + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new DefaultNamingConventions()); + Assert.IsType(convention); + Assert.Equal(convention, myNamingConvention); + Assert.Equal(testType.Context.Naming, myNamingConvention); + } + + [Fact] + public void UseDefaultConvention() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddType() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + + // assert + var testType = schema.GetType("ConventionTestType"); + var convention = testType.Context.GetConventionOrDefault( + new TestConvention2()); + Assert.IsType(convention); + } + + [Fact] + public void AggregateState() + { + var sum = 0; + var schema = SchemaBuilder.New() + .SetContextData("abc", _ => 1) + .SetContextData("abc", o => ((int)o) + 1) + .SetContextData("abc", o => sum = (int)o) + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .Create(); + Assert.Equal(2, sum); + } + + [Fact] + public void UseStateAndDelayedConfiguration() + { + SchemaBuilder.New() + .SetContextData("name", "QueryRoot") + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Resolve("bar")) + .TryAddSchemaInterceptor(new DummySchemaInterceptor( + c => c.ContextData["name"] = c.ContextData["name"] + "1")) + .TryAddTypeInterceptor(new DelegateTypeInterceptor( + onAfterRegisterDependencies: (c, d, _) => + { + if (d is ObjectTypeDefinition def && def.Name.Equals("Query")) + { + ObjectTypeDescriptor + .From(c.DescriptorContext, def) + .Name(c.ContextData["name"]?.ToString()); + } + })) + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Convention_Should_AddConvention_When_CalledWithInstance() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - // assert - Assert.Collection(schema.GetType("Query").ContextData, - item => Assert.Equal("touched", item.Key)); + // assert + Assert.Equal(convention, result); + } - Assert.Collection(schema.GetType("String").ContextData, - item => Assert.Equal("touched", item.Key)); - } + [Fact] + public void Convention_Should_AddConvention_When_CalledWithGeneric() + { + // arrange + IDescriptorContext context = null!; - [Fact] - public void AddInterceptor_Generic_TypesAreTouched() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .TryAddTypeInterceptor() - .AddQueryType(d => d + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - Assert.Collection(schema.GetType("Query").ContextData, - item => Assert.Equal("touched", item.Key)); + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention() + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - Assert.Collection(schema.GetType("String").ContextData, - item => Assert.Equal("touched", item.Key)); - } + // assert + Assert.IsType(result); + } - [Fact] - public void AddInterceptor_AsService_TypesAreTouched() - { - // arrange - var services = new ServiceCollection(); - services.AddSingleton(); - - // act - ISchema schema = SchemaBuilder.New() - .AddServices(services.BuildServiceProvider()) - .AddQueryType(d => d + [Fact] + public void Convention_Should_AddConvention_When_CalledWithFactory() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(_ => convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - // assert - Assert.Collection(schema.GetType("Query").ContextData, - item => Assert.Equal("touched", item.Key)); + // assert + Assert.Equal(convention, result); + } - Assert.Collection(schema.GetType("String").ContextData, - item => Assert.Equal("touched", item.Key)); - } + [Fact] + public void Convention_Should_AddConvention_When_CalledWithType() + { + // arrange + IDescriptorContext context = null!; + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(MockConvention)) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_TypeIsNullConcreteIsSet_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(null, new TestConvention()); + // assert + Assert.IsType(result); + } - // assert - Assert.Throws(action); - } + [Fact] + public void Convention_Should_TryAddConvention_When_CalledWithInstance() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention(convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_ConventionIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(typeof(IConvention), default(TestConvention)); + // assert + Assert.Equal(convention, result); + } - // assert - Assert.Throws(action); - } + [Fact] + public void Convention_Should_TryAddConvention_When_CalledWithGeneric() + { + // arrange + IDescriptorContext context = null!; - [Fact] - public void AddConvention_ConventionTypeIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(null, typeof(IConvention)); + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention() + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - // assert - Assert.Throws(action); - } + // assert + Assert.IsType(result); + } - [Fact] - public void AddConvention_ConcreteConventionTypeIsNull_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(typeof(IConvention), default(Type)); + [Fact] + public void Convention_Should_TryAddConvention_When_CalledWithFactory() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention(_ => convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - // assert - Assert.Throws(action); - } + // assert + Assert.Equal(convention, result); + } + [Fact] + public void Convention_Should_TryAddConvention_When_CalledWithType() + { + // arrange + IDescriptorContext context = null!; + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention(typeof(MockConvention)) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_ConventionHasInvalidTypeConcrete_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(typeof(IInvalidTestConvention), new TestConvention()); + // assert + Assert.IsType(result); + } - // assert - Assert.Throws(action); - } + [Fact] + public void Convention_Should_AddConventionType_When_CalledWithInstance() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(IMockConvention), convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_ConventionTypeHasInvalidType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(typeof(IInvalidTestConvention), typeof(IConvention)); + // assert + Assert.Equal(convention, result); + } - // assert - Assert.Throws(action); - } + [Fact] + public void Convention_Should_AddConventionType_When_CalledWithFactory() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(IMockConvention),_ => convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_ConventionHasInvalidType_ArgumentException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddConvention(typeof(IConvention), typeof(IInvalidTestConvention)); + // assert + Assert.Equal(convention, result); + } - // assert - Assert.Throws(action); - } + [Fact] + public void Convention_Should_AddConventionType_When_CalledWithType() + { + // arrange + IDescriptorContext context = null!; - [Fact] - public void AddConvention_WithImplementation_Generic() - { - // arrange - var convention = TestConvention.New(); - - // act - ISchema schema = SchemaBuilder.New() - .AddConvention(convention) - .AddType() - .AddQueryType(d => d + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var retrieved = testType.Context.GetConventionOrDefault( - new TestConvention()); - Assert.Equal(convention, retrieved); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(IMockConvention),typeof(MockConvention)) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_WithImplementation() - { - // arrange - var convention = TestConvention.New(); - - // act - ISchema schema = SchemaBuilder.New() - .AddConvention(typeof(ITestConvention), convention) - .AddType() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var retrieved = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.NotNull(convention); - Assert.Equal(convention, retrieved); - } + // assert + Assert.IsType(result); + } - [Fact] - public void AddConvention_NoImplementation_Generic() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddConvention() - .AddType() - .AddQueryType(d => d + [Fact] + public void Convention_Should_TryAddConventionType_When_CalledWithInstance() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.NotNull(convention); - Assert.IsType(convention); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention(typeof(IMockConvention),convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_NoImplementation() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddConvention(typeof(ITestConvention), typeof(TestConvention)) - .AddType() - .AddQueryType(d => d + // assert + Assert.Equal(convention, result); + } + + [Fact] + public void Convention_Should_TryAddConventionType_When_CalledWithFactory() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.NotNull(convention); - Assert.IsType(convention); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention(typeof(IMockConvention), _ => convention) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); + // assert + Assert.Equal(convention, result); + } - [Fact] - public void AddConvention_ServiceDependency() - { - // arrange - var services = new ServiceCollection(); - var provider = services.AddSingleton() - .BuildServiceProvider(); - var dependencyOfConvention = provider.GetService(); - - // act - ISchema schema = SchemaBuilder.New() - .AddServices(provider) - .AddConvention( - typeof(ITestConvention), - typeof(TestConventionServiceDependency)) - .AddType() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention()); - Assert.IsType(convention); - Assert.Equal( - dependencyOfConvention, - ((TestConventionServiceDependency)convention).Dependency); - } + [Fact] + public void Convention_Should_TryAddConventionType_When_CalledWithType() + { + // arrange + IDescriptorContext context = null!; - [Fact] - public void AddConvention_Through_ServiceCollection() - { - // arrange - var services = new ServiceCollection(); - services.AddTransient(); - ServiceProvider provider = services.BuildServiceProvider(); - - // act - ISchema schema = SchemaBuilder.New() - .AddServices(provider) - .AddType() - .AddQueryType(d => d + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.IsType(convention); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .TryAddConvention(typeof(MockConvention)) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); - [Fact] - public void AddConvention_Through_ServiceCollection_ProvideImplementation() - { - // arrange - var services = new ServiceCollection(); - var conventionImpl = new TestConvention(); - services.AddSingleton(conventionImpl); - var provider = services.BuildServiceProvider(); - - // act - ISchema schema = SchemaBuilder.New() - .AddServices(provider) - .AddType() - .AddQueryType(d => d + // assert + Assert.IsType(result); + } + + [Fact] + public void ConventionExtension_Should_AddConvention_When_CalledWithInstance() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.IsType(convention); - Assert.Equal(convention, conventionImpl); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(convention) + .AddConvention(new MockConventionExtension()) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); + + // assert + Assert.True(convention.IsExtended); + } - [Fact] - public void AddConvention_Through_ServiceCollection_And_SchemaBuilderOverrides() - { - // arrange - var services = new ServiceCollection(); - services.AddSingleton(); - var provider = services.BuildServiceProvider(); - - // act - ISchema schema = SchemaBuilder.New() - .AddServices(provider) - .AddConvention(typeof(IConvention), typeof(TestConvention2)) - .AddType() - .AddQueryType(d => d + [Fact] + public void ConventionExtension_Should_AddConvention_When_CalledWithGeneric() + { + // arrange + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.IsType(convention); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention() + .AddConvention() + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); + + // assert + Assert.True(Assert.IsType(result).IsExtended); + } - [Fact] - public void AddConvention_NamingConvention() - { - // arrange - var myNamingConvention = new DefaultNamingConventions(); - - // act - ISchema schema = SchemaBuilder.New() - .AddConvention(myNamingConvention) - .AddType() - .AddQueryType(d => d + [Fact] + public void ConventionExtension_Should_AddConvention_When_CalledWithFactory() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new DefaultNamingConventions()); - Assert.IsType(convention); - Assert.Equal(convention, myNamingConvention); - Assert.Equal(testType.Context.Naming, myNamingConvention); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(_ => convention) + .AddConvention(_ => new MockConventionExtension()) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); + + // assert + Assert.True(Assert.IsType(result).IsExtended); + } - [Fact] - public void UseDefaultConvention() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .AddQueryType(d => d + [Fact] + public void ConventionExtension_Should_AddConvention_When_CalledWithType() + { + // arrange + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - - // assert - var testType = schema.GetType("ConventionTestType"); - var convention = testType.Context.GetConventionOrDefault( - new TestConvention2()); - Assert.IsType(convention); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(MockConvention)) + .AddConvention(typeof(MockConventionExtension)) + .Create(); + var result = context.GetConventionOrDefault( + () => throw new InvalidOperationException()); + + // assert + Assert.True(Assert.IsType(result).IsExtended); + } - [Fact] - public void AggregateState() - { - int sum = 0; - ISchema schema = SchemaBuilder.New() - .SetContextData("abc", _ => 1) - .SetContextData("abc", o => ((int)o) + 1) - .SetContextData("abc", o => sum = (int)o) - .AddQueryType(d => d + [Fact] + public void Convention_Should_Throw_When_DuplicatedConvention() + { + // arrange + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .Create(); - Assert.Equal(2, sum); - } + .Resolve("bar") + .Extend().OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(MockConvention)) + .AddConvention(typeof(MockConvention)) + .Create(); + + // assert + var schemaException = Assert.Throws( + () => context.GetConventionOrDefault( + () => throw new InvalidOperationException())); + schemaException.Message.MatchSnapshot(); + } - [Fact] - public void UseStateAndDelayedConfiguration() - { - SchemaBuilder.New() - .SetContextData("name", "QueryRoot") - .AddQueryType(d => d + [Fact] + public void Convention_Should_UseDefault_When_NotRegistered() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d .Name("Query") .Field("foo") - .Resolve("bar")) - .TryAddSchemaInterceptor(new DummySchemaInterceptor( - c => c.ContextData["name"] = c.ContextData["name"] + "1")) - .TryAddTypeInterceptor(new DelegateTypeInterceptor( - onAfterRegisterDependencies: (c, d, _) => + .Resolve("bar") + .Extend() + .OnBeforeCreate((ctx, _) => { - if (d is ObjectTypeDefinition def && def.Name.Equals("Query")) - { - ObjectTypeDescriptor - .From(c.DescriptorContext, def) - .Name(c.ContextData["name"]?.ToString()); - } + context = ctx; })) - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Convention_Should_AddConvention_When_CalledWithInstance() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } - - [Fact] - public void Convention_Should_AddConvention_When_CalledWithGeneric() - { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention() - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.IsType(result); - } - - [Fact] - public void Convention_Should_AddConvention_When_CalledWithFactory() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(_ => convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } - - [Fact] - public void Convention_Should_AddConvention_When_CalledWithType() - { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(MockConvention)) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.IsType(result); - } - - [Fact] - public void Convention_Should_TryAddConvention_When_CalledWithInstance() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention(convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } - - [Fact] - public void Convention_Should_TryAddConvention_When_CalledWithGeneric() - { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention() - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.IsType(result); - } - - [Fact] - public void Convention_Should_TryAddConvention_When_CalledWithFactory() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention(_ => convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } - - [Fact] - public void Convention_Should_TryAddConvention_When_CalledWithType() - { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention(typeof(MockConvention)) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.IsType(result); - } - - [Fact] - public void Convention_Should_AddConventionType_When_CalledWithInstance() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(IMockConvention), convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } + .Create(); + var result = context.GetConventionOrDefault( + () => convention); - [Fact] - public void Convention_Should_AddConventionType_When_CalledWithFactory() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(IMockConvention),_ => convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } + // assert + Assert.Equal(convention, result); + } - [Fact] - public void Convention_Should_AddConventionType_When_CalledWithType() - { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(IMockConvention),typeof(MockConvention)) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.IsType(result); - } + [Fact] + public void Convention_Should_UseDefault_When_NotRegisteredAndApplyExtensions() + { + // arrange + var convention = new MockConvention(); + IDescriptorContext context = null!; + + // act + SchemaBuilder.New() + .AddQueryType( + d => d + .Name("Query") + .Field("foo") + .Resolve("bar") + .Extend() + .OnBeforeCreate( + (ctx, _) => + { + context = ctx; + })) + .AddConvention(typeof(MockConventionExtension)) + .Create(); + var result = context.GetConventionOrDefault( + () => convention); + + // assert + Assert.Equal(result, convention); + Assert.True(Assert.IsType(result).IsExtended); + } - [Fact] - public void Convention_Should_TryAddConventionType_When_CalledWithInstance() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention(typeof(IMockConvention),convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } + public interface IMockConvention : IConvention + { + } - [Fact] - public void Convention_Should_TryAddConventionType_When_CalledWithFactory() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention(typeof(IMockConvention), _ => convention) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.Equal(convention, result); - } + public class MockConventionDefinition + { + public bool IsExtended { get; set; } + } - [Fact] - public void Convention_Should_TryAddConventionType_When_CalledWithType() + public class MockConvention : Convention, IMockConvention + { + public bool IsExtended { get; set; } + public new MockConventionDefinition Definition => base.Definition; + protected override MockConventionDefinition CreateDefinition(IConventionContext context) { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .TryAddConvention(typeof(MockConvention)) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.IsType(result); + return new MockConventionDefinition(); } - [Fact] - public void ConventionExtension_Should_AddConvention_When_CalledWithInstance() + protected internal override void Complete(IConventionContext context) { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(convention) - .AddConvention(new MockConventionExtension()) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.True(convention.IsExtended); + IsExtended = Definition.IsExtended; + base.Complete(context); } + } - [Fact] - public void ConventionExtension_Should_AddConvention_When_CalledWithGeneric() + public class MockConventionExtension : ConventionExtension + { + protected override MockConventionDefinition CreateDefinition(IConventionContext context) { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention() - .AddConvention() - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.True(Assert.IsType(result).IsExtended); + return new MockConventionDefinition(); } - [Fact] - public void ConventionExtension_Should_AddConvention_When_CalledWithFactory() + public override void Merge(IConventionContext context, Convention convention) { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(_ => convention) - .AddConvention(_ => new MockConventionExtension()) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.True(Assert.IsType(result).IsExtended); + if (convention is MockConvention mockConvention) + { + mockConvention.Definition.IsExtended = true; + } } + } - [Fact] - public void ConventionExtension_Should_AddConvention_When_CalledWithType() - { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(MockConvention)) - .AddConvention(typeof(MockConventionExtension)) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => throw new InvalidOperationException()); - - // assert - Assert.True(Assert.IsType(result).IsExtended); - } + public class DynamicFooType : ObjectType + { + private readonly NameString _typeName; - [Fact] - public void Convention_Should_Throw_When_DuplicatedConvention() + public DynamicFooType(NameString typeName) { - // arrange - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend().OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(MockConvention)) - .AddConvention(typeof(MockConvention)) - .Create(); - - // assert - SchemaException schemaException = Assert.Throws( - () => context.GetConventionOrDefault( - () => throw new InvalidOperationException())); - schemaException.Message.MatchSnapshot(); + _typeName = typeName; } - [Fact] - public void Convention_Should_UseDefault_When_NotRegistered() + protected override void Configure(IObjectTypeDescriptor descriptor) { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend() - .OnBeforeCreate((ctx, _) => - { - context = ctx; - })) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => convention); - - // assert - Assert.Equal(convention, result); + descriptor.Name(_typeName); + descriptor.Field("bar").Resolve("baz"); } + } - [Fact] - public void Convention_Should_UseDefault_When_NotRegisteredAndApplyExtensions() - { - // arrange - var convention = new MockConvention(); - IDescriptorContext context = null!; - - // act - SchemaBuilder.New() - .AddQueryType( - d => d - .Name("Query") - .Field("foo") - .Resolve("bar") - .Extend() - .OnBeforeCreate( - (ctx, _) => - { - context = ctx; - })) - .AddConvention(typeof(MockConventionExtension)) - .Create(); - IMockConvention result = context.GetConventionOrDefault( - () => convention); - - // assert - Assert.Equal(result, convention); - Assert.True(Assert.IsType(result).IsExtended); - } + public interface IInvalidTestConvention + { - public interface IMockConvention : IConvention - { - } + } + public interface ITestConvention : IConvention + { - public class MockConventionDefinition - { - public bool IsExtended { get; set; } - } + } + public class TestConvention2 : Convention, ITestConvention + { + } + public class TestConvention : Convention, ITestConvention + { + public static TestConvention New () => new(); + } - public class MockConvention : Convention, IMockConvention + public class TestConventionServiceDependency : Convention, ITestConvention + { + public TestConventionServiceDependency(MyInterceptor dependency) { - public bool IsExtended { get; set; } - public new MockConventionDefinition Definition => base.Definition; - protected override MockConventionDefinition CreateDefinition(IConventionContext context) - { - return new MockConventionDefinition(); - } - - protected internal override void Complete(IConventionContext context) - { - IsExtended = Definition.IsExtended; - base.Complete(context); - } + Dependency = dependency; } - public class MockConventionExtension : ConventionExtension - { - protected override MockConventionDefinition CreateDefinition(IConventionContext context) - { - return new MockConventionDefinition(); - } + public MyInterceptor Dependency { get; } + } - public override void Merge(IConventionContext context, Convention convention) - { - if (convention is MockConvention mockConvention) - { - mockConvention.Definition.IsExtended = true; - } - } - } + public class ConventionTestType : ObjectType + { + public IDescriptorContext Context { get; private set; } - public class DynamicFooType : ObjectType + protected override void Configure(IObjectTypeDescriptor descriptor) { - private readonly NameString _typeName; - - public DynamicFooType(NameString typeName) - { - _typeName = typeName; - } - - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name(_typeName); - descriptor.Field("bar").Resolve("baz"); - } + descriptor.Name("ConventionTestType"); + base.Configure(descriptor); } - - public interface IInvalidTestConvention + protected override void OnCompleteName( + ITypeCompletionContext context, + ObjectTypeDefinition definition) { - + base.OnCompleteName(context, definition); + Context = context.DescriptorContext; } - public interface ITestConvention : IConvention - { + } - } - public class TestConvention2 : Convention, ITestConvention - { - } - public class TestConvention : Convention, ITestConvention + public class QueryType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public static TestConvention New () => new(); + descriptor.Name("Query"); + descriptor.Field("foo").Type().Resolve("bar"); } + } - public class TestConventionServiceDependency : Convention, ITestConvention + public class MutationType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public TestConventionServiceDependency(MyInterceptor dependency) - { - Dependency = dependency; - } - - public MyInterceptor Dependency { get; } + descriptor.Name("Mutation"); + descriptor.Field("bar").Type().Resolve(123); } + } - public class ConventionTestType : ObjectType + public class SubscriptionType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - public IDescriptorContext Context { get; private set; } - - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("ConventionTestType"); - base.Configure(descriptor); - } - protected override void OnCompleteName( - ITypeCompletionContext context, - ObjectTypeDefinition definition) - { - base.OnCompleteName(context, definition); - Context = context.DescriptorContext; - } + descriptor.Name("Subscription"); + descriptor.Field("onFoo").Type().Resolve(123); } + } - public class QueryType : ObjectType + public class FooType : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("foo").Type().Resolve("bar"); - } + descriptor.Field(t => t.Bar).Type>(); } + } - public class MutationType : ObjectType - { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Mutation"); - descriptor.Field("bar").Type().Resolve(123); - } - } + public class BarType : ObjectType + { + } - public class SubscriptionType : ObjectType - { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Subscription"); - descriptor.Field("onFoo").Type().Resolve(123); - } - } + public class Foo + { + public Bar Bar { get; } + } - public class FooType : ObjectType - { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Bar).Type>(); - } - } + public class Bar + { + public string Baz { get; } + } - public class BarType : ObjectType + public class MySchema : Schema + { + protected override void Configure(ISchemaTypeDescriptor descriptor) { + descriptor.Description("Description"); } + } - public class Foo - { - public Bar Bar { get; } - } + public class MyEnumType : EnumType { } - public class Bar - { - public string Baz { get; } - } + public class QueryWithIntField + { + public int Foo { get; set; } + } - public class MySchema : Schema - { - protected override void Configure(ISchemaTypeDescriptor descriptor) - { - descriptor.Description("Description"); - } - } + public abstract class AbstractQuery + { + public string Foo { get; set; } - public class MyEnumType : EnumType { } + public AbstractChild Object { get; set; } + } - public class QueryWithIntField - { - public int Foo { get; set; } - } + public abstract class AbstractChild + { + public string Foo { get; set; } + } - public abstract class AbstractQuery + public class MyInterceptor : TypeInterceptor + { + public override void OnAfterCompleteType( + ITypeCompletionContext completionContext, + DefinitionBase definition, + IDictionary contextData) { - public string Foo { get; set; } - - public AbstractChild Object { get; set; } + contextData.Add("touched", true); } + } - public abstract class AbstractChild - { - public string Foo { get; set; } - } + public class DummySchemaInterceptor : SchemaInterceptor + { + private readonly Action _onBeforeCreate; - public class MyInterceptor : TypeInterceptor + public DummySchemaInterceptor(Action onBeforeCreate) { - public override void OnAfterCompleteType( - ITypeCompletionContext completionContext, - DefinitionBase definition, - IDictionary contextData) - { - contextData.Add("touched", true); - } + _onBeforeCreate = onBeforeCreate; } - public class DummySchemaInterceptor : SchemaInterceptor - { - private readonly Action _onBeforeCreate; - - public DummySchemaInterceptor(Action onBeforeCreate) - { - _onBeforeCreate = onBeforeCreate; - } - - public override void OnBeforeCreate( - IDescriptorContext context, - ISchemaBuilder schemaBuilder) => - _onBeforeCreate(context); - } + public override void OnBeforeCreate( + IDescriptorContext context, + ISchemaBuilder schemaBuilder) => + _onBeforeCreate(context); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/SchemaCoordinateTests.cs b/src/HotChocolate/Core/test/Types.Tests/SchemaCoordinateTests.cs index c96bdc5e84c..1f5ec9bf95c 100644 --- a/src/HotChocolate/Core/test/Types.Tests/SchemaCoordinateTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/SchemaCoordinateTests.cs @@ -13,10 +13,10 @@ public class SchemaCoordinateTests public void GetMember_ObjectType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Baz"); + var member = schema.GetMember("Baz"); // assert Assert.Equal("Baz", Assert.IsType(member).Name); @@ -26,13 +26,13 @@ public void GetMember_ObjectType() public void GetMember_ObjectType_Field() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Baz.name"); + var member = schema.GetMember("Baz.name"); // assert - ObjectField field = Assert.IsType(member); + var field = Assert.IsType(member); Assert.Equal("name", field.Name); Assert.Equal("Baz", field.DeclaringType.Name); } @@ -41,13 +41,13 @@ public void GetMember_ObjectType_Field() public void GetMember_ObjectType_FieldArg() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Baz.name(baz:)"); + var member = schema.GetMember("Baz.name(baz:)"); // assert - Argument arg = Assert.IsType(member); + var arg = Assert.IsType(member); Assert.Equal("baz", arg.Name); Assert.Equal("name", Assert.IsType(arg.DeclaringMember).Name); Assert.Equal("Baz", arg.DeclaringType.Name); @@ -57,7 +57,7 @@ public void GetMember_ObjectType_FieldArg() public void GetMember_Object_Invalid_FieldName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("Baz.foo"); @@ -70,7 +70,7 @@ public void GetMember_Object_Invalid_FieldName() public void GetMember_Object_Invalid_FieldArgName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("Baz.name(bar:)"); @@ -83,10 +83,10 @@ public void GetMember_Object_Invalid_FieldArgName() public void GetMember_InterfaceType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Bar"); + var member = schema.GetMember("Bar"); // assert Assert.Equal("Bar", Assert.IsType(member).Name); @@ -96,13 +96,13 @@ public void GetMember_InterfaceType() public void GetMember_InterfaceType_Field() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Bar.id"); + var member = schema.GetMember("Bar.id"); // assert - InterfaceField field = Assert.IsType(member); + var field = Assert.IsType(member); Assert.Equal("id", field.Name); Assert.Equal("Bar", field.DeclaringType.Name); } @@ -111,13 +111,13 @@ public void GetMember_InterfaceType_Field() public void GetMember_InterfaceType_FieldArg() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Bar.name(baz:)"); + var member = schema.GetMember("Bar.name(baz:)"); // assert - Argument arg = Assert.IsType(member); + var arg = Assert.IsType(member); Assert.Equal("baz", arg.Name); Assert.Equal("name", Assert.IsType(arg.DeclaringMember).Name); Assert.Equal("Bar", arg.DeclaringType.Name); @@ -127,7 +127,7 @@ public void GetMember_InterfaceType_FieldArg() public void GetMember_Interface_Invalid_FieldName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("Bar.xyz"); @@ -140,7 +140,7 @@ public void GetMember_Interface_Invalid_FieldName() public void GetMember_Interface_Invalid_FieldArgName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("Bar.name(bar:)"); @@ -153,10 +153,10 @@ public void GetMember_Interface_Invalid_FieldArgName() public void GetMember_UnionType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("FooOrBaz"); + var member = schema.GetMember("FooOrBaz"); // assert Assert.Equal("FooOrBaz", Assert.IsType(member).Name); @@ -166,7 +166,7 @@ public void GetMember_UnionType() public void GetMember_UnionType_Invalid_MemberName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("FooOrBaz.Foo"); @@ -179,10 +179,10 @@ public void GetMember_UnionType_Invalid_MemberName() public void GetMember_InputObjectType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("BazInput"); + var member = schema.GetMember("BazInput"); // assert Assert.Equal("BazInput", Assert.IsType(member).Name); @@ -192,13 +192,13 @@ public void GetMember_InputObjectType() public void GetMember_InputObjectType_Field() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("BazInput.name"); + var member = schema.GetMember("BazInput.name"); // assert - InputField argument = Assert.IsType(member); + var argument = Assert.IsType(member); Assert.Equal("name", argument.Name); Assert.Equal("BazInput", argument.DeclaringType.Name); } @@ -207,7 +207,7 @@ public void GetMember_InputObjectType_Field() public void GetMember_InputObjectType_Invalid_FieldName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("BazInput.abc"); @@ -220,7 +220,7 @@ public void GetMember_InputObjectType_Invalid_FieldName() public void GetMember_InputObjectType_Invalid_FieldArgName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("BazInput.name(a:)"); @@ -233,10 +233,10 @@ public void GetMember_InputObjectType_Invalid_FieldArgName() public void GetMember_EnumType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Abc"); + var member = schema.GetMember("Abc"); // assert Assert.Equal("Abc", Assert.IsType(member).Name); @@ -246,10 +246,10 @@ public void GetMember_EnumType() public void GetMember_EnumType_Value() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("Abc.DEF"); + var member = schema.GetMember("Abc.DEF"); // assert Assert.Equal("DEF", Assert.IsType(member).Name.Value); @@ -259,7 +259,7 @@ public void GetMember_EnumType_Value() public void GetMember_EnumType_Invalid_Value() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("Abc.XYZ"); @@ -272,10 +272,10 @@ public void GetMember_EnumType_Invalid_Value() public void GetMember_ScalarType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("String"); + var member = schema.GetMember("String"); // assert Assert.Equal("String", Assert.IsType(member).Name); @@ -285,10 +285,10 @@ public void GetMember_ScalarType() public void GetMember_DirectiveType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("@qux"); + var member = schema.GetMember("@qux"); // assert Assert.Equal("qux", Assert.IsType(member).Name); @@ -298,13 +298,13 @@ public void GetMember_DirectiveType() public void GetMember_DirectiveType_Argument() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - ITypeSystemMember member = schema.GetMember("@qux(a:)"); + var member = schema.GetMember("@qux(a:)"); // assert - Argument argument = Assert.IsType(member); + var argument = Assert.IsType(member); Assert.Equal("a", argument.Name); Assert.Equal("qux", argument.DeclaringType.Name); } @@ -313,7 +313,7 @@ public void GetMember_DirectiveType_Argument() public void GetMember_DirectiveType_Invalid_ArgumentName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("@qux(b:)"); @@ -326,7 +326,7 @@ public void GetMember_DirectiveType_Invalid_ArgumentName() public void GetMember_Invalid_TypeName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("Abc123"); @@ -340,7 +340,7 @@ public void GetMember_Invalid_TypeName() public void GetMember_Invalid_DirectiveName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act void Fail() => schema.GetMember("@foo123"); @@ -353,10 +353,10 @@ public void GetMember_Invalid_DirectiveName() public void TryGetMember_ObjectType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Baz", out var member); + var success = schema.TryGetMember("Baz", out var member); // assert Assert.True(success); @@ -367,14 +367,14 @@ public void TryGetMember_ObjectType() public void TryGetMember_ObjectType_Field() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Baz.name", out var member); + var success = schema.TryGetMember("Baz.name", out var member); // assert Assert.True(success); - ObjectField field = Assert.IsType(member); + var field = Assert.IsType(member); Assert.Equal("name", field.Name); Assert.Equal("Baz", field.DeclaringType.Name); } @@ -383,14 +383,14 @@ public void TryGetMember_ObjectType_Field() public void TryGetMember_ObjectType_FieldArg() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Baz.name(baz:)", out var member); + var success = schema.TryGetMember("Baz.name(baz:)", out var member); // assert Assert.True(success); - Argument arg = Assert.IsType(member); + var arg = Assert.IsType(member); Assert.Equal("baz", arg.Name); Assert.Equal("name", Assert.IsType(arg.DeclaringMember).Name); Assert.Equal("Baz", arg.DeclaringType.Name); @@ -400,10 +400,10 @@ public void TryGetMember_ObjectType_FieldArg() public void TryGetMember_Object_Invalid_FieldName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Baz.foo", out var member); + var success = schema.TryGetMember("Baz.foo", out var member); // assert Assert.False(success); @@ -413,10 +413,10 @@ public void TryGetMember_Object_Invalid_FieldName() public void TryGetMember_Object_Invalid_FieldArgName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Baz.name(bar:)", out var member); + var success = schema.TryGetMember("Baz.name(bar:)", out var member); // assert Assert.False(success); @@ -426,10 +426,10 @@ public void TryGetMember_Object_Invalid_FieldArgName() public void TryGetMember_InterfaceType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Bar", out var member); + var success = schema.TryGetMember("Bar", out var member); // assert Assert.True(success); @@ -440,14 +440,14 @@ public void TryGetMember_InterfaceType() public void TryGetMember_InterfaceType_Field() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Bar.id", out var member); + var success = schema.TryGetMember("Bar.id", out var member); // assert Assert.True(success); - InterfaceField field = Assert.IsType(member); + var field = Assert.IsType(member); Assert.Equal("id", field.Name); Assert.Equal("Bar", field.DeclaringType.Name); } @@ -456,14 +456,14 @@ public void TryGetMember_InterfaceType_Field() public void TryGetMember_InterfaceType_FieldArg() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Bar.name(baz:)", out var member); + var success = schema.TryGetMember("Bar.name(baz:)", out var member); // assert Assert.True(success); - Argument arg = Assert.IsType(member); + var arg = Assert.IsType(member); Assert.Equal("baz", arg.Name); Assert.Equal("name", Assert.IsType(arg.DeclaringMember).Name); Assert.Equal("Bar", arg.DeclaringType.Name); @@ -473,10 +473,10 @@ public void TryGetMember_InterfaceType_FieldArg() public void TryGetMember_Interface_Invalid_FieldName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Baz.xyz", out var member); + var success = schema.TryGetMember("Baz.xyz", out var member); // assert Assert.False(success); @@ -486,10 +486,10 @@ public void TryGetMember_Interface_Invalid_FieldName() public void TryGetMember_Interface_Invalid_FieldArgName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Bar.name(bar:)", out var member); + var success = schema.TryGetMember("Bar.name(bar:)", out var member); // assert Assert.False(success); @@ -499,10 +499,10 @@ public void TryGetMember_Interface_Invalid_FieldArgName() public void TryGetMember_UnionType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("FooOrBaz", out var member); + var success = schema.TryGetMember("FooOrBaz", out var member); // assert Assert.True(success); @@ -512,10 +512,10 @@ public void TryGetMember_UnionType() public void TryGetMember_UnionType_Invalid_MemberName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("FooOrBaz.Foo", out var member); + var success = schema.TryGetMember("FooOrBaz.Foo", out var member); // assert Assert.False(success); @@ -525,10 +525,10 @@ public void TryGetMember_UnionType_Invalid_MemberName() public void TryGetMember_InputObjectType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("BazInput", out var member); + var success = schema.TryGetMember("BazInput", out var member); // assert Assert.True(success); @@ -539,14 +539,14 @@ public void TryGetMember_InputObjectType() public void TryGetMember_InputObjectType_Field() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("BazInput.name", out var member); + var success = schema.TryGetMember("BazInput.name", out var member); // assert Assert.True(success); - InputField argument = Assert.IsType(member); + var argument = Assert.IsType(member); Assert.Equal("name", argument.Name); Assert.Equal("BazInput", argument.DeclaringType.Name); } @@ -555,10 +555,10 @@ public void TryGetMember_InputObjectType_Field() public void TryGetMember_InputObjectType_Invalid_FieldName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("BazInput.abc", out var member); + var success = schema.TryGetMember("BazInput.abc", out var member); // assert Assert.False(success); @@ -568,10 +568,10 @@ public void TryGetMember_InputObjectType_Invalid_FieldName() public void TryGetMember_InputObjectType_Invalid_FieldArgName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("BazInput.name(a:)", out var member); + var success = schema.TryGetMember("BazInput.name(a:)", out var member); // assert Assert.False(success); @@ -581,10 +581,10 @@ public void TryGetMember_InputObjectType_Invalid_FieldArgName() public void TryGetMember_EnumType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Abc", out var member); + var success = schema.TryGetMember("Abc", out var member); // assert Assert.True(success); @@ -595,10 +595,10 @@ public void TryGetMember_EnumType() public void TryGetMember_EnumType_Value() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Abc.DEF", out var member); + var success = schema.TryGetMember("Abc.DEF", out var member); // assert Assert.True(success); @@ -609,10 +609,10 @@ public void TryGetMember_EnumType_Value() public void TryGetMember_EnumType_Invalid_Value() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Abc.XYZ", out var member); + var success = schema.TryGetMember("Abc.XYZ", out var member); // assert Assert.False(success); @@ -622,10 +622,10 @@ public void TryGetMember_EnumType_Invalid_Value() public void TryGetMember_ScalarType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("String", out var member); + var success = schema.TryGetMember("String", out var member); // assert Assert.True(success); @@ -636,10 +636,10 @@ public void TryGetMember_ScalarType() public void TryGetMember_DirectiveType() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("@qux", out var member); + var success = schema.TryGetMember("@qux", out var member); // assert Assert.True(success); @@ -650,14 +650,14 @@ public void TryGetMember_DirectiveType() public void TryGetMember_DirectiveType_Argument() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("@qux(a:)", out var member); + var success = schema.TryGetMember("@qux(a:)", out var member); // assert Assert.True(success); - Argument argument = Assert.IsType(member); + var argument = Assert.IsType(member); Assert.Equal("a", argument.Name); Assert.Equal("qux", argument.DeclaringType.Name); } @@ -666,10 +666,10 @@ public void TryGetMember_DirectiveType_Argument() public void TryGetMember_DirectiveType_Invalid_ArgumentName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("@qux(b:)", out var member); + var success = schema.TryGetMember("@qux(b:)", out var member); // assert Assert.False(success); @@ -679,10 +679,10 @@ public void TryGetMember_DirectiveType_Invalid_ArgumentName() public void TryGetMember_Invalid_TypeName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("Abc123", out var member); + var success = schema.TryGetMember("Abc123", out var member); // assert Assert.False(success); @@ -692,10 +692,10 @@ public void TryGetMember_Invalid_TypeName() public void TryGetMember_Invalid_DirectiveName() { // arrange - ISchema schema = CreateSchema(); + var schema = CreateSchema(); // act - bool success = schema.TryGetMember("@abc", out var member); + var success = schema.TryGetMember("@abc", out var member); // assert Assert.False(success); @@ -714,4 +714,4 @@ private ISchema CreateSchema() .Use(next => context => default) .Create(); } -} \ No newline at end of file +} diff --git a/src/HotChocolate/Core/test/Types.Tests/SchemaErrorTests.cs b/src/HotChocolate/Core/test/Types.Tests/SchemaErrorTests.cs index 52d7157d898..0a3f0dbc87f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/SchemaErrorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/SchemaErrorTests.cs @@ -6,159 +6,158 @@ using HotChocolate.Types.Descriptors; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaErrorTests { - public class SchemaErrorTests + [Fact] + public void CreateSchemaError_ExceptionAndMessage() { - [Fact] - public void CreateSchemaError_ExceptionAndMessage() - { - // arrange - var message = "FooBar"; - var exception = new Exception(); - - // act - ISchemaError schemaError = SchemaErrorBuilder.New() - .SetMessage(message) - .SetException(exception) - .Build(); - - // assert - Assert.Equal(message, schemaError.Message); - Assert.Equal(exception, schemaError.Exception); - Assert.Empty(schemaError.SyntaxNodes); - Assert.Empty(schemaError.Extensions); - Assert.Null(schemaError.TypeSystemObject); - Assert.Null(schemaError.Path); - Assert.Null(schemaError.Code); - } + // arrange + var message = "FooBar"; + var exception = new Exception(); + + // act + var schemaError = SchemaErrorBuilder.New() + .SetMessage(message) + .SetException(exception) + .Build(); + + // assert + Assert.Equal(message, schemaError.Message); + Assert.Equal(exception, schemaError.Exception); + Assert.Empty(schemaError.SyntaxNodes); + Assert.Empty(schemaError.Extensions); + Assert.Null(schemaError.TypeSystemObject); + Assert.Null(schemaError.Path); + Assert.Null(schemaError.Code); + } - [Fact] - public void CreateSchemaError_Exception() - { - // arrange - var exception = new Exception("FooBar"); - - // act - ISchemaError schemaError = SchemaErrorBuilder.New() - .SetException(exception) - .Build(); - - // assert - Assert.Equal(exception.Message, schemaError.Message); - Assert.Equal(exception, schemaError.Exception); - Assert.Empty(schemaError.SyntaxNodes); - Assert.Empty(schemaError.Extensions); - Assert.Null(schemaError.TypeSystemObject); - Assert.Null(schemaError.Path); - Assert.Null(schemaError.Code); - } + [Fact] + public void CreateSchemaError_Exception() + { + // arrange + var exception = new Exception("FooBar"); + + // act + var schemaError = SchemaErrorBuilder.New() + .SetException(exception) + .Build(); + + // assert + Assert.Equal(exception.Message, schemaError.Message); + Assert.Equal(exception, schemaError.Exception); + Assert.Empty(schemaError.SyntaxNodes); + Assert.Empty(schemaError.Extensions); + Assert.Null(schemaError.TypeSystemObject); + Assert.Null(schemaError.Path); + Assert.Null(schemaError.Code); + } - [Fact] - public void CreateSchemaError_ThreeArguments_PopertiesAreSet() - { - // arrange - var message = "FooBar"; - var exception = new Exception(); - var type = new StringType(); - - // act - ISchemaError schemaError = SchemaErrorBuilder.New() - .SetMessage(message) - .SetException(exception) - .SetTypeSystemObject(type) - .Build(); - - // assert - Assert.Equal(message, schemaError.Message); - Assert.Equal(exception, schemaError.Exception); - Assert.Equal(type, schemaError.TypeSystemObject); - Assert.Empty(schemaError.SyntaxNodes); - Assert.Empty(schemaError.Extensions); - Assert.Null(schemaError.Path); - Assert.Null(schemaError.Code); - } + [Fact] + public void CreateSchemaError_ThreeArguments_PopertiesAreSet() + { + // arrange + var message = "FooBar"; + var exception = new Exception(); + var type = new StringType(); + + // act + var schemaError = SchemaErrorBuilder.New() + .SetMessage(message) + .SetException(exception) + .SetTypeSystemObject(type) + .Build(); + + // assert + Assert.Equal(message, schemaError.Message); + Assert.Equal(exception, schemaError.Exception); + Assert.Equal(type, schemaError.TypeSystemObject); + Assert.Empty(schemaError.SyntaxNodes); + Assert.Empty(schemaError.Extensions); + Assert.Null(schemaError.Path); + Assert.Null(schemaError.Code); + } - [Fact] - public void CreateSchemaError_SetExtension() - { - // arrange - var message = "FooBar"; - var key = "foo"; - var value = "bar"; - - // act - ISchemaError schemaError = SchemaErrorBuilder.New() - .SetMessage(message) - .SetExtension(key, value) - .Build(); - - // assert - Assert.Equal(message, schemaError.Message); - Assert.Empty(schemaError.SyntaxNodes); - Assert.Collection(schemaError.Extensions, - t => - { - Assert.Equal(key, t.Key); - Assert.Equal(value, t.Value); - }); - Assert.Null(schemaError.Exception); - Assert.Null(schemaError.TypeSystemObject); - Assert.Null(schemaError.Path); - Assert.Null(schemaError.Code); - } + [Fact] + public void CreateSchemaError_SetExtension() + { + // arrange + var message = "FooBar"; + var key = "foo"; + var value = "bar"; + + // act + var schemaError = SchemaErrorBuilder.New() + .SetMessage(message) + .SetExtension(key, value) + .Build(); + + // assert + Assert.Equal(message, schemaError.Message); + Assert.Empty(schemaError.SyntaxNodes); + Assert.Collection(schemaError.Extensions, + t => + { + Assert.Equal(key, t.Key); + Assert.Equal(value, t.Value); + }); + Assert.Null(schemaError.Exception); + Assert.Null(schemaError.TypeSystemObject); + Assert.Null(schemaError.Path); + Assert.Null(schemaError.Code); + } - [Fact] - public void CreateSchemaError_AddSyntaxNode() - { - // arrange - var message = "FooBar"; - var node = new NameNode("foo"); - - - // act - ISchemaError schemaError = SchemaErrorBuilder.New() - .SetMessage(message) - .AddSyntaxNode(node) - .Build(); - - // assert - Assert.Equal(message, schemaError.Message); - Assert.Collection(schemaError.SyntaxNodes, - t => Assert.Equal(node, t)); - Assert.Empty(schemaError.Extensions); - Assert.Null(schemaError.Exception); - Assert.Null(schemaError.TypeSystemObject); - Assert.Null(schemaError.Path); - Assert.Null(schemaError.Code); - } + [Fact] + public void CreateSchemaError_AddSyntaxNode() + { + // arrange + var message = "FooBar"; + var node = new NameNode("foo"); + + + // act + var schemaError = SchemaErrorBuilder.New() + .SetMessage(message) + .AddSyntaxNode(node) + .Build(); + + // assert + Assert.Equal(message, schemaError.Message); + Assert.Collection(schemaError.SyntaxNodes, + t => Assert.Equal(node, t)); + Assert.Empty(schemaError.Extensions); + Assert.Null(schemaError.Exception); + Assert.Null(schemaError.TypeSystemObject); + Assert.Null(schemaError.Path); + Assert.Null(schemaError.Code); + } - [Fact] - public void Intercept_Schema_Error() - { - // arrange - var errorInterceptor = new ErrorInterceptor(); - - // act - void Action() => SchemaBuilder.New() - .TryAddSchemaInterceptor(errorInterceptor) - .Create(); - - // assert - Assert.Throws(Action); - Assert.Collection( - errorInterceptor.Exceptions, - ex => Assert.IsType(ex)); - } + [Fact] + public void Intercept_Schema_Error() + { + // arrange + var errorInterceptor = new ErrorInterceptor(); + + // act + void Action() => SchemaBuilder.New() + .TryAddSchemaInterceptor(errorInterceptor) + .Create(); + + // assert + Assert.Throws(Action); + Assert.Collection( + errorInterceptor.Exceptions, + ex => Assert.IsType(ex)); + } - private sealed class ErrorInterceptor : SchemaInterceptor - { - public List Exceptions { get; } = new List(); + private sealed class ErrorInterceptor : SchemaInterceptor + { + public List Exceptions { get; } = new List(); - public override void OnError(IDescriptorContext context, Exception exception) - { - Exceptions.Add(exception); - } + public override void OnError(IDescriptorContext context, Exception exception) + { + Exceptions.Add(exception); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/SchemaFirstTests.cs b/src/HotChocolate/Core/test/Types.Tests/SchemaFirstTests.cs index f405d2c5305..a9f4f90e2f5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/SchemaFirstTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/SchemaFirstTests.cs @@ -13,33 +13,33 @@ using HotChocolate.Types.Descriptors; using HotChocolate.Types.Descriptors.Definitions; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaFirstTests { - public class SchemaFirstTests + [Fact] + public async Task DescriptionsAreCorrectlyRead() { - [Fact] - public async Task DescriptionsAreCorrectlyRead() - { - // arrange - Snapshot.FullName(); - var source = FileResource.Open("schema_with_multiline_descriptions.graphql"); - var query = FileResource.Open("IntrospectionQuery.graphql"); - - // act & act - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(source) - .ModifyOptions(o => o.SortFieldsByName = true) - .UseField(next => next) - .ExecuteRequestAsync(query) - .MatchSnapshotAsync(); - } + // arrange + Snapshot.FullName(); + var source = FileResource.Open("schema_with_multiline_descriptions.graphql"); + var query = FileResource.Open("IntrospectionQuery.graphql"); + + // act & act + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(source) + .ModifyOptions(o => o.SortFieldsByName = true) + .UseField(next => next) + .ExecuteRequestAsync(query) + .MatchSnapshotAsync(); + } - [Fact] - public async Task Interfaces_Impl_Interfaces_Are_Correctly_Exposed_Through_Introspection() - { - // arrange - var source = @" + [Fact] + public async Task Interfaces_Impl_Interfaces_Are_Correctly_Exposed_Through_Introspection() + { + // arrange + var source = @" type Query { c: C } @@ -56,27 +56,27 @@ type C implements A & B { a: String } "; - var query = FileResource.Open("IntrospectionQuery.graphql"); - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .Use(next => next) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - IExecutionResult result = await executor.ExecuteAsync(query); - result.ToJson().MatchSnapshot(); - } + var query = FileResource.Open("IntrospectionQuery.graphql"); + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .Use(next => next) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var result = await executor.ExecuteAsync(query); + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task Execute_Against_Schema_With_Interface_Schema() - { - Snapshot.FullName(); + [Fact] + public async Task Execute_Against_Schema_With_Interface_Schema() + { + Snapshot.FullName(); - var source = @" + var source = @" type Query { pet: Pet } @@ -94,22 +94,22 @@ type Dog implements Pet { } "; - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(source) - .AddResolver("Query") - .BindRuntimeType() - .BindRuntimeType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(source) + .AddResolver("Query") + .BindRuntimeType() + .BindRuntimeType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Execute_Against_Schema_With_Interface_Execute() - { - Snapshot.FullName(); + [Fact] + public async Task Execute_Against_Schema_With_Interface_Execute() + { + Snapshot.FullName(); - var source = @" + var source = @" type Query { pet: Pet } @@ -127,81 +127,81 @@ type Dog implements Pet { } "; - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(source) - .AddResolver("Query") - .BindRuntimeType() - .BindRuntimeType() - .ExecuteRequestAsync("{ pet { name __typename } }") - .MatchSnapshotAsync(); - } - - [Fact] - public async Task SchemaDescription() - { - // arrange - var sourceText = "\"\"\"\nMy Schema Description\n\"\"\"" + - "schema" + - "{ query: Foo }" + - "type Foo { bar: String }"; - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .Use(next => next) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - IExecutionResult result = - await executor.ExecuteAsync("{ __schema { description } }"); - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task SchemaBuilder_BindType() - { - // arrange - var sourceText = "type Query { hello: String }"; - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .AddRootResolver(new { Query = new Query() }) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - IExecutionResult result = - await executor.ExecuteAsync("{ hello }"); - result.ToJson().MatchSnapshot(); - } + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(source) + .AddResolver("Query") + .BindRuntimeType() + .BindRuntimeType() + .ExecuteRequestAsync("{ pet { name __typename } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task SchemaBuilder_AddResolver() - { - // arrange - var sourceText = "type Query { hello: String }"; + [Fact] + public async Task SchemaDescription() + { + // arrange + var sourceText = "\"\"\"\nMy Schema Description\n\"\"\"" + + "schema" + + "{ query: Foo }" + + "type Foo { bar: String }"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .Use(next => next) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var result = + await executor.ExecuteAsync("{ __schema { description } }"); + result.ToJson().MatchSnapshot(); + } - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .AddResolver("Query", "hello", () => "World") - .Create(); + [Fact] + public async Task SchemaBuilder_BindType() + { + // arrange + var sourceText = "type Query { hello: String }"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .AddRootResolver(new { Query = new Query() }) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var result = + await executor.ExecuteAsync("{ hello }"); + result.ToJson().MatchSnapshot(); + } - // assert - IRequestExecutor executor = schema.MakeExecutable(); - IExecutionResult result = - await executor.ExecuteAsync("{ hello }"); - result.ToJson().MatchSnapshot(); - } + [Fact] + public async Task SchemaBuilder_AddResolver() + { + // arrange + var sourceText = "type Query { hello: String }"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .AddResolver("Query", "hello", () => "World") + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var result = + await executor.ExecuteAsync("{ hello }"); + result.ToJson().MatchSnapshot(); + } - [Fact] - public void DirectiveArgumentsAreValidated() - { - // arrange - var sourceText = @" + [Fact] + public void DirectiveArgumentsAreValidated() + { + // arrange + var sourceText = @" type Query { foo: String @a(b:1 e:true) } @@ -209,32 +209,32 @@ type Query { directive @a(c:Int d:Int! e:Int) on FIELD_DEFINITION "; - // act - void Action() => - SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .AddResolver("Query", "foo", "bar") - .Create(); - - // assert - Assert.Collection( - Assert.Throws(Action).Errors, - error => Assert.Equal( - ErrorCodes.Schema.InvalidArgument, - error.Code), - error => Assert.Equal( - ErrorCodes.Schema.ArgumentValueTypeWrong, - error.Code), - error => Assert.Equal( - ErrorCodes.Schema.NonNullArgument, - error.Code)); - } + // act + void Action() => + SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .AddResolver("Query", "foo", "bar") + .Create(); - [Fact] - public void BuiltInScalarsAreRecognized() - { - // arrange - var sourceText = @" + // assert + Assert.Collection( + Assert.Throws(Action).Errors, + error => Assert.Equal( + ErrorCodes.Schema.InvalidArgument, + error.Code), + error => Assert.Equal( + ErrorCodes.Schema.ArgumentValueTypeWrong, + error.Code), + error => Assert.Equal( + ErrorCodes.Schema.NonNullArgument, + error.Code)); + } + + [Fact] + public void BuiltInScalarsAreRecognized() + { + // arrange + var sourceText = @" type Query { string_field: String string_non_null_field: String! @@ -246,21 +246,21 @@ type Query { bool_non_null_field: Boolean! }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .Use(_ => _) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .Use(_ => _) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void BuiltInScalarsAreRecognized2() - { - // arrange - var sourceText = @" + [Fact] + public void BuiltInScalarsAreRecognized2() + { + // arrange + var sourceText = @" type Query { foo: Foo } @@ -277,21 +277,21 @@ type Foo { } "; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .Use(_ => _) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .Use(_ => _) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void ListTypesAreRecognized() - { - // arrange - var sourceText = @" + [Fact] + public void ListTypesAreRecognized() + { + // arrange + var sourceText = @" type Query { foo: Foo } @@ -306,388 +306,387 @@ type Foo { } "; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .Use(_ => _) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .Use(_ => _) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaBuilder_AnyType() - { - // arrange - var sourceText = "type Query { hello: Any }"; + [Fact] + public async Task SchemaBuilder_AnyType() + { + // arrange + var sourceText = "type Query { hello: Any }"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(sourceText) + .AddResolver() + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var result = await executor.ExecuteAsync("{ hello }"); + result.ToJson().MatchSnapshot(); + } - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(sourceText) - .AddResolver() - .Create(); + [Fact] + public async Task SchemaFirst_Cursor_Paging() + { + // arrange + var sdl = "type Query { items: [String!] }"; - // assert - IRequestExecutor executor = schema.MakeExecutable(); - IExecutionResult result = await executor.ExecuteAsync("{ hello }"); - result.ToJson().MatchSnapshot(); - } + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType("Query") + .BuildSchemaAsync(); - [Fact] - public async Task SchemaFirst_Cursor_Paging() - { - // arrange - var sdl = "type Query { items: [String!] }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType("Query") - .BuildSchemaAsync(); - - // assert - schema.Print().MatchSnapshot(); - } + // assert + schema.Print().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_Cursor_OffsetPaging() - { - // arrange - var sdl = "type Query { items: [String!] }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType("Query") - .BuildSchemaAsync(); - - // assert - schema.Print().MatchSnapshot(); - } + [Fact] + public async Task SchemaFirst_Cursor_OffsetPaging() + { + // arrange + var sdl = "type Query { items: [String!] }"; - [Fact] - public async Task SchemaFirst_Cursor_Paging_With_Objects() - { - // arrange - var sdl = "type Query { items: [Person!] } type Person { name: String }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType("Query") - .BuildSchemaAsync(); - - // assert - schema.Print().MatchSnapshot(); - } + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType("Query") + .BuildSchemaAsync(); - // we need to apply the changes we did to cursor paging to offset paging. - [Fact(Skip = "Offset paging for schema first is not supported in 12.")] - public async Task SchemaFirst_Cursor_OffSetPaging_With_Objects() - { - // arrange - var sdl = "type Query { items: [Person!] } type Person { name: String }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType("Query") - .BuildSchemaAsync(); - - // assert - schema.Print().MatchSnapshot(); - } + // assert + schema.Print().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_Cursor_Paging_Execute() - { - // arrange - var sdl = "type Query { items: [String!] }"; - - // act - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType("Query") - .ExecuteRequestAsync("{ items { nodes } }"); - - // assert - result.MatchSnapshot(); - } + [Fact] + public async Task SchemaFirst_Cursor_Paging_With_Objects() + { + // arrange + var sdl = "type Query { items: [Person!] } type Person { name: String }"; - [Fact] - public async Task SchemaFirst_Cursor_Paging_With_Objects_Execute() - { - // arrange - var sdl = "type Query { items: [Person!] } type Person { name: String }"; - - // act - IExecutionResult result = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType("Query") - .ExecuteRequestAsync("{ items { nodes { name } } }"); - - // assert - result.MatchSnapshot(); - } + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType("Query") + .BuildSchemaAsync(); - [Fact] - public async Task SchemaFirst_Cursor_Paging_With_Resolver() - { - // arrange - var sdl = "type Query { items: [String!] }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .AddResolver("Query") - .BuildSchemaAsync(); - - // assert - schema.Print().MatchSnapshot(); - } + // assert + schema.Print().MatchSnapshot(); + } - [Fact] - public async Task Reference_Schema_First_Types_From_Code_First_Models() - { - // arrange - var sdl = "type Person { name: String! }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .AddQueryType() - .BindRuntimeType() - .BuildSchemaAsync(); - - // assert - schema.Print().MatchSnapshot(); - } + // we need to apply the changes we did to cursor paging to offset paging. + [Fact(Skip = "Offset paging for schema first is not supported in 12.")] + public async Task SchemaFirst_Cursor_OffSetPaging_With_Objects() + { + // arrange + var sdl = "type Query { items: [Person!] } type Person { name: String }"; - [Fact] - public async Task Apply_Schema_Building_Directive() - { - // arrange - var sdl = "type Person { name: String! @desc(value: \"abc\") }"; - - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .AddQueryType() - .BindRuntimeType() - .ConfigureSchema(sb => sb.AddSchemaDirective(new CustomDescriptionDirective())) - .BuildSchemaAsync(); - - // assert - Assert.Equal( - "abc", - schema.GetType("Person")?.Fields["name"].Description); - } + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType("Query") + .BuildSchemaAsync(); - [Fact] - public async Task Ensure_Input_Only_Enums_Are_Correctly_Bound() - { + // assert + schema.Print().MatchSnapshot(); + } + + [Fact] + public async Task SchemaFirst_Cursor_Paging_Execute() + { + // arrange + var sdl = "type Query { items: [String!] }"; + // act + var result = await new ServiceCollection() .AddGraphQL() - .AddDocumentFromString(@" + .AddDocumentFromString(sdl) + .BindRuntimeType("Query") + .ExecuteRequestAsync("{ items { nodes } }"); + + // assert + result.MatchSnapshot(); + } + + [Fact] + public async Task SchemaFirst_Cursor_Paging_With_Objects_Execute() + { + // arrange + var sdl = "type Query { items: [Person!] } type Person { name: String }"; + + // act + var result = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType("Query") + .ExecuteRequestAsync("{ items { nodes { name } } }"); + + // assert + result.MatchSnapshot(); + } + + [Fact] + public async Task SchemaFirst_Cursor_Paging_With_Resolver() + { + // arrange + var sdl = "type Query { items: [String!] }"; + + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .AddResolver("Query") + .BuildSchemaAsync(); + + // assert + schema.Print().MatchSnapshot(); + } + + [Fact] + public async Task Reference_Schema_First_Types_From_Code_First_Models() + { + // arrange + var sdl = "type Person { name: String! }"; + + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .AddQueryType() + .BindRuntimeType() + .BuildSchemaAsync(); + + // assert + schema.Print().MatchSnapshot(); + } + + [Fact] + public async Task Apply_Schema_Building_Directive() + { + // arrange + var sdl = "type Person { name: String! @desc(value: \"abc\") }"; + + // act + var schema = + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .AddQueryType() + .BindRuntimeType() + .ConfigureSchema(sb => sb.AddSchemaDirective(new CustomDescriptionDirective())) + .BuildSchemaAsync(); + + // assert + Assert.Equal( + "abc", + schema.GetType("Person")?.Fields["name"].Description); + } + + [Fact] + public async Task Ensure_Input_Only_Enums_Are_Correctly_Bound() + { + + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(@" type Query { book(input: TestEnumInput): TestEnum } enum TestEnumInput { FOO_BAR_INPUT } enum TestEnum { FOO_BAR }") - .AddResolver("Query") - .ExecuteRequestAsync("{ book(input: FOO_BAR_INPUT) }") - .MatchSnapshotAsync(); - } + .AddResolver("Query") + .ExecuteRequestAsync("{ book(input: FOO_BAR_INPUT) }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Default_Values_With_Inputs_Are_Applied() - { - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(@" + [Fact] + public async Task Ensure_Default_Values_With_Inputs_Are_Applied() + { + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(@" type Query { book(input: Foo): String } input Foo { bar: String = ""baz"" }") - .AddResolver("Query") - .ExecuteRequestAsync("{ book(input: { }) }") - .MatchSnapshotAsync(); - } + .AddResolver("Query") + .ExecuteRequestAsync("{ book(input: { }) }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Default_Values_With_Inputs_Can_Be_Overriden() - { - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(@" + [Fact] + public async Task Ensure_Default_Values_With_Inputs_Can_Be_Overriden() + { + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(@" type Query { book(input: Foo): String } input Foo { bar: String = ""baz"" }") - .AddResolver("Query") - .ExecuteRequestAsync("{ book(input: { bar: \"baz123\" }) }") - .MatchSnapshotAsync(); - } + .AddResolver("Query") + .ExecuteRequestAsync("{ book(input: { bar: \"baz123\" }) }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Ensure_Input_Only_Enums_Are_Correctly_Bound_When_Using_BindRuntimeType() - { + [Fact] + public async Task Ensure_Input_Only_Enums_Are_Correctly_Bound_When_Using_BindRuntimeType() + { - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(@" + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(@" type Query { book(input: TestEnumInput): TestEnum } enum TestEnumInput { FOO_BAR_INPUT } enum TestEnum { FOO_BAR }") - .BindRuntimeType("Query") - .ExecuteRequestAsync("{ book(input: FOO_BAR_INPUT) }") - .MatchSnapshotAsync(); - } + .BindRuntimeType("Query") + .ExecuteRequestAsync("{ book(input: FOO_BAR_INPUT) }") + .MatchSnapshotAsync(); + } - public class Query - { - public string Hello() => "World"; - } + public class Query + { + public string Hello() => "World"; + } - public class QueryWithItems - { - [UsePaging] - public string[] GetItems() => new[] { "a", "b" }; - } + public class QueryWithItems + { + [UsePaging] + public string[] GetItems() => new[] { "a", "b" }; + } - public class QueryWithOffsetItems - { - [UseOffsetPaging] - public string[] GetItems() => new[] { "a", "b" }; - } + public class QueryWithOffsetItems + { + [UseOffsetPaging] + public string[] GetItems() => new[] { "a", "b" }; + } - public class QueryWithPersons - { - [UsePaging] - public Person[] GetItems() => new[] { new Person { Name = "Foo" } }; - } + public class QueryWithPersons + { + [UsePaging] + public Person[] GetItems() => new[] { new Person { Name = "Foo" } }; + } - public class QueryWithOffsetPersons - { - [UseOffsetPaging] - public Person[] GetItems() => new[] { new Person { Name = "Foo" } }; - } + public class QueryWithOffsetPersons + { + [UseOffsetPaging] + public Person[] GetItems() => new[] { new Person { Name = "Foo" } }; + } - public class QueryCodeFirst - { - [GraphQLType("Person!")] - public object GetPerson() => new Person { Name = "Hello" }; - } + public class QueryCodeFirst + { + [GraphQLType("Person!")] + public object GetPerson() => new Person { Name = "Hello" }; + } - public class Person - { - public string Name { get; set; } - } + public class Person + { + public string Name { get; set; } + } - public class CustomDescriptionDirective : ISchemaDirective - { - public NameString Name => "desc"; + public class CustomDescriptionDirective : ISchemaDirective + { + public NameString Name => "desc"; - public void ApplyConfiguration( - IDescriptorContext context, - DirectiveNode directiveNode, - IDefinition definition, - Stack path) + public void ApplyConfiguration( + IDescriptorContext context, + DirectiveNode directiveNode, + IDefinition definition, + Stack path) + { + if (definition is ObjectFieldDefinition objectField) { - if (definition is ObjectFieldDefinition objectField) - { - objectField.Description = (string)directiveNode.Arguments.First().Value.Value; - } + objectField.Description = (string)directiveNode.Arguments.First().Value.Value; } } + } - public class PetQuery - { - public IPet GetPet() => new Cat("Mauzi"); - } + public class PetQuery + { + public IPet GetPet() => new Cat("Mauzi"); + } - public interface IPet - { - string Name { get; } - } + public interface IPet + { + string Name { get; } + } - public class Cat : IPet + public class Cat : IPet + { + public Cat(string name) { - public Cat(string name) - { - Name = name; - } - - public string Name { get; } + Name = name; } - public class Dog : IPet - { - public Dog(string name) - { - Name = name; - } - - public string Name { get; } - } + public string Name { get; } } - public class QueryEnumExample + public class Dog : IPet { - public TestEnum GetBook(TestEnumInput input) + public Dog(string name) { - return TestEnum.FooBar; + Name = name; } - } - public enum TestEnum - { - FooBar + public string Name { get; } } +} - public enum TestEnumInput +public class QueryEnumExample +{ + public TestEnum GetBook(TestEnumInput input) { - FooBarInput + return TestEnum.FooBar; } +} - public class QueryWithFooInput - { - public string GetBook(Foo input) => input.Bar; - } +public enum TestEnum +{ + FooBar +} - public class Foo - { - public Foo(string bar) - { - Bar = bar; - } +public enum TestEnumInput +{ + FooBarInput +} + +public class QueryWithFooInput +{ + public string GetBook(Foo input) => input.Bar; +} - public string Bar { get; } +public class Foo +{ + public Foo(string bar) + { + Bar = bar; } + + public string Bar { get; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/SchemaSerializerTests.cs b/src/HotChocolate/Core/test/Types.Tests/SchemaSerializerTests.cs index 883b657258a..0f63b89743f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/SchemaSerializerTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/SchemaSerializerTests.cs @@ -8,210 +8,209 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate +namespace HotChocolate; + +public class SchemaSerializerTests { - public class SchemaSerializerTests + [Fact] + public void Serialize_SchemaIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => SchemaSerializer.Serialize(null); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void SerializeSchemaWriter_SchemaIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => SchemaSerializer.Serialize(null, new StringWriter()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void SerializeSchemaWriter_WriterIsNull_ArgumentNullException() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", "bar") + .Create(); + + // act + void Action() => SchemaSerializer.Serialize(schema, null); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void SerializeAsync_SchemaIsNull_ArgumentNullException() + { + // arrange + // act + async Task Action() => await SchemaSerializer.SerializeAsync( + default(ISchema), + new MemoryStream()); + + // assert + Assert.ThrowsAsync(Action); + } + + [Fact] + public void SerializeAsync_WriterIsNull_ArgumentNullException() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", "bar") + .Create(); + + // act + async Task Action() => await SchemaSerializer.SerializeAsync(schema, null); + + // assert + Assert.ThrowsAsync(Action); + } + + [Fact] + public void SerializeSchemaWriter_Serialize() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", "bar") + .Create(); + var stringBuilder = new StringBuilder(); + + // act + SchemaSerializer.Serialize(schema, new StringWriter(stringBuilder)); + + // assert + stringBuilder.ToString().MatchSnapshot(); + } + + [Fact] + public async Task SerializeAsync_Serialize() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString("type Query { foo: String }") + .AddResolver("Query", "foo", "bar") + .Create(); + using var stream = new MemoryStream(); + + // act + await SchemaSerializer.SerializeAsync(schema, stream); + + // assert + Encoding.UTF8.GetString(stream.ToArray()).MatchSnapshot(); + } + + [Fact] + public void SerializeSchemaWithDirective() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(FileResource.Open("serialize_schema.graphql")) + .AddDirectiveType(new DirectiveType(t => t + .Name("upper") + .Location(DirectiveLocation.FieldDefinition))) + .Use(next => next) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // act + var serializedSchema = schema.ToString(); + + // assert + serializedSchema.MatchSnapshot(); + } + + [Fact] + public void SerializeSchemaWithMutationWithoutSubscription() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) + .Use(next => next) + .Create(); + + // act + var serializedSchema = schema.ToString(); + + // assert + serializedSchema.MatchSnapshot(); + } + + [Fact] + public async Task SerializeTypes() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) + .Use(next => next) + .Create(); + + // act + using var stream = new MemoryStream(); + await SchemaSerializer.SerializeAsync( + new INamedType[] { schema.QueryType }, + stream, + true); + + // assert + Encoding.UTF8.GetString(stream.ToArray()).MatchSnapshot(); + } + + [Fact] + public async Task SerializeTypes_Types_Is_Null() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) + .Use(next => next) + .Create(); + + // act + using var stream = new MemoryStream(); + async Task Fail() => await SchemaSerializer.SerializeAsync( + default(IEnumerable), + stream, + true); + + // assert + await Assert.ThrowsAsync(Fail); + } + + [Fact] + public async Task SerializeTypes_Stream_Is_Null() + { + // arrange + var schema = SchemaBuilder.New() + .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) + .Use(next => next) + .Create(); + + // act + using var stream = new MemoryStream(); + async Task Fail() => await SchemaSerializer.SerializeAsync( + new INamedType[] { schema.QueryType }, + null, + true); + + // assert + await Assert.ThrowsAsync(Fail); + } + + public class Query { - [Fact] - public void Serialize_SchemaIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => SchemaSerializer.Serialize(null); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void SerializeSchemaWriter_SchemaIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => SchemaSerializer.Serialize(null, new StringWriter()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void SerializeSchemaWriter_WriterIsNull_ArgumentNullException() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", "bar") - .Create(); - - // act - void Action() => SchemaSerializer.Serialize(schema, null); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void SerializeAsync_SchemaIsNull_ArgumentNullException() - { - // arrange - // act - async Task Action() => await SchemaSerializer.SerializeAsync( - default(ISchema), - new MemoryStream()); - - // assert - Assert.ThrowsAsync(Action); - } - - [Fact] - public void SerializeAsync_WriterIsNull_ArgumentNullException() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", "bar") - .Create(); - - // act - async Task Action() => await SchemaSerializer.SerializeAsync(schema, null); - - // assert - Assert.ThrowsAsync(Action); - } - - [Fact] - public void SerializeSchemaWriter_Serialize() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", "bar") - .Create(); - var stringBuilder = new StringBuilder(); - - // act - SchemaSerializer.Serialize(schema, new StringWriter(stringBuilder)); - - // assert - stringBuilder.ToString().MatchSnapshot(); - } - - [Fact] - public async Task SerializeAsync_Serialize() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString("type Query { foo: String }") - .AddResolver("Query", "foo", "bar") - .Create(); - using var stream = new MemoryStream(); - - // act - await SchemaSerializer.SerializeAsync(schema, stream); - - // assert - Encoding.UTF8.GetString(stream.ToArray()).MatchSnapshot(); - } - - [Fact] - public void SerializeSchemaWithDirective() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(FileResource.Open("serialize_schema.graphql")) - .AddDirectiveType(new DirectiveType(t => t - .Name("upper") - .Location(DirectiveLocation.FieldDefinition))) - .Use(next => next) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // act - var serializedSchema = schema.ToString(); - - // assert - serializedSchema.MatchSnapshot(); - } - - [Fact] - public void SerializeSchemaWithMutationWithoutSubscription() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) - .Use(next => next) - .Create(); - - // act - var serializedSchema = schema.ToString(); - - // assert - serializedSchema.MatchSnapshot(); - } - - [Fact] - public async Task SerializeTypes() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) - .Use(next => next) - .Create(); - - // act - using var stream = new MemoryStream(); - await SchemaSerializer.SerializeAsync( - new INamedType[] { schema.QueryType }, - stream, - true); - - // assert - Encoding.UTF8.GetString(stream.ToArray()).MatchSnapshot(); - } - - [Fact] - public async Task SerializeTypes_Types_Is_Null() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) - .Use(next => next) - .Create(); - - // act - using var stream = new MemoryStream(); - async Task Fail() => await SchemaSerializer.SerializeAsync( - default(IEnumerable), - stream, - true); - - // assert - await Assert.ThrowsAsync(Fail); - } - - [Fact] - public async Task SerializeTypes_Stream_Is_Null() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(FileResource.Open("serialize_schema_with_mutation.graphql")) - .Use(next => next) - .Create(); - - // act - using var stream = new MemoryStream(); - async Task Fail() => await SchemaSerializer.SerializeAsync( - new INamedType[] { schema.QueryType }, - null, - true); - - // assert - await Assert.ThrowsAsync(Fail); - } - - public class Query - { - public string Bar { get; set; } - } + public string Bar { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/TestUtils.cs b/src/HotChocolate/Core/test/Types.Tests/TestUtils.cs index 31986be091f..ba54d3a0c43 100644 --- a/src/HotChocolate/Core/test/Types.Tests/TestUtils.cs +++ b/src/HotChocolate/Core/test/Types.Tests/TestUtils.cs @@ -1,17 +1,16 @@ using System; -namespace HotChocolate +namespace HotChocolate; + +public static class TestUtils { - public static class TestUtils + public static string CreateTypeName() { - public static string CreateTypeName() - { - return "Type_" + Guid.NewGuid().ToString("N"); - } + return "Type_" + Guid.NewGuid().ToString("N"); + } - public static string CreateFieldName() - { - return "field_" + Guid.NewGuid().ToString("N"); - } + public static string CreateFieldName() + { + return "field_" + Guid.NewGuid().ToString("N"); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/RequiredAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/RequiredAttributeTests.cs index d2a358cd360..ced8d02419c 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/RequiredAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/RequiredAttributeTests.cs @@ -7,48 +7,47 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class RequiredAttributeTests { - public class RequiredAttributeTests + [Fact] + public void Infer_RequiredAttribute_As_NonNull() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Ignore_RequiredAttribute() + { + // arrange + var inspector = new DefaultTypeInspector(ignoreRequiredAttribute: true); + var services = new DictionaryServiceProvider(typeof(ITypeInspector), inspector); + + // act & assert + SchemaBuilder.New() + .AddQueryType() + .AddServices(services) + .Create() + .Print() + .MatchSnapshot(); + } + + public class Foo + { + [Required] + public string? SomeString { get; } + + public string? AddFoo([Required] Bar? input) => throw new NotSupportedException(); + } + + public class Bar { - [Fact] - public void Infer_RequiredAttribute_As_NonNull() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Ignore_RequiredAttribute() - { - // arrange - var inspector = new DefaultTypeInspector(ignoreRequiredAttribute: true); - var services = new DictionaryServiceProvider(typeof(ITypeInspector), inspector); - - // act & assert - SchemaBuilder.New() - .AddQueryType() - .AddServices(services) - .Create() - .Print() - .MatchSnapshot(); - } - - public class Foo - { - [Required] - public string? SomeString { get; } - - public string? AddFoo([Required] Bar? input) => throw new NotSupportedException(); - } - - public class Bar - { - [Required] - public string? Foo { get; set; } - } + [Required] + public string? Foo { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/UseServiceScopeAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/UseServiceScopeAttributeTests.cs index 2dbf01203e2..6e4b20e002b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/UseServiceScopeAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Attributes/UseServiceScopeAttributeTests.cs @@ -5,44 +5,43 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class UseServiceScopeAttributeTests { - public class UseServiceScopeAttributeTests + [Fact] + public async Task UseServiceScope() { - [Fact] - public async Task UseServiceScope() - { - // arrange - Snapshot.FullName(); + // arrange + Snapshot.FullName(); - // assert - IExecutionResult result = await new ServiceCollection() - .AddScoped() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ a: scoped b: scoped }"); + // assert + var result = await new ServiceCollection() + .AddScoped() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ a: scoped b: scoped }"); - // assert - Assert.Null(result.ExpectQueryResult().Errors); - IQueryResult queryResult = Assert.IsAssignableFrom(result); - Assert.NotEqual(queryResult.Data!["a"], queryResult.Data!["b"]); - } + // assert + Assert.Null(result.ExpectQueryResult().Errors); + var queryResult = Assert.IsAssignableFrom(result); + Assert.NotEqual(queryResult.Data!["a"], queryResult.Data!["b"]); + } - [Fact] - public void UseServiceScope_FieldDescriptor() - => Assert.Throws( - () => default(IObjectFieldDescriptor).UseServiceScope()); + [Fact] + public void UseServiceScope_FieldDescriptor() + => Assert.Throws( + () => default(IObjectFieldDescriptor).UseServiceScope()); - public class Query - { - [UseServiceScope] - public string GetScoped([Service] Service service) - => service.Id; - } + public class Query + { + [UseServiceScope] + public string GetScoped([Service] Service service) + => service.Id; + } - public class Service - { - public string Id { get; } = Guid.NewGuid().ToString("N"); - } + public class Service + { + public string Id { get; } = Guid.NewGuid().ToString("N"); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ArgumentDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ArgumentDescriptorTests.cs index dc87fc0c37c..242aa980f71 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ArgumentDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ArgumentDescriptorTests.cs @@ -5,245 +5,244 @@ using HotChocolate.Types.Descriptors.Definitions; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ArgumentDescriptorTests + : DescriptorTestBase { - public class ArgumentDescriptorTests - : DescriptorTestBase - { - [Fact] - public void Create_TypeIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => new ArgumentDescriptor(Context, "Type", null); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void DotNetTypesDoNotOverwriteSchemaTypes() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "Type"); - - // act - descriptor - .Type>() - .Type>>(); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal(typeof(ListType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SetTypeInstance() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "Type"); - - // act - descriptor.Type(new StringType()); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.IsType( - Assert.IsType(typeRef).Type); - } - - [Fact] - public void SetGenericType() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "Type"); - - // act - descriptor.Type(); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(StringType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SetNonGenericType() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "Type"); - - // act - descriptor.Type(typeof(StringType)); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(StringType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SchemaTypesOverwriteDotNetTypes() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "Type"); - - // act - ((IArgumentDescriptor)descriptor) - .Type>>() - .Type>(); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(ListType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void GetName() - { - // act - var descriptor = new ArgumentDescriptor(Context, "args"); - - // assert - Assert.Equal("args", descriptor.CreateDefinition().Name); - } - - [Fact] - public void GetNameAndType() - { - // act - var descriptor = new ArgumentDescriptor( - Context, "args", typeof(string)); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - Assert.Equal("args", description.Name); - Assert.Equal(typeof(string), - Assert.IsType(description.Type).Type.Source); - } - - [Fact] - public void SetDescription() - { - // arrange - string expectedDescription = Guid.NewGuid().ToString(); - var descriptor = new ArgumentDescriptor(Context, "Type"); - - // act - descriptor.Description(expectedDescription); - - // assert - Assert.Equal(expectedDescription, - descriptor.CreateDefinition().Description); - } - - [Fact] - public void SetDefaultValueAndInferType() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "args"); - - // act - descriptor.DefaultValue("string"); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - Assert.Equal(typeof(string), - Assert.IsType(description.Type).Type.Source); - Assert.Equal("string", - description.RuntimeDefaultValue); - } - - [Fact] - public void SetDefaultValueNull() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "args"); - - // act - descriptor.DefaultValue(null); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - Assert.Equal(NullValueNode.Default, description.DefaultValue); - Assert.Null(description.RuntimeDefaultValue); - } - - [Fact] - public void OverwriteDefaultValueLiteralWithNativeDefaultValue() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "args"); - - // act - descriptor - .DefaultValue(new StringValueNode("123")) - .DefaultValue("string"); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - Assert.Null(description.DefaultValue); - Assert.Equal("string", description.RuntimeDefaultValue); - } - - [Fact] - public void SettingTheNativeDefaultValueToNullCreatesNullLiteral() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "args"); - - // act - descriptor - .DefaultValue(new StringValueNode("123")) - .DefaultValue("string") - .DefaultValue(null); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - Assert.IsType(description.DefaultValue); - Assert.Null(description.RuntimeDefaultValue); - } - - [Fact] - public void OverwriteNativeDefaultValueWithDefaultValueLiteral() - { - // arrange - var descriptor = new ArgumentDescriptor(Context, "args"); - - // act - descriptor - .DefaultValue("string") - .DefaultValue(new StringValueNode("123")); - - // assert - ArgumentDefinition description = descriptor.CreateDefinition(); - Assert.IsType(description.DefaultValue); - Assert.Equal("123", ((StringValueNode)description.DefaultValue).Value); - Assert.Null(description.RuntimeDefaultValue); - } - - [Fact] - public void Type_Syntax_Type_Null() - { - void Error() => ArgumentDescriptor.New(Context, "foo").Type((string)null); - Assert.Throws(Error); - } - - [Fact] - public void Type_Syntax_Descriptor_Null() - { - void Error() => default(ArgumentDescriptor).Type("foo"); - Assert.Throws(Error); - } + [Fact] + public void Create_TypeIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => new ArgumentDescriptor(Context, "Type", null); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void DotNetTypesDoNotOverwriteSchemaTypes() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "Type"); + + // act + descriptor + .Type>() + .Type>>(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal(typeof(ListType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SetTypeInstance() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "Type"); + + // act + descriptor.Type(new StringType()); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.IsType( + Assert.IsType(typeRef).Type); + } + + [Fact] + public void SetGenericType() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "Type"); + + // act + descriptor.Type(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(StringType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SetNonGenericType() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "Type"); + + // act + descriptor.Type(typeof(StringType)); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(StringType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SchemaTypesOverwriteDotNetTypes() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "Type"); + + // act + ((IArgumentDescriptor)descriptor) + .Type>>() + .Type>(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(ListType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void GetName() + { + // act + var descriptor = new ArgumentDescriptor(Context, "args"); + + // assert + Assert.Equal("args", descriptor.CreateDefinition().Name); + } + + [Fact] + public void GetNameAndType() + { + // act + var descriptor = new ArgumentDescriptor( + Context, "args", typeof(string)); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal("args", description.Name); + Assert.Equal(typeof(string), + Assert.IsType(description.Type).Type.Source); + } + + [Fact] + public void SetDescription() + { + // arrange + var expectedDescription = Guid.NewGuid().ToString(); + var descriptor = new ArgumentDescriptor(Context, "Type"); + + // act + descriptor.Description(expectedDescription); + + // assert + Assert.Equal(expectedDescription, + descriptor.CreateDefinition().Description); + } + + [Fact] + public void SetDefaultValueAndInferType() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "args"); + + // act + descriptor.DefaultValue("string"); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal(typeof(string), + Assert.IsType(description.Type).Type.Source); + Assert.Equal("string", + description.RuntimeDefaultValue); + } + + [Fact] + public void SetDefaultValueNull() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "args"); + + // act + descriptor.DefaultValue(null); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal(NullValueNode.Default, description.DefaultValue); + Assert.Null(description.RuntimeDefaultValue); + } + + [Fact] + public void OverwriteDefaultValueLiteralWithNativeDefaultValue() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "args"); + + // act + descriptor + .DefaultValue(new StringValueNode("123")) + .DefaultValue("string"); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Null(description.DefaultValue); + Assert.Equal("string", description.RuntimeDefaultValue); + } + + [Fact] + public void SettingTheNativeDefaultValueToNullCreatesNullLiteral() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "args"); + + // act + descriptor + .DefaultValue(new StringValueNode("123")) + .DefaultValue("string") + .DefaultValue(null); + + // assert + var description = descriptor.CreateDefinition(); + Assert.IsType(description.DefaultValue); + Assert.Null(description.RuntimeDefaultValue); + } + + [Fact] + public void OverwriteNativeDefaultValueWithDefaultValueLiteral() + { + // arrange + var descriptor = new ArgumentDescriptor(Context, "args"); + + // act + descriptor + .DefaultValue("string") + .DefaultValue(new StringValueNode("123")); + + // assert + var description = descriptor.CreateDefinition(); + Assert.IsType(description.DefaultValue); + Assert.Equal("123", ((StringValueNode)description.DefaultValue).Value); + Assert.Null(description.RuntimeDefaultValue); + } + + [Fact] + public void Type_Syntax_Type_Null() + { + void Error() => ArgumentDescriptor.New(Context, "foo").Type((string)null); + Assert.Throws(Error); + } + + [Fact] + public void Type_Syntax_Descriptor_Null() + { + void Error() => default(ArgumentDescriptor).Type("foo"); + Assert.Throws(Error); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultNamingConventionsTypes.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultNamingConventionsTypes.cs index 2ea38fd9a35..6d767104cdb 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultNamingConventionsTypes.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultNamingConventionsTypes.cs @@ -1,137 +1,136 @@ using System; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class DefaultNamingConventionsTests { - public class DefaultNamingConventionsTests + [InlineData("Foo", "FOO")] + [InlineData("FooBar", "FOO_BAR")] + [InlineData("FooBarBaz", "FOO_BAR_BAZ")] + [InlineData("StringGUID", "STRING_GUID")] + [InlineData("IPAddress", "IP_ADDRESS")] + [InlineData("FOO_BAR_BAZ", "FOO_BAR_BAZ")] + [InlineData("FOOBAR", "FOOBAR")] + [InlineData("F", "F")] + [InlineData("f", "F")] + [Theory] + public void GetEnumName(string runtimeName, string expectedSchemaName) + { + // arrange + var namingConventions = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + + // act + var schemaName = namingConventions.GetEnumValueName(runtimeName); + + // assert + Assert.Equal(expectedSchemaName, schemaName.Value); + } + + [InlineData(true)] + [InlineData(1)] + [InlineData("abc")] + [InlineData(Foo.Bar)] + [Theory] + public void GetEnumValueDescription_NoDescription(object value) + { + // arrange + var namingConventions = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + + // act + var result = namingConventions.GetEnumValueDescription(value); + + // assert + Assert.Null(result); + } + + [Fact] + public void GetEnumValueDescription_XmlDescription() + { + // arrange + var namingConventions = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + + // act + var result = namingConventions.GetEnumValueDescription(EnumWithDocEnum.Value1); + + // assert + Assert.Equal("Value1 Documentation", result); + } + + [Fact] + public void GetEnumValueDescription_AttributeDescription() + { + // arrange + var namingConventions = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + // act + var result = namingConventions.GetEnumValueDescription(Foo.Baz); + + // assert + Assert.Equal("Baz Desc", result); + } + + [InlineData(typeof(MyInputType), "MyInput")] + [InlineData(typeof(MyType), "MyTypeInput")] + [InlineData(typeof(MyInput), "MyInput")] + [InlineData(typeof(YourInputType), "YourInputTypeInput")] + [InlineData(typeof(YourInput), "YourInput")] + [InlineData(typeof(Your), "YourInput")] + [Theory] + public void Input_Naming_Convention(Type type, string expectedName) + { + // arrange + var namingConventions = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + + // act + var typeName = namingConventions.GetTypeName(type, TypeKind.InputObject); + + // assert + Assert.Equal(expectedName, typeName.Value); + } + + private enum Foo + { + Bar, + + [GraphQLDescription("Baz Desc")] Baz + } + + private sealed class MyInputType : InputObjectType + { + } + + private sealed class MyType : InputObjectType + { + } + + private sealed class MyInput : InputObjectType + { + } + + public class YourInputType + { + } + + public class YourInput + { + } + + public class Your { - [InlineData("Foo", "FOO")] - [InlineData("FooBar", "FOO_BAR")] - [InlineData("FooBarBaz", "FOO_BAR_BAZ")] - [InlineData("StringGUID", "STRING_GUID")] - [InlineData("IPAddress", "IP_ADDRESS")] - [InlineData("FOO_BAR_BAZ", "FOO_BAR_BAZ")] - [InlineData("FOOBAR", "FOOBAR")] - [InlineData("F", "F")] - [InlineData("f", "F")] - [Theory] - public void GetEnumName(string runtimeName, string expectedSchemaName) - { - // arrange - var namingConventions = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - - // act - NameString schemaName = namingConventions.GetEnumValueName(runtimeName); - - // assert - Assert.Equal(expectedSchemaName, schemaName.Value); - } - - [InlineData(true)] - [InlineData(1)] - [InlineData("abc")] - [InlineData(Foo.Bar)] - [Theory] - public void GetEnumValueDescription_NoDescription(object value) - { - // arrange - var namingConventions = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - - // act - var result = namingConventions.GetEnumValueDescription(value); - - // assert - Assert.Null(result); - } - - [Fact] - public void GetEnumValueDescription_XmlDescription() - { - // arrange - var namingConventions = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - - // act - var result = namingConventions.GetEnumValueDescription(EnumWithDocEnum.Value1); - - // assert - Assert.Equal("Value1 Documentation", result); - } - - [Fact] - public void GetEnumValueDescription_AttributeDescription() - { - // arrange - var namingConventions = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - // act - var result = namingConventions.GetEnumValueDescription(Foo.Baz); - - // assert - Assert.Equal("Baz Desc", result); - } - - [InlineData(typeof(MyInputType), "MyInput")] - [InlineData(typeof(MyType), "MyTypeInput")] - [InlineData(typeof(MyInput), "MyInput")] - [InlineData(typeof(YourInputType), "YourInputTypeInput")] - [InlineData(typeof(YourInput), "YourInput")] - [InlineData(typeof(Your), "YourInput")] - [Theory] - public void Input_Naming_Convention(Type type, string expectedName) - { - // arrange - var namingConventions = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - - // act - NameString typeName = namingConventions.GetTypeName(type, TypeKind.InputObject); - - // assert - Assert.Equal(expectedName, typeName.Value); - } - - private enum Foo - { - Bar, - - [GraphQLDescription("Baz Desc")] Baz - } - - private sealed class MyInputType : InputObjectType - { - } - - private sealed class MyType : InputObjectType - { - } - - private sealed class MyInput : InputObjectType - { - } - - public class YourInputType - { - } - - public class YourInput - { - } - - public class Your - { - } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultTypeInspectorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultTypeInspectorTests.cs index eb765a8b02d..6e440619c6a 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultTypeInspectorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/DefaultTypeInspectorTests.cs @@ -6,815 +6,814 @@ using HotChocolate.Internal; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class DefaultTypeInspectorTests { - public class DefaultTypeInspectorTests + [Fact] + public void Discover_Property_That_Returns_Object_And_Has_TypeAttribute() { - [Fact] - public void Discover_Property_That_Returns_Object_And_Has_TypeAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(ObjectPropWithTypeAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(ObjectPropWithTypeAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Property_That_Returns_Object_And_Has_DescriptorAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Property_That_Returns_Object_And_Has_DescriptorAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(ObjectPropWithDescriptorAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(ObjectPropWithDescriptorAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_That_Returns_Object_And_Has_TypeAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_That_Returns_Object_And_Has_TypeAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(ObjectMethodWithTypeAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(ObjectMethodWithTypeAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_That_Returns_Object_And_Has_DescriptorAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_That_Returns_Object_And_Has_DescriptorAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(ObjectMethodWithDescriptorAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(ObjectMethodWithDescriptorAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_With_Object_Parameter_And_Has_TypeAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_With_Object_Parameter_And_Has_TypeAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers( - typeof(MethodAndObjectParameterWithTypeAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers( + typeof(MethodAndObjectParameterWithTypeAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_With_Object_Parameter_And_Has_DescriptorAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_With_Object_Parameter_And_Has_DescriptorAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers( - typeof(MethodAndObjectParameterWithDescriptorAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers( + typeof(MethodAndObjectParameterWithDescriptorAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_That_Returns_TaskObject_And_Has_TypeAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_That_Returns_TaskObject_And_Has_TypeAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(TaskObjectMethodWithTypeAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(TaskObjectMethodWithTypeAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_That_Returns_TaskObject_And_Has_DescriptorAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_That_Returns_TaskObject_And_Has_DescriptorAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(TaskObjectMethodWithDescriptorAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(TaskObjectMethodWithDescriptorAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_That_Returns_ValueTaskObject_And_Has_TypeAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_That_Returns_ValueTaskObject_And_Has_TypeAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers(typeof(ValueTaskObjectMethodWithTypeAttribute)).ToArray(); + // act + var discovered = + typeInspector.GetMembers(typeof(ValueTaskObjectMethodWithTypeAttribute)).ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void Discover_Method_That_Returns_ValueTaskObject_And_Has_DescriptorAttribute() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void Discover_Method_That_Returns_ValueTaskObject_And_Has_DescriptorAttribute() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo[] discovered = - typeInspector.GetMembers( + // act + var discovered = + typeInspector.GetMembers( typeof(ValueTaskObjectMethodWithDescriptorAttribute)) - .ToArray(); + .ToArray(); - // assert - Assert.Collection(discovered, - p => Assert.Equal("ShouldBeFound", p.Name)); - } + // assert + Assert.Collection(discovered, + p => Assert.Equal("ShouldBeFound", p.Name)); + } - [Fact] - public void GetReturnTypeRef_FromMethod() - { - // arrange - MethodInfo method = typeof(Foo).GetMethod(nameof(Foo.Bar)); - var typeInspector = new DefaultTypeInspector(); - - // act - ITypeReference typeReference = - typeInspector.GetReturnTypeRef(method!, TypeContext.Output); - - // assert - ExtendedTypeReference extTypeRef = Assert.IsType(typeReference); - Assert.Equal("List!", extTypeRef.Type.ToString()); - Assert.Equal(TypeContext.Output, typeReference.Context); - Assert.Null(typeReference.Scope); - } + [Fact] + public void GetReturnTypeRef_FromMethod() + { + // arrange + var method = typeof(Foo).GetMethod(nameof(Foo.Bar)); + var typeInspector = new DefaultTypeInspector(); + + // act + var typeReference = + typeInspector.GetReturnTypeRef(method!, TypeContext.Output); + + // assert + var extTypeRef = Assert.IsType(typeReference); + Assert.Equal("List!", extTypeRef.Type.ToString()); + Assert.Equal(TypeContext.Output, typeReference.Context); + Assert.Null(typeReference.Scope); + } - [Fact] - public void GetReturnTypeRef_FromMethod_With_Scope() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - MethodInfo method = typeof(Foo).GetMethod(nameof(Foo.Bar)); - // act - ITypeReference typeReference = - typeInspector.GetReturnTypeRef(method!, TypeContext.Output, "abc"); - - // assert - ExtendedTypeReference extTypeRef = Assert.IsType(typeReference); - Assert.Equal("List!", extTypeRef.Type.ToString()); - Assert.Equal(TypeContext.Output, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } + [Fact] + public void GetReturnTypeRef_FromMethod_With_Scope() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var method = typeof(Foo).GetMethod(nameof(Foo.Bar)); + // act + var typeReference = + typeInspector.GetReturnTypeRef(method!, TypeContext.Output, "abc"); + + // assert + var extTypeRef = Assert.IsType(typeReference); + Assert.Equal("List!", extTypeRef.Type.ToString()); + Assert.Equal(TypeContext.Output, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } - [Fact] - public void GetReturnTypeRef_FromMethod_Member_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetReturnTypeRef_FromMethod_Member_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => - typeInspector.GetReturnTypeRef(null!, TypeContext.Output); + // act + void Action() => + typeInspector.GetReturnTypeRef(null!, TypeContext.Output); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetReturnType_FromMethod() - { - // arrange - MethodInfo method = typeof(Foo).GetMethod(nameof(Foo.Bar)); - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetReturnType_FromMethod() + { + // arrange + var method = typeof(Foo).GetMethod(nameof(Foo.Bar)); + var typeInspector = new DefaultTypeInspector(); - // act - IExtendedType extendedType = typeInspector.GetReturnType(method!); + // act + var extendedType = typeInspector.GetReturnType(method!); - // assert - Assert.Equal("List!", extendedType.ToString()); - } + // assert + Assert.Equal("List!", extendedType.ToString()); + } - [Fact] - public void GetReturnType_FromMethod_Member_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetReturnType_FromMethod_Member_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetReturnType(null!); + // act + void Action() => typeInspector.GetReturnType(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetArgumentTypeRef() - { - // arrange - ParameterInfo parameter = typeof(Foo).GetMethod(nameof(Foo.Baz))!.GetParameters()[0]; - var typeInspector = new DefaultTypeInspector(); - - // act - ITypeReference typeReference = typeInspector.GetArgumentTypeRef(parameter!); - - // assert - ExtendedTypeReference extTypeRef = Assert.IsType(typeReference); - Assert.Equal("String!", extTypeRef.Type.ToString()); - Assert.Equal(TypeContext.Input, typeReference.Context); - Assert.Null(typeReference.Scope); - } + [Fact] + public void GetArgumentTypeRef() + { + // arrange + var parameter = typeof(Foo).GetMethod(nameof(Foo.Baz))!.GetParameters()[0]; + var typeInspector = new DefaultTypeInspector(); + + // act + var typeReference = typeInspector.GetArgumentTypeRef(parameter!); + + // assert + var extTypeRef = Assert.IsType(typeReference); + Assert.Equal("String!", extTypeRef.Type.ToString()); + Assert.Equal(TypeContext.Input, typeReference.Context); + Assert.Null(typeReference.Scope); + } - [Fact] - public void GetArgumentTypeRef_With_Scope() - { - // arrange - ParameterInfo parameter = typeof(Foo).GetMethod(nameof(Foo.Baz))!.GetParameters()[0]; - var typeInspector = new DefaultTypeInspector(); - - // act - ITypeReference typeReference = typeInspector.GetArgumentTypeRef(parameter!, "abc"); - - // assert - ExtendedTypeReference extTypeRef = Assert.IsType(typeReference); - Assert.Equal("String!", extTypeRef.Type.ToString()); - Assert.Equal(TypeContext.Input, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } + [Fact] + public void GetArgumentTypeRef_With_Scope() + { + // arrange + var parameter = typeof(Foo).GetMethod(nameof(Foo.Baz))!.GetParameters()[0]; + var typeInspector = new DefaultTypeInspector(); + + // act + var typeReference = typeInspector.GetArgumentTypeRef(parameter!, "abc"); + + // assert + var extTypeRef = Assert.IsType(typeReference); + Assert.Equal("String!", extTypeRef.Type.ToString()); + Assert.Equal(TypeContext.Input, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } - [Fact] - public void GetMemberType_With_SyntaxTypeRef() - { - // arrange - PropertyInfo property = - typeof(ObjectPropWithSyntaxType) - .GetProperty(nameof(ObjectPropWithSyntaxType.ShouldBeFound))!; - var typeInspector = new DefaultTypeInspector(); - - // act - ITypeReference typeReference = typeInspector.GetReturnTypeRef(property!); - - // assert - SyntaxTypeReference extTypeRef = Assert.IsType(typeReference); - Assert.Equal("[String]", extTypeRef.Type.ToString()); - Assert.Equal(TypeContext.None, typeReference.Context); - Assert.Null(typeReference.Scope); - } + [Fact] + public void GetMemberType_With_SyntaxTypeRef() + { + // arrange + var property = + typeof(ObjectPropWithSyntaxType) + .GetProperty(nameof(ObjectPropWithSyntaxType.ShouldBeFound))!; + var typeInspector = new DefaultTypeInspector(); + + // act + var typeReference = typeInspector.GetReturnTypeRef(property!); + + // assert + var extTypeRef = Assert.IsType(typeReference); + Assert.Equal("[String]", extTypeRef.Type.ToString()); + Assert.Equal(TypeContext.None, typeReference.Context); + Assert.Null(typeReference.Scope); + } - [Fact] - public void GetArgumentTypeRef_Parameter_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetArgumentTypeRef_Parameter_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetArgumentTypeRef(null!); + // act + void Action() => typeInspector.GetArgumentTypeRef(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetArgumentType() - { - // arrange - ParameterInfo parameter = typeof(Foo).GetMethod(nameof(Foo.Baz))!.GetParameters()[0]; - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetArgumentType() + { + // arrange + var parameter = typeof(Foo).GetMethod(nameof(Foo.Baz))!.GetParameters()[0]; + var typeInspector = new DefaultTypeInspector(); - // act - IExtendedType extendedType = typeInspector.GetArgumentType(parameter!); + // act + var extendedType = typeInspector.GetArgumentType(parameter!); - // assert - Assert.Equal("String!", extendedType.ToString()); - } + // assert + Assert.Equal("String!", extendedType.ToString()); + } - [Fact] - public void GetArgumentType_Parameter_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetArgumentType_Parameter_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetArgumentType(null!); + // act + void Action() => typeInspector.GetArgumentType(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetTypeRef() - { - // arrange - Type type = typeof(Foo); - var typeInspector = new DefaultTypeInspector(); - - // act - ExtendedTypeReference typeReference = - typeInspector.GetTypeRef(type!, TypeContext.Output); - - // assert - Assert.Equal("Foo", typeReference.Type.ToString()); - Assert.Equal(TypeContext.Output, typeReference.Context); - Assert.Null(typeReference.Scope); - } + [Fact] + public void GetTypeRef() + { + // arrange + var type = typeof(Foo); + var typeInspector = new DefaultTypeInspector(); + + // act + var typeReference = + typeInspector.GetTypeRef(type!, TypeContext.Output); + + // assert + Assert.Equal("Foo", typeReference.Type.ToString()); + Assert.Equal(TypeContext.Output, typeReference.Context); + Assert.Null(typeReference.Scope); + } - [Fact] - public void GetTypeRef_With_Scope() - { - // arrange - Type type = typeof(Foo); - var typeInspector = new DefaultTypeInspector(); - - // act - ExtendedTypeReference typeReference = - typeInspector.GetTypeRef(type!, TypeContext.Output, "abc"); - - // assert - Assert.Equal("Foo", typeReference.Type.ToString()); - Assert.Equal(TypeContext.Output, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } + [Fact] + public void GetTypeRef_With_Scope() + { + // arrange + var type = typeof(Foo); + var typeInspector = new DefaultTypeInspector(); + + // act + var typeReference = + typeInspector.GetTypeRef(type!, TypeContext.Output, "abc"); + + // assert + Assert.Equal("Foo", typeReference.Type.ToString()); + Assert.Equal(TypeContext.Output, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } - [Fact] - public void GetTypeRef_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetTypeRef_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetTypeRef(null!); + // act + void Action() => typeInspector.GetTypeRef(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetType_Type_Is_Foo() - { - // arrange - Type type = typeof(Foo); - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetType_Type_Is_Foo() + { + // arrange + var type = typeof(Foo); + var typeInspector = new DefaultTypeInspector(); - // act - IExtendedType extendedType = typeInspector.GetType(type!); + // act + var extendedType = typeInspector.GetType(type!); - // assert - Assert.Equal("Foo", extendedType.ToString()); - } + // assert + Assert.Equal("Foo", extendedType.ToString()); + } - [Fact] - public void GetType_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetType_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetType(null!); + // act + void Action() => typeInspector.GetType(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetType2_Rewrite_Foo_To_NonNullFoo() - { - // arrange - Type type = typeof(Foo); - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetType2_Rewrite_Foo_To_NonNullFoo() + { + // arrange + var type = typeof(Foo); + var typeInspector = new DefaultTypeInspector(); - // act - IExtendedType extendedType = typeInspector.GetType(type!, false); + // act + var extendedType = typeInspector.GetType(type!, false); - // assert - Assert.Equal("Foo!", extendedType.ToString()); - } + // assert + Assert.Equal("Foo!", extendedType.ToString()); + } - [Fact] - public void GetType2_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetType2_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetType(null!, false); + // act + void Action() => typeInspector.GetType(null!, false); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetType2_Nullable_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetType2_Nullable_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetType(typeof(Foo), default!); + // act + void Action() => typeInspector.GetType(typeof(Foo), default!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetEnumValues() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetEnumValues() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - IEnumerable values = typeInspector.GetEnumValues(typeof(BarEnum)); + // act + var values = typeInspector.GetEnumValues(typeof(BarEnum)); - // assert - Assert.Collection( - values, - t => Assert.Equal(BarEnum.Bar, t), - t => Assert.Equal(BarEnum.Baz, t)); - } + // assert + Assert.Collection( + values, + t => Assert.Equal(BarEnum.Bar, t), + t => Assert.Equal(BarEnum.Baz, t)); + } - [Fact] - public void GetEnumValues_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetEnumValues_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetEnumValues(null!); + // act + void Action() => typeInspector.GetEnumValues(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void GetEnumValueMember() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetEnumValueMember() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - MemberInfo valueMember = typeInspector.GetEnumValueMember(BarEnum.Bar); + // act + var valueMember = typeInspector.GetEnumValueMember(BarEnum.Bar); - // assert - Assert.Equal("Bar", valueMember!.Name); - } + // assert + Assert.Equal("Bar", valueMember!.Name); + } - [Fact] - public void GetEnumValueMember_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void GetEnumValueMember_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.GetEnumValueMember(null!); + // act + void Action() => typeInspector.GetEnumValueMember(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void ExtractNamedType_From_Non_SchemaType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void ExtractNamedType_From_Non_SchemaType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - Type type = typeInspector.ExtractNamedType(typeof(List)); + // act + var type = typeInspector.ExtractNamedType(typeof(List)); - // assert - Assert.Equal(typeof(List), type); - } + // assert + Assert.Equal(typeof(List), type); + } - [Fact] - public void ExtractNamedType_From_SchemaType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void ExtractNamedType_From_SchemaType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - Type type = typeInspector.ExtractNamedType(typeof(ListType)); + // act + var type = typeInspector.ExtractNamedType(typeof(ListType)); - // assert - Assert.Equal(typeof(StringType), type); - } + // assert + Assert.Equal(typeof(StringType), type); + } - [Fact] - public void ExtractNamedType_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void ExtractNamedType_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.ExtractNamedType(null!); + // act + void Action() => typeInspector.ExtractNamedType(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void IsSchemaType_From_Non_SchemaType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void IsSchemaType_From_Non_SchemaType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - var isSchemaType = typeInspector.IsSchemaType(typeof(List)); + // act + var isSchemaType = typeInspector.IsSchemaType(typeof(List)); - // assert - Assert.False(isSchemaType); - } + // assert + Assert.False(isSchemaType); + } - [Fact] - public void IsSchemaType_From_SchemaType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void IsSchemaType_From_SchemaType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - var isSchemaType = typeInspector.IsSchemaType(typeof(ListType)); + // act + var isSchemaType = typeInspector.IsSchemaType(typeof(ListType)); - // assert - Assert.True(isSchemaType); - } + // assert + Assert.True(isSchemaType); + } - [Fact] - public void IsSchemaType_Type_Is_Null() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void IsSchemaType_Type_Is_Null() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - void Action() => typeInspector.IsSchemaType(null!); + // act + void Action() => typeInspector.IsSchemaType(null!); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void CollectNullability_Nullable_StringType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType extendedType = typeInspector.GetType(typeof(StringType)); + [Fact] + public void CollectNullability_Nullable_StringType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var extendedType = typeInspector.GetType(typeof(StringType)); - // act - var nullability = typeInspector.CollectNullability(extendedType); + // act + var nullability = typeInspector.CollectNullability(extendedType); - // assert - Assert.Collection(nullability, item => Assert.True(item)); - } + // assert + Assert.Collection(nullability, item => Assert.True(item)); + } - [Fact] - public void CollectNullability_NonNull_StringType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType extendedType = typeInspector.GetType(typeof(NonNullType)); + [Fact] + public void CollectNullability_NonNull_StringType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var extendedType = typeInspector.GetType(typeof(NonNullType)); - // act - var nullability = typeInspector.CollectNullability(extendedType); + // act + var nullability = typeInspector.CollectNullability(extendedType); - // assert - Assert.Collection(nullability, item => Assert.False(item)); - } + // assert + Assert.Collection(nullability, item => Assert.False(item)); + } - [Fact] - public void CollectNullability_List_NonNull_StringType() - { - // arrange - var typeInspector = new DefaultTypeInspector(); - IExtendedType extendedType = typeInspector.GetType( - typeof(ListType>)); + [Fact] + public void CollectNullability_List_NonNull_StringType() + { + // arrange + var typeInspector = new DefaultTypeInspector(); + var extendedType = typeInspector.GetType( + typeof(ListType>)); - // act - var nullability = typeInspector.CollectNullability(extendedType); + // act + var nullability = typeInspector.CollectNullability(extendedType); - // assert - Assert.Collection(nullability, Assert.True, Assert.False); - } + // assert + Assert.Collection(nullability, Assert.True, Assert.False); + } - [Fact] - public void EnsureOnlyThingsWeUnderstandAreInferred() - { - // arrange - var typeInspector = new DefaultTypeInspector(); + [Fact] + public void EnsureOnlyThingsWeUnderstandAreInferred() + { + // arrange + var typeInspector = new DefaultTypeInspector(); - // act - var members = typeInspector.GetMembers(typeof(DoNotInfer)).ToList(); + // act + var members = typeInspector.GetMembers(typeof(DoNotInfer)).ToList(); - // assert - Assert.Collection( - members.OrderBy(t => t.Name), - member => Assert.Equal("AsyncEnumerable", member.Name), - member => Assert.Equal("DoInfer", member.Name)); - } + // assert + Assert.Collection( + members.OrderBy(t => t.Name), + member => Assert.Equal("AsyncEnumerable", member.Name), + member => Assert.Equal("DoInfer", member.Name)); + } - public class ObjectPropWithTypeAttribute - { - public object ShouldNotBeFound { get; } + public class ObjectPropWithTypeAttribute + { + public object ShouldNotBeFound { get; } - [GraphQLType(typeof(StringType))] - public object ShouldBeFound { get; } - } + [GraphQLType(typeof(StringType))] + public object ShouldBeFound { get; } + } - public class ObjectPropWithDescriptorAttribute - { - public object ShouldNotBeFound { get; } + public class ObjectPropWithDescriptorAttribute + { + public object ShouldNotBeFound { get; } - [SomeAttribute] - public object ShouldBeFound { get; } - } + [SomeAttribute] + public object ShouldBeFound { get; } + } - public class ObjectPropWithSyntaxType - { - [GraphQLType("[String]")] - public object ShouldBeFound { get; } - } + public class ObjectPropWithSyntaxType + { + [GraphQLType("[String]")] + public object ShouldBeFound { get; } + } - public class ObjectMethodWithTypeAttribute - { - public object ShouldNotBeFound() => null; + public class ObjectMethodWithTypeAttribute + { + public object ShouldNotBeFound() => null; - [GraphQLType(typeof(StringType))] - public object ShouldBeFound() => null; - } + [GraphQLType(typeof(StringType))] + public object ShouldBeFound() => null; + } - public class ObjectMethodWithDescriptorAttribute - { - public object ShouldNotBeFound() => null; + public class ObjectMethodWithDescriptorAttribute + { + public object ShouldNotBeFound() => null; - [SomeAttribute] - public object ShouldBeFound() => null; - } + [SomeAttribute] + public object ShouldBeFound() => null; + } - public class MethodAndObjectParameterWithTypeAttribute - { - public string ShouldNotBeFound( - object o) => null; + public class MethodAndObjectParameterWithTypeAttribute + { + public string ShouldNotBeFound( + object o) => null; - public string ShouldBeFound( - [GraphQLType(typeof(StringType))] - object o) => null; - } + public string ShouldBeFound( + [GraphQLType(typeof(StringType))] + object o) => null; + } - public class MethodAndObjectParameterWithDescriptorAttribute - { - public string ShouldNotBeFound( - object o) => null; + public class MethodAndObjectParameterWithDescriptorAttribute + { + public string ShouldNotBeFound( + object o) => null; - public string ShouldBeFound( - [SomeAttribute] - object o) => null; - } + public string ShouldBeFound( + [SomeAttribute] + object o) => null; + } - public class TaskObjectMethodWithTypeAttribute - { - public Task ShouldNotBeFound() => null; + public class TaskObjectMethodWithTypeAttribute + { + public Task ShouldNotBeFound() => null; - [GraphQLType(typeof(StringType))] - public Task ShouldBeFound() => null; - } + [GraphQLType(typeof(StringType))] + public Task ShouldBeFound() => null; + } - public class TaskObjectMethodWithDescriptorAttribute - { - public Task ShouldNotBeFound() => null; + public class TaskObjectMethodWithDescriptorAttribute + { + public Task ShouldNotBeFound() => null; - [SomeAttribute] - public Task ShouldBeFound() => null; - } + [SomeAttribute] + public Task ShouldBeFound() => null; + } - public class ValueTaskObjectMethodWithTypeAttribute - { - public ValueTask ShouldNotBeFound() => default; + public class ValueTaskObjectMethodWithTypeAttribute + { + public ValueTask ShouldNotBeFound() => default; - [GraphQLType(typeof(StringType))] - public ValueTask ShouldBeFound() => default; - } + [GraphQLType(typeof(StringType))] + public ValueTask ShouldBeFound() => default; + } - public class ValueTaskObjectMethodWithDescriptorAttribute - { - public ValueTask ShouldNotBeFound() => default; + public class ValueTaskObjectMethodWithDescriptorAttribute + { + public ValueTask ShouldNotBeFound() => default; - [SomeAttribute] - public ValueTask ShouldBeFound() => default; - } + [SomeAttribute] + public ValueTask ShouldBeFound() => default; + } - public sealed class SomeAttribute - : DescriptorAttribute + public sealed class SomeAttribute + : DescriptorAttribute + { + protected internal override void TryConfigure( + IDescriptorContext context, + IDescriptor descriptor, + ICustomAttributeProvider element) { - protected internal override void TryConfigure( - IDescriptorContext context, - IDescriptor descriptor, - ICustomAttributeProvider element) - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } + } #nullable enable - public class Foo - { - public List Bar() => throw new NotImplementedException(); + public class Foo + { + public List Bar() => throw new NotImplementedException(); - public List Baz(string s) => throw new NotImplementedException(); - } + public List Baz(string s) => throw new NotImplementedException(); + } #nullable restore - public enum BarEnum - { - Bar, - Baz - } + public enum BarEnum + { + Bar, + Baz + } - public class DoNotInfer - { - private string _s = ""; + public class DoNotInfer + { + private string _s = ""; - public string DoInfer() => "abc"; + public string DoInfer() => "abc"; - public void ReturnsVoid() {} + public void ReturnsVoid() {} - public object ObjectProp { get; } = null; + public object ObjectProp { get; } = null; - public string ByRefParameter(ref string s) => s; + public string ByRefParameter(ref string s) => s; - public string ByRefInParameter(in string s) => s; + public string ByRefInParameter(in string s) => s; - public string OutParameter(out string s) - { - s = ""; - return ""; - } + public string OutParameter(out string s) + { + s = ""; + return ""; + } - public ref string ByRefReturn() - { - return ref _s; - } + public ref string ByRefReturn() + { + return ref _s; + } - public string TypeParameter(Type type) => "abc"; + public string TypeParameter(Type type) => "abc"; - public string TypeParameter(ParameterInfo type) => "abc"; + public string TypeParameter(ParameterInfo type) => "abc"; - public string TypeParameter(MemberInfo type) => "abc"; + public string TypeParameter(MemberInfo type) => "abc"; - public string ActionParam(Action action) => "abc"; + public string ActionParam(Action action) => "abc"; - public Type GetMyType() => typeof(Foo); + public Type GetMyType() => typeof(Foo); - public IAsyncResult GetSomeAsyncResult() => null; + public IAsyncResult GetSomeAsyncResult() => null; #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public async void GetAsyncVoid() { } + public async void GetAsyncVoid() { } #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously #if !NETCOREAPP2_1 - public string RefStruct(ReadOnlySpan bytes) => ""; + public string RefStruct(ReadOnlySpan bytes) => ""; #endif - public Action Action { get; } + public Action Action { get; } - public async IAsyncEnumerable AsyncEnumerable() - { - await Task.Delay(10); - yield return "abc"; - } + public async IAsyncEnumerable AsyncEnumerable() + { + await Task.Delay(10); + yield return "abc"; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/NoOpStringBuilderPool.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/NoOpStringBuilderPool.cs index 71d47b30871..66ff05688dc 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/NoOpStringBuilderPool.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/NoOpStringBuilderPool.cs @@ -1,15 +1,14 @@ using System.Text; using Microsoft.Extensions.ObjectPool; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class NoOpStringBuilderPool : ObjectPool { - public class NoOpStringBuilderPool : ObjectPool - { - public override StringBuilder Get() => new(); + public override StringBuilder Get() => new(); - public override void Return(StringBuilder obj) - { - obj.Clear(); - } + public override void Return(StringBuilder obj) + { + obj.Clear(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/XmlDocumentationProviderTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/XmlDocumentationProviderTests.cs index 940f5b709a2..84864ff1147 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/XmlDocumentationProviderTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/Conventions/XmlDocumentationProviderTests.cs @@ -4,398 +4,397 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class XmlDocumentationProviderTests { - public class XmlDocumentationProviderTests + [Fact] + public void When_xml_doc_is_missing_then_description_is_empty() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription(typeof(Point)); + + // assert + Assert.Null(description); + } + + [Fact] + public void When_xml_doc_with_multiple_breaks_is_read_then_they_are_not_stripped_away() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(WithMultilineXmlDoc) + .GetProperty(nameof(WithMultilineXmlDoc.Foo))!); + + // assert + Assert.Matches(new Regex(@"\n[ \t]*\n"), description); + Assert.Contains(" * Users", description); + Assert.Equal(description.Trim(), description); + } + + [Fact] + public void When_description_has_see_tag_then_it_is_converted() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(WithSeeTagInXmlDoc) + .GetProperty(nameof(WithSeeTagInXmlDoc.Foo))!); + + // asssert + Assert.Equal( + "null for the default Record.\nSee this and\nthis" + + " at\nhttps://foo.com/bar/baz.", + description); + } + + [Fact] + public void When_description_has_generic_tags_then_it_is_converted() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(WithGenericTagsInXmlDoc) + .GetProperty(nameof(WithGenericTagsInXmlDoc.Foo))!); + + // assert + Assert.Equal("These are some tags.", description); + } + + [Fact] + public void When_type_has_description_then_it_it_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(BaseBaseClass)); + + // assert + Assert.Equal("I am the most base class.", description); + } + + [Fact] + public void When_we_use_custom_documentation_files_they_are_correctly_loaded() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(_ => "Dummy.xml"), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(BaseBaseClass)); + + // assert + Assert.Equal("I am the most base class from dummy.", description); + } + + [Fact] + public void When_parameter_has_inheritdoc_then_it_is_resolved() { - [Fact] - public void When_xml_doc_is_missing_then_description_is_empty() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription(typeof(Point)); - - // assert - Assert.Null(description); - } - - [Fact] - public void When_xml_doc_with_multiple_breaks_is_read_then_they_are_not_stripped_away() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(WithMultilineXmlDoc) - .GetProperty(nameof(WithMultilineXmlDoc.Foo))!); - - // assert - Assert.Matches(new Regex(@"\n[ \t]*\n"), description); - Assert.Contains(" * Users", description); - Assert.Equal(description.Trim(), description); - } - - [Fact] - public void When_description_has_see_tag_then_it_is_converted() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(WithSeeTagInXmlDoc) - .GetProperty(nameof(WithSeeTagInXmlDoc.Foo))!); - - // asssert - Assert.Equal( - "null for the default Record.\nSee this and\nthis" + - " at\nhttps://foo.com/bar/baz.", - description); - } - - [Fact] - public void When_description_has_generic_tags_then_it_is_converted() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(WithGenericTagsInXmlDoc) - .GetProperty(nameof(WithGenericTagsInXmlDoc.Foo))!); - - // assert - Assert.Equal("These are some tags.", description); - } - - [Fact] - public void When_type_has_description_then_it_it_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(BaseBaseClass)); - - // assert - Assert.Equal("I am the most base class.", description); - } - - [Fact] - public void When_we_use_custom_documentation_files_they_are_correctly_loaded() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(_ => "Dummy.xml"), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(BaseBaseClass)); - - // assert - Assert.Equal("I am the most base class from dummy.", description); - } - - [Fact] - public void When_parameter_has_inheritdoc_then_it_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var parameterXml = documentationProvider.GetDescription( - typeof(ClassWithInheritdoc) + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var parameterXml = documentationProvider.GetDescription( + typeof(ClassWithInheritdoc) .GetMethod(nameof(ClassWithInheritdoc.Bar))! .GetParameters() .Single(p => p.Name == "baz")); - // assert - Assert.Equal("Parameter details.", parameterXml); - } - - [Fact] - public void When_method_has_inheritdoc_then_it_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methoddescription = documentationProvider.GetDescription( - typeof(ClassWithInheritdoc) - .GetMethod(nameof(ClassWithInheritdoc.Bar))!); - - // assert - Assert.Equal("Method doc.", methoddescription); - } - - [Fact] - public void When_property_has_inheritdoc_then_it_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithInheritdoc) - .GetProperty(nameof(ClassWithInheritdoc.Foo))!); - - // assert - Assert.Equal("Summary of foo.", description); - } - - [Fact] - public void When_type_is_an_interface_then_description_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(IBaseBaseInterface)); - - // assert - Assert.Equal("I am an interface.", description); - } - - [Fact] - public void When_parameter_has_inheritdoc_on_interface_then_it_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithInheritdocOnInterface) - .GetMethod(nameof(ClassWithInheritdocOnInterface.Bar))! - .GetParameters() - .Single(p => p.Name == "baz")); - - // assert - Assert.Equal("Parameter summary.", description); - } - - [Fact] - public void When_property_has_inheritdoc_on_interface_then_it_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithInheritdocOnInterface) + // assert + Assert.Equal("Parameter details.", parameterXml); + } + + [Fact] + public void When_method_has_inheritdoc_then_it_is_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methoddescription = documentationProvider.GetDescription( + typeof(ClassWithInheritdoc) + .GetMethod(nameof(ClassWithInheritdoc.Bar))!); + + // assert + Assert.Equal("Method doc.", methoddescription); + } + + [Fact] + public void When_property_has_inheritdoc_then_it_is_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithInheritdoc) + .GetProperty(nameof(ClassWithInheritdoc.Foo))!); + + // assert + Assert.Equal("Summary of foo.", description); + } + + [Fact] + public void When_type_is_an_interface_then_description_is_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(IBaseBaseInterface)); + + // assert + Assert.Equal("I am an interface.", description); + } + + [Fact] + public void When_parameter_has_inheritdoc_on_interface_then_it_is_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithInheritdocOnInterface) + .GetMethod(nameof(ClassWithInheritdocOnInterface.Bar))! + .GetParameters() + .Single(p => p.Name == "baz")); + + // assert + Assert.Equal("Parameter summary.", description); + } + + [Fact] + public void When_property_has_inheritdoc_on_interface_then_it_is_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithInheritdocOnInterface) .GetProperty(nameof(ClassWithInheritdocOnInterface.Foo))!); - // assert - Assert.Equal("Property summary.", description); - } - - [Fact] - public void When_method_has_inheritdoc_then_on_interface_it_is_resolved() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(ClassWithInheritdocOnInterface) + // assert + Assert.Equal("Property summary.", description); + } + + [Fact] + public void When_method_has_inheritdoc_then_on_interface_it_is_resolved() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(ClassWithInheritdocOnInterface) .GetMethod(nameof(ClassWithInheritdocOnInterface.Bar))!); - // assert - Assert.Equal("Method summary.", methodDescription); - } - - [Fact] - public void When_class_implements_interface_and_property_has_description_then_property_description_is_used() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithInterfaceAndCustomSummaries) + // assert + Assert.Equal("Method summary.", methodDescription); + } + + [Fact] + public void When_class_implements_interface_and_property_has_description_then_property_description_is_used() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithInterfaceAndCustomSummaries) .GetProperty(nameof(ClassWithInterfaceAndCustomSummaries.Foo))!); - // assert - Assert.Equal("I am my own property.", description); - } - - [Fact] - public void When_class_implements_interface_and_method_has_description_then_method_description_is_used() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithInterfaceAndCustomSummaries) - .GetMethod(nameof(ClassWithInterfaceAndCustomSummaries.Bar))!); - - // assert - Assert.Equal("I am my own method.", description); - } - - [Fact] - public void When_class_implements_interface_and_method_has_description_then_method_parameter_description_is_used() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithInterfaceAndCustomSummaries) + // assert + Assert.Equal("I am my own property.", description); + } + + [Fact] + public void When_class_implements_interface_and_method_has_description_then_method_description_is_used() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithInterfaceAndCustomSummaries) + .GetMethod(nameof(ClassWithInterfaceAndCustomSummaries.Bar))!); + + // assert + Assert.Equal("I am my own method.", description); + } + + [Fact] + public void When_class_implements_interface_and_method_has_description_then_method_parameter_description_is_used() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithInterfaceAndCustomSummaries) .GetMethod(nameof(ClassWithInterfaceAndCustomSummaries.Bar))! .GetParameters() .Single(p => p.Name == "baz")); - // assert - Assert.Equal("I am my own parameter.", description); - } - - [Fact] - public void When_class_has_description_then_it_is_converted() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var description = documentationProvider.GetDescription( - typeof(ClassWithSummary)); - - // assert - Assert.Equal("I am a test class.", description); - } - - [Fact] - public void When_method_has_exceptions_then_it_is_converted() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(WithExceptionsXmlDoc).GetMethod(nameof(WithExceptionsXmlDoc.Foo))!); - - // assert - methodDescription.MatchSnapshot(); - } - - [Fact] - public void When_method_has_exceptions_then_exceptions_with_no_code_will_be_ignored() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(WithExceptionsXmlDoc).GetMethod(nameof(WithExceptionsXmlDoc.Bar))!); - - // assert - methodDescription.MatchSnapshot(); - } - - [Fact] - public void When_method_has_only_exceptions_with_no_code_then_error_section_will_not_be_written() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(WithExceptionsXmlDoc).GetMethod(nameof(WithExceptionsXmlDoc.Baz))!); - - // assert - methodDescription.MatchSnapshot(); - } - - [Fact] - public void When_method_has_no_exceptions_then_it_is_ignored() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(WithoutExceptionsXmlDoc).GetMethod(nameof(WithoutExceptionsXmlDoc.Foo))!); - - // assert - methodDescription.MatchSnapshot(); - } - - [Fact] - public void When_method_has_returns_then_it_is_converted() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(WithReturnsXmlDoc).GetMethod(nameof(WithReturnsXmlDoc.Foo))!); - - // assert - methodDescription.MatchSnapshot(); - } - - [Fact] - public void When_method_has_no_returns_then_it_is_ignored() - { - // arrange - var documentationProvider = new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool()); - - // act - var methodDescription = documentationProvider.GetDescription( - typeof(WithoutReturnsXmlDoc).GetMethod(nameof(WithoutReturnsXmlDoc.Foo))!); - - // assert - methodDescription.MatchSnapshot(); - } + // assert + Assert.Equal("I am my own parameter.", description); + } + + [Fact] + public void When_class_has_description_then_it_is_converted() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var description = documentationProvider.GetDescription( + typeof(ClassWithSummary)); + + // assert + Assert.Equal("I am a test class.", description); + } + + [Fact] + public void When_method_has_exceptions_then_it_is_converted() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(WithExceptionsXmlDoc).GetMethod(nameof(WithExceptionsXmlDoc.Foo))!); + + // assert + methodDescription.MatchSnapshot(); + } + + [Fact] + public void When_method_has_exceptions_then_exceptions_with_no_code_will_be_ignored() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(WithExceptionsXmlDoc).GetMethod(nameof(WithExceptionsXmlDoc.Bar))!); + + // assert + methodDescription.MatchSnapshot(); + } + + [Fact] + public void When_method_has_only_exceptions_with_no_code_then_error_section_will_not_be_written() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(WithExceptionsXmlDoc).GetMethod(nameof(WithExceptionsXmlDoc.Baz))!); + + // assert + methodDescription.MatchSnapshot(); + } + + [Fact] + public void When_method_has_no_exceptions_then_it_is_ignored() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(WithoutExceptionsXmlDoc).GetMethod(nameof(WithoutExceptionsXmlDoc.Foo))!); + + // assert + methodDescription.MatchSnapshot(); + } + + [Fact] + public void When_method_has_returns_then_it_is_converted() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(WithReturnsXmlDoc).GetMethod(nameof(WithReturnsXmlDoc.Foo))!); + + // assert + methodDescription.MatchSnapshot(); + } + + [Fact] + public void When_method_has_no_returns_then_it_is_ignored() + { + // arrange + var documentationProvider = new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool()); + + // act + var methodDescription = documentationProvider.GetDescription( + typeof(WithoutReturnsXmlDoc).GetMethod(nameof(WithoutReturnsXmlDoc.Foo))!); + + // assert + methodDescription.MatchSnapshot(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs index 2f0e61d1fe6..966556157d5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorContextTests.cs @@ -4,114 +4,113 @@ using HotChocolate.Utilities; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class DescriptorContextTests { - public class DescriptorContextTests + [Fact] + public void Create_With_Custom_NamingConventions() { - [Fact] - public void Create_With_Custom_NamingConventions() - { - // arrange - var options = new SchemaOptions(); - var namingConventions = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - var conventions = new Dictionary<(Type, string), List>(); - var services = new DictionaryServiceProvider( - typeof(INamingConventions), - namingConventions); + // arrange + var options = new SchemaOptions(); + var namingConventions = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + var conventions = new Dictionary<(Type, string), List>(); + var services = new DictionaryServiceProvider( + typeof(INamingConventions), + namingConventions); - // act - var context = DescriptorContext.Create( - options, - services, - conventions, - new Dictionary(), - new SchemaBuilder.LazySchema(), - new AggregateSchemaInterceptor(), - new AggregateTypeInterceptor()); + // act + var context = DescriptorContext.Create( + options, + services, + conventions, + new Dictionary(), + new SchemaBuilder.LazySchema(), + new AggregateSchemaInterceptor(), + new AggregateTypeInterceptor()); - // assert - Assert.Equal(namingConventions, context.Naming); - Assert.NotNull(context.TypeInspector); - Assert.Equal(options, context.Options); - } + // assert + Assert.Equal(namingConventions, context.Naming); + Assert.NotNull(context.TypeInspector); + Assert.Equal(options, context.Options); + } - [Fact] - public void Create_With_Custom_NamingConventions_AsIConvention() + [Fact] + public void Create_With_Custom_NamingConventions_AsIConvention() + { + // arrange + var options = new SchemaOptions(); + var naming = new DefaultNamingConventions( + new XmlDocumentationProvider( + new XmlDocumentationFileResolver(), + new NoOpStringBuilderPool())); + var conventions = new Dictionary<(Type, string), List> { - // arrange - var options = new SchemaOptions(); - var naming = new DefaultNamingConventions( - new XmlDocumentationProvider( - new XmlDocumentationFileResolver(), - new NoOpStringBuilderPool())); - var conventions = new Dictionary<(Type, string), List> - { - { (typeof(INamingConventions), null), new List{s => naming} } - }; + { (typeof(INamingConventions), null), new List{s => naming} } + }; - // act - var context = DescriptorContext.Create( - options, - new EmptyServiceProvider(), - conventions, - new Dictionary(), - new SchemaBuilder.LazySchema(), - new AggregateSchemaInterceptor(), - new AggregateTypeInterceptor()); + // act + var context = DescriptorContext.Create( + options, + new EmptyServiceProvider(), + conventions, + new Dictionary(), + new SchemaBuilder.LazySchema(), + new AggregateSchemaInterceptor(), + new AggregateTypeInterceptor()); - // assert - Assert.Equal(naming, context.Naming); - Assert.NotNull(context.TypeInspector); - Assert.Equal(options, context.Options); - } + // assert + Assert.Equal(naming, context.Naming); + Assert.NotNull(context.TypeInspector); + Assert.Equal(options, context.Options); + } - [Fact] - public void Create_With_Custom_TypeInspector() - { - // arrange - var options = new SchemaOptions(); - var inspector = new DefaultTypeInspector(); - var conventions = new Dictionary<(Type, string), List>(); - var services = new DictionaryServiceProvider( - typeof(ITypeInspector), - inspector); + [Fact] + public void Create_With_Custom_TypeInspector() + { + // arrange + var options = new SchemaOptions(); + var inspector = new DefaultTypeInspector(); + var conventions = new Dictionary<(Type, string), List>(); + var services = new DictionaryServiceProvider( + typeof(ITypeInspector), + inspector); - // act - var context = DescriptorContext.Create( - options, - services, - conventions, - new Dictionary(), - new SchemaBuilder.LazySchema(), - new AggregateSchemaInterceptor(), - new AggregateTypeInterceptor()); + // act + var context = DescriptorContext.Create( + options, + services, + conventions, + new Dictionary(), + new SchemaBuilder.LazySchema(), + new AggregateSchemaInterceptor(), + new AggregateTypeInterceptor()); - // assert - Assert.Equal(inspector, context.TypeInspector); - Assert.NotNull(context.Naming); - Assert.Equal(options, context.Options); - } + // assert + Assert.Equal(inspector, context.TypeInspector); + Assert.NotNull(context.Naming); + Assert.Equal(options, context.Options); + } - [Fact] - public void Create_Without_Services() - { - // arrange - // act - var context = DescriptorContext.Create(); + [Fact] + public void Create_Without_Services() + { + // arrange + // act + var context = DescriptorContext.Create(); - // assert - Assert.NotNull(context.Options); - Assert.NotNull(context.Naming); - Assert.NotNull(context.TypeInspector); - } + // assert + Assert.NotNull(context.Options); + Assert.NotNull(context.Naming); + Assert.NotNull(context.TypeInspector); + } - private sealed class Convention : Descriptors.Convention - { - public static Convention Default { get; } = new Convention(); - } + private sealed class Convention : Descriptors.Convention + { + public static Convention Default { get; } = new Convention(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorTestBase.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorTestBase.cs index dc850805191..711cd9ade2b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorTestBase.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DescriptorTestBase.cs @@ -1,14 +1,13 @@ using HotChocolate.Types.Descriptors; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DescriptorTestBase { - public class DescriptorTestBase + protected DescriptorTestBase() { - protected DescriptorTestBase() - { - } - - public IDescriptorContext Context { get; } = - DescriptorContext.Create(); } + + public IDescriptorContext Context { get; } = + DescriptorContext.Create(); } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveArgumentDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveArgumentDescriptorTests.cs index 29b9d5ea49a..87adc2d8269 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveArgumentDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveArgumentDescriptorTests.cs @@ -2,22 +2,21 @@ using HotChocolate.Types.Descriptors; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DirectiveArgumentDescriptorTests : DescriptorTestBase { - public class DirectiveArgumentDescriptorTests : DescriptorTestBase + [Fact] + public void Type_Syntax_Type_Null() { - [Fact] - public void Type_Syntax_Type_Null() - { - void Error() => DirectiveArgumentDescriptor.New(Context, "foo").Type((string)null); - Assert.Throws(Error); - } + void Error() => DirectiveArgumentDescriptor.New(Context, "foo").Type((string)null); + Assert.Throws(Error); + } - [Fact] - public void Type_Syntax_Descriptor_Null() - { - void Error() => default(DirectiveArgumentDescriptor).Type("foo"); - Assert.Throws(Error); - } + [Fact] + public void Type_Syntax_Descriptor_Null() + { + void Error() => default(DirectiveArgumentDescriptor).Type("foo"); + Assert.Throws(Error); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveDescriptorTests.cs index 440789c5215..a02cefbcf17 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/DirectiveDescriptorTests.cs @@ -4,256 +4,255 @@ using HotChocolate.Types.Descriptors.Definitions; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DirectiveDescriptorTests + : DescriptorTestBase { - public class DirectiveDescriptorTests - : DescriptorTestBase + [Fact] + public void DeclareName() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Name("Foo"); + + // assert + Assert.Equal("Foo", descriptor.CreateDefinition().Name); + } + + [Fact] + public void InferName() + { + // arrange + // act + var descriptor = + DirectiveTypeDescriptor.New(Context); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Equal("CustomDirective", description.Name); + } + + [Fact] + public void OverrideName() + { + // arrange + var descriptor = + DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Name("Foo"); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Equal("Foo", description.Name); + } + + [Fact] + public void DeclareNullName() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + Action a = () => descriptor.Name(null); + + // assert + Assert.Throws(a); + } + + [Fact] + public void DeclareEmptyName() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + Action a = () => descriptor.Name(string.Empty); + + // assert + Assert.Throws(a); + } + + [Fact] + public void DeclareDescription() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Description("Desc"); + + // assert + Assert.Equal("Desc", descriptor.CreateDefinition().Description); + } + + [Fact] + public void DeclareArgument() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Argument("arg").Type(); ; + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal("arg", description.Arguments.Single().Name); + } + + [Fact] + public void DeclareArgumentWithProperty() + { + // arrange + // act + var descriptor = DirectiveTypeDescriptor.New(Context); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Collection(description.Arguments, + t => Assert.Equal("fieldA", t.Name), + t => Assert.Equal("fieldB", t.Name)); + } + + [Fact] + public void DeclareExplicitArgumentBinding() + { + // arrange + var descriptor = + DirectiveTypeDescriptor.New(Context); + + // act + descriptor.BindArguments(BindingBehavior.Explicit); + descriptor.Argument(t => t.FieldA); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Collection(description.Arguments, + t => Assert.Equal("fieldA", t.Name)); + } + + [Fact] + public void DeclareArgumentAndSpecifyType() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Argument(t => t.FieldA).Type>(); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Arguments, + t => Assert.Equal( + typeof(NonNullType), + Assert.IsType(t.Type).Type.Source), + t => Assert.Equal( + typeof(string), + Assert.IsType(t.Type).Type.Source)); + } + + [Fact] + public void DeclareArgumentAndSpecifyClrType() { - [Fact] - public void DeclareName() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Name("Foo"); - - // assert - Assert.Equal("Foo", descriptor.CreateDefinition().Name); - } - - [Fact] - public void InferName() - { - // arrange - // act - var descriptor = - DirectiveTypeDescriptor.New(Context); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Equal("CustomDirective", description.Name); - } - - [Fact] - public void OverrideName() - { - // arrange - var descriptor = - DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Name("Foo"); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Equal("Foo", description.Name); - } - - [Fact] - public void DeclareNullName() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - Action a = () => descriptor.Name(null); - - // assert - Assert.Throws(a); - } - - [Fact] - public void DeclareEmptyName() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - Action a = () => descriptor.Name(string.Empty); - - // assert - Assert.Throws(a); - } - - [Fact] - public void DeclareDescription() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Description("Desc"); - - // assert - Assert.Equal("Desc", descriptor.CreateDefinition().Description); - } - - [Fact] - public void DeclareArgument() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Argument("arg").Type(); ; - - // assert - DirectiveTypeDefinition description = descriptor.CreateDefinition(); - Assert.Equal("arg", description.Arguments.Single().Name); - } - - [Fact] - public void DeclareArgumentWithProperty() - { - // arrange - // act - var descriptor = DirectiveTypeDescriptor.New(Context); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Collection(description.Arguments, - t => Assert.Equal("fieldA", t.Name), - t => Assert.Equal("fieldB", t.Name)); - } - - [Fact] - public void DeclareExplicitArgumentBinding() - { - // arrange - var descriptor = - DirectiveTypeDescriptor.New(Context); - - // act - descriptor.BindArguments(BindingBehavior.Explicit); - descriptor.Argument(t => t.FieldA); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Collection(description.Arguments, - t => Assert.Equal("fieldA", t.Name)); - } - - [Fact] - public void DeclareArgumentAndSpecifyType() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Argument(t => t.FieldA).Type>(); - - // assert - DirectiveTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Arguments, - t => Assert.Equal( - typeof(NonNullType), - Assert.IsType(t.Type).Type.Source), - t => Assert.Equal( - typeof(string), - Assert.IsType(t.Type).Type.Source)); - } - - [Fact] - public void DeclareArgumentAndSpecifyClrType() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Argument(t => t.FieldA).Type(typeof(NonNullType)); - - // assert - DirectiveTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Arguments, - t => Assert.Equal( - typeof(NonNullType), - Assert.IsType(t.Type).Type.Source), - t => Assert.Equal( - typeof(string), - Assert.IsType(t.Type).Type.Source)); - } - - [Fact] - public void IgnoreArgumentBinding() - { - // arrange - var descriptor = - DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Argument(t => t.FieldA).Ignore(); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Collection(description.Arguments, - t => Assert.Equal("fieldB", t.Name)); - } - - [Fact] - public void UnignoreArgumentBinding() - { - // arrange - var descriptor = - DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Argument(t => t.FieldA).Ignore(); - descriptor.Argument(t => t.FieldA).Ignore(false); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Collection(description.Arguments, - t => Assert.Equal("fieldA", t.Name), - t => Assert.Equal("fieldB", t.Name)); - } - - [Fact] - public void MethodsAreNotAllowedAsArguments() - { - // arrange - var descriptor = - DirectiveTypeDescriptor.New(Context); - - // act - Action action = () => descriptor.Argument(t => t.Foo()).Ignore(); - - // assert - Assert.Throws(action); - } - - [Fact] - public void DeclareLocation() - { - // arrange - var descriptor = DirectiveTypeDescriptor.New(Context); - - // act - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.EnumValue); - - // assert - DirectiveTypeDefinition description = - descriptor.CreateDefinition(); - Assert.Collection(description.Locations, - t => Assert.Equal(DirectiveLocation.Enum, t), - t => Assert.Equal(DirectiveLocation.EnumValue, t)); - } - - public class CustomDirective - { - public string FieldA { get; } - - public string FieldB { get; } - - public string Foo() => throw new NotSupportedException(); - } + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Argument(t => t.FieldA).Type(typeof(NonNullType)); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Arguments, + t => Assert.Equal( + typeof(NonNullType), + Assert.IsType(t.Type).Type.Source), + t => Assert.Equal( + typeof(string), + Assert.IsType(t.Type).Type.Source)); + } + + [Fact] + public void IgnoreArgumentBinding() + { + // arrange + var descriptor = + DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Argument(t => t.FieldA).Ignore(); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Collection(description.Arguments, + t => Assert.Equal("fieldB", t.Name)); + } + + [Fact] + public void UnignoreArgumentBinding() + { + // arrange + var descriptor = + DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Argument(t => t.FieldA).Ignore(); + descriptor.Argument(t => t.FieldA).Ignore(false); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Collection(description.Arguments, + t => Assert.Equal("fieldA", t.Name), + t => Assert.Equal("fieldB", t.Name)); + } + + [Fact] + public void MethodsAreNotAllowedAsArguments() + { + // arrange + var descriptor = + DirectiveTypeDescriptor.New(Context); + + // act + Action action = () => descriptor.Argument(t => t.Foo()).Ignore(); + + // assert + Assert.Throws(action); + } + + [Fact] + public void DeclareLocation() + { + // arrange + var descriptor = DirectiveTypeDescriptor.New(Context); + + // act + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.EnumValue); + + // assert + var description = + descriptor.CreateDefinition(); + Assert.Collection(description.Locations, + t => Assert.Equal(DirectiveLocation.Enum, t), + t => Assert.Equal(DirectiveLocation.EnumValue, t)); + } + + public class CustomDirective + { + public string FieldA { get; } + + public string FieldB { get; } + + public string Foo() => throw new NotSupportedException(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/EnumTypeDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/EnumTypeDescriptorTests.cs index 8155bba8d7f..d4b12869589 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/EnumTypeDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/EnumTypeDescriptorTests.cs @@ -4,162 +4,161 @@ using HotChocolate.Types.Descriptors.Definitions; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class EnumTypeDescriptorTests + : DescriptorTestBase { - public class EnumTypeDescriptorTests - : DescriptorTestBase + [Fact] + public void InferNameFromType() + { + // act + var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); + + // assert + Assert.Equal("FooEnum", descriptor.CreateDefinition().Name); + } + + [Fact] + public void NoTypeProvided() + { + // act + Action a = () => EnumTypeDescriptor.New(Context, (Type)null); + + // assert + Assert.Throws(a); + } + + [Fact] + public void InferValuesFromType() + { + // act + var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Values, + t => + { + Assert.Equal("BAR1", t.Name); + Assert.Equal(FooEnum.Bar1, t.RuntimeValue); + }, + t => + { + Assert.Equal("BAR2", t.Name); + Assert.Equal(FooEnum.Bar2, t.RuntimeValue); + }); + } + + [Fact] + public void SpecifyOneValueInferTheOthers() + { + // arrange + var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); + + // act + IEnumTypeDescriptor desc = descriptor; + desc.Value(FooEnum.Bar1).Name("FOOBAR"); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Values, + t => + { + Assert.Equal("FOOBAR", t.Name); + Assert.Equal(FooEnum.Bar1, t.RuntimeValue); + }, + t => + { + Assert.Equal("BAR2", t.Name); + Assert.Equal(FooEnum.Bar2, t.RuntimeValue); + }); + } + + [Fact] + public void ExplicitValueBinding() + { + // arrange + var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); + + // act + IEnumTypeDescriptor desc = descriptor; + desc.Value(FooEnum.Bar1).Name("FOOBAR"); + desc.BindValues(BindingBehavior.Explicit); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Values, + t => + { + Assert.Equal("FOOBAR", t.Name); + Assert.Equal(FooEnum.Bar1, t.RuntimeValue); + }); + } + + [Fact] + public void AddDirective() + { + // arrange + var descriptor = EnumTypeDescriptor.New(Context); + + // act + IEnumTypeDescriptor desc = descriptor; + desc.Directive(new NameString("Bar")); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Directives, + t => Assert.Equal("Bar", t.ParsedDirective.Name.Value)); + } + + [Fact] + public void AddDirectiveWithDirectiveNode() + { + // arrange + var descriptor = EnumTypeDescriptor.New(Context); + + // act + IEnumTypeDescriptor desc = descriptor; + desc.Directive(new DirectiveNode("Bar")); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Directives, + t => Assert.Equal("Bar", t.ParsedDirective.Name.Value)); + } + + [Fact] + public void AddDirectiveWithArgument() + { + // arrange + var descriptor = EnumTypeDescriptor.New(Context); + + // act + IEnumTypeDescriptor desc = descriptor; + desc.Directive("Bar", + new ArgumentNode("a", new StringValueNode("b"))); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Collection(description.Directives, + t => + { + Assert.Equal("Bar", t.ParsedDirective.Name.Value); + Assert.Collection(t.ParsedDirective.Arguments, + x => + { + Assert.Equal("a", x.Name.Value); + Assert.IsType(x.Value); + Assert.Equal("b", ((StringValueNode)x.Value).Value); + }); + }); + } + + + private enum FooEnum { - [Fact] - public void InferNameFromType() - { - // act - var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); - - // assert - Assert.Equal("FooEnum", descriptor.CreateDefinition().Name); - } - - [Fact] - public void NoTypeProvided() - { - // act - Action a = () => EnumTypeDescriptor.New(Context, (Type)null); - - // assert - Assert.Throws(a); - } - - [Fact] - public void InferValuesFromType() - { - // act - var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); - - // assert - EnumTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Values, - t => - { - Assert.Equal("BAR1", t.Name); - Assert.Equal(FooEnum.Bar1, t.RuntimeValue); - }, - t => - { - Assert.Equal("BAR2", t.Name); - Assert.Equal(FooEnum.Bar2, t.RuntimeValue); - }); - } - - [Fact] - public void SpecifyOneValueInferTheOthers() - { - // arrange - var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); - - // act - IEnumTypeDescriptor desc = descriptor; - desc.Value(FooEnum.Bar1).Name("FOOBAR"); - - // assert - EnumTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Values, - t => - { - Assert.Equal("FOOBAR", t.Name); - Assert.Equal(FooEnum.Bar1, t.RuntimeValue); - }, - t => - { - Assert.Equal("BAR2", t.Name); - Assert.Equal(FooEnum.Bar2, t.RuntimeValue); - }); - } - - [Fact] - public void ExplicitValueBinding() - { - // arrange - var descriptor = EnumTypeDescriptor.New(Context, typeof(FooEnum)); - - // act - IEnumTypeDescriptor desc = descriptor; - desc.Value(FooEnum.Bar1).Name("FOOBAR"); - desc.BindValues(BindingBehavior.Explicit); - - // assert - EnumTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Values, - t => - { - Assert.Equal("FOOBAR", t.Name); - Assert.Equal(FooEnum.Bar1, t.RuntimeValue); - }); - } - - [Fact] - public void AddDirective() - { - // arrange - var descriptor = EnumTypeDescriptor.New(Context); - - // act - IEnumTypeDescriptor desc = descriptor; - desc.Directive(new NameString("Bar")); - - // assert - EnumTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Directives, - t => Assert.Equal("Bar", t.ParsedDirective.Name.Value)); - } - - [Fact] - public void AddDirectiveWithDirectiveNode() - { - // arrange - var descriptor = EnumTypeDescriptor.New(Context); - - // act - IEnumTypeDescriptor desc = descriptor; - desc.Directive(new DirectiveNode("Bar")); - - // assert - EnumTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Directives, - t => Assert.Equal("Bar", t.ParsedDirective.Name.Value)); - } - - [Fact] - public void AddDirectiveWithArgument() - { - // arrange - var descriptor = EnumTypeDescriptor.New(Context); - - // act - IEnumTypeDescriptor desc = descriptor; - desc.Directive("Bar", - new ArgumentNode("a", new StringValueNode("b"))); - - // assert - EnumTypeDefinition description = descriptor.CreateDefinition(); - Assert.Collection(description.Directives, - t => - { - Assert.Equal("Bar", t.ParsedDirective.Name.Value); - Assert.Collection(t.ParsedDirective.Arguments, - x => - { - Assert.Equal("a", x.Name.Value); - Assert.IsType(x.Value); - Assert.Equal("b", ((StringValueNode)x.Value).Value); - }); - }); - } - - - private enum FooEnum - { - Bar1, - Bar2 - } + Bar1, + Bar2 } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputFieldDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputFieldDescriptorTests.cs index 1c50604e2df..1180e765787 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputFieldDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputFieldDescriptorTests.cs @@ -5,264 +5,263 @@ using HotChocolate.Types.Descriptors.Definitions; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputFieldDescriptorTests + : DescriptorTestBase { - public class InputFieldDescriptorTests - : DescriptorTestBase + [Fact] + public void DotNetTypesDoNotOverwriteSchemaTypes() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor + .Type>() + .Type>>(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(ListType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SchemaTypesOverwriteDotNetTypes() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor + .Type>>() + .Type>(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(ListType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SetSchemaType() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor.Type(new StringType()); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.IsType( + Assert.IsType(typeRef).Type); + } + + [Fact] + public void SetGenericType() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor.Type(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(StringType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SetNonGenericType() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor.Type(typeof(StringType)); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(StringType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void OverwriteName() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + "field1234"); + + // act + descriptor.Name("args"); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal("args", description.Name); + } + + [Fact] + public void OverwriteName2() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor.Name("args"); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal("args", description.Name); + } + + [Fact] + public void SetDescription() + { + // arrange + var expectedDescription = Guid.NewGuid().ToString(); + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor.Description(expectedDescription); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal(expectedDescription, description.Description); + } + + [Fact] + public void SetDefaultValueAndInferType() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor.DefaultValue("string"); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal( + typeof(string), + Assert.IsType(description.Type).Type.Source); + Assert.Equal("string", description.RuntimeDefaultValue); + } + + [Fact] + public void OverwriteDefaultValueLiteralWithNativeDefaultValue() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + descriptor + .DefaultValue(new StringValueNode("123")) + .DefaultValue("string"); + + // asser + var description = descriptor.CreateDefinition(); + Assert.Null(description.DefaultValue); + Assert.Equal("string", description.RuntimeDefaultValue); + } + + [Fact] + public void SettingTheNativeDefaultValueToNullCreatesNullLiteral() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + ((IInputFieldDescriptor)descriptor) + .DefaultValue(new StringValueNode("123")) + .DefaultValue("string") + .DefaultValue(null); + + // assert + var description = descriptor.CreateDefinition(); + Assert.IsType(description.DefaultValue); + Assert.Null(description.RuntimeDefaultValue); + } + + [Fact] + public void OverwriteNativeDefaultValueWithDefaultValueLiteral() + { + // arrange + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // act + ((IInputFieldDescriptor)descriptor) + .DefaultValue("string") + .DefaultValue(new StringValueNode("123")); + + // assert + var description = descriptor.CreateDefinition(); + Assert.IsType(description.DefaultValue); + Assert.Equal("123", + ((StringValueNode)description.DefaultValue).Value); + Assert.Null(description.RuntimeDefaultValue); + } + + [Fact] + public void InferTypeFromProperty() + { + // act + var descriptor = InputFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")); + + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal(typeof(FieldCollection), + Assert.IsType(description.Type).Type.Source); + Assert.Equal("arguments", description.Name); + } + + [Fact] + public void Type_Syntax_Type_Null() + { + void Error() => InputFieldDescriptor.New(Context, "foo").Type((string)null); + Assert.Throws(Error); + } + + [Fact] + public void Type_Syntax_Descriptor_Null() { - [Fact] - public void DotNetTypesDoNotOverwriteSchemaTypes() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor - .Type>() - .Type>>(); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(ListType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SchemaTypesOverwriteDotNetTypes() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor - .Type>>() - .Type>(); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(ListType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SetSchemaType() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor.Type(new StringType()); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.IsType( - Assert.IsType(typeRef).Type); - } - - [Fact] - public void SetGenericType() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor.Type(); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(StringType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SetNonGenericType() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor.Type(typeof(StringType)); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(StringType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void OverwriteName() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - "field1234"); - - // act - descriptor.Name("args"); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.Equal("args", description.Name); - } - - [Fact] - public void OverwriteName2() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor.Name("args"); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.Equal("args", description.Name); - } - - [Fact] - public void SetDescription() - { - // arrange - string expectedDescription = Guid.NewGuid().ToString(); - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor.Description(expectedDescription); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.Equal(expectedDescription, description.Description); - } - - [Fact] - public void SetDefaultValueAndInferType() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor.DefaultValue("string"); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.Equal( - typeof(string), - Assert.IsType(description.Type).Type.Source); - Assert.Equal("string", description.RuntimeDefaultValue); - } - - [Fact] - public void OverwriteDefaultValueLiteralWithNativeDefaultValue() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - descriptor - .DefaultValue(new StringValueNode("123")) - .DefaultValue("string"); - - // asser - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.Null(description.DefaultValue); - Assert.Equal("string", description.RuntimeDefaultValue); - } - - [Fact] - public void SettingTheNativeDefaultValueToNullCreatesNullLiteral() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - ((IInputFieldDescriptor)descriptor) - .DefaultValue(new StringValueNode("123")) - .DefaultValue("string") - .DefaultValue(null); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.IsType(description.DefaultValue); - Assert.Null(description.RuntimeDefaultValue); - } - - [Fact] - public void OverwriteNativeDefaultValueWithDefaultValueLiteral() - { - // arrange - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // act - ((IInputFieldDescriptor)descriptor) - .DefaultValue("string") - .DefaultValue(new StringValueNode("123")); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.IsType(description.DefaultValue); - Assert.Equal("123", - ((StringValueNode)description.DefaultValue).Value); - Assert.Null(description.RuntimeDefaultValue); - } - - [Fact] - public void InferTypeFromProperty() - { - // act - var descriptor = InputFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")); - - // assert - InputFieldDefinition description = descriptor.CreateDefinition(); - Assert.Equal(typeof(FieldCollection), - Assert.IsType(description.Type).Type.Source); - Assert.Equal("arguments", description.Name); - } - - [Fact] - public void Type_Syntax_Type_Null() - { - void Error() => InputFieldDescriptor.New(Context, "foo").Type((string)null); - Assert.Throws(Error); - } - - [Fact] - public void Type_Syntax_Descriptor_Null() - { - void Error() => default(InputFieldDescriptor).Type("foo"); - Assert.Throws(Error); - } + void Error() => default(InputFieldDescriptor).Type("foo"); + Assert.Throws(Error); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputObjectTypeDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputObjectTypeDescriptorTests.cs index c33bae0953b..520ad1ca09b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputObjectTypeDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InputObjectTypeDescriptorTests.cs @@ -2,54 +2,53 @@ using HotChocolate.Types.Descriptors.Definitions; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputObjectTypeDescriptorTests + : DescriptorTestBase { - public class InputObjectTypeDescriptorTests - : DescriptorTestBase + [Fact] + public void Field_Ignore_PropertyIsExcluded() + { + // arrange + var descriptor = + InputObjectTypeDescriptor.New(Context); + + // act + descriptor.Field(t => t.Id).Ignore(); + + // assert + var description = + descriptor.CreateDefinition(); + + Assert.Collection(description.Fields, + t => Assert.Equal("name", t.Name)); + } + + + [Fact] + public void Field_Unignore_PropertyIsExcluded() + { + // arrange + var descriptor = + InputObjectTypeDescriptor.New(Context); + + // act + descriptor.Field(t => t.Id).Ignore(); + descriptor.Field(t => t.Id).Ignore(false); + + // assert + var description = + descriptor.CreateDefinition(); + + Assert.Collection(description.Fields, + t => Assert.Equal("id", t.Name), + t => Assert.Equal("name", t.Name)); + } + + public class SimpleInput { - [Fact] - public void Field_Ignore_PropertyIsExcluded() - { - // arrange - var descriptor = - InputObjectTypeDescriptor.New(Context); - - // act - descriptor.Field(t => t.Id).Ignore(); - - // assert - InputObjectTypeDefinition description = - descriptor.CreateDefinition(); - - Assert.Collection(description.Fields, - t => Assert.Equal("name", t.Name)); - } - - - [Fact] - public void Field_Unignore_PropertyIsExcluded() - { - // arrange - var descriptor = - InputObjectTypeDescriptor.New(Context); - - // act - descriptor.Field(t => t.Id).Ignore(); - descriptor.Field(t => t.Id).Ignore(false); - - // assert - InputObjectTypeDefinition description = - descriptor.CreateDefinition(); - - Assert.Collection(description.Fields, - t => Assert.Equal("id", t.Name), - t => Assert.Equal("name", t.Name)); - } - - public class SimpleInput - { - public int Id { get; set; } - public string Name { get; set; } - } + public int Id { get; set; } + public string Name { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InterfaceFieldDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InterfaceFieldDescriptorTests.cs index e4055250bfb..d57c7838766 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InterfaceFieldDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/InterfaceFieldDescriptorTests.cs @@ -2,22 +2,21 @@ using HotChocolate.Types.Descriptors; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InterfaceFieldDescriptorTests : DescriptorTestBase { - public class InterfaceFieldDescriptorTests : DescriptorTestBase + [Fact] + public void Type_Syntax_Type_Null() { - [Fact] - public void Type_Syntax_Type_Null() - { - void Error() => InterfaceFieldDescriptor.New(Context, "foo").Type((string)null); - Assert.Throws(Error); - } + void Error() => InterfaceFieldDescriptor.New(Context, "foo").Type((string)null); + Assert.Throws(Error); + } - [Fact] - public void Type_Syntax_Descriptor_Null() - { - void Error() => default(InterfaceFieldDescriptor).Type("foo"); - Assert.Throws(Error); - } + [Fact] + public void Type_Syntax_Descriptor_Null() + { + void Error() => default(InterfaceFieldDescriptor).Type("foo"); + Assert.Throws(Error); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectFieldDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectFieldDescriptorTests.cs index aa8c73111c9..50be39dad8e 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectFieldDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectFieldDescriptorTests.cs @@ -7,222 +7,221 @@ using Moq; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ObjectFieldDescriptorTests : DescriptorTestBase { - public class ObjectFieldDescriptorTests : DescriptorTestBase + [Fact] + public void SetGenericType() + { + // arrange + var descriptor = + ObjectFieldDescriptor.New(Context, "field"); + + // act + descriptor.Type(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(StringType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SetNonGenericType() + { + // arrange + var descriptor = + ObjectFieldDescriptor.New(Context, "field"); + + // act + descriptor.Type(typeof(StringType)); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(StringType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void DotNetTypesDoNotOverwriteSchemaTypes() + { + // arrange + var descriptor = + ObjectFieldDescriptor.New(Context, "field"); + + // act + descriptor + .Type>() + .Type>>(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal(typeof(ListType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void SchemaTypesOverwriteDotNetTypes() + { + // arrange + var descriptor = + ObjectFieldDescriptor.New(Context, "field"); + + // act + descriptor + .Type>>() + .Type>(); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal(typeof(ListType), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void ResolverTypesDoNotOverwriteSchemaTypes() + { + // arrange + var descriptor = ObjectFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")!, + typeof(ObjectField)); + + // act + descriptor + .Name("args") + .Type>>>() + .Resolve(c => c.Parent().Arguments); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(NonNullType>>), + Assert.IsType(typeRef).Type.Source); + } + + [Fact] + public void OverwriteName() + { + // arrange + var descriptor = ObjectFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")!, + typeof(ObjectField)); + + // act + descriptor.Name("args"); + + // assert + Assert.Equal("args", descriptor.CreateDefinition().Name); + } + + [Fact] + public void SetDescription() + { + // arrange + var expectedDescription = Guid.NewGuid().ToString(); + var descriptor = ObjectFieldDescriptor.New( + Context, + typeof(ObjectField).GetProperty("Arguments")!, + typeof(ObjectField)); + + // act + descriptor.Description(expectedDescription); + + // assert + Assert.Equal(expectedDescription, + descriptor.CreateDefinition().Description); + } + + [Fact] + public void SetResolverAndInferTypeFromResolver() { - [Fact] - public void SetGenericType() - { - // arrange - var descriptor = - ObjectFieldDescriptor.New(Context, "field"); - - // act - descriptor.Type(); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(StringType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SetNonGenericType() - { - // arrange - var descriptor = - ObjectFieldDescriptor.New(Context, "field"); - - // act - descriptor.Type(typeof(StringType)); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(StringType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void DotNetTypesDoNotOverwriteSchemaTypes() - { - // arrange - var descriptor = - ObjectFieldDescriptor.New(Context, "field"); - - // act - descriptor - .Type>() - .Type>>(); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal(typeof(ListType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void SchemaTypesOverwriteDotNetTypes() - { - // arrange - var descriptor = - ObjectFieldDescriptor.New(Context, "field"); - - // act - descriptor - .Type>>() - .Type>(); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal(typeof(ListType), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void ResolverTypesDoNotOverwriteSchemaTypes() - { - // arrange - var descriptor = ObjectFieldDescriptor.New( + // arrange + var descriptor = + ObjectFieldDescriptor.New( Context, typeof(ObjectField).GetProperty("Arguments")!, typeof(ObjectField)); - // act - descriptor - .Name("args") - .Type>>>() - .Resolve(c => c.Parent().Arguments); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(NonNullType>>), - Assert.IsType(typeRef).Type.Source); - } - - [Fact] - public void OverwriteName() - { - // arrange - var descriptor = ObjectFieldDescriptor.New( + // act + descriptor.Resolve(() => "ThisIsAString"); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(string), + Assert.IsType(typeRef).Type.Source); + + Assert.NotNull(description.Resolver); + + var context = new Mock(MockBehavior.Strict); + Assert.Equal("ThisIsAString", + description.Resolver(context.Object).Result); + } + + [Fact] + public void SetResolverAndInferTypeIsAlwaysRecognisedAsDotNetType() + { + // arrange + var descriptor = + ObjectFieldDescriptor.New( Context, typeof(ObjectField).GetProperty("Arguments")!, typeof(ObjectField)); - // act - descriptor.Name("args"); + // act + descriptor + .Type<__Type>() + .Resolve(ctx => ctx.Schema + .GetType(ctx.ArgumentValue("type"))); + + // assert + var description = descriptor.CreateDefinition(); + var typeRef = description.Type; + Assert.Equal( + typeof(__Type), + Assert.IsType(typeRef).Type.Source); + Assert.NotNull(description.Resolver); + } - // assert - Assert.Equal("args", descriptor.CreateDefinition().Name); - } + [Fact] + public void Type_Syntax_Type_Null() + { + void Error() => ObjectFieldDescriptor.New(Context, "foo").Type((string)null); + Assert.Throws(Error); + } - [Fact] - public void SetDescription() - { - // arrange - var expectedDescription = Guid.NewGuid().ToString(); - var descriptor = ObjectFieldDescriptor.New( + [Fact] + public void Type_Syntax_Descriptor_Null() + { + void Error() => default(IObjectFieldDescriptor).Type("foo"); + Assert.Throws(Error); + } + + [Fact] + public void ResolverTypeIsSet() + { + // arrange + // act + var descriptor = + ObjectFieldDescriptor.New( Context, typeof(ObjectField).GetProperty("Arguments")!, - typeof(ObjectField)); + typeof(ObjectField), + typeof(string)); - // act - descriptor.Description(expectedDescription); - - // assert - Assert.Equal(expectedDescription, - descriptor.CreateDefinition().Description); - } - - [Fact] - public void SetResolverAndInferTypeFromResolver() - { - // arrange - var descriptor = - ObjectFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")!, - typeof(ObjectField)); - - // act - descriptor.Resolve(() => "ThisIsAString"); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(string), - Assert.IsType(typeRef).Type.Source); - - Assert.NotNull(description.Resolver); - - var context = new Mock(MockBehavior.Strict); - Assert.Equal("ThisIsAString", - description.Resolver(context.Object).Result); - } - - [Fact] - public void SetResolverAndInferTypeIsAlwaysRecognisedAsDotNetType() - { - // arrange - var descriptor = - ObjectFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")!, - typeof(ObjectField)); - - // act - descriptor - .Type<__Type>() - .Resolve(ctx => ctx.Schema - .GetType(ctx.ArgumentValue("type"))); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - ITypeReference typeRef = description.Type; - Assert.Equal( - typeof(__Type), - Assert.IsType(typeRef).Type.Source); - Assert.NotNull(description.Resolver); - } - - [Fact] - public void Type_Syntax_Type_Null() - { - void Error() => ObjectFieldDescriptor.New(Context, "foo").Type((string)null); - Assert.Throws(Error); - } - - [Fact] - public void Type_Syntax_Descriptor_Null() - { - void Error() => default(IObjectFieldDescriptor).Type("foo"); - Assert.Throws(Error); - } - - [Fact] - public void ResolverTypeIsSet() - { - // arrange - // act - var descriptor = - ObjectFieldDescriptor.New( - Context, - typeof(ObjectField).GetProperty("Arguments")!, - typeof(ObjectField), - typeof(string)); - - // assert - ObjectFieldDefinition description = descriptor.CreateDefinition(); - Assert.Equal(typeof(string), description.ResolverType); - } + // assert + var description = descriptor.CreateDefinition(); + Assert.Equal(typeof(string), description.ResolverType); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectTypeDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectTypeDescriptorTests.cs index c7ad139bfa7..dc7c68faae5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectTypeDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ObjectTypeDescriptorTests.cs @@ -7,264 +7,263 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ObjectTypeDescriptorTests : DescriptorTestBase { - public class ObjectTypeDescriptorTests : DescriptorTestBase + [Fact] + public void InferNameFromType() { - [Fact] - public void InferNameFromType() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); + // arrange + var descriptor = new ObjectTypeDescriptor(Context); - // act - IObjectTypeDescriptor desc = descriptor; + // act + IObjectTypeDescriptor desc = descriptor; - // assert - Assert.Equal("Foo", descriptor.CreateDefinition().Name); - } + // assert + Assert.Equal("Foo", descriptor.CreateDefinition().Name); + } - [Fact] - public void GetNameFromAttribute() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); + [Fact] + public void GetNameFromAttribute() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); - // act - IObjectTypeDescriptor desc = descriptor; + // act + IObjectTypeDescriptor desc = descriptor; - // assert - Assert.Equal("FooAttr", descriptor.CreateDefinition().Name); - } + // assert + Assert.Equal("FooAttr", descriptor.CreateDefinition().Name); + } - [Fact] - public void OverwriteDefaultName() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); + [Fact] + public void OverwriteDefaultName() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); - // act - descriptor.Name("FooBar"); + // act + descriptor.Name("FooBar"); - // assert - Assert.Equal("FooBar", descriptor.CreateDefinition().Name); - } + // assert + Assert.Equal("FooBar", descriptor.CreateDefinition().Name); + } - [Fact] - public void OverwriteAttributeName() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); + [Fact] + public void OverwriteAttributeName() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); - // act - IObjectTypeDescriptor desc = descriptor; - desc.Name("FooBar"); + // act + IObjectTypeDescriptor desc = descriptor; + desc.Name("FooBar"); - // assert - Assert.Equal("FooBar", descriptor.CreateDefinition().Name); - } + // assert + Assert.Equal("FooBar", descriptor.CreateDefinition().Name); + } - [Fact] - public void InferFieldsFromType() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); - - // act - IObjectTypeDescriptor desc = descriptor; - - // assert - Assert.Collection( - descriptor.CreateDefinition().Fields - .Select(t => t.Name) - .OrderBy(t => t), - t => Assert.Equal("a", t), - t => Assert.Equal("b", t), - t => Assert.Equal("c", t)); - } + [Fact] + public void InferFieldsFromType() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); + + // act + IObjectTypeDescriptor desc = descriptor; + + // assert + Assert.Collection( + descriptor.CreateDefinition().Fields + .Select(t => t.Name) + .OrderBy(t => t), + t => Assert.Equal("a", t), + t => Assert.Equal("b", t), + t => Assert.Equal("c", t)); + } - [Fact] - public void IgnoreOverridenPropertyField() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); - - // act - descriptor.Field(t => t.B).Ignore(); - - // assert - Assert.Collection( - descriptor.CreateDefinition().Fields - .Select(t => t.Name) - .OrderBy(t => t), - t => Assert.Equal("a", t), - t => Assert.Equal("c", t)); - } + [Fact] + public void IgnoreOverridenPropertyField() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); + + // act + descriptor.Field(t => t.B).Ignore(); + + // assert + Assert.Collection( + descriptor.CreateDefinition().Fields + .Select(t => t.Name) + .OrderBy(t => t), + t => Assert.Equal("a", t), + t => Assert.Equal("c", t)); + } - [Fact] - public void UnignoreOverridenPropertyField() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); - - // act - descriptor.Field(t => t.B).Ignore(); - descriptor.Field(t => t.B).Ignore(false); - - // assert - Assert.Collection( - descriptor.CreateDefinition().Fields - .Select(t => t.Name) - .OrderBy(t => t), - t => Assert.Equal("a", t), - t => Assert.Equal("b", t), - t => Assert.Equal("c", t)); - } + [Fact] + public void UnignoreOverridenPropertyField() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); + + // act + descriptor.Field(t => t.B).Ignore(); + descriptor.Field(t => t.B).Ignore(false); + + // assert + Assert.Collection( + descriptor.CreateDefinition().Fields + .Select(t => t.Name) + .OrderBy(t => t), + t => Assert.Equal("a", t), + t => Assert.Equal("b", t), + t => Assert.Equal("c", t)); + } - [Fact] - public void IgnoreOverridenMethodField() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); - - // act - IObjectTypeDescriptor desc = descriptor; - desc.Field(t => t.Equals(default)).Ignore(); - - // assert - Assert.Collection( - descriptor.CreateDefinition().Fields - .Select(t => t.Name) - .OrderBy(t => t), - t => Assert.Equal("a", t), - t => Assert.Equal("b", t), - t => Assert.Equal("c", t)); - } + [Fact] + public void IgnoreOverridenMethodField() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); + + // act + IObjectTypeDescriptor desc = descriptor; + desc.Field(t => t.Equals(default)).Ignore(); + + // assert + Assert.Collection( + descriptor.CreateDefinition().Fields + .Select(t => t.Name) + .OrderBy(t => t), + t => Assert.Equal("a", t), + t => Assert.Equal("b", t), + t => Assert.Equal("c", t)); + } - [Fact] - public void UnignoreOverridenMethodField() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); - - // act - IObjectTypeDescriptor desc = descriptor; - desc.Field(t => t.Equals(default)).Ignore(); - desc.Field(t => t.Equals(default)).Ignore(false); - - // assert - Assert.Collection( - descriptor.CreateDefinition().Fields - .Select(t => t.Name) - .OrderBy(t => t), - t => Assert.Equal("a", t), - t => Assert.Equal("b", t), - t => Assert.Equal("c", t), - t => Assert.Equal("equals", t)); - } + [Fact] + public void UnignoreOverridenMethodField() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); + + // act + IObjectTypeDescriptor desc = descriptor; + desc.Field(t => t.Equals(default)).Ignore(); + desc.Field(t => t.Equals(default)).Ignore(false); + + // assert + Assert.Collection( + descriptor.CreateDefinition().Fields + .Select(t => t.Name) + .OrderBy(t => t), + t => Assert.Equal("a", t), + t => Assert.Equal("b", t), + t => Assert.Equal("c", t), + t => Assert.Equal("equals", t)); + } - [Fact] - public void DeclareFieldsExplicitly() - { - // arrange - var descriptor = new ObjectTypeDescriptor(Context); - - // act - IObjectTypeDescriptor desc = descriptor; - desc.Field(t => t.A); - desc.BindFields(BindingBehavior.Explicit); - - // assert - Assert.Collection( - descriptor.CreateDefinition().Fields.Select(t => t.Name), - t => Assert.Equal("a", t)); - } + [Fact] + public void DeclareFieldsExplicitly() + { + // arrange + var descriptor = new ObjectTypeDescriptor(Context); + + // act + IObjectTypeDescriptor desc = descriptor; + desc.Field(t => t.A); + desc.BindFields(BindingBehavior.Explicit); + + // assert + Assert.Collection( + descriptor.CreateDefinition().Fields.Select(t => t.Name), + t => Assert.Equal("a", t)); + } - [Fact] - public async Task UseMiddleware() - { - // arrange - ISchema schema = SchemaBuilder.New().AddQueryType().Create(); - IRequestExecutor executor = schema.MakeExecutable(); + [Fact] + public async Task UseMiddleware() + { + // arrange + var schema = SchemaBuilder.New().AddQueryType().Create(); + var executor = schema.MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync("{ a b c}"); + // act + var result = await executor.ExecuteAsync("{ a b c}"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - public class Foo : FooBase - { - public string A { get; set; } - public override string B { get; set; } - public string C { get; set; } + public class Foo : FooBase + { + public string A { get; set; } + public override string B { get; set; } + public string C { get; set; } - public override bool Equals(object obj) => true; + public override bool Equals(object obj) => true; - public override int GetHashCode() => 0; - } + public override int GetHashCode() => 0; + } - [GraphQLName("FooAttr")] - public class Foo2 : FooBase - { - } + [GraphQLName("FooAttr")] + public class Foo2 : FooBase + { + } + + public class FooBase + { + public virtual string B { get; set; } + } - public class FooBase + public class BarType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - public virtual string B { get; set; } + descriptor.Name("Bar"); + + descriptor.Field("a").Use(next => context => + { + context.Result = "a_123"; + return next(context); + }).Type(); + + descriptor.Field("b").Use() + .Type(); + descriptor.Field("c").Use() + .Type(); } + } - public class BarType : ObjectType + public class TestFieldMiddleware1 + { + private readonly FieldDelegate _next; + + public TestFieldMiddleware1(FieldDelegate next) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Bar"); - - descriptor.Field("a").Use(next => context => - { - context.Result = "a_123"; - return next(context); - }).Type(); - - descriptor.Field("b").Use() - .Type(); - descriptor.Field("c").Use() - .Type(); - } + _next = next ?? throw new ArgumentNullException(nameof(next)); } - public class TestFieldMiddleware1 + public ValueTask InvokeAsync(IMiddlewareContext context) { - private readonly FieldDelegate _next; + context.Result = context.Selection.Field.Name + "_456"; + return _next(context); + } + } - public TestFieldMiddleware1(FieldDelegate next) - { - _next = next ?? throw new ArgumentNullException(nameof(next)); - } + public class TestFieldMiddleware2 + { + private FieldDelegate _next; - public ValueTask InvokeAsync(IMiddlewareContext context) - { - context.Result = context.Selection.Field.Name + "_456"; - return _next(context); - } + public TestFieldMiddleware2(FieldDelegate next) + { + _next = next ?? throw new ArgumentNullException(nameof(next)); } - public class TestFieldMiddleware2 + public ValueTask InvokeAsync(IMiddlewareContext context) { - private FieldDelegate _next; - - public TestFieldMiddleware2(FieldDelegate next) - { - _next = next ?? throw new ArgumentNullException(nameof(next)); - } - - public ValueTask InvokeAsync(IMiddlewareContext context) - { - context.Result = context.Selection.Field.Name + "_789"; - return _next(context); - } + context.Result = context.Selection.Field.Name + "_789"; + return _next(context); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolveObjectFieldDescriptorExtensionsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolveObjectFieldDescriptorExtensionsTests.cs index 366bf484d05..cd67b81ddb5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolveObjectFieldDescriptorExtensionsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolveObjectFieldDescriptorExtensionsTests.cs @@ -5,457 +5,456 @@ using Moq; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ResolveObjectFieldDescriptorExtensionsTests { - public class ResolveObjectFieldDescriptorExtensionsTests + [Fact] + public void Resolver_IResolverContextObject_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func(c => new object())); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func)); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task Resolver_IResolverContextObject_ResolverIsSet() { - [Fact] - public void Resolver_IResolverContextObject_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func(c => new object())); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func)); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task Resolver_IResolverContextObject_ResolverIsSet() - { - // arrange - FieldResolverDelegate resolver = null; - var resolverFunc = new Func(c => "foo"); - var descriptor = new Mock(); - descriptor.Setup(t => t.Resolve(It.IsAny())) - .Returns( - new Func( + // arrange + FieldResolverDelegate resolver = null; + var resolverFunc = new Func(c => "foo"); + var descriptor = new Mock(); + descriptor.Setup(t => t.Resolve(It.IsAny())) + .Returns( + new Func( r => { resolver = r; return descriptor.Object; })); - // act + // act + ResolveObjectFieldDescriptorExtensions + .Resolve(descriptor.Object, resolverFunc); + + // assert + Assert.Equal("foo", await resolver.Invoke( + new Mock().Object)); + } + + [Fact] + public void Resolver_IResolverContextTaskOfObject_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func>(c => + Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextTaskOfObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func>)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextT_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func(c => new object())); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextTaskOfT_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func>(c => + Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextTaskOfT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func>)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_Object_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func(() => new object())); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_Object_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_TaskOfObject_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func>(() => + Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_TaskOfObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func>)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_T_DescNull_ArgExc() + { + // arrange + // act + Action action = () => ResolveObjectFieldDescriptorExtensions - .Resolve(descriptor.Object, resolverFunc); - - // assert - Assert.Equal("foo", await resolver.Invoke( - new Mock().Object)); - } - - [Fact] - public void Resolver_IResolverContextTaskOfObject_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func>(c => - Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextTaskOfObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func>)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextT_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func(c => new object())); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextTaskOfT_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func>(c => - Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextTaskOfT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func>)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_Object_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func(() => new object())); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_Object_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_TaskOfObject_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func>(() => - Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_TaskOfObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func>)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_T_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func(() => new object())); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_T_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_TaskOfT_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func>(() => - Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_TaskOfT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func>)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextCtObject_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func( - (c, ct) => new object())); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextCtObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default( - Func)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextCtTaskOfObject_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func>((c, ct) => - Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverCtxCtTaskOfObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func>)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextCtT_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func( - (c, ct) => new object())); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextCtT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default( - Func)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverContextCtTaskOfT_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - null, - new Func>((c, ct) => - Task.FromResult(new object()))); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_IResolverCtxCtTaskOfT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve( - descriptor.Object, - default(Func>)); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_Constant_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve(null, new object()); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Resolver_ConstantT_DescNull_ArgExc() - { - // arrange - // act - Action action = () => - ResolveObjectFieldDescriptorExtensions - .Resolve(null, new object()); - - // assert - Assert.Throws(action); - } + .Resolve( + null, + new Func(() => new object())); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_T_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_TaskOfT_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func>(() => + Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_TaskOfT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func>)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextCtObject_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func( + (c, ct) => new object())); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextCtObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default( + Func)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextCtTaskOfObject_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func>((c, ct) => + Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverCtxCtTaskOfObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func>)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextCtT_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func( + (c, ct) => new object())); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextCtT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default( + Func)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverContextCtTaskOfT_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + null, + new Func>((c, ct) => + Task.FromResult(new object()))); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_IResolverCtxCtTaskOfT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve( + descriptor.Object, + default(Func>)); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_Constant_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve(null, new object()); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Resolver_ConstantT_DescNull_ArgExc() + { + // arrange + // act + Action action = () => + ResolveObjectFieldDescriptorExtensions + .Resolve(null, new object()); + + // assert + Assert.Throws(action); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolverObjectFieldDescriptorExtensionsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolverObjectFieldDescriptorExtensionsTests.cs index dda749e2377..a4b6daeb6b0 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolverObjectFieldDescriptorExtensionsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/ResolverObjectFieldDescriptorExtensionsTests.cs @@ -5,395 +5,394 @@ using Moq; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +[Obsolete] +public class ResolverObjectFieldDescriptorExtensionsTests { - [Obsolete] - public class ResolverObjectFieldDescriptorExtensionsTests + [Fact] + public void Resolver_IResolverContextObject_DescNull_ArgExc() + { + // arrange + // act + void Action() => + ResolverObjectFieldDescriptorExtensions.Resolver( + null!, _ => new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextObject_ResolverNull_ArgExc() { - [Fact] - public void Resolver_IResolverContextObject_DescNull_ArgExc() - { - // arrange - // act - void Action() => - ResolverObjectFieldDescriptorExtensions.Resolver( - null!, _ => new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public async Task Resolver_IResolverContextObject_ResolverIsSet() - { - // arrange - FieldResolverDelegate resolver = null; - var resolverFunc = new Func(_ => "foo"); - var descriptor = new Mock(MockBehavior.Strict); - descriptor.Setup(t => t.Resolve(It.IsAny())) - .Returns( - new Func( + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public async Task Resolver_IResolverContextObject_ResolverIsSet() + { + // arrange + FieldResolverDelegate resolver = null; + var resolverFunc = new Func(_ => "foo"); + var descriptor = new Mock(MockBehavior.Strict); + descriptor.Setup(t => t.Resolve(It.IsAny())) + .Returns( + new Func( r => { resolver = r; return descriptor.Object; })); - // act - ResolverObjectFieldDescriptorExtensions.Resolver(descriptor.Object, resolverFunc); - - // assert - Assert.Equal("foo", await resolver.Invoke( - new Mock().Object)); - } - - [Fact] - public void Resolver_IResolverContextTaskOfObject_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - _ => Task.FromResult(new object())); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextTaskOfObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func>)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextT_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - _ => new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextTaskOfT_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - _ => Task.FromResult(new object())); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextTaskOfT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func>)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_Object_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - () => new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_Object_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_TaskOfObject_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - () => Task.FromResult(new object())); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_TaskOfObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func>)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_T_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - () => new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_T_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_TaskOfT_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - () => Task.FromResult(new object())); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_TaskOfT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func>)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextCtObject_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - (_, _) => new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextCtObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextCtTaskOfObject_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - (_, _) => Task.FromResult(new object())); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverCtxCtTaskOfObject_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func>)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextCtT_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - (_, _) => new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextCtT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverContextCtTaskOfT_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - (_, _) => Task.FromResult(new object())); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_IResolverCtxCtTaskOfT_ResolverNull_ArgExc() - { - // arrange - var descriptor = new Mock(); - - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - descriptor.Object, - default(Func>)!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_Constant_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - new object()); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Resolver_ConstantT_DescNull_ArgExc() - { - // arrange - // act - void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( - null!, - new object()); - - // assert - Assert.Throws(Action); - } + // act + ResolverObjectFieldDescriptorExtensions.Resolver(descriptor.Object, resolverFunc); + + // assert + Assert.Equal("foo", await resolver.Invoke( + new Mock().Object)); + } + + [Fact] + public void Resolver_IResolverContextTaskOfObject_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + _ => Task.FromResult(new object())); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextTaskOfObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func>)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextT_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + _ => new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextTaskOfT_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + _ => Task.FromResult(new object())); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextTaskOfT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func>)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_Object_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + () => new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_Object_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_TaskOfObject_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + () => Task.FromResult(new object())); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_TaskOfObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func>)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_T_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + () => new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_T_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_TaskOfT_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + () => Task.FromResult(new object())); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_TaskOfT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func>)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextCtObject_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + (_, _) => new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextCtObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextCtTaskOfObject_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + (_, _) => Task.FromResult(new object())); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverCtxCtTaskOfObject_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func>)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextCtT_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + (_, _) => new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextCtT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverContextCtTaskOfT_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + (_, _) => Task.FromResult(new object())); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_IResolverCtxCtTaskOfT_ResolverNull_ArgExc() + { + // arrange + var descriptor = new Mock(); + + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + descriptor.Object, + default(Func>)!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_Constant_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + new object()); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Resolver_ConstantT_DescNull_ArgExc() + { + // arrange + // act + void Action() => ResolverObjectFieldDescriptorExtensions.Resolver( + null!, + new object()); + + // assert + Assert.Throws(Action); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/ClrTypeReferenceTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/ClrTypeReferenceTests.cs index 4e41cbb6969..f7d52538bf4 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/ClrTypeReferenceTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/ClrTypeReferenceTests.cs @@ -2,612 +2,611 @@ using HotChocolate.Internal; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class ClrTypeReferenceTests { - public class ClrTypeReferenceTests + private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); + + [InlineData(typeof(string[]), TypeContext.Input, "foo")] + [InlineData(typeof(string[]), TypeContext.Input, null)] + [InlineData(typeof(string), TypeContext.Input, null)] + [InlineData(typeof(string[]), TypeContext.Output, null)] + [InlineData(typeof(string), TypeContext.None, null)] + [Theory] + public void TypeReference_Create( + Type clrType, + TypeContext context, + string scope) + { + // arrange + // act + var typeReference = TypeReference.Create( + _typeInspector.GetType(clrType), + context, + scope: scope); + + // assert + Assert.Equal(clrType, typeReference.Type.Source); + Assert.Equal(context, typeReference.Context); + Assert.Equal(scope, typeReference.Scope); + } + + [Fact] + public void TypeReference_Create_And_Infer_Output_Context() + { + // arrange + // act + var typeReference = TypeReference.Create( + _typeInspector.GetType(typeof(ObjectType)), + scope: "abc"); + + // assert + Assert.Equal(typeof(ObjectType), typeReference.Type.Source); + Assert.Equal(TypeContext.Output, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } + + [Fact] + public void TypeReference_Create_And_Infer_Input_Context() + { + // arrange + // act + var typeReference = TypeReference.Create( + _typeInspector.GetType(typeof(InputObjectType)), + scope: "abc"); + + // assert + Assert.Equal(typeof(InputObjectType), typeReference.Type.Source); + Assert.Equal(TypeContext.Input, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } + + [Fact] + public void ClrTypeReference_Equals_To_Null() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var result = x.Equals((ExtendedTypeReference)null); + + // assert + Assert.False(result); + } + + [Fact] + public void ClrTypeReference_Equals_To_Same() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var xx = x.Equals((ExtendedTypeReference)x); + + // assert + Assert.True(xx); + } + + [Fact] + public void ClrTypeReference_Equals_Context_None_Does_Not_Matter() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xy = x.Equals(y); + var xz = x.Equals(z); + var yz = y.Equals(z); + + // assert + Assert.True(xy); + Assert.True(xz); + Assert.False(yz); + } + + [Fact] + public void ClrTypeReference_Equals_Scope_Different() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None, + scope: "a"); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output, + scope: "a"); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xy = x.Equals(y); + var xz = x.Equals(z); + var yz = y.Equals(z); + + // assert + Assert.True(xy); + Assert.False(xz); + Assert.False(yz); + } + + [Fact] + public void ITypeReference_Equals_To_Null() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var result = x.Equals((ITypeReference)null); + + // assert + Assert.False(result); + } + + [Fact] + public void ITypeReference_Equals_To_Same() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var xx = x.Equals((ITypeReference)x); + + // assert + Assert.True(xx); + } + + [Fact] + public void ITypeReference_Equals_To_SyntaxTypeRef() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var xx = x.Equals(TypeReference.Create(new NameType("foo"))); + + // assert + Assert.False(xx); + } + + [Fact] + public void ITypeReference_Equals_Context_None_Does_Not_Matter() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xy = x.Equals((ITypeReference)y); + var xz = x.Equals((ITypeReference)z); + var yz = y.Equals((ITypeReference)z); + + // assert + Assert.True(xy); + Assert.True(xz); + Assert.False(yz); + } + + [Fact] + public void ITypeReference_Equals_Scope_Different() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None, + scope: "a"); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output, + scope: "a"); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xy = x.Equals((ITypeReference)y); + var xz = x.Equals((ITypeReference)z); + var yz = y.Equals((ITypeReference)z); + + // assert + Assert.True(xy); + Assert.False(xz); + Assert.False(yz); + } + + [Fact] + public void Object_Equals_To_Null() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var result = x.Equals((object)null); + + // assert + Assert.False(result); + } + + [Fact] + public void Object_Equals_To_Same() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var xx = x.Equals((object)x); + + // assert + Assert.True(xx); + } + + [Fact] + public void Object_Equals_To_Object() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + // act + var xx = x.Equals(new object()); + + // assert + Assert.False(xx); + } + + [Fact] + public void Object_Equals_Context_None_Does_Not_Matter() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string))); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xy = x.Equals((object)y); + var xz = x.Equals((object)z); + var yz = y.Equals((object)z); + + // assert + Assert.True(xy); + Assert.True(xz); + Assert.False(yz); + } + + [Fact] + public void Object_Equals_Scope_Different() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None, + scope: "a"); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output, + scope: "a"); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xy = x.Equals((object)y); + var xz = x.Equals((object)z); + var yz = y.Equals((object)z); + + // assert + Assert.True(xy); + Assert.False(xz); + Assert.False(yz); + } + + [Fact] + public void ClrTypeReference_ToString() + { + // arrange + var typeReference = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var result = typeReference.ToString(); + + // assert + Assert.Equal("Input: String", result); + } + + [Fact] + public void ClrTypeReference_WithType() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = + typeReference1.WithType(_typeInspector.GetType(typeof(int))); + + // assert + Assert.Equal(typeof(int), typeReference2.Type.Source); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_WithType_Null() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + Action action = () => typeReference1.WithType(default(IExtendedType)!); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ClrTypeReference_WithContext() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithContext(TypeContext.Output); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.Output, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_WithContext_Nothing() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithContext(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_WithScope() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithScope("bar"); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_WithScope_Nothing() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithScope(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Null(typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_With() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With( + _typeInspector.GetType(typeof(int)), + TypeContext.Output, + scope: "bar"); + + // assert + Assert.Equal(typeof(int), typeReference2.Type.Source); + Assert.Equal(TypeContext.Output, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_With_Nothing() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_With_Type() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With( + _typeInspector.GetType(typeof(int))); + + // assert + Assert.Equal(typeof(int), typeReference2.Type.Source); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_With_Context() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(context: TypeContext.None); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_With_Scope() + { + // arrange + var typeReference1 = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(scope: "bar"); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public void ClrTypeReference_GetHashCode() + { + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None, + scope: "foo"); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None, + scope: "foo"); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xh = x.GetHashCode(); + var yh = y.GetHashCode(); + var zh = z.GetHashCode(); + + // assert + Assert.Equal(xh, yh); + Assert.NotEqual(xh, zh); + } + + [Fact] + public void ClrTypeReference_GetHashCode_Context_HasNoEffect() { - private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); - - [InlineData(typeof(string[]), TypeContext.Input, "foo")] - [InlineData(typeof(string[]), TypeContext.Input, null)] - [InlineData(typeof(string), TypeContext.Input, null)] - [InlineData(typeof(string[]), TypeContext.Output, null)] - [InlineData(typeof(string), TypeContext.None, null)] - [Theory] - public void TypeReference_Create( - Type clrType, - TypeContext context, - string scope) - { - // arrange - // act - ExtendedTypeReference typeReference = TypeReference.Create( - _typeInspector.GetType(clrType), - context, - scope: scope); - - // assert - Assert.Equal(clrType, typeReference.Type.Source); - Assert.Equal(context, typeReference.Context); - Assert.Equal(scope, typeReference.Scope); - } - - [Fact] - public void TypeReference_Create_And_Infer_Output_Context() - { - // arrange - // act - ExtendedTypeReference typeReference = TypeReference.Create( - _typeInspector.GetType(typeof(ObjectType)), - scope: "abc"); - - // assert - Assert.Equal(typeof(ObjectType), typeReference.Type.Source); - Assert.Equal(TypeContext.Output, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } - - [Fact] - public void TypeReference_Create_And_Infer_Input_Context() - { - // arrange - // act - ExtendedTypeReference typeReference = TypeReference.Create( - _typeInspector.GetType(typeof(InputObjectType)), - scope: "abc"); - - // assert - Assert.Equal(typeof(InputObjectType), typeReference.Type.Source); - Assert.Equal(TypeContext.Input, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } - - [Fact] - public void ClrTypeReference_Equals_To_Null() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var result = x.Equals((ExtendedTypeReference)null); - - // assert - Assert.False(result); - } - - [Fact] - public void ClrTypeReference_Equals_To_Same() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var xx = x.Equals((ExtendedTypeReference)x); - - // assert - Assert.True(xx); - } - - [Fact] - public void ClrTypeReference_Equals_Context_None_Does_Not_Matter() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - ExtendedTypeReference y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output); - - ExtendedTypeReference z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xy = x.Equals(y); - var xz = x.Equals(z); - var yz = y.Equals(z); - - // assert - Assert.True(xy); - Assert.True(xz); - Assert.False(yz); - } - - [Fact] - public void ClrTypeReference_Equals_Scope_Different() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None, - scope: "a"); - - ExtendedTypeReference y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output, - scope: "a"); - - ExtendedTypeReference z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xy = x.Equals(y); - var xz = x.Equals(z); - var yz = y.Equals(z); - - // assert - Assert.True(xy); - Assert.False(xz); - Assert.False(yz); - } - - [Fact] - public void ITypeReference_Equals_To_Null() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var result = x.Equals((ITypeReference)null); - - // assert - Assert.False(result); - } - - [Fact] - public void ITypeReference_Equals_To_Same() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var xx = x.Equals((ITypeReference)x); - - // assert - Assert.True(xx); - } - - [Fact] - public void ITypeReference_Equals_To_SyntaxTypeRef() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var xx = x.Equals(TypeReference.Create(new NameType("foo"))); - - // assert - Assert.False(xx); - } - - [Fact] - public void ITypeReference_Equals_Context_None_Does_Not_Matter() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None); - - var y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output); - - var z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xy = x.Equals((ITypeReference)y); - var xz = x.Equals((ITypeReference)z); - var yz = y.Equals((ITypeReference)z); - - // assert - Assert.True(xy); - Assert.True(xz); - Assert.False(yz); - } - - [Fact] - public void ITypeReference_Equals_Scope_Different() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None, - scope: "a"); - - var y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output, - scope: "a"); - - var z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xy = x.Equals((ITypeReference)y); - var xz = x.Equals((ITypeReference)z); - var yz = y.Equals((ITypeReference)z); - - // assert - Assert.True(xy); - Assert.False(xz); - Assert.False(yz); - } - - [Fact] - public void Object_Equals_To_Null() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var result = x.Equals((object)null); - - // assert - Assert.False(result); - } - - [Fact] - public void Object_Equals_To_Same() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var xx = x.Equals((object)x); - - // assert - Assert.True(xx); - } - - [Fact] - public void Object_Equals_To_Object() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - // act - var xx = x.Equals(new object()); - - // assert - Assert.False(xx); - } - - [Fact] - public void Object_Equals_Context_None_Does_Not_Matter() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string))); - - ExtendedTypeReference y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output); - - ExtendedTypeReference z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xy = x.Equals((object)y); - var xz = x.Equals((object)z); - var yz = y.Equals((object)z); - - // assert - Assert.True(xy); - Assert.True(xz); - Assert.False(yz); - } - - [Fact] - public void Object_Equals_Scope_Different() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None, - scope: "a"); - - var y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output, - scope: "a"); - - var z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xy = x.Equals((object)y); - var xz = x.Equals((object)z); - var yz = y.Equals((object)z); - - // assert - Assert.True(xy); - Assert.False(xz); - Assert.False(yz); - } - - [Fact] - public void ClrTypeReference_ToString() - { - // arrange - ExtendedTypeReference typeReference = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var result = typeReference.ToString(); - - // assert - Assert.Equal("Input: String", result); - } - - [Fact] - public void ClrTypeReference_WithType() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = - typeReference1.WithType(_typeInspector.GetType(typeof(int))); - - // assert - Assert.Equal(typeof(int), typeReference2.Type.Source); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_WithType_Null() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - Action action = () => typeReference1.WithType(default(IExtendedType)!); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ClrTypeReference_WithContext() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.WithContext(TypeContext.Output); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.Output, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_WithContext_Nothing() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.WithContext(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_WithScope() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.WithScope("bar"); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_WithScope_Nothing() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.WithScope(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Null(typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_With() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.With( - _typeInspector.GetType(typeof(int)), - TypeContext.Output, - scope: "bar"); - - // assert - Assert.Equal(typeof(int), typeReference2.Type.Source); - Assert.Equal(TypeContext.Output, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_With_Nothing() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.With(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_With_Type() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.With( - _typeInspector.GetType(typeof(int))); - - // assert - Assert.Equal(typeof(int), typeReference2.Type.Source); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_With_Context() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.With(context: TypeContext.None); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_With_Scope() - { - // arrange - ExtendedTypeReference typeReference1 = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input, - scope: "foo"); - - // act - ExtendedTypeReference typeReference2 = typeReference1.With(scope: "bar"); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public void ClrTypeReference_GetHashCode() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None, - scope: "foo"); - - ExtendedTypeReference y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None, - scope: "foo"); - - ExtendedTypeReference z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xh = x.GetHashCode(); - var yh = y.GetHashCode(); - var zh = z.GetHashCode(); - - // assert - Assert.Equal(xh, yh); - Assert.NotEqual(xh, zh); - } - - [Fact] - public void ClrTypeReference_GetHashCode_Context_HasNoEffect() - { - // arrange - ExtendedTypeReference x = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.None); - - ExtendedTypeReference y = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Output); - - ExtendedTypeReference z = TypeReference.Create( - _typeInspector.GetType(typeof(string)), - TypeContext.Input); - - // act - var xh = x.GetHashCode(); - var yh = y.GetHashCode(); - var zh = z.GetHashCode(); - - // assert - Assert.Equal(xh, yh); - Assert.Equal(xh, zh); - } + // arrange + var x = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.None); + + var y = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Output); + + var z = TypeReference.Create( + _typeInspector.GetType(typeof(string)), + TypeContext.Input); + + // act + var xh = x.GetHashCode(); + var yh = y.GetHashCode(); + var zh = z.GetHashCode(); + + // assert + Assert.Equal(xh, yh); + Assert.Equal(xh, zh); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SchemaTypeReferenceTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SchemaTypeReferenceTests.cs index 3a89737c016..1952a519ca7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SchemaTypeReferenceTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SchemaTypeReferenceTests.cs @@ -3,547 +3,546 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class SchemaTypeReferenceTests { - public class SchemaTypeReferenceTests - { - [Fact] - public async Task TypeReference_Create_From_OutputType() - { - // arrange - ObjectType type = await CreateTypeAsync>(); - - // act - SchemaTypeReference typeReference = TypeReference.Create( - type, - scope: "abc"); - - // assert - Assert.Equal(type, typeReference.Type); - Assert.Equal(TypeContext.Output, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } - - [Fact] - public async Task TypeReference_Create_From_InputType() - { - // arrange - InputObjectType type = await CreateTypeAsync>(); - - // act - SchemaTypeReference typeReference = TypeReference.Create( - type, - scope: "abc"); - - // assert - Assert.Equal(type, typeReference.Type); - Assert.Equal(TypeContext.Input, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } - - [Fact] - public async Task TypeReference_Create_From_ScalarType() - { - // arrange - StringType type = await CreateTypeAsync(); - - // act - SchemaTypeReference typeReference = TypeReference.Create( - type, - scope: "abc"); - - // assert - Assert.Equal(type, typeReference.Type); - Assert.Equal(TypeContext.None, typeReference.Context); - Assert.Equal("abc", typeReference.Scope); - } - - [Fact] - public async Task SchemaTypeReference_Equals_To_Null() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var result = x.Equals((SchemaTypeReference)null); - - // assert - Assert.False(result); - } - - [Fact] - public async Task SchemaTypeReference_Equals_To_Same() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var xx = x.Equals((SchemaTypeReference)x); - - // assert - Assert.True(xx); - } - - [Fact] - public async Task SchemaTypeReference_Equals_Scope_Different() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type, scope: "abc"); - SchemaTypeReference y = TypeReference.Create(type, scope: "def"); - SchemaTypeReference z = TypeReference.Create(type, scope: "abc"); - - // act - var xy = x.Equals(y); - var xz = x.Equals(y); - - // assert - Assert.False(xy); - Assert.False(xz); - } - - [Fact] - public async Task ITypeReference_Equals_To_Null() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var result = x.Equals((ITypeReference)null); - - // assert - Assert.False(result); - } - - [Fact] - public async Task ITypeReference_Equals_To_Same() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var xx = x.Equals((ITypeReference)x); - - // assert - Assert.True(xx); - } - - [Fact] - public async Task ITypeReference_Equals_To_SyntaxTypeRef() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var xx = x.Equals(TypeReference.Create(new NameType("foo"))); - - // assert - Assert.False(xx); - } - - [Fact] - public async Task ITypeReference_Equals_Scope_Different() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type, scope: "abc"); - SchemaTypeReference y = TypeReference.Create(type, scope: "def"); - SchemaTypeReference z = TypeReference.Create(type, scope: "abc"); - - // act - var xy = x.Equals((ITypeReference)y); - var xz = x.Equals((ITypeReference)y); - - // assert - Assert.False(xy); - Assert.False(xz); - } - - [Fact] - public async Task Object_Equals_To_Null() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var result = x.Equals((object)null); - - // assert - Assert.False(result); - } - - [Fact] - public async Task Object_Equals_To_Same() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var xx = x.Equals((object)x); - - // assert - Assert.True(xx); - } - - [Fact] - public async Task Object_Equals_To_Object() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type); - - // act - var xx = x.Equals(new object()); - - // assert - Assert.False(xx); - } - - [Fact] - public async Task Object_Equals_Scope_Different() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create(type, scope: "abc"); - SchemaTypeReference y = TypeReference.Create(type, scope: "def"); - SchemaTypeReference z = TypeReference.Create(type, scope: "abc"); - - // act - var xy = x.Equals((object)y); - var xz = x.Equals((object)y); - - // assert - Assert.False(xy); - Assert.False(xz); - } - - [Fact] - public async Task SchemaTypeReference_ToString() - { - // arrange - StringType type = await CreateTypeAsync(); - SchemaTypeReference typeReference = TypeReference.Create(type); - - // act - var result = typeReference.ToString(); - - // assert - Assert.Equal("None: HotChocolate.Types.StringType", result); - } - - [Fact] - public async Task SchemaTypeReference_WithType() - { - // arrange - StringType stringType = await CreateTypeAsync(); - IntType intType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.WithType(intType); - - // assert - Assert.Equal(intType, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_WithType_Null() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - Action action = () => typeReference1.WithType(null!); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task SchemaTypeReference_WithContext() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.WithContext(TypeContext.Output); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.Output, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_WithContext_Nothing() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.WithContext(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_WithScope() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.WithScope("bar"); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_WithScope_Nothing() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.WithScope(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Null(typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_With() - { - // arrange - StringType stringType = await CreateTypeAsync(); - IntType intType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.With( - intType, - scope: "bar"); - - // assert - Assert.Equal(intType, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_With_Nothing() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.With(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_With_Type() - { - // arrange - StringType stringType = await CreateTypeAsync(); - IntType intType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.With(intType); - - // assert - Assert.Equal(intType, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_With_Type_Null() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - Action action = () => typeReference1.With(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public async Task SchemaTypeReference_With_Context() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.With(context: TypeContext.None); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_With_Scope() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference typeReference1 = TypeReference.Create( - stringType, - scope: "foo"); - - // act - SchemaTypeReference typeReference2 = typeReference1.With(scope: "bar"); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public async Task SchemaTypeReference_GetHashCode() - { - // arrange - StringType stringType = await CreateTypeAsync(); - SchemaTypeReference x = TypeReference.Create( - stringType, - scope: "foo"); - - SchemaTypeReference y = TypeReference.Create( - stringType, - scope: "foo"); - - SchemaTypeReference z = TypeReference.Create( - stringType); - - // act - var xh = x.GetHashCode(); - var yh = y.GetHashCode(); - var zh = z.GetHashCode(); - - // assert - Assert.Equal(xh, yh); - Assert.NotEqual(xh, zh); - } - - [Fact] - public void SchemaTypeReference_InferTypeContext_From_SchemaType() - { - // arrange - // act - TypeContext context = SchemaTypeReference.InferTypeContext(typeof(ObjectType)); - - // assert - Assert.Equal(TypeContext.Output, context); - } - - [Fact] - public void SchemaTypeReference_InferTypeContext_Object_From_SchemaType() - { - // arrange - // act - TypeContext context = SchemaTypeReference.InferTypeContext((object)typeof(ObjectType)); - - // assert - Assert.Equal(TypeContext.Output, context); - } - - [Fact] - public void SchemaTypeReference_InferTypeContext_Object_From_String_None() - { - // arrange - // act - TypeContext context = SchemaTypeReference.InferTypeContext((object)"foo"); - - // assert - Assert.Equal(TypeContext.None, context); - } - - [Fact] - public void SchemaTypeReference_InferTypeContext_From_RuntimeType_None() - { - // arrange - // act - TypeContext context = SchemaTypeReference.InferTypeContext(typeof(Foo)); - - // assert - Assert.Equal(TypeContext.None, context); - } - - [Fact] - public void SchemaTypeReference_InferTypeContext_Type_Is_Null() - { - // arrange - // act - Action action = () => SchemaTypeReference.InferTypeContext(default(Type)!); - - // assert - Assert.Throws(action); - } - - public class Foo - { - public string Bar => "bar"; - } - - public class Bar - { - public string Baz { get; set; } - } + [Fact] + public async Task TypeReference_Create_From_OutputType() + { + // arrange + var type = await CreateTypeAsync>(); + + // act + var typeReference = TypeReference.Create( + type, + scope: "abc"); + + // assert + Assert.Equal(type, typeReference.Type); + Assert.Equal(TypeContext.Output, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } + + [Fact] + public async Task TypeReference_Create_From_InputType() + { + // arrange + var type = await CreateTypeAsync>(); + + // act + var typeReference = TypeReference.Create( + type, + scope: "abc"); + + // assert + Assert.Equal(type, typeReference.Type); + Assert.Equal(TypeContext.Input, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } + + [Fact] + public async Task TypeReference_Create_From_ScalarType() + { + // arrange + var type = await CreateTypeAsync(); + + // act + var typeReference = TypeReference.Create( + type, + scope: "abc"); + + // assert + Assert.Equal(type, typeReference.Type); + Assert.Equal(TypeContext.None, typeReference.Context); + Assert.Equal("abc", typeReference.Scope); + } + + [Fact] + public async Task SchemaTypeReference_Equals_To_Null() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var result = x.Equals((SchemaTypeReference)null); + + // assert + Assert.False(result); + } + + [Fact] + public async Task SchemaTypeReference_Equals_To_Same() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var xx = x.Equals((SchemaTypeReference)x); + + // assert + Assert.True(xx); + } + + [Fact] + public async Task SchemaTypeReference_Equals_Scope_Different() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type, scope: "abc"); + var y = TypeReference.Create(type, scope: "def"); + var z = TypeReference.Create(type, scope: "abc"); + + // act + var xy = x.Equals(y); + var xz = x.Equals(y); + + // assert + Assert.False(xy); + Assert.False(xz); + } + + [Fact] + public async Task ITypeReference_Equals_To_Null() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var result = x.Equals((ITypeReference)null); + + // assert + Assert.False(result); + } + + [Fact] + public async Task ITypeReference_Equals_To_Same() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var xx = x.Equals((ITypeReference)x); + + // assert + Assert.True(xx); + } + + [Fact] + public async Task ITypeReference_Equals_To_SyntaxTypeRef() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var xx = x.Equals(TypeReference.Create(new NameType("foo"))); + + // assert + Assert.False(xx); + } + + [Fact] + public async Task ITypeReference_Equals_Scope_Different() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type, scope: "abc"); + var y = TypeReference.Create(type, scope: "def"); + var z = TypeReference.Create(type, scope: "abc"); + + // act + var xy = x.Equals((ITypeReference)y); + var xz = x.Equals((ITypeReference)y); + + // assert + Assert.False(xy); + Assert.False(xz); + } + + [Fact] + public async Task Object_Equals_To_Null() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var result = x.Equals((object)null); + + // assert + Assert.False(result); + } + + [Fact] + public async Task Object_Equals_To_Same() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var xx = x.Equals((object)x); + + // assert + Assert.True(xx); + } + + [Fact] + public async Task Object_Equals_To_Object() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type); + + // act + var xx = x.Equals(new object()); + + // assert + Assert.False(xx); + } + + [Fact] + public async Task Object_Equals_Scope_Different() + { + // arrange + var type = await CreateTypeAsync(); + var x = TypeReference.Create(type, scope: "abc"); + var y = TypeReference.Create(type, scope: "def"); + var z = TypeReference.Create(type, scope: "abc"); + + // act + var xy = x.Equals((object)y); + var xz = x.Equals((object)y); + + // assert + Assert.False(xy); + Assert.False(xz); + } + + [Fact] + public async Task SchemaTypeReference_ToString() + { + // arrange + var type = await CreateTypeAsync(); + var typeReference = TypeReference.Create(type); + + // act + var result = typeReference.ToString(); + + // assert + Assert.Equal("None: HotChocolate.Types.StringType", result); + } + + [Fact] + public async Task SchemaTypeReference_WithType() + { + // arrange + var stringType = await CreateTypeAsync(); + var intType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithType(intType); + + // assert + Assert.Equal(intType, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_WithType_Null() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + Action action = () => typeReference1.WithType(null!); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task SchemaTypeReference_WithContext() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithContext(TypeContext.Output); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.Output, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_WithContext_Nothing() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithContext(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_WithScope() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithScope("bar"); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_WithScope_Nothing() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithScope(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Null(typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_With() + { + // arrange + var stringType = await CreateTypeAsync(); + var intType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With( + intType, + scope: "bar"); + + // assert + Assert.Equal(intType, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_With_Nothing() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_With_Type() + { + // arrange + var stringType = await CreateTypeAsync(); + var intType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(intType); + + // assert + Assert.Equal(intType, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_With_Type_Null() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + Action action = () => typeReference1.With(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public async Task SchemaTypeReference_With_Context() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(context: TypeContext.None); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_With_Scope() + { + // arrange + var stringType = await CreateTypeAsync(); + var typeReference1 = TypeReference.Create( + stringType, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(scope: "bar"); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public async Task SchemaTypeReference_GetHashCode() + { + // arrange + var stringType = await CreateTypeAsync(); + var x = TypeReference.Create( + stringType, + scope: "foo"); + + var y = TypeReference.Create( + stringType, + scope: "foo"); + + var z = TypeReference.Create( + stringType); + + // act + var xh = x.GetHashCode(); + var yh = y.GetHashCode(); + var zh = z.GetHashCode(); + + // assert + Assert.Equal(xh, yh); + Assert.NotEqual(xh, zh); + } + + [Fact] + public void SchemaTypeReference_InferTypeContext_From_SchemaType() + { + // arrange + // act + var context = SchemaTypeReference.InferTypeContext(typeof(ObjectType)); + + // assert + Assert.Equal(TypeContext.Output, context); + } + + [Fact] + public void SchemaTypeReference_InferTypeContext_Object_From_SchemaType() + { + // arrange + // act + var context = SchemaTypeReference.InferTypeContext((object)typeof(ObjectType)); + + // assert + Assert.Equal(TypeContext.Output, context); + } + + [Fact] + public void SchemaTypeReference_InferTypeContext_Object_From_String_None() + { + // arrange + // act + var context = SchemaTypeReference.InferTypeContext((object)"foo"); + + // assert + Assert.Equal(TypeContext.None, context); + } + + [Fact] + public void SchemaTypeReference_InferTypeContext_From_RuntimeType_None() + { + // arrange + // act + var context = SchemaTypeReference.InferTypeContext(typeof(Foo)); + + // assert + Assert.Equal(TypeContext.None, context); + } + + [Fact] + public void SchemaTypeReference_InferTypeContext_Type_Is_Null() + { + // arrange + // act + Action action = () => SchemaTypeReference.InferTypeContext(default(Type)!); + + // assert + Assert.Throws(action); + } + + public class Foo + { + public string Bar => "bar"; + } + + public class Bar + { + public string Baz { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SyntaxTypeReferenceTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SyntaxTypeReferenceTests.cs index 636b011ff1d..64b474595a8 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SyntaxTypeReferenceTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Descriptors/TypeReferences/SyntaxTypeReferenceTests.cs @@ -2,590 +2,589 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types.Descriptors +namespace HotChocolate.Types.Descriptors; + +public class SyntaxTypeReferenceTests { - public class SyntaxTypeReferenceTests + private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); + + [Fact] + public void TypeReference_Create() + { + // arrange + var namedType = new NamedTypeNode("Foo"); + + // act + var typeReference = TypeReference.Create( + namedType, + TypeContext.Input, + scope: "foo"); + + // assert + Assert.Equal(namedType, typeReference.Type); + Assert.Equal(TypeContext.Input, typeReference.Context); + Assert.Equal("foo", typeReference.Scope); + } + + [Fact] + public void TypeReference_Create_With_Name() + { + // arrange + // act + var typeReference = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // assert + Assert.Equal("Foo", typeReference.Type.NamedType().Name.Value); + Assert.Equal(TypeContext.Input, typeReference.Context); + Assert.Equal("foo", typeReference.Scope); + } + + [Fact] + public void SyntaxTypeReference_Equals_To_Null() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var result = x.Equals((SyntaxTypeReference)null); + + // assert + Assert.False(result); + } + + [Fact] + public void SyntaxTypeReference_Equals_To_Same() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var xx = x.Equals((SyntaxTypeReference)x); + + // assert + Assert.True(xx); + } + + [Fact] + public void SyntaxTypeReference_Equals_Context_None_Does_Not_Matter() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + var y = TypeReference.Create( + "Foo", + TypeContext.Output); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xy = x.Equals(y); + var xz = x.Equals(z); + var yz = y.Equals(z); + + // assert + Assert.True(xy); + Assert.True(xz); + Assert.False(yz); + } + + [Fact] + public void SyntaxTypeReference_Equals_Scope_Different() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None, + scope: "a"); + + var y = TypeReference.Create( + "Foo", + TypeContext.Output, + scope: "a"); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xy = x.Equals(y); + var xz = x.Equals(z); + var yz = y.Equals(z); + + // assert + Assert.True(xy); + Assert.False(xz); + Assert.False(yz); + } + + [Fact] + public void ITypeReference_Equals_To_Null() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var result = x.Equals((ITypeReference)null); + + // assert + Assert.False(result); + } + + [Fact] + public void ITypeReference_Equals_To_Same() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var xx = x.Equals((ITypeReference)x); + + // assert + Assert.True(xx); + } + + [Fact] + public void ITypeReference_Equals_To_SyntaxTypeRef() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var xx = x.Equals(TypeReference.Create(_typeInspector.GetType(typeof(int)))); + + // assert + Assert.False(xx); + } + + [Fact] + public void ITypeReference_Equals_Context_None_Does_Not_Matter() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + var y = TypeReference.Create( + "Foo", + TypeContext.Output); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xy = x.Equals((ITypeReference)y); + var xz = x.Equals((ITypeReference)z); + var yz = y.Equals((ITypeReference)z); + + // assert + Assert.True(xy); + Assert.True(xz); + Assert.False(yz); + } + + [Fact] + public void ITypeReference_Equals_Scope_Different() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None, + scope: "a"); + + var y = TypeReference.Create( + "Foo", + TypeContext.Output, + scope: "a"); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xy = x.Equals((ITypeReference)y); + var xz = x.Equals((ITypeReference)z); + var yz = y.Equals((ITypeReference)z); + + // assert + Assert.True(xy); + Assert.False(xz); + Assert.False(yz); + } + + [Fact] + public void Object_Equals_To_Null() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var result = x.Equals((object)null); + + // assert + Assert.False(result); + } + + [Fact] + public void Object_Equals_To_Same() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var xx = x.Equals((object)x); + + // assert + Assert.True(xx); + } + + [Fact] + public void Object_Equals_To_Object() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + // act + var xx = x.Equals(new object()); + + // assert + Assert.False(xx); + } + + [Fact] + public void Object_Equals_Context_None_Does_Not_Matter() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None); + + var y = TypeReference.Create( + "Foo", + TypeContext.Output); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xy = x.Equals((object)y); + var xz = x.Equals((object)z); + var yz = y.Equals((object)z); + + // assert + Assert.True(xy); + Assert.True(xz); + Assert.False(yz); + } + + [Fact] + public void Object_Equals_Scope_Different() + { + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None, + scope: "a"); + + var y = TypeReference.Create( + "Foo", + TypeContext.Output, + scope: "a"); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xy = x.Equals((object)y); + var xz = x.Equals((object)z); + var yz = y.Equals((object)z); + + // assert + Assert.True(xy); + Assert.False(xz); + Assert.False(yz); + } + + [Fact] + public void SyntaxTypeReference_ToString() + { + // arrange + var typeReference = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var result = typeReference.ToString(); + + // assert + Assert.Equal("Input: Foo", result); + } + + [Fact] + public void SyntaxTypeReference_WithType() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithType(new NamedTypeNode("Bar")); + + // assert + Assert.Equal("Bar", Assert.IsType(typeReference2.Type).Name.Value); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_WithType_Null() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + Action action = () => typeReference1.WithType(null!); + + // assert + Assert.Throws(action); + } + + [Fact] + public void SyntaxTypeReference_WithContext() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithContext(TypeContext.Output); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.Output, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_WithContext_Nothing() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithContext(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_WithScope() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithScope("bar"); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_WithScope_Nothing() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.WithScope(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Null(typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_With() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With( + new NamedTypeNode("Bar"), + TypeContext.Output, + scope: "bar"); + + // assert + Assert.Equal("Bar", Assert.IsType(typeReference2.Type).Name.Value); + Assert.Equal(TypeContext.Output, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_With_Nothing() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_With_Type() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(new NamedTypeNode("Bar")); + + // assert + Assert.Equal("Bar", Assert.IsType(typeReference2.Type).Name.Value); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_With_Type_Null() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + Action action = () => typeReference1.With(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void SyntaxTypeReference_With_Context() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(context: TypeContext.None); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(TypeContext.None, typeReference2.Context); + Assert.Equal(typeReference1.Scope, typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_With_Scope() + { + // arrange + var typeReference1 = TypeReference.Create( + "Foo", + TypeContext.Input, + scope: "foo"); + + // act + var typeReference2 = typeReference1.With(scope: "bar"); + + // assert + Assert.Equal(typeReference1.Type, typeReference2.Type); + Assert.Equal(typeReference1.Context, typeReference2.Context); + Assert.Equal("bar", typeReference2.Scope); + } + + [Fact] + public void SyntaxTypeReference_GetHashCode() { - private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); - - [Fact] - public void TypeReference_Create() - { - // arrange - var namedType = new NamedTypeNode("Foo"); - - // act - SyntaxTypeReference typeReference = TypeReference.Create( - namedType, - TypeContext.Input, - scope: "foo"); - - // assert - Assert.Equal(namedType, typeReference.Type); - Assert.Equal(TypeContext.Input, typeReference.Context); - Assert.Equal("foo", typeReference.Scope); - } - - [Fact] - public void TypeReference_Create_With_Name() - { - // arrange - // act - SyntaxTypeReference typeReference = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // assert - Assert.Equal("Foo", typeReference.Type.NamedType().Name.Value); - Assert.Equal(TypeContext.Input, typeReference.Context); - Assert.Equal("foo", typeReference.Scope); - } - - [Fact] - public void SyntaxTypeReference_Equals_To_Null() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var result = x.Equals((SyntaxTypeReference)null); - - // assert - Assert.False(result); - } - - [Fact] - public void SyntaxTypeReference_Equals_To_Same() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var xx = x.Equals((SyntaxTypeReference)x); - - // assert - Assert.True(xx); - } - - [Fact] - public void SyntaxTypeReference_Equals_Context_None_Does_Not_Matter() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.Output); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xy = x.Equals(y); - var xz = x.Equals(z); - var yz = y.Equals(z); - - // assert - Assert.True(xy); - Assert.True(xz); - Assert.False(yz); - } - - [Fact] - public void SyntaxTypeReference_Equals_Scope_Different() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None, - scope: "a"); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.Output, - scope: "a"); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xy = x.Equals(y); - var xz = x.Equals(z); - var yz = y.Equals(z); - - // assert - Assert.True(xy); - Assert.False(xz); - Assert.False(yz); - } - - [Fact] - public void ITypeReference_Equals_To_Null() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var result = x.Equals((ITypeReference)null); - - // assert - Assert.False(result); - } - - [Fact] - public void ITypeReference_Equals_To_Same() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var xx = x.Equals((ITypeReference)x); - - // assert - Assert.True(xx); - } - - [Fact] - public void ITypeReference_Equals_To_SyntaxTypeRef() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var xx = x.Equals(TypeReference.Create(_typeInspector.GetType(typeof(int)))); - - // assert - Assert.False(xx); - } - - [Fact] - public void ITypeReference_Equals_Context_None_Does_Not_Matter() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.Output); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xy = x.Equals((ITypeReference)y); - var xz = x.Equals((ITypeReference)z); - var yz = y.Equals((ITypeReference)z); - - // assert - Assert.True(xy); - Assert.True(xz); - Assert.False(yz); - } - - [Fact] - public void ITypeReference_Equals_Scope_Different() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None, - scope: "a"); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.Output, - scope: "a"); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xy = x.Equals((ITypeReference)y); - var xz = x.Equals((ITypeReference)z); - var yz = y.Equals((ITypeReference)z); - - // assert - Assert.True(xy); - Assert.False(xz); - Assert.False(yz); - } - - [Fact] - public void Object_Equals_To_Null() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var result = x.Equals((object)null); - - // assert - Assert.False(result); - } - - [Fact] - public void Object_Equals_To_Same() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var xx = x.Equals((object)x); - - // assert - Assert.True(xx); - } - - [Fact] - public void Object_Equals_To_Object() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - // act - var xx = x.Equals(new object()); - - // assert - Assert.False(xx); - } - - [Fact] - public void Object_Equals_Context_None_Does_Not_Matter() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.Output); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xy = x.Equals((object)y); - var xz = x.Equals((object)z); - var yz = y.Equals((object)z); - - // assert - Assert.True(xy); - Assert.True(xz); - Assert.False(yz); - } - - [Fact] - public void Object_Equals_Scope_Different() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None, - scope: "a"); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.Output, - scope: "a"); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xy = x.Equals((object)y); - var xz = x.Equals((object)z); - var yz = y.Equals((object)z); - - // assert - Assert.True(xy); - Assert.False(xz); - Assert.False(yz); - } - - [Fact] - public void SyntaxTypeReference_ToString() - { - // arrange - SyntaxTypeReference typeReference = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var result = typeReference.ToString(); - - // assert - Assert.Equal("Input: Foo", result); - } - - [Fact] - public void SyntaxTypeReference_WithType() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.WithType(new NamedTypeNode("Bar")); - - // assert - Assert.Equal("Bar", Assert.IsType(typeReference2.Type).Name.Value); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_WithType_Null() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - Action action = () => typeReference1.WithType(null!); - - // assert - Assert.Throws(action); - } - - [Fact] - public void SyntaxTypeReference_WithContext() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.WithContext(TypeContext.Output); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.Output, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_WithContext_Nothing() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.WithContext(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_WithScope() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.WithScope("bar"); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_WithScope_Nothing() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.WithScope(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Null(typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_With() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.With( - new NamedTypeNode("Bar"), - TypeContext.Output, - scope: "bar"); - - // assert - Assert.Equal("Bar", Assert.IsType(typeReference2.Type).Name.Value); - Assert.Equal(TypeContext.Output, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_With_Nothing() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.With(); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_With_Type() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.With(new NamedTypeNode("Bar")); - - // assert - Assert.Equal("Bar", Assert.IsType(typeReference2.Type).Name.Value); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_With_Type_Null() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - Action action = () => typeReference1.With(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void SyntaxTypeReference_With_Context() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.With(context: TypeContext.None); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(TypeContext.None, typeReference2.Context); - Assert.Equal(typeReference1.Scope, typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_With_Scope() - { - // arrange - SyntaxTypeReference typeReference1 = TypeReference.Create( - "Foo", - TypeContext.Input, - scope: "foo"); - - // act - SyntaxTypeReference typeReference2 = typeReference1.With(scope: "bar"); - - // assert - Assert.Equal(typeReference1.Type, typeReference2.Type); - Assert.Equal(typeReference1.Context, typeReference2.Context); - Assert.Equal("bar", typeReference2.Scope); - } - - [Fact] - public void SyntaxTypeReference_GetHashCode() - { - // arrange - SyntaxTypeReference x = TypeReference.Create( - "Foo", - TypeContext.None, - scope: "foo"); - - SyntaxTypeReference y = TypeReference.Create( - "Foo", - TypeContext.None, - scope: "foo"); - - SyntaxTypeReference z = TypeReference.Create( - "Foo", - TypeContext.Input); - - // act - var xh = x.GetHashCode(); - var yh = y.GetHashCode(); - var zh = z.GetHashCode(); - - // assert - Assert.Equal(xh, yh); - Assert.NotEqual(xh, zh); - } + // arrange + var x = TypeReference.Create( + "Foo", + TypeContext.None, + scope: "foo"); + + var y = TypeReference.Create( + "Foo", + TypeContext.None, + scope: "foo"); + + var z = TypeReference.Create( + "Foo", + TypeContext.Input); + + // act + var xh = x.GetHashCode(); + var yh = y.GetHashCode(); + var zh = z.GetHashCode(); + + // assert + Assert.Equal(xh, yh); + Assert.NotEqual(xh, zh); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveCollectionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveCollectionTests.cs index a1357e0a1b8..e03ee1c87b4 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveCollectionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveCollectionTests.cs @@ -2,134 +2,133 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DirectiveCollectionTests + : TypeTestBase { - public class DirectiveCollectionTests - : TypeTestBase + [Fact] + public void DirectiveOrderIsSignificant() { - [Fact] - public void DirectiveOrderIsSignificant() - { - // arrange - var someType = new ObjectType(t => - t.Name("Foo") - .Field("abc") - .Type() - .Resolve("abc") - .Directive(new DirectiveNode("foo")) - .Directive(new DirectiveNode("bar"))); - - var foo = new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.FieldDefinition)); - - var bar = new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.FieldDefinition)); - - // act - ISchema schema = CreateSchema(b => - { - b.AddType(someType); - b.AddDirectiveType(foo); - b.AddDirectiveType(bar); - }); - - // assert - Assert.Collection(someType.Fields["abc"].Directives, - t => Assert.Equal("foo", t.Name), - t => Assert.Equal("bar", t.Name)); - } - - [Fact] - public void DirectiveIsNotRepeatable() - { - // arrange - var someType = new ObjectType(t => - t.Name("Foo") - .Field("abc") - .Type() - .Resolve("abc") - .Directive(new DirectiveNode("foo")) - .Directive(new DirectiveNode("foo"))); - - var foo = new DirectiveType(d => - d.Name("foo").Location(DirectiveLocation.FieldDefinition)); - - // act - Action action = () => CreateSchema(b => - { - b.AddType(someType); - b.AddDirectiveType(foo); - }); - - // assert - Assert.Collection(Assert.Throws(action).Errors, - t => Assert.Equal( - "The specified directive `@foo` " + - "is unique and cannot be added twice.", - t.Message)); - } - - [Fact] - public void DirectiveIsRepeatable() + // arrange + var someType = new ObjectType(t => + t.Name("Foo") + .Field("abc") + .Type() + .Resolve("abc") + .Directive(new DirectiveNode("foo")) + .Directive(new DirectiveNode("bar"))); + + var foo = new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.FieldDefinition)); + + var bar = new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.FieldDefinition)); + + // act + var schema = CreateSchema(b => { - // arrange - var someType = new ObjectType(t => - t.Name("Foo") - .Field("abc") - .Type() - .Resolve("abc") - .Directive(new DirectiveNode("foo")) - .Directive(new DirectiveNode("foo"))); - - var foo = new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.FieldDefinition) - .Repeatable()); - - // act - CreateSchema(b => - { - b.AddType(someType); - b.AddDirectiveType(foo); - }); - - // assert - Assert.Collection(someType.Fields["abc"].Directives, - t => Assert.Equal("foo", t.Name), - t => Assert.Equal("foo", t.Name)); - } - - [Fact] - public void InvalidLocation() + b.AddType(someType); + b.AddDirectiveType(foo); + b.AddDirectiveType(bar); + }); + + // assert + Assert.Collection(someType.Fields["abc"].Directives, + t => Assert.Equal("foo", t.Name), + t => Assert.Equal("bar", t.Name)); + } + + [Fact] + public void DirectiveIsNotRepeatable() + { + // arrange + var someType = new ObjectType(t => + t.Name("Foo") + .Field("abc") + .Type() + .Resolve("abc") + .Directive(new DirectiveNode("foo")) + .Directive(new DirectiveNode("foo"))); + + var foo = new DirectiveType(d => + d.Name("foo").Location(DirectiveLocation.FieldDefinition)); + + // act + Action action = () => CreateSchema(b => { - // arrange - var someType = new ObjectType(t => t - .Name("Foo") + b.AddType(someType); + b.AddDirectiveType(foo); + }); + + // assert + Assert.Collection(Assert.Throws(action).Errors, + t => Assert.Equal( + "The specified directive `@foo` " + + "is unique and cannot be added twice.", + t.Message)); + } + + [Fact] + public void DirectiveIsRepeatable() + { + // arrange + var someType = new ObjectType(t => + t.Name("Foo") .Field("abc") .Type() .Resolve("abc") + .Directive(new DirectiveNode("foo")) .Directive(new DirectiveNode("foo"))); - var foo = new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object)); - - // act - Action action = () => CreateSchema(b => - { - b.AddType(someType); - b.AddDirectiveType(foo); - }); - - // assert - Assert.Collection(Assert.Throws(action).Errors, - t => Assert.Equal( - "The specified directive `@foo` " + - "is not allowed on the current location " + - $"`{DirectiveLocation.FieldDefinition}`.", - t.Message)); - } + var foo = new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.FieldDefinition) + .Repeatable()); + + // act + CreateSchema(b => + { + b.AddType(someType); + b.AddDirectiveType(foo); + }); + + // assert + Assert.Collection(someType.Fields["abc"].Directives, + t => Assert.Equal("foo", t.Name), + t => Assert.Equal("foo", t.Name)); + } + + [Fact] + public void InvalidLocation() + { + // arrange + var someType = new ObjectType(t => t + .Name("Foo") + .Field("abc") + .Type() + .Resolve("abc") + .Directive(new DirectiveNode("foo"))); + + var foo = new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object)); + + // act + Action action = () => CreateSchema(b => + { + b.AddType(someType); + b.AddDirectiveType(foo); + }); + + // assert + Assert.Collection(Assert.Throws(action).Errors, + t => Assert.Equal( + "The specified directive `@foo` " + + "is not allowed on the current location " + + $"`{DirectiveLocation.FieldDefinition}`.", + t.Message)); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveLocationTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveLocationTests.cs index c9d0643d096..9316652a098 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveLocationTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveLocationTests.cs @@ -2,22 +2,21 @@ using System.Linq; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DirectiveLocationTests { - public class DirectiveLocationTests + // flag values must be set correct + [Fact] + public void FlagsCorrect() { - // flag values must be set correct - [Fact] - public void FlagsCorrect() - { - Enum.GetValues(typeof(DirectiveLocation)) - .Cast() - .Aggregate(0, (acc, loc) => - { - var v = acc == 0 ? 1 : acc * 2; - Assert.Equal(v, (int)loc); - return v; - }); - } + Enum.GetValues(typeof(DirectiveLocation)) + .Cast() + .Aggregate(0, (acc, loc) => + { + var v = acc == 0 ? 1 : acc * 2; + Assert.Equal(v, (int)loc); + return v; + }); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTests.cs index d1d7e40da47..530984d92a3 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTests.cs @@ -7,203 +7,202 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DirectiveTests : TypeTestBase { - public class DirectiveTests : TypeTestBase - { - private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); + private readonly ITypeInspector _typeInspector = new DefaultTypeInspector(); - [Fact] - public void ConvertCustomDirectiveToDirectiveNode() + [Fact] + public void ConvertCustomDirectiveToDirectiveNode() + { + // arrange + var schema = CreateSchema(); + var directiveType = schema.GetDirectiveType("Foo"); + var fooDirective = new FooDirective { - // arrange - ISchema schema = CreateSchema(); - DirectiveType directiveType = schema.GetDirectiveType("Foo"); - var fooDirective = new FooDirective + Bar = "123", + Child = new FooChild { - Bar = "123", - Child = new FooChild - { - Bar = "456" - } - }; - - // act - var directive = Directive.FromDescription( - directiveType, - new DirectiveDefinition( - fooDirective, - _typeInspector.GetTypeRef(fooDirective.GetType())), - new object()); - DirectiveNode directiveNode = directive.ToNode(); - - // assert - Assert.Equal(directiveType.Name, directiveNode.Name.Value); - Assert.Collection(directiveNode.Arguments, - t => - { - Assert.Equal("bar", t.Name.Value); - Assert.Equal("123", ((StringValueNode)t.Value).Value); - }, - t => - { - Assert.Equal("child", t.Name.Value); - Assert.Collection(((ObjectValueNode)t.Value).Fields, - x => - { - Assert.Equal("bar", x.Name.Value); - Assert.Equal("456", - ((StringValueNode)x.Value).Value); - }); - }); - } + Bar = "456" + } + }; + + // act + var directive = Directive.FromDescription( + directiveType, + new DirectiveDefinition( + fooDirective, + _typeInspector.GetTypeRef(fooDirective.GetType())), + new object()); + var directiveNode = directive.ToNode(); + + // assert + Assert.Equal(directiveType.Name, directiveNode.Name.Value); + Assert.Collection(directiveNode.Arguments, + t => + { + Assert.Equal("bar", t.Name.Value); + Assert.Equal("123", ((StringValueNode)t.Value).Value); + }, + t => + { + Assert.Equal("child", t.Name.Value); + Assert.Collection(((ObjectValueNode)t.Value).Fields, + x => + { + Assert.Equal("bar", x.Name.Value); + Assert.Equal("456", + ((StringValueNode)x.Value).Value); + }); + }); + } - [Fact] - public void MapCustomDirectiveToDifferentType() + [Fact] + public void MapCustomDirectiveToDifferentType() + { + // arrange + var schema = CreateSchema(); + var directiveType = schema.GetDirectiveType("Foo"); + var fooDirective = new FooDirective { - // arrange - ISchema schema = CreateSchema(); - DirectiveType directiveType = schema.GetDirectiveType("Foo"); - var fooDirective = new FooDirective + Bar = "123", + Child = new FooChild { - Bar = "123", - Child = new FooChild - { - Bar = "456" - } - }; - - // act - var directive = Directive.FromDescription( - directiveType, - new DirectiveDefinition( - fooDirective, - _typeInspector.GetTypeRef(fooDirective.GetType())), - new object()); - FooChild mappedObject = directive.ToObject(); - - // assert - Assert.Equal("123", mappedObject.Bar); - } + Bar = "456" + } + }; + + // act + var directive = Directive.FromDescription( + directiveType, + new DirectiveDefinition( + fooDirective, + _typeInspector.GetTypeRef(fooDirective.GetType())), + new object()); + var mappedObject = directive.ToObject(); + + // assert + Assert.Equal("123", mappedObject.Bar); + } - [Fact] - public void GetArgumentFromCustomDirective() + [Fact] + public void GetArgumentFromCustomDirective() + { + // arrange + var schema = CreateSchema(); + var directiveType = schema.GetDirectiveType("Foo"); + var fooDirective = new FooDirective { - // arrange - ISchema schema = CreateSchema(); - DirectiveType directiveType = schema.GetDirectiveType("Foo"); - var fooDirective = new FooDirective + Bar = "123", + Child = new FooChild { - Bar = "123", - Child = new FooChild - { - Bar = "456" - } - }; - - // act - var directive = Directive.FromDescription( - directiveType, - new DirectiveDefinition( - fooDirective, - _typeInspector.GetTypeRef(fooDirective.GetType())), - new object()); - var barValue = directive.GetArgument("bar"); - - // assert - Assert.Equal("123", barValue); - } + Bar = "456" + } + }; + + // act + var directive = Directive.FromDescription( + directiveType, + new DirectiveDefinition( + fooDirective, + _typeInspector.GetTypeRef(fooDirective.GetType())), + new object()); + var barValue = directive.GetArgument("bar"); + + // assert + Assert.Equal("123", barValue); + } - [Fact] - public async Task QueryDirectives_AreAddedToTheSchema() - { - // arrange - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve("Bar")) - .AddType() - .BuildSchemaAsync(); - - // act - var printedSchema = schema.Print(); - - // assert - printedSchema.MatchSnapshot(); - } + [Fact] + public async Task QueryDirectives_AreAddedToTheSchema() + { + // arrange + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve("Bar")) + .AddType() + .BuildSchemaAsync(); + + // act + var printedSchema = schema.Print(); + + // assert + printedSchema.MatchSnapshot(); + } - [Fact] - public void ExplicitArguments() - { - SchemaBuilder.New() - .AddDirectiveType() - .AddQueryType(d => d - .Name("Query") - .Field("abc") - .Resolve("def") - .Directive(new FooDirective())) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void ExplicitArguments() + { + SchemaBuilder.New() + .AddDirectiveType() + .AddQueryType(d => d + .Name("Query") + .Field("abc") + .Resolve("def") + .Directive(new FooDirective())) + .Create() + .Print() + .MatchSnapshot(); + } - private static ISchema CreateSchema() + private static ISchema CreateSchema() + { + return CreateSchema(b => { - return CreateSchema(b => - { - b.AddDirectiveType(); - b.AddType>(); - }); - } + b.AddDirectiveType(); + b.AddType>(); + }); + } - public class FooQueryDirectiveType - : DirectiveType + public class FooQueryDirectiveType + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Location(DirectiveLocation.Query); - } + descriptor.Name("Foo"); + descriptor.Location(DirectiveLocation.Query); } + } - public class FooDirectiveType - : DirectiveType + public class FooDirectiveType + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Location(DirectiveLocation.Schema); - } + descriptor.Name("Foo"); + descriptor.Location(DirectiveLocation.Schema); } + } - public class FooDirectiveTypeExplicit - : DirectiveType + public class FooDirectiveTypeExplicit + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.BindArgumentsExplicitly(); - } + descriptor.Name("Foo"); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.BindArgumentsExplicitly(); } + } - public class FooDirective - { - public string Bar { get; set; } + public class FooDirective + { + public string Bar { get; set; } - public FooChild Child { get; set; } - } + public FooChild Child { get; set; } + } - public class FooChild - { - public string Bar { get; set; } - } + public class FooChild + { + public string Bar { get; set; } + } - public class FooChild2 - { - public string Bar { get; set; } - } + public class FooChild2 + { + public string Bar { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTypeTests.cs index 190fa654d83..ec232233b57 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/DirectiveTypeTests.cs @@ -10,731 +10,730 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DirectiveTypeTests : TypeTestBase { - public class DirectiveTypeTests : TypeTestBase + [Fact] + public void ConfigureTypedDirectiveWithResolver() { - [Fact] - public void ConfigureTypedDirectiveWithResolver() - { - // arrange - // act - DirectiveType directiveType = - CreateDirective(new CustomDirectiveType()); - - // assert - Assert.True(directiveType.HasMiddleware); - Assert.NotEmpty(directiveType.MiddlewareComponents); - Assert.Equal(typeof(CustomDirective), directiveType.RuntimeType); - Assert.Collection(directiveType.Arguments, - t => Assert.Equal("argument", t.Name.Value)); - } - - [Fact] - public void ConfigureTypedDirective_DefaultBinding_Explicit() - { - // arrange - // act - DirectiveType directiveType = - CreateDirective(new CustomDirectiveType(), - b => b.ModifyOptions(o => - o.DefaultBindingBehavior = BindingBehavior.Explicit)); - - // assert - Assert.True(directiveType.HasMiddleware); - Assert.NotEmpty(directiveType.MiddlewareComponents); - Assert.Equal(typeof(CustomDirective), directiveType.RuntimeType); - Assert.Empty(directiveType.Arguments); - } + // arrange + // act + DirectiveType directiveType = + CreateDirective(new CustomDirectiveType()); + + // assert + Assert.True(directiveType.HasMiddleware); + Assert.NotEmpty(directiveType.MiddlewareComponents); + Assert.Equal(typeof(CustomDirective), directiveType.RuntimeType); + Assert.Collection(directiveType.Arguments, + t => Assert.Equal("argument", t.Name.Value)); + } - [Fact] - public void ConfigureTypedDirectiveNoArguments() - { - // arrange - // act - DirectiveType directiveType = - CreateDirective(new Custom2DirectiveType()); - - // assert - Assert.True(directiveType.HasMiddleware); - Assert.NotEmpty(directiveType.MiddlewareComponents); - Assert.Equal(typeof(CustomDirective), directiveType.RuntimeType); - Assert.Empty(directiveType.Arguments); - } + [Fact] + public void ConfigureTypedDirective_DefaultBinding_Explicit() + { + // arrange + // act + DirectiveType directiveType = + CreateDirective(new CustomDirectiveType(), + b => b.ModifyOptions(o => + o.DefaultBindingBehavior = BindingBehavior.Explicit)); + + // assert + Assert.True(directiveType.HasMiddleware); + Assert.NotEmpty(directiveType.MiddlewareComponents); + Assert.Equal(typeof(CustomDirective), directiveType.RuntimeType); + Assert.Empty(directiveType.Arguments); + } - [Fact] - public void ConfigureDirectiveWithResolver() - { - // arrange - var directiveType = new DirectiveType(t => t - .Name("Foo") - .Location(DirectiveLocation.Field) - .Use(_ => _ => default)); - - // act - directiveType = CreateDirective(directiveType); - - // assert - Assert.True(directiveType.HasMiddleware); - Assert.NotEmpty(directiveType.MiddlewareComponents); - Assert.Equal(typeof(object), directiveType.RuntimeType); - } + [Fact] + public void ConfigureTypedDirectiveNoArguments() + { + // arrange + // act + DirectiveType directiveType = + CreateDirective(new Custom2DirectiveType()); + + // assert + Assert.True(directiveType.HasMiddleware); + Assert.NotEmpty(directiveType.MiddlewareComponents); + Assert.Equal(typeof(CustomDirective), directiveType.RuntimeType); + Assert.Empty(directiveType.Arguments); + } - [Fact] - public void ConfigureIsNull() - { - // act - void Action() => new DirectiveType(null!); + [Fact] + public void ConfigureDirectiveWithResolver() + { + // arrange + var directiveType = new DirectiveType(t => t + .Name("Foo") + .Location(DirectiveLocation.Field) + .Use(_ => _ => default)); + + // act + directiveType = CreateDirective(directiveType); + + // assert + Assert.True(directiveType.HasMiddleware); + Assert.NotEmpty(directiveType.MiddlewareComponents); + Assert.Equal(typeof(object), directiveType.RuntimeType); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void ConfigureIsNull() + { + // act + void Action() => new DirectiveType(null!); - [Fact] - public void NoName() - { - // act - void Action() => CreateDirective(new DirectiveType(_ => { })); + // assert + Assert.Throws(Action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void NoName() + { + // act + void Action() => CreateDirective(new DirectiveType(_ => { })); - [Fact] - public void RepeatableDirective() - { - // arrange - var directiveType = new DirectiveType( - t => t.Name("foo") - .Repeatable() - .Location(DirectiveLocation.Object) - .Argument("a").Type()); + // assert + Assert.Throws(Action); + } - var objectType = new ObjectType(t => + [Fact] + public void RepeatableDirective() + { + // arrange + var directiveType = new DirectiveType( + t => t.Name("foo") + .Repeatable() + .Location(DirectiveLocation.Object) + .Argument("a").Type()); + + var objectType = new ObjectType(t => + { + t.Name("Bar"); + t.Directive("foo", new ArgumentNode("a", "1")); + t.Directive("foo", new ArgumentNode("a", "2")); + t.Field("foo").Resolve(() => "baz"); + }); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(objectType) + .AddDirectiveType(directiveType) + .Create(); + + // assert + Assert.Collection( + schema.GetType("Bar").Directives, + t => { - t.Name("Bar"); - t.Directive("foo", new ArgumentNode("a", "1")); - t.Directive("foo", new ArgumentNode("a", "2")); - t.Field("foo").Resolve(() => "baz"); + Assert.Equal("foo", t.Name); + Assert.Equal("1", t.GetArgument("a")); + }, + t => + { + Assert.Equal("foo", t.Name); + Assert.Equal("2", t.GetArgument("a")); }); + } - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(objectType) - .AddDirectiveType(directiveType) - .Create(); - - // assert - Assert.Collection( - schema.GetType("Bar").Directives, - t => - { - Assert.Equal("foo", t.Name); - Assert.Equal("1", t.GetArgument("a")); - }, - t => - { - Assert.Equal("foo", t.Name); - Assert.Equal("2", t.GetArgument("a")); - }); - } - - [Fact] - public void ExecutableRepeatableDirectives() - { - // arrange - var directiveType = new DirectiveType( - t => t.Name("foo") - .Repeatable() - .Location(DirectiveLocation.Object) - .Location(DirectiveLocation.FieldDefinition) - .Use(_ => _ => default) - .Argument("a").Type()); - - - var objectType = new ObjectType(t => + [Fact] + public void ExecutableRepeatableDirectives() + { + // arrange + var directiveType = new DirectiveType( + t => t.Name("foo") + .Repeatable() + .Location(DirectiveLocation.Object) + .Location(DirectiveLocation.FieldDefinition) + .Use(_ => _ => default) + .Argument("a").Type()); + + + var objectType = new ObjectType(t => + { + t.Name("Bar"); + t.Directive("foo", new ArgumentNode("a", "1")); + t.Field("foo").Resolve(() => "baz").Directive("foo", new ArgumentNode("a", "2")); + }); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(objectType) + .AddDirectiveType(directiveType) + .Create(); + + // assert + IReadOnlyCollection collection = + schema.GetType("Bar") + .Fields["foo"].ExecutableDirectives; + + Assert.Collection(collection, + t => { - t.Name("Bar"); - t.Directive("foo", new ArgumentNode("a", "1")); - t.Field("foo").Resolve(() => "baz").Directive("foo", new ArgumentNode("a", "2")); + Assert.Equal("foo", t.Name); + Assert.Equal("1", t.GetArgument("a")); + }, + t => + { + Assert.Equal("foo", t.Name); + Assert.Equal("2", t.GetArgument("a")); }); + } - // act - ISchema schema = SchemaBuilder.New() + [Fact] + public void UniqueDirective() + { + // arrange + var directiveType = new DirectiveType( + t => t.Name("foo") + .Location(DirectiveLocation.Object) + .Argument("a").Type()); + + var objectType = new ObjectType(t => + { + t.Name("Bar"); + t.Directive("foo", new ArgumentNode("a", "1")); + t.Directive("foo", new ArgumentNode("a", "2")); + t.Field("foo").Resolve(() => "baz"); + }); + + // act + void Action() => + SchemaBuilder.New() .AddQueryType(objectType) .AddDirectiveType(directiveType) .Create(); - // assert - IReadOnlyCollection collection = - schema.GetType("Bar") - .Fields["foo"].ExecutableDirectives; - - Assert.Collection(collection, - t => - { - Assert.Equal("foo", t.Name); - Assert.Equal("1", t.GetArgument("a")); - }, - t => - { - Assert.Equal("foo", t.Name); - Assert.Equal("2", t.GetArgument("a")); - }); - } - - [Fact] - public void UniqueDirective() - { - // arrange - var directiveType = new DirectiveType( - t => t.Name("foo") - .Location(DirectiveLocation.Object) - .Argument("a").Type()); - - var objectType = new ObjectType(t => + // assert + var exception = Assert.Throws(Action); + Assert.Collection(exception.Errors, + t => { - t.Name("Bar"); - t.Directive("foo", new ArgumentNode("a", "1")); - t.Directive("foo", new ArgumentNode("a", "2")); - t.Field("foo").Resolve(() => "baz"); + Assert.Equal( + "The specified directive `@foo` " + + "is unique and cannot be added twice.", + t.Message); }); + } - // act - void Action() => - SchemaBuilder.New() - .AddQueryType(objectType) - .AddDirectiveType(directiveType) - .Create(); - - // assert - SchemaException exception = Assert.Throws(Action); - Assert.Collection(exception.Errors, - t => - { - Assert.Equal( - "The specified directive `@foo` " + - "is unique and cannot be added twice.", - t.Message); - }); - } - - [Fact] - public void ExecutableUniqueDirectives() - { - // arrange - var directiveType = new DirectiveType( - t => t.Name("foo") - .Location(DirectiveLocation.Object) - .Location(DirectiveLocation.FieldDefinition) - .Use(_ => _ => default) - .Argument("a").Type()); - - - var objectType = new ObjectType(t => + [Fact] + public void ExecutableUniqueDirectives() + { + // arrange + var directiveType = new DirectiveType( + t => t.Name("foo") + .Location(DirectiveLocation.Object) + .Location(DirectiveLocation.FieldDefinition) + .Use(_ => _ => default) + .Argument("a").Type()); + + + var objectType = new ObjectType(t => + { + t.Name("Bar"); + t.Directive("foo", new ArgumentNode("a", "1")); + t.Field("foo").Resolve(() => "baz") + .Directive("foo", new ArgumentNode("a", "2")); + }); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(objectType) + .AddDirectiveType(directiveType) + .Create(); + + // assert + IReadOnlyCollection collection = + schema.GetType("Bar") + .Fields["foo"].ExecutableDirectives; + + Assert.Collection(collection, + t => { - t.Name("Bar"); - t.Directive("foo", new ArgumentNode("a", "1")); - t.Field("foo").Resolve(() => "baz") - .Directive("foo", new ArgumentNode("a", "2")); + Assert.Equal("foo", t.Name); + Assert.Equal("2", t.GetArgument("a")); }); + } - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(objectType) - .AddDirectiveType(directiveType) - .Create(); - - // assert - IReadOnlyCollection collection = - schema.GetType("Bar") - .Fields["foo"].ExecutableDirectives; - - Assert.Collection(collection, - t => - { - Assert.Equal("foo", t.Name); - Assert.Equal("2", t.GetArgument("a")); - }); - } - - [Fact] - public void Ignore_DescriptorIsNull_ArgumentNullException() - { - // arrange - // act - Action action = () => - DirectiveTypeDescriptorExtensions - .Ignore(null, t => t.Argument2); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Ignore_ExpressionIsNull_ArgumentNullException() - { - // arrange - var descriptor = - DirectiveTypeDescriptor.New( - DescriptorContext.Create()); - - // act - void Action() => descriptor.Ignore(null); + [Fact] + public void Ignore_DescriptorIsNull_ArgumentNullException() + { + // arrange + // act + Action action = () => + DirectiveTypeDescriptorExtensions + .Ignore(null, t => t.Argument2); + + // assert + Assert.Throws(action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void Ignore_ExpressionIsNull_ArgumentNullException() + { + // arrange + var descriptor = + DirectiveTypeDescriptor.New( + DescriptorContext.Create()); - [Fact] - public void Ignore_Argument2_Property() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object) - .Ignore(t => t.Argument2))) - .Create(); + // act + void Action() => descriptor.Ignore(null); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void Use_DelegateMiddleware() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object) - .Use(_ => _ => default))) - .Create(); + [Fact] + public void Ignore_Argument2_Property() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Ignore(t => t.Argument2))) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - DirectiveType directive = schema.GetDirectiveType("foo"); - Assert.Collection(directive.MiddlewareComponents, - t => Assert.NotNull(t)); - } + [Fact] + public void Use_DelegateMiddleware() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use(_ => _ => default))) + .Create(); + + // assert + var directive = schema.GetDirectiveType("foo"); + Assert.Collection(directive.MiddlewareComponents, + t => Assert.NotNull(t)); + } - [Fact] - public void Use_ClassMiddleware() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object) - .Use())) - .Create(); + [Fact] + public void Use_ClassMiddleware() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use())) + .Create(); + + // assert + var directive = schema.GetDirectiveType("foo"); + Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); + } - // assert - DirectiveType directive = schema.GetDirectiveType("foo"); - Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); - } + [Fact] + public void Use_ClassMiddleware_WithFactory() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use((_, next) => new DirectiveMiddleware(next)))) + .Create(); + + // assert + var directive = schema.GetDirectiveType("foo"); + Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); + } - [Fact] - public void Use_ClassMiddleware_WithFactory() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") + [Fact] + public void Use_ClassMiddleware_WithFactoryNull_ArgumentNullException() + { + // arrange + // act + void Action() => + SchemaBuilder.New() + .AddQueryType(c => c.Name("Query") .Directive("foo") .Field("foo") .Type() .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") + .AddDirectiveType(new DirectiveType(d => d.Name("foo") .Location(DirectiveLocation.Object) - .Use((_, next) => new DirectiveMiddleware(next)))) + .Use(null))) .Create(); - // assert - DirectiveType directive = schema.GetDirectiveType("foo"); - Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); - } - - [Fact] - public void Use_ClassMiddleware_WithFactoryNull_ArgumentNullException() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddQueryType(c => c.Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d.Name("foo") - .Location(DirectiveLocation.Object) - .Use(null))) - .Create(); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Use2_DelegateMiddleware() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object) - .Use(_ => _ => default))) - .Create(); + // assert + Assert.Throws(Action); + } - // assert - DirectiveType directive = schema.GetDirectiveType("foo"); - Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); - } + [Fact] + public void Use2_DelegateMiddleware() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use(_ => _ => default))) + .Create(); + + // assert + var directive = schema.GetDirectiveType("foo"); + Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); + } - [Fact] - public void Use2_ClassMiddleware() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object) - .Use())) - .Create(); + [Fact] + public void Use2_ClassMiddleware() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use())) + .Create(); + + // assert + var directive = schema.GetDirectiveType("foo"); + Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); + } - // assert - DirectiveType directive = schema.GetDirectiveType("foo"); - Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); - } + [Fact] + public void Use2_ClassMiddleware_WithFactory() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use((_, next) => new DirectiveMiddleware(next)))) + .Create(); + + // assert + var directive = schema.GetDirectiveType("foo"); + Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); + } - [Fact] - public void Use2_ClassMiddleware_WithFactory() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") + [Fact] + public void Use2_ClassMiddleware_WithFactoryNull_ArgumentNullException() + { + // arrange + // act + void Action() => + SchemaBuilder.New() + .AddQueryType(c => c.Name("Query") .Directive("foo") .Field("foo") .Type() .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") + .AddDirectiveType(new DirectiveType(d => d.Name("foo") .Location(DirectiveLocation.Object) - .Use((_, next) => new DirectiveMiddleware(next)))) + .Use(null))) .Create(); - // assert - DirectiveType directive = schema.GetDirectiveType("foo"); - Assert.Collection(directive.MiddlewareComponents, Assert.NotNull); - } - - [Fact] - public void Use2_ClassMiddleware_WithFactoryNull_ArgumentNullException() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddQueryType(c => c.Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d.Name("foo") - .Location(DirectiveLocation.Object) - .Use(null))) - .Create(); - - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void Infer_Directive_Argument_Defaults_From_Properties() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Directive("foo") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(new DirectiveType(d => d - .Name("foo") - .Location(DirectiveLocation.Object) - .Use())) - .Create(); + [Fact] + public void Infer_Directive_Argument_Defaults_From_Properties() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Directive("foo") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(new DirectiveType(d => d + .Name("foo") + .Location(DirectiveLocation.Object) + .Use())) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Specify_Argument_Type_With_SDL_Syntax() + { + SchemaBuilder.New() + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void Specify_Argument_Type_With_SDL_Syntax() - { - SchemaBuilder.New() - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public async Task AnnotationBased_Depreacted_NullableArguments_Valid() + { + // arrange + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Name("Query") + .Field("bar") + .Resolve("asd") + .Directive()) + .AddDirectiveType(new DirectiveType( + x => x.Location(DirectiveLocation.FieldDefinition))) + .BuildRequestExecutorAsync(); + + // assert + executor.Schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task AnnotationBased_Depreacted_NullableArguments_Valid() - { - // arrange - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Name("Query") - .Field("bar") - .Resolve("asd") - .Directive()) - .AddDirectiveType(new DirectiveType( - x => x.Location(DirectiveLocation.FieldDefinition))) - .BuildRequestExecutorAsync(); - - // assert - executor.Schema.ToString().MatchSnapshot(); - } + [Fact] + public async Task AnnotationBased_DepreactedInputTypes_NonNullableField_Invalid() + { + // arrange + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Name("Query") + .Field("bar") + .Resolve("asd") + .Directive()) + .AddDirectiveType(new DirectiveType( + x => x.Location(DirectiveLocation.FieldDefinition))) + .BuildRequestExecutorAsync(); + + // assert + var exception = await Assert.ThrowsAsync(call); + exception.Errors.Single().ToString().MatchSnapshot(); + } - [Fact] - public async Task AnnotationBased_DepreactedInputTypes_NonNullableField_Invalid() - { - // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Name("Query") - .Field("bar") - .Resolve("asd") - .Directive()) - .AddDirectiveType(new DirectiveType( - x => x.Location(DirectiveLocation.FieldDefinition))) - .BuildRequestExecutorAsync(); - - // assert - SchemaException exception = await Assert.ThrowsAsync(call); - exception.Errors.Single().ToString().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_Depreacted_NullableArguments_Valid() + { + // arrange + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Name("Query") + .Field("bar") + .Resolve("asd") + .Directive("Qux")) + .AddDirectiveType( + new DirectiveType(x => x + .Name("Qux") + .Location(DirectiveLocation.FieldDefinition) + .Argument("bar") + .Type() + .Deprecated("a"))) + .BuildRequestExecutorAsync(); - [Fact] - public async Task CodeFirst_Depreacted_NullableArguments_Valid() - { - // arrange - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Name("Query") - .Field("bar") - .Resolve("asd") - .Directive("Qux")) - .AddDirectiveType( - new DirectiveType(x => x - .Name("Qux") - .Location(DirectiveLocation.FieldDefinition) - .Argument("bar") - .Type() - .Deprecated("a"))) - .BuildRequestExecutorAsync(); - - // assert - executor.Schema.ToString().MatchSnapshot(); - } + // assert + executor.Schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DepreactedInputTypes_NonNullableField_Invalid() - { - // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Name("Query") - .Field("bar") - .Resolve("asd") - .Directive("Qux")) - .AddDirectiveType( - new DirectiveType(x => x - .Name("Qux") - .Location(DirectiveLocation.FieldDefinition) - .Argument("bar") - .Type>() - .Deprecated("a"))) - .BuildRequestExecutorAsync(); - - // assert - SchemaException exception = await Assert.ThrowsAsync(call); - exception.Errors.Single().ToString().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_DepreactedInputTypes_NonNullableField_Invalid() + { + // arrange + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Name("Query") + .Field("bar") + .Resolve("asd") + .Directive("Qux")) + .AddDirectiveType( + new DirectiveType(x => x + .Name("Qux") + .Location(DirectiveLocation.FieldDefinition) + .Argument("bar") + .Type>() + .Deprecated("a"))) + .BuildRequestExecutorAsync(); + + // assert + var exception = await Assert.ThrowsAsync(call); + exception.Errors.Single().ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DepreactedDirective_NullableFields_Valid() - { - // arrange - // act - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Name("Query") - .Field("bar") - .Resolve("asd") - .Directive("Qux")) - .AddDocumentFromString(@" + [Fact] + public async Task SchemaFirst_DepreactedDirective_NullableFields_Valid() + { + // arrange + // act + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Name("Query") + .Field("bar") + .Resolve("asd") + .Directive("Qux")) + .AddDocumentFromString(@" directive @Qux(bar: String @deprecated(reason: ""reason"")) on FIELD_DEFINITION ") - .BuildSchemaAsync(); + .BuildSchemaAsync(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DepreactedDirective_NonNullableField_Invalid() - { - // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd").Directive("Qux")) - .AddDocumentFromString(@" + [Fact] + public async Task SchemaFirst_DepreactedDirective_NonNullableField_Invalid() + { + // arrange + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd").Directive("Qux")) + .AddDocumentFromString(@" directive @Qux(bar: String! @deprecated(reason: ""reason"")) on FIELD_DEFINITION ") - .BuildSchemaAsync(); + .BuildSchemaAsync(); - // assert - SchemaException exception = await Assert.ThrowsAsync(call); - exception.Errors.Single().ToString().MatchSnapshot(); - } + // assert + var exception = await Assert.ThrowsAsync(call); + exception.Errors.Single().ToString().MatchSnapshot(); + } - public class DirectiveWithSyntaxTypeArg : DirectiveType + public class DirectiveWithSyntaxTypeArg : DirectiveType + { + protected override void Configure(IDirectiveTypeDescriptor descriptor) { - protected override void Configure(IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("bar"); - descriptor.Location(DirectiveLocation.Field); - descriptor.Argument("a").Type("Int"); - } + descriptor.Name("bar"); + descriptor.Location(DirectiveLocation.Field); + descriptor.Argument("a").Type("Int"); } + } - public class CustomDirectiveType : DirectiveType + public class CustomDirectiveType : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("Custom"); - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.Field); - descriptor.Use(_ => _ => default); - } + descriptor.Name("Custom"); + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.Field); + descriptor.Use(_ => _ => default); } + } - public class Custom2DirectiveType : DirectiveType + public class Custom2DirectiveType : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("Custom"); - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.Field); - descriptor.Use(_ => _ => default); - descriptor.BindArgumentsImplicitly().BindArgumentsExplicitly(); - } + descriptor.Name("Custom"); + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.Field); + descriptor.Use(_ => _ => default); + descriptor.BindArgumentsImplicitly().BindArgumentsExplicitly(); } + } - public class DirectiveMiddleware - { - private readonly FieldDelegate _next; - - public DirectiveMiddleware(FieldDelegate next) - { - _next = next; - } + public class DirectiveMiddleware + { + private readonly FieldDelegate _next; - public Task InvokeAsync(IDirectiveContext context) => - Task.CompletedTask; + public DirectiveMiddleware(FieldDelegate next) + { + _next = next; } - public class DeprecatedDirective - { - [Obsolete("reason")] - public int? ObsoleteWithReason { get; set; } + public Task InvokeAsync(IDirectiveContext context) => + Task.CompletedTask; + } - [Obsolete] - public int? Obsolete { get; set; } + public class DeprecatedDirective + { + [Obsolete("reason")] + public int? ObsoleteWithReason { get; set; } - [GraphQLDeprecated("reason")] - public int? Deprecated { get; set; } - } + [Obsolete] + public int? Obsolete { get; set; } - public class DeprecatedNonNull - { - [Obsolete("reason")] - public int ObsoleteWithReason { get; set; } - } + [GraphQLDeprecated("reason")] + public int? Deprecated { get; set; } + } - public class CustomDirective - { - public string Argument { get; set; } - } + public class DeprecatedNonNull + { + [Obsolete("reason")] + public int ObsoleteWithReason { get; set; } + } - public class CustomDirective2 - { - public string Argument1 { get; set; } - public string Argument2 { get; set; } - } + public class CustomDirective + { + public string Argument { get; set; } + } - public class DirectiveWithDefaults - { - [DefaultValue("abc")] - public string Argument1 { get; set; } - public string Argument2 { get; set; } - } + public class CustomDirective2 + { + public string Argument1 { get; set; } + public string Argument2 { get; set; } + } + + public class DirectiveWithDefaults + { + [DefaultValue("abc")] + public string Argument1 { get; set; } + public string Argument2 { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTests.cs index 68425a4ef39..e1b6667972b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTests.cs @@ -1,60 +1,59 @@ using System; using Xunit; -namespace HotChocolate.Types.Directives +namespace HotChocolate.Types.Directives; + +public class CostDirectiveTests { - public class CostDirectiveTests + [Fact] + public void ComplexityEqualsZero() + { + // arrange + // act + void Action() => new CostDirective(0); + void Action1() => new CostDirective(0, "a"); + + // assert + Assert.Throws(Action); + Assert.Throws(Action1); + } + + [Fact] + public void InvalidMultipliers() { - [Fact] - public void ComplexityEqualsZero() - { - // arrange - // act - void Action() => new CostDirective(0); - void Action1() => new CostDirective(0, "a"); - - // assert - Assert.Throws(Action); - Assert.Throws(Action1); - } - - [Fact] - public void InvalidMultipliers() - { - // arrange - // act - void Action() => new CostDirective(1, " "); - void Action1() => new CostDirective(1, null); - - // assert - Assert.Throws(Action); - Assert.Throws(Action1); - } - - [Fact] - public void ValidMultipliers() - { - // arrange - // act - var cost = new CostDirective(6, "", "b", "c", null); - - // assert - Assert.Equal(6, cost.Complexity); - Assert.Collection(cost.Multipliers, - s => Assert.Equal("b", s), - s => Assert.Equal("c", s)); - } - - [Fact] - public void NoMultipliers() - { - // arrange - // act - var cost = new CostDirective(5); - - // assert - Assert.Equal(5, cost.Complexity); - Assert.Empty(cost.Multipliers); - } + // arrange + // act + void Action() => new CostDirective(1, " "); + void Action1() => new CostDirective(1, null); + + // assert + Assert.Throws(Action); + Assert.Throws(Action1); + } + + [Fact] + public void ValidMultipliers() + { + // arrange + // act + var cost = new CostDirective(6, "", "b", "c", null); + + // assert + Assert.Equal(6, cost.Complexity); + Assert.Collection(cost.Multipliers, + s => Assert.Equal("b", s), + s => Assert.Equal("c", s)); + } + + [Fact] + public void NoMultipliers() + { + // arrange + // act + var cost = new CostDirective(5); + + // assert + Assert.Equal(5, cost.Complexity); + Assert.Empty(cost.Multipliers); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTypeTests.cs index 03831c88e45..2d4e274e043 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/CostDirectiveTypeTests.cs @@ -1,201 +1,201 @@ using System.Linq; using Xunit; -namespace HotChocolate.Types.Directives +namespace HotChocolate.Types.Directives; + +public class CostDirectiveTypeTests : TypeTestBase { - public class CostDirectiveTypeTests : TypeTestBase + [Fact] + public void AnnotateCostToObjectFieldCodeFirst() { - [Fact] - public void AnnotateCostToObjectFieldCodeFirst() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("field") - .Argument("a", a => a.Type()) - .Type() - .Cost(5)) - .AddDirectiveType() - .Use(_ => _) - .Create(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("field") + .Argument("a", a => a.Type()) + .Type() + .Cost(5)) + .AddDirectiveType() + .Use(_ => _) + .Create(); - ObjectType query = schema.GetType("Query"); - IDirective directive = query.Fields["field"].Directives.Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - } + var query = schema.GetType("Query"); + var directive = query.Fields["field"].Directives.Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + } - [Fact] - public void AnnotateCostToObjectFieldCodeFirstOneMultiplier() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("field") - .Argument("a", a => a.Type()) - .Type() - .Cost(5, "a")) - .AddDirectiveType() - .Use(_ => _) - .Create(); + [Fact] + public void AnnotateCostToObjectFieldCodeFirstOneMultiplier() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("field") + .Argument("a", a => a.Type()) + .Type() + .Cost(5, "a")) + .AddDirectiveType() + .Use(_ => _) + .Create(); - ObjectType query = schema.GetType("Query"); - IDirective directive = query.Fields["field"].Directives.Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - Assert.Collection(obj.Multipliers, t => Assert.Equal("a", t)); - } + var query = schema.GetType("Query"); + var directive = query.Fields["field"].Directives.Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + Assert.Collection(obj.Multipliers, t => Assert.Equal("a", t)); + } - [Fact] - public void AnnotateCostToObjectFieldCodeFirstTwoMultiplier() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("field") - .Argument("a", a => a.Type()) - .Type() - .Cost(5, "a", "b")) - .AddDirectiveType() - .Use(_ => _) - .Create(); + [Fact] + public void AnnotateCostToObjectFieldCodeFirstTwoMultiplier() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("field") + .Argument("a", a => a.Type()) + .Type() + .Cost(5, "a", "b")) + .AddDirectiveType() + .Use(_ => _) + .Create(); - ObjectType query = schema.GetType("Query"); - IDirective directive = query.Fields["field"].Directives - .Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - Assert.Collection(obj.Multipliers, - t => Assert.Equal("a", t), - t => Assert.Equal("b", t)); - } + var query = schema.GetType("Query"); + var directive = query.Fields["field"].Directives + .Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + Assert.Collection(obj.Multipliers, + t => Assert.Equal("a", t), + t => Assert.Equal("b", t)); + } - [Fact] - public void AnnotateCostToInterfaceFieldCodeFirst() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("field") - .Argument("a", a => a.Type()) - .Type()) - .AddInterfaceType(d => d - .Name("IQuery") - .Field("field") - .Argument("a", a => a.Type()) - .Type() - .Cost(5)) - .AddDirectiveType() - .Use(_ => _) - .Create(); + [Fact] + public void AnnotateCostToInterfaceFieldCodeFirst() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("field") + .Argument("a", a => a.Type()) + .Type()) + .AddInterfaceType(d => d + .Name("IQuery") + .Field("field") + .Argument("a", a => a.Type()) + .Type() + .Cost(5)) + .AddDirectiveType() + .Use(_ => _) + .Create(); - InterfaceType queryInterface = schema.GetType("IQuery"); - IDirective directive = queryInterface.Fields["field"].Directives - .Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - } + var queryInterface = schema.GetType("IQuery"); + var directive = queryInterface.Fields["field"].Directives + .Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + } - [Fact] - public void AnnotateCostToInterfaceFieldCodeFirstOneMultiplier() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("field") - .Argument("a", a => a.Type()) - .Type()) - .AddInterfaceType(d => d - .Name("IQuery") - .Field("field") - .Argument("a", a => a.Type()) - .Type() - .Cost(5, "a")) - .AddDirectiveType() - .Use(_ => _) - .Create(); + [Fact] + public void AnnotateCostToInterfaceFieldCodeFirstOneMultiplier() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("field") + .Argument("a", a => a.Type()) + .Type()) + .AddInterfaceType(d => d + .Name("IQuery") + .Field("field") + .Argument("a", a => a.Type()) + .Type() + .Cost(5, "a")) + .AddDirectiveType() + .Use(_ => _) + .Create(); - InterfaceType queryInterface = schema.GetType("IQuery"); - IDirective directive = queryInterface.Fields["field"].Directives - .Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - Assert.Collection(obj.Multipliers, t => Assert.Equal("a", t)); - } + var queryInterface = schema.GetType("IQuery"); + var directive = queryInterface.Fields["field"].Directives + .Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + Assert.Collection(obj.Multipliers, t => Assert.Equal("a", t)); + } - [Fact] - public void AnnotateCostToInterfaceFieldCodeFirstTwoMultiplier() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("field") - .Argument("a", a => a.Type()) - .Type()) - .AddInterfaceType(d => d - .Name("IQuery") - .Field("field") - .Argument("a", a => a.Type()) - .Type() - .Cost(5, "a", "b")) - .AddDirectiveType() - .Use(_ => _) - .Create(); + [Fact] + public void AnnotateCostToInterfaceFieldCodeFirstTwoMultiplier() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("field") + .Argument("a", a => a.Type()) + .Type()) + .AddInterfaceType(d => d + .Name("IQuery") + .Field("field") + .Argument("a", a => a.Type()) + .Type() + .Cost(5, "a", "b")) + .AddDirectiveType() + .Use(_ => _) + .Create(); - InterfaceType queryInterface = schema.GetType("IQuery"); - IDirective directive = queryInterface.Fields["field"].Directives - .Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - Assert.Collection(obj.Multipliers, - t => Assert.Equal("a", t), - t => Assert.Equal("b", t)); - } + var queryInterface = schema.GetType("IQuery"); + var directive = queryInterface.Fields["field"].Directives + .Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + Assert.Collection(obj.Multipliers, + t => Assert.Equal("a", t), + t => Assert.Equal("b", t)); + } - [Fact] - public void AnnotateCostToObjectFieldSchemaFirst() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + [Fact] + public void AnnotateCostToObjectFieldSchemaFirst() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { field(a: Int): String @cost(complexity: 5 multipliers: [""a""]) }") - .AddDirectiveType() - .Use(_ => _) - .Create(); + .AddDirectiveType() + .Use(_ => _) + .Create(); - ObjectType query = schema.GetType("Query"); - IDirective directive = query.Fields["field"].Directives - .Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - Assert.Collection(obj.Multipliers, - t => Assert.Equal("a", t)); - } + var query = schema.GetType("Query"); + var directive = query.Fields["field"].Directives + .Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + Assert.Collection(obj.Multipliers, + t => Assert.Equal("a", t)); + } - [Fact] - public void AnnotateCostToInterfaceFieldSchemaFirst() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString( - @" + [Fact] + public void AnnotateCostToInterfaceFieldSchemaFirst() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString( + @" type Query { field(a: Int): String @cost(complexity: 5 multipliers: [""a""]) @@ -206,52 +206,51 @@ interface IQuery { @cost(complexity: 5 multipliers: [""a""]) } ") - .AddDirectiveType() - .Use(_ => _) - .Create(); + .AddDirectiveType() + .Use(_ => _) + .Create(); - InterfaceType queryInterface = schema.GetType("IQuery"); - IDirective directive = - queryInterface.Fields["field"].Directives.Single(t => t.Name == "cost"); - CostDirective obj = directive.ToObject(); - Assert.Equal(5, obj.Complexity); - Assert.Collection(obj.Multipliers, t => Assert.Equal("a", t)); - } + var queryInterface = schema.GetType("IQuery"); + var directive = + queryInterface.Fields["field"].Directives.Single(t => t.Name == "cost"); + var obj = directive.ToObject(); + Assert.Equal(5, obj.Complexity); + Assert.Collection(obj.Multipliers, t => Assert.Equal("a", t)); + } - [Fact] - public void CreateCostDirective() - { - // arrange - // act - ISchema schema = CreateSchema(b => b.AddDirectiveType()); - CostDirectiveType directive = - schema.DirectiveTypes.OfType().FirstOrDefault(); + [Fact] + public void CreateCostDirective() + { + // arrange + // act + var schema = CreateSchema(b => b.AddDirectiveType()); + var directive = + schema.DirectiveTypes.OfType().FirstOrDefault(); - // assert - Assert.NotNull(directive); - Assert.IsType(directive); - Assert.Equal("cost", directive.Name); - Assert.Collection(directive.Arguments, - t => - { - Assert.Equal("complexity", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - }, - t => - { - Assert.Equal("multipliers", t.Name); - Assert.IsType( - Assert.IsType( - Assert.IsType(t.Type).ElementType).Type); - }, - t => - { - Assert.Equal("defaultMultiplier", t.Name); - Assert.IsType(t.Type); - }); - Assert.Collection(directive.Locations, - t => Assert.Equal(DirectiveLocation.FieldDefinition, t)); - } + // assert + Assert.NotNull(directive); + Assert.IsType(directive); + Assert.Equal("cost", directive.Name); + Assert.Collection(directive.Arguments, + t => + { + Assert.Equal("complexity", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + }, + t => + { + Assert.Equal("multipliers", t.Name); + Assert.IsType( + Assert.IsType( + Assert.IsType(t.Type).ElementType).Type); + }, + t => + { + Assert.Equal("defaultMultiplier", t.Name); + Assert.IsType(t.Type); + }); + Assert.Collection(directive.Locations, + t => Assert.Equal(DirectiveLocation.FieldDefinition, t)); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/MultiplierPathStringTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/MultiplierPathStringTests.cs index 8fc0a10cbe0..ec4de48ab0e 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/MultiplierPathStringTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/MultiplierPathStringTests.cs @@ -1,377 +1,376 @@ using System; using Xunit; -namespace HotChocolate.Types.Directives +namespace HotChocolate.Types.Directives; + +public class MultiplierPathStringTests { - public class MultiplierPathStringTests + [Fact] + public void Create_DefaultConstructor_IsEmpty() + { + // arrange + // act + var nameString = new MultiplierPathString(); + + // assert + Assert.True(nameString.IsEmpty); + Assert.False(nameString.HasValue); + Assert.Null(nameString.Value); + } + + [InlineData("_")] + [InlineData("_Test")] + [InlineData("_1Test")] + [InlineData("Test")] + [InlineData("Test_Test")] + [InlineData("Test_Test.Test")] + [Theory] + public void Create_WithValidName_HasValue(string value) + { + // arrange + // act + var nameString = new MultiplierPathString(value); + + // assert + Assert.Equal(nameString.Value, value); + Assert.True(nameString.HasValue); + Assert.False(nameString.IsEmpty); + } + + [InlineData("1Test")] + [InlineData("Test-Test")] + [InlineData(".Test-Test")] + [Theory] + public void Create_WithInvalidName_ArgumentException(string value) + { + // arrange + // act + Action a = () => new MultiplierPathString(value); + + // assert + Assert.Throws(a); + } + + [InlineData("_")] + [InlineData("_Test")] + [InlineData("_1Test")] + [InlineData("Test")] + [InlineData("Test_Test")] + [InlineData("Test_Test.Test")] + [Theory] + public void ImplicitCast_ValidName_MultiplierPathString(string name) + { + // arrange + // act + MultiplierPathString nameString = name; + + // assert + Assert.Equal(name, nameString.Value); + } + + [InlineData("1Test")] + [InlineData("Test-Test")] + [InlineData("Täst")] + [InlineData(".Test-Test")] + [Theory] + public void ImplicitCast_InvalidName_MultiplierPathString(string name) { - [Fact] - public void Create_DefaultConstructor_IsEmpty() - { - // arrange - // act - var nameString = new MultiplierPathString(); - - // assert - Assert.True(nameString.IsEmpty); - Assert.False(nameString.HasValue); - Assert.Null(nameString.Value); - } - - [InlineData("_")] - [InlineData("_Test")] - [InlineData("_1Test")] - [InlineData("Test")] - [InlineData("Test_Test")] - [InlineData("Test_Test.Test")] - [Theory] - public void Create_WithValidName_HasValue(string value) - { - // arrange - // act - var nameString = new MultiplierPathString(value); - - // assert - Assert.Equal(nameString.Value, value); - Assert.True(nameString.HasValue); - Assert.False(nameString.IsEmpty); - } - - [InlineData("1Test")] - [InlineData("Test-Test")] - [InlineData(".Test-Test")] - [Theory] - public void Create_WithInvalidName_ArgumentException(string value) - { - // arrange - // act - Action a = () => new MultiplierPathString(value); - - // assert - Assert.Throws(a); - } - - [InlineData("_")] - [InlineData("_Test")] - [InlineData("_1Test")] - [InlineData("Test")] - [InlineData("Test_Test")] - [InlineData("Test_Test.Test")] - [Theory] - public void ImplicitCast_ValidName_MultiplierPathString(string name) - { - // arrange - // act - MultiplierPathString nameString = name; - - // assert - Assert.Equal(name, nameString.Value); - } - - [InlineData("1Test")] - [InlineData("Test-Test")] - [InlineData("Täst")] - [InlineData(".Test-Test")] - [Theory] - public void ImplicitCast_InvalidName_MultiplierPathString(string name) - { - // arrange - // act - Action a = () => { MultiplierPathString nameString = name; }; - - // assert - Assert.Throws(a); - } - - [Fact] - public void ImplicitCast_MultiplierPathString_String() - { - // arrange - var nameString = new MultiplierPathString("Foo"); - - // act - string name = nameString; - - // assert - Assert.Equal(nameString.Value, name); - } - - [Fact] - public void ToString_ReturnsValue() - { - // arrange - var nameString = new MultiplierPathString("Foo"); - - // act - string value = nameString.ToString(); ; - - // assert - Assert.Equal(nameString.Value, value); - } - - [Fact] - public void Append_MultiplierPathString_CombinedMultiplierPathString() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Bar"); - - // act - MultiplierPathString combined = a.Add(b); - - // assert - Assert.Equal("FooBar", combined.ToString()); - } - - [Fact] - public void AddOp_MultiplierPathString_CombinedMultiplierPathString() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Bar"); - - // act - MultiplierPathString combined = a + b; - - // assert - Assert.Equal("FooBar", combined.ToString()); - } - - [Fact] - public void AddOp_String_CombinedMultiplierPathString() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Bar"; - - // act - MultiplierPathString combined = a + b; - - // assert - Assert.Equal("FooBar", combined.ToString()); - } - - [Fact] - public void Equals_MultiplierPathStringWithSameValue_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Foo"); - - // act - bool result = a.Equals(b); - - // assert - Assert.True(result); - } - - [Fact] - public void Equals_SameInstance_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - - // act - bool result = a.Equals(a); - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsIgnoreCasing_MultiplierPathStringWithDifferentCasing_True() - { - // arrange - var a = new MultiplierPathString("FOO"); - var b = new MultiplierPathString("foo"); - - // act - bool result = a.Equals(b, StringComparison.OrdinalIgnoreCase); - - // assert - Assert.True(result); - } - - [Fact] - public void Equals_MultiplierPathStringDifferentValue_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Bar"); - - // act - bool result = a.Equals(b); - - // assert - Assert.False(result); - } - - [Fact] - public void Equals_StringWithSameValue_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Foo"; - - // act - bool result = a.Equals(b); - - // assert - Assert.True(result); - } - - [Fact] - public void Equals_StringDifferentValue_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Bar"; - - // act - bool result = a.Equals(b); - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsOp_MultiplierPathStringWithSameValue_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Foo"); - - // act - bool result = a == b; - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsOp_SameInstance_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - MultiplierPathString b = a; - - // act - bool result = a == b; - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsOp_MultiplierPathStringDifferentValue_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Bar"); - - // act - bool result = a == b; - - // assert - Assert.False(result); - } - - [Fact] - public void EqualsOp_StringWithSameValue_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Foo"; - - // act - bool result = a == b; - - // assert - Assert.True(result); - } - - [Fact] - public void EqualsOp_StringDifferentValue_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Bar"; - - // act - bool result = a == b; - - // assert - Assert.False(result); - } - - [Fact] - public void NotEqualsOp_MultiplierPathStringWithSameValue_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Foo"); - - // act - bool result = a != b; - - // assert - Assert.False(result); - } - - [Fact] - public void NotEqualsOp_SameInstance_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - MultiplierPathString b = a; - - // act - bool result = a != b; - - // assert - Assert.False(result); - } - - [Fact] - public void NotEqualsOp_MultiplierPathStringDifferentValue_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = new MultiplierPathString("Bar"); - - // act - bool result = a != b; - - // assert - Assert.True(result); - } - - [Fact] - public void NotEqualsOp_StringWithSameValue_False() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Foo"; - - // act - bool result = a != b; - - // assert - Assert.False(result); - } - - [Fact] - public void NotEqualsOp_StringDifferentValue_True() - { - // arrange - var a = new MultiplierPathString("Foo"); - var b = "Bar"; - - // act - bool result = a != b; - - // assert - Assert.True(result); - } + // arrange + // act + var a = () => { MultiplierPathString nameString = name; }; + + // assert + Assert.Throws(a); + } + + [Fact] + public void ImplicitCast_MultiplierPathString_String() + { + // arrange + var nameString = new MultiplierPathString("Foo"); + + // act + string name = nameString; + + // assert + Assert.Equal(nameString.Value, name); + } + + [Fact] + public void ToString_ReturnsValue() + { + // arrange + var nameString = new MultiplierPathString("Foo"); + + // act + var value = nameString.ToString(); ; + + // assert + Assert.Equal(nameString.Value, value); + } + + [Fact] + public void Append_MultiplierPathString_CombinedMultiplierPathString() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Bar"); + + // act + var combined = a.Add(b); + + // assert + Assert.Equal("FooBar", combined.ToString()); + } + + [Fact] + public void AddOp_MultiplierPathString_CombinedMultiplierPathString() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Bar"); + + // act + var combined = a + b; + + // assert + Assert.Equal("FooBar", combined.ToString()); + } + + [Fact] + public void AddOp_String_CombinedMultiplierPathString() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Bar"; + + // act + MultiplierPathString combined = a + b; + + // assert + Assert.Equal("FooBar", combined.ToString()); + } + + [Fact] + public void Equals_MultiplierPathStringWithSameValue_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Foo"); + + // act + var result = a.Equals(b); + + // assert + Assert.True(result); + } + + [Fact] + public void Equals_SameInstance_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + + // act + var result = a.Equals(a); + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsIgnoreCasing_MultiplierPathStringWithDifferentCasing_True() + { + // arrange + var a = new MultiplierPathString("FOO"); + var b = new MultiplierPathString("foo"); + + // act + var result = a.Equals(b, StringComparison.OrdinalIgnoreCase); + + // assert + Assert.True(result); + } + + [Fact] + public void Equals_MultiplierPathStringDifferentValue_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Bar"); + + // act + var result = a.Equals(b); + + // assert + Assert.False(result); + } + + [Fact] + public void Equals_StringWithSameValue_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Foo"; + + // act + var result = a.Equals(b); + + // assert + Assert.True(result); + } + + [Fact] + public void Equals_StringDifferentValue_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Bar"; + + // act + var result = a.Equals(b); + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsOp_MultiplierPathStringWithSameValue_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Foo"); + + // act + var result = a == b; + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsOp_SameInstance_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = a; + + // act + var result = a == b; + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsOp_MultiplierPathStringDifferentValue_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Bar"); + + // act + var result = a == b; + + // assert + Assert.False(result); + } + + [Fact] + public void EqualsOp_StringWithSameValue_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Foo"; + + // act + var result = a == b; + + // assert + Assert.True(result); + } + + [Fact] + public void EqualsOp_StringDifferentValue_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Bar"; + + // act + var result = a == b; + + // assert + Assert.False(result); + } + + [Fact] + public void NotEqualsOp_MultiplierPathStringWithSameValue_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Foo"); + + // act + var result = a != b; + + // assert + Assert.False(result); + } + + [Fact] + public void NotEqualsOp_SameInstance_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = a; + + // act + var result = a != b; + + // assert + Assert.False(result); + } + + [Fact] + public void NotEqualsOp_MultiplierPathStringDifferentValue_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = new MultiplierPathString("Bar"); + + // act + var result = a != b; + + // assert + Assert.True(result); + } + + [Fact] + public void NotEqualsOp_StringWithSameValue_False() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Foo"; + + // act + var result = a != b; + + // assert + Assert.False(result); + } + + [Fact] + public void NotEqualsOp_StringDifferentValue_True() + { + // arrange + var a = new MultiplierPathString("Foo"); + var b = "Bar"; + + // act + var result = a != b; + + // assert + Assert.True(result); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/SpecedDirectiveTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/SpecedDirectiveTypeTests.cs index 72db1602d2d..8b70748ea7c 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Directives/SpecedDirectiveTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Directives/SpecedDirectiveTypeTests.cs @@ -1,64 +1,63 @@ using System.Linq; using Xunit; -namespace HotChocolate.Types.Directives +namespace HotChocolate.Types.Directives; + +public class SpecedDirectiveTypeTests : TypeTestBase { - public class SpecedDirectiveTypeTests : TypeTestBase + [Fact] + public void EnsureSkipDirectiveIsAvailable() { - [Fact] - public void EnsureSkipDirectiveIsAvailable() - { - // arrange - ISchema schema = CreateSchema(b => { }); + // arrange + var schema = CreateSchema(b => { }); - // act - DirectiveType directive = - schema.DirectiveTypes.FirstOrDefault( - t => t.Name.Equals("skip")); + // act + var directive = + schema.DirectiveTypes.FirstOrDefault( + t => t.Name.Equals("skip")); - // assert - Assert.NotNull(directive); - Assert.IsType(directive); - Assert.Equal("skip", directive.Name); - Assert.Collection(directive.Arguments, - t => - { - Assert.Equal("if", t.Name); - Assert.IsType(t.Type); - Assert.IsType(((NonNullType)t.Type).Type); - }); - Assert.Collection(directive.Locations, - t => Assert.Equal(DirectiveLocation.Field, t), - t => Assert.Equal(DirectiveLocation.FragmentSpread, t), - t => Assert.Equal(DirectiveLocation.InlineFragment, t)); - } + // assert + Assert.NotNull(directive); + Assert.IsType(directive); + Assert.Equal("skip", directive.Name); + Assert.Collection(directive.Arguments, + t => + { + Assert.Equal("if", t.Name); + Assert.IsType(t.Type); + Assert.IsType(((NonNullType)t.Type).Type); + }); + Assert.Collection(directive.Locations, + t => Assert.Equal(DirectiveLocation.Field, t), + t => Assert.Equal(DirectiveLocation.FragmentSpread, t), + t => Assert.Equal(DirectiveLocation.InlineFragment, t)); + } - [Fact] - public void EnsureIncludeDirectiveIsAvailable() - { - // arrange - ISchema schema = CreateSchema(b => { }); + [Fact] + public void EnsureIncludeDirectiveIsAvailable() + { + // arrange + var schema = CreateSchema(b => { }); - // act - DirectiveType directive = - schema.DirectiveTypes.FirstOrDefault( - t => t.Name.Equals("include")); + // act + var directive = + schema.DirectiveTypes.FirstOrDefault( + t => t.Name.Equals("include")); - // assert - Assert.NotNull(directive); - Assert.IsType(directive); - Assert.Equal("include", directive.Name); - Assert.Collection(directive.Arguments, - t => - { - Assert.Equal("if", t.Name); - Assert.IsType(t.Type); - Assert.IsType(((NonNullType)t.Type).Type); - }); - Assert.Collection(directive.Locations, - t => Assert.Equal(DirectiveLocation.Field, t), - t => Assert.Equal(DirectiveLocation.FragmentSpread, t), - t => Assert.Equal(DirectiveLocation.InlineFragment, t)); - } + // assert + Assert.NotNull(directive); + Assert.IsType(directive); + Assert.Equal("include", directive.Name); + Assert.Collection(directive.Arguments, + t => + { + Assert.Equal("if", t.Name); + Assert.IsType(t.Type); + Assert.IsType(((NonNullType)t.Type).Type); + }); + Assert.Collection(directive.Locations, + t => Assert.Equal(DirectiveLocation.Field, t), + t => Assert.Equal(DirectiveLocation.FragmentSpread, t), + t => Assert.Equal(DirectiveLocation.InlineFragment, t)); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeDescriptorAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeDescriptorAttributeTests.cs index 226f108a3e0..2f360359211 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeDescriptorAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeDescriptorAttributeTests.cs @@ -4,96 +4,95 @@ using HotChocolate.Types.Descriptors; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class EnumTypeDescriptorAttributeTests { - public class EnumTypeDescriptorAttributeTests + [Fact] + public void Change_Value_Name_With_Attribute() { - [Fact] - public void Change_Value_Name_With_Attribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - IEnumValue value = schema.GetType("Enum1").Values.First(); - Assert.Equal("ABC", value.Name); - } + // assert + var value = schema.GetType("Enum1").Values.First(); + Assert.Equal("ABC", value.Name); + } - [Fact] - public void Change_Type_Name_With_Attribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void Change_Type_Name_With_Attribute() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.NotNull(schema.GetType("Abc")); - } + // assert + Assert.NotNull(schema.GetType("Abc")); + } - [Fact] - public void Annotated_Enum3_With_EnumTypeAttribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void Annotated_Enum3_With_EnumTypeAttribute() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.NotNull(schema.GetType("Foo")); - } + // assert + Assert.NotNull(schema.GetType("Foo")); + } - public enum Enum1 - { + public enum Enum1 + { - [RenameValue] - Value1, - Value2 - } + [RenameValue] + Value1, + Value2 + } - public class RenameValueAttribute - : EnumValueDescriptorAttribute + public class RenameValueAttribute + : EnumValueDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IEnumValueDescriptor descriptor, + FieldInfo field) { - public override void OnConfigure( - IDescriptorContext context, - IEnumValueDescriptor descriptor, - FieldInfo field) - { - descriptor.Name("ABC"); - } + descriptor.Name("ABC"); } + } - [RenameType] - public enum Enum2 - { + [RenameType] + public enum Enum2 + { - Value1, - Value2 - } + Value1, + Value2 + } - [EnumType(Name = "Foo")] - public enum Enum3 - { + [EnumType(Name = "Foo")] + public enum Enum3 + { - Value1, - Value2 - } + Value1, + Value2 + } - public class RenameTypeAttribute - : EnumTypeDescriptorAttribute + public class RenameTypeAttribute + : EnumTypeDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IEnumTypeDescriptor descriptor, + Type type) { - public override void OnConfigure( - IDescriptorContext context, - IEnumTypeDescriptor descriptor, - Type type) - { - descriptor.Name("Abc"); - } + descriptor.Name("Abc"); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeExtensionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeExtensionTests.cs index 3adc059881a..c2f24bcc2f5 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeExtensionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeExtensionTests.cs @@ -4,222 +4,221 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class EnumTypeExtensionTests { - public class EnumTypeExtensionTests + [Fact] + public void EnumTypeExtension_AddValue() { - [Fact] - public void EnumTypeExtension_AddValue() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create(); - - // assert - FooType type = schema.GetType("Foo"); - Assert.True(type.TryGetRuntimeValue("_QUOX", out _)); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.TryGetRuntimeValue("_QUOX", out _)); + } - [Fact] - public void EnumTypeExtension_AddValueThatDoesNotMatchClrType() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new EnumTypeExtension(d => d - .Name("Foo") - .Value("FOOBAR"))) - .Create(); - - // assert - Assert.Throws(action); - } + [Fact] + public void EnumTypeExtension_AddValueThatDoesNotMatchClrType() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new EnumTypeExtension(d => d + .Name("Foo") + .Value("FOOBAR"))) + .Create(); + + // assert + Assert.Throws(action); + } - [Fact] - public void EnumTypeExtension_SetDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new EnumTypeExtension(d => d - .Name("Foo") - .Directive("dummy"))) - .AddDirectiveType() - .Create(); - - // assert - FooType type = schema.GetType("Foo"); - Assert.Collection(type.Directives["dummy"], - t => { }); - } + [Fact] + public void EnumTypeExtension_SetDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new EnumTypeExtension(d => d + .Name("Foo") + .Directive("dummy"))) + .AddDirectiveType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Directives["dummy"], + t => { }); + } - [Fact] - public void EnumTypeExtension_ReplaceDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new EnumType(d => d - .Directive("dummy_arg", new ArgumentNode("a", "a")))) - .AddType(new EnumTypeExtension(d => d - .Name("Foo") - .Directive("dummy_arg", new ArgumentNode("a", "b")))) - .AddDirectiveType() - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - string value = type.Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public void EnumTypeExtension_ReplaceDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new EnumType(d => d + .Directive("dummy_arg", new ArgumentNode("a", "a")))) + .AddType(new EnumTypeExtension(d => d + .Name("Foo") + .Directive("dummy_arg", new ArgumentNode("a", "b")))) + .AddDirectiveType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + var value = type.Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void EnumTypeExtension_RepeatableDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new EnumType(d => d - .Directive("dummy_rep"))) - .AddType(new EnumTypeExtension(d => d - .Name("Foo") - .Directive("dummy_rep"))) - .AddDirectiveType() - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - int count = type.Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + [Fact] + public void EnumTypeExtension_RepeatableDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new EnumType(d => d + .Directive("dummy_rep"))) + .AddType(new EnumTypeExtension(d => d + .Name("Foo") + .Directive("dummy_rep"))) + .AddDirectiveType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + var count = type.Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - [Fact] - public void EnumTypeExtension_SetTypeContextData() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new EnumTypeExtension(d => d - .Name("Foo") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - Assert.True(type.ContextData.ContainsKey("foo")); - } + [Fact] + public void EnumTypeExtension_SetTypeContextData() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new EnumTypeExtension(d => d + .Name("Foo") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.ContextData.ContainsKey("foo")); + } - [Fact] - public void EnumTypeExtension_Ignore_Fields() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void EnumTypeExtension_Ignore_Fields() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - public class DummyQuery - { - public string Foo { get; set; } - } + public class DummyQuery + { + public string Foo { get; set; } + } - public class FooType - : EnumType + public class FooType + : EnumType + { + protected override void Configure( + IEnumTypeDescriptor descriptor) { - protected override void Configure( - IEnumTypeDescriptor descriptor) - { - descriptor.BindValues(BindingBehavior.Explicit); - descriptor.Value(Foo.Bar); - descriptor.Value(Foo.Baz); - } + descriptor.BindValues(BindingBehavior.Explicit); + descriptor.Value(Foo.Bar); + descriptor.Value(Foo.Baz); } + } - public class FooTypeExtension - : EnumTypeExtension + public class FooTypeExtension + : EnumTypeExtension + { + protected override void Configure(IEnumTypeDescriptor descriptor) { - protected override void Configure(IEnumTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Value(Foo.Quox).Name("_QUOX"); - } + descriptor.Name("Foo"); + descriptor.Value(Foo.Quox).Name("_QUOX"); } + } - public class FooIgnoreTypeExtension - : EnumTypeExtension + public class FooIgnoreTypeExtension + : EnumTypeExtension + { + protected override void Configure(IEnumTypeDescriptor descriptor) { - protected override void Configure(IEnumTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Value(Foo.Bar).Ignore(); - } + descriptor.Name("Foo"); + descriptor.Value(Foo.Bar).Ignore(); } + } - public enum Foo - { - Bar, - Baz, - Quox - } + public enum Foo + { + Bar, + Baz, + Quox + } - public class DummyDirective - : DirectiveType + public class DummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy"); - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } + descriptor.Name("dummy"); + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class DummyWithArgDirective - : DirectiveType + public class DummyWithArgDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_arg"); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } + descriptor.Name("dummy_arg"); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class RepeatableDummyDirective - : DirectiveType + public class RepeatableDummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_rep"); - descriptor.Repeatable(); - descriptor.Location(DirectiveLocation.Enum); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } + descriptor.Name("dummy_rep"); + descriptor.Repeatable(); + descriptor.Location(DirectiveLocation.Enum); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeTests.cs index 986d07706f9..22fa3f390b0 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeTests.cs @@ -7,703 +7,702 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class EnumTypeTests : TypeTestBase { - public class EnumTypeTests : TypeTestBase + [Fact] + public void EnumType_DynamicName() { - [Fact] - public void EnumType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => d - .Name(dep => dep.Name + "Enum") - .DependsOn() - .Value("BAR")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("StringEnum"); - Assert.NotNull(type); - } - - [Fact] - public void EnumType_GraphQLDescriptionAttribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("DescriptionTestEnum"); - Assert.Equal("TestDescription", type.Description); - } - - [Fact] - public void EnumType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => d - .Name(dep => dep.Name + "Enum") - .DependsOn(typeof(StringType)) - .Value("BAR")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("StringEnum"); - Assert.NotNull(type); - } - - [Fact] - public void GenericEnumType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => d - .Name(dep => dep.Name + "Enum") - .DependsOn() - .Value("ABC")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("StringEnum"); - Assert.NotNull(type); - } - - [Fact] - public void GenericEnumType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => d - .Name(dep => dep.Name + "Enum") - .DependsOn(typeof(StringType)) - .Value("ABC")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("StringEnum"); - Assert.NotNull(type); - } - - [Fact] - public void EnumType_WithDirectives() - { - // act - ISchema schema = SchemaBuilder.New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.Enum))) - .AddEnumType(d => d.Name("Foo").Directive(new DirectiveNode("bar")).Value("ABC")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Directives, t => Assert.Equal("bar", t.Type.Name)); - } - - [Fact] - public void EnumType_WithDirectivesT() - { - // act - ISchema schema = SchemaBuilder.New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.Enum))) - .AddEnumType(d => d.Name("Foo").Directive().Value("ABC")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Directives, - t => Assert.Equal("bar", t.Type.Name)); - } - - [Fact] - public void ImplicitEnumType_DetectEnumValues() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - Assert.NotNull(type); - Assert.True(type.TryGetRuntimeValue("BAR1", out var value)); - Assert.Equal(Foo.Bar1, value); - Assert.True(type.TryGetRuntimeValue("BAR2", out value)); - Assert.Equal(Foo.Bar2, value); - } - - [Fact] - public void ExplicitEnumType_OnlyContainDeclaredValues() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => - { - d.BindValues(BindingBehavior.Explicit); - d.Value(Foo.Bar1); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => d + .Name(dep => dep.Name + "Enum") + .DependsOn() + .Value("BAR")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringEnum"); + Assert.NotNull(type); + } - // assert - EnumType type = schema.GetType("Foo"); - Assert.NotNull(type); - Assert.True(type.TryGetRuntimeValue("BAR1", out var value)); - Assert.Equal(Foo.Bar1, value); - Assert.False(type.TryGetRuntimeValue("BAR2", out value)); - Assert.Null(value); - } + [Fact] + public void EnumType_GraphQLDescriptionAttribute() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("DescriptionTestEnum"); + Assert.Equal("TestDescription", type.Description); + } - [Fact] - public void ExplicitEnumType_OnlyContainDeclaredValues_2() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => - { - d.BindValuesImplicitly().BindValuesExplicitly(); - d.Value(Foo.Bar1); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void EnumType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => d + .Name(dep => dep.Name + "Enum") + .DependsOn(typeof(StringType)) + .Value("BAR")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringEnum"); + Assert.NotNull(type); + } - // assert - EnumType type = schema.GetType("Foo"); - Assert.NotNull(type); - Assert.True(type.TryGetRuntimeValue("BAR1", out var value)); - Assert.Equal(Foo.Bar1, value); - Assert.False(type.TryGetRuntimeValue("BAR2", out value)); - Assert.Null(value); - } + [Fact] + public void GenericEnumType_DynamicName() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => d + .Name(dep => dep.Name + "Enum") + .DependsOn() + .Value("ABC")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringEnum"); + Assert.NotNull(type); + } - [Fact] - public void EnumTypeT_Ignore_Fields() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType() - .Create(); + [Fact] + public void GenericEnumType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => d + .Name(dep => dep.Name + "Enum") + .DependsOn(typeof(StringType)) + .Value("ABC")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringEnum"); + Assert.NotNull(type); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void EnumType_WithDirectives() + { + // act + var schema = SchemaBuilder.New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.Enum))) + .AddEnumType(d => d.Name("Foo").Directive(new DirectiveNode("bar")).Value("ABC")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Directives, t => Assert.Equal("bar", t.Type.Name)); + } - [Fact] - public void EnumTypeT_Ignore_Fields_With_Extension() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType() - .Create(); + [Fact] + public void EnumType_WithDirectivesT() + { + // act + var schema = SchemaBuilder.New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.Enum))) + .AddEnumType(d => d.Name("Foo").Directive().Value("ABC")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Directives, + t => Assert.Equal("bar", t.Type.Name)); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void ImplicitEnumType_DetectEnumValues() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.NotNull(type); + Assert.True(type.TryGetRuntimeValue("BAR1", out var value)); + Assert.Equal(Foo.Bar1, value); + Assert.True(type.TryGetRuntimeValue("BAR2", out value)); + Assert.Equal(Foo.Bar2, value); + } - [Fact] - public void ImplicitEnumType_OnlyBar1HasCustomName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddEnumType(d => - { - d.Value(Foo.Bar1).Name("FOOBAR"); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void ExplicitEnumType_OnlyContainDeclaredValues() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => + { + d.BindValues(BindingBehavior.Explicit); + d.Value(Foo.Bar1); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.NotNull(type); + Assert.True(type.TryGetRuntimeValue("BAR1", out var value)); + Assert.Equal(Foo.Bar1, value); + Assert.False(type.TryGetRuntimeValue("BAR2", out value)); + Assert.Null(value); + } - // assert - EnumType type = schema.GetType("Foo"); - Assert.NotNull(type); + [Fact] + public void ExplicitEnumType_OnlyContainDeclaredValues_2() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => + { + d.BindValuesImplicitly().BindValuesExplicitly(); + d.Value(Foo.Bar1); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.NotNull(type); + Assert.True(type.TryGetRuntimeValue("BAR1", out var value)); + Assert.Equal(Foo.Bar1, value); + Assert.False(type.TryGetRuntimeValue("BAR2", out value)); + Assert.Null(value); + } - Assert.Collection( - type.Values, - t => - { - Assert.Equal(Foo.Bar1, t.Value); - Assert.Equal("FOOBAR", t.Name); - }, - t => - { - Assert.Equal(Foo.Bar2, t.Value); - Assert.Equal("BAR2", t.Name); - }); - } + [Fact] + public void EnumTypeT_Ignore_Fields() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void EnumType_WithNoValues() - { - // act - void Action() => SchemaBuilder.New().AddType().Create(); + [Fact] + public void EnumTypeT_Ignore_Fields_With_Extension() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void ImplicitEnumType_OnlyBar1HasCustomName() + { + // act + var schema = SchemaBuilder.New() + .AddEnumType(d => + { + d.Value(Foo.Bar1).Name("FOOBAR"); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.NotNull(type); + + Assert.Collection( + type.Values, + t => + { + Assert.Equal(Foo.Bar1, t.Value); + Assert.Equal("FOOBAR", t.Name); + }, + t => + { + Assert.Equal(Foo.Bar2, t.Value); + Assert.Equal("BAR2", t.Name); + }); + } - [Fact] - public void EnsureEnumTypeKindIsCorrect() - { - // act - ISchema schema = SchemaBuilder.New() - .AddType>() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void EnumType_WithNoValues() + { + // act + void Action() => SchemaBuilder.New().AddType().Create(); - // assert - EnumType type = schema.GetType("Foo"); - Assert.Equal(TypeKind.Enum, type.Kind); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void EnumValue_ValueIsNull_SchemaException() - { - // arrange - // act - void Action() => SchemaBuilder.New() - .AddQueryType() - .AddType(new EnumType(d => d.Name("Foo") - .Value(null))) - .Create(); + [Fact] + public void EnsureEnumTypeKindIsCorrect() + { + // act + var schema = SchemaBuilder.New() + .AddType>() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Equal(TypeKind.Enum, type.Kind); + } - // assert + [Fact] + public void EnumValue_ValueIsNull_SchemaException() + { + // arrange + // act + void Action() => SchemaBuilder.New() + .AddQueryType() + .AddType(new EnumType(d => d.Name("Foo") + .Value(null))) + .Create(); + + // assert #if NETCOREAPP2_1 Assert.Throws(Action) .Errors.Single().Message.MatchSnapshot( new SnapshotNameExtension("NETCOREAPP2_1")); #else - Assert.Throws(Action) - .Errors.Single().Message.MatchSnapshot(); + Assert.Throws(Action) + .Errors.Single().Message.MatchSnapshot(); #endif - } - - [Fact] - public void EnumValueT_ValueIsNull_SchemaException() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddQueryType() - .AddType(new EnumType(d => d.Name("Foo") - .Value(null))) - .Create(); - - // assert - - Exception ex = - Assert.Throws(Action) - .Errors.Single().Exception; - - Assert.Equal( - "runtimeValue", - Assert.IsType(ex).ParamName); - } + } - [Fact] - public void EnumValue_WithDirectives() - { - // act - ISchema schema = SchemaBuilder - .New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.EnumValue))) - .AddEnumType(d => d - .Name("Foo") - .Value("baz") - .Directive(new DirectiveNode("bar"))) - .ModifyOptions(o => o.StrictValidation = false) + [Fact] + public void EnumValueT_ValueIsNull_SchemaException() + { + // arrange + // act + void Action() => + SchemaBuilder.New() + .AddQueryType() + .AddType(new EnumType(d => d.Name("Foo") + .Value(null))) .Create(); - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Values, - v => Assert.Collection(v.Directives, - t => Assert.Equal("bar", t.Type.Name))); - } + // assert - [Fact] - public void EnumValue_WithDirectivesNameArgs() - { - // act - ISchema schema = SchemaBuilder - .New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.EnumValue))) - .AddEnumType(d => d - .Name("Foo") - .Value("baz") - .Directive("bar", Array.Empty())) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Values, - v => Assert.Collection(v.Directives, - t => Assert.Equal("bar", t.Type.Name))); - } + var ex = + Assert.Throws(Action) + .Errors.Single().Exception; - [Fact] - public void Serialize_EnumValue_WithDirectives() - { - // act - ISchema schema = SchemaBuilder - .New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.EnumValue))) - .AddEnumType(d => d - .Name("Foo") - .Value("baz") - .Directive(new DirectiveNode("bar"))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + Assert.Equal( + "runtimeValue", + Assert.IsType(ex).ParamName); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void EnumValue_WithDirectives() + { + // act + var schema = SchemaBuilder + .New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.EnumValue))) + .AddEnumType(d => d + .Name("Foo") + .Value("baz") + .Directive(new DirectiveNode("bar"))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Values, + v => Assert.Collection(v.Directives, + t => Assert.Equal("bar", t.Type.Name))); + } - [Fact] - public void EnumValue_WithDirectivesT() - { - // act - ISchema schema = SchemaBuilder - .New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.EnumValue))) - .AddEnumType(d => d - .Name("Foo") - .Value("baz") - .Directive()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void EnumValue_WithDirectivesNameArgs() + { + // act + var schema = SchemaBuilder + .New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.EnumValue))) + .AddEnumType(d => d + .Name("Foo") + .Value("baz") + .Directive("bar", Array.Empty())) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Values, + v => Assert.Collection(v.Directives, + t => Assert.Equal("bar", t.Type.Name))); + } - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Values, - v => Assert.Collection(v.Directives, - t => Assert.Equal("bar", t.Type.Name))); - } + [Fact] + public void Serialize_EnumValue_WithDirectives() + { + // act + var schema = SchemaBuilder + .New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.EnumValue))) + .AddEnumType(d => d + .Name("Foo") + .Value("baz") + .Directive(new DirectiveNode("bar"))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void EnumValue_WithDirectivesTInstance() - { - // act - ISchema schema = SchemaBuilder - .New() - .AddDirectiveType(new DirectiveType(d => d - .Name("bar") - .Location(DirectiveLocation.EnumValue))) - .AddEnumType(d => d - .Name("Foo") - .Value("baz") - .Directive(new Bar())) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void EnumValue_WithDirectivesT() + { + // act + var schema = SchemaBuilder + .New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.EnumValue))) + .AddEnumType(d => d + .Name("Foo") + .Value("baz") + .Directive()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Values, + v => Assert.Collection(v.Directives, + t => Assert.Equal("bar", t.Type.Name))); + } - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Values, - v => Assert.Collection(v.Directives, - t => Assert.Equal("bar", t.Type.Name))); - } + [Fact] + public void EnumValue_WithDirectivesTInstance() + { + // act + var schema = SchemaBuilder + .New() + .AddDirectiveType(new DirectiveType(d => d + .Name("bar") + .Location(DirectiveLocation.EnumValue))) + .AddEnumType(d => d + .Name("Foo") + .Value("baz") + .Directive(new Bar())) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Values, + v => Assert.Collection(v.Directives, + t => Assert.Equal("bar", t.Type.Name))); + } - [Fact] - public void EnumValue_SetContextData() - { - // act - ISchema schema = SchemaBuilder - .New() - .AddEnumType(d => d - .Name("Foo") - .Value("bar") - .Extend() - .OnBeforeCreate(def => def.ContextData["baz"] = "qux")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void EnumValue_SetContextData() + { + // act + var schema = SchemaBuilder + .New() + .AddEnumType(d => d + .Name("Foo") + .Value("bar") + .Extend() + .OnBeforeCreate(def => def.ContextData["baz"] = "qux")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Values, + v => Assert.Collection(v.ContextData, + c => + { + Assert.Equal("baz", c.Key); + Assert.Equal("qux", c.Value); + })); + } - // assert - EnumType type = schema.GetType("Foo"); - Assert.Collection(type.Values, - v => Assert.Collection(v.ContextData, - c => - { - Assert.Equal("baz", c.Key); - Assert.Equal("qux", c.Value); - })); - } + [Fact] + public void EnumValue_DefinitionIsNull_ArgumentNullException() + { + // arrange + var completionContext = new Mock(); - [Fact] - public void EnumValue_DefinitionIsNull_ArgumentNullException() - { - // arrange - var completionContext = new Mock(); + // act + void Action() => new EnumValue(completionContext.Object, null!); - // act - void Action() => new EnumValue(completionContext.Object, null!); + // assert + Assert.Throws(Action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void EnumValue_ContextIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => new EnumValue(null!, new EnumValueDefinition()); - [Fact] - public void EnumValue_ContextIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => new EnumValue(null!, new EnumValueDefinition()); + // assert + Assert.Throws(Action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void EnumValue_DefinitionValueIsNull_ArgumentNullException() + { + // arrange + var completionContext = new Mock(); - [Fact] - public void EnumValue_DefinitionValueIsNull_ArgumentNullException() - { - // arrange - var completionContext = new Mock(); + // act + void Action() => new EnumValue(completionContext.Object, new EnumValueDefinition()); - // act - void Action() => new EnumValue(completionContext.Object, new EnumValueDefinition()); + // assert + Assert.Throws(Action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void Deprecate_Obsolete_Values() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Deprecate_Obsolete_Values() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType() - .Create(); + [Fact] + public void Deprecate_Fields_With_Deprecated_Attribute() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Ignore_Fields_With_GraphQLIgnoreAttribute() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Deprecate_Fields_With_Deprecated_Attribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType() - .Create(); + [Fact] + public void EnumType_That_Is_Bound_To_String_Should_Not_Interfere_With_Scalar() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .ToString() + .MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Recognize_GraphQLNameAttribute_On_EnumType_And_EnumValue() + { + SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Ignore_Fields_With_GraphQLIgnoreAttribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType() - .Create(); + [Fact] + public void ValueContainingUnderline_Should_NotResultInDoubleUnderline() + { + SchemaBuilder.New() + .AddEnumType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .ToString() + .MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Generic_Ignore_Descriptor_Is_Null() + { + void Fail() + => EnumTypeDescriptorExtensions.Ignore(default(IEnumTypeDescriptor)!, 1); - [Fact] - public void EnumType_That_Is_Bound_To_String_Should_Not_Interfere_With_Scalar() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .ToString() - .MatchSnapshot(); - } + Assert.Throws(Fail); + } - [Fact] - public void Recognize_GraphQLNameAttribute_On_EnumType_And_EnumValue() - { - SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void Generic_Ignore_Value_Is_Null() + { + var descriptor = new Mock>(); - [Fact] - public void ValueContainingUnderline_Should_NotResultInDoubleUnderline() - { - SchemaBuilder.New() - .AddEnumType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .ToString() - .MatchSnapshot(); - } + void Fail() + => EnumTypeDescriptorExtensions.Ignore(descriptor.Object, null); - [Fact] - public void Generic_Ignore_Descriptor_Is_Null() - { - void Fail() - => EnumTypeDescriptorExtensions.Ignore(default(IEnumTypeDescriptor)!, 1); - - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void Generic_Ignore_Value_Is_Null() - { - var descriptor = new Mock>(); + [Fact] + public void Ignore_Descriptor_Is_Null() + { + void Fail() + => EnumTypeDescriptorExtensions.Ignore(default(IEnumTypeDescriptor)!, 1); - void Fail() - => EnumTypeDescriptorExtensions.Ignore(descriptor.Object, null); - - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void Ignore_Descriptor_Is_Null() - { - void Fail() - => EnumTypeDescriptorExtensions.Ignore(default(IEnumTypeDescriptor)!, 1); - - Assert.Throws(Fail); - } + [Fact] + public void Ignore_Value_Is_Null() + { + var descriptor = new Mock(); - [Fact] - public void Ignore_Value_Is_Null() - { - var descriptor = new Mock(); + void Fail() + => EnumTypeDescriptorExtensions.Ignore(descriptor.Object, null); - void Fail() - => EnumTypeDescriptorExtensions.Ignore(descriptor.Object, null); - - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - public enum Foo - { - Bar1, - Bar2 - } + public enum Foo + { + Bar1, + Bar2 + } - public class Bar { } + public class Bar { } - public enum FooObsolete - { - Bar1, + public enum FooObsolete + { + Bar1, - [Obsolete] - Bar2 - } + [Obsolete] + Bar2 + } - public enum FooIgnore - { - Bar1, - [GraphQLIgnore] - Bar2 - } + public enum FooIgnore + { + Bar1, + [GraphQLIgnore] + Bar2 + } - public class FooIgnoredType : EnumType + public class FooIgnoredType : EnumType + { + protected override void Configure(IEnumTypeDescriptor descriptor) { - protected override void Configure(IEnumTypeDescriptor descriptor) - { - descriptor.Value(Foo.Bar2).Ignore(); - } + descriptor.Value(Foo.Bar2).Ignore(); } + } - public class FooIgnoredTypeWithExtension : EnumType + public class FooIgnoredTypeWithExtension : EnumType + { + protected override void Configure(IEnumTypeDescriptor descriptor) { - protected override void Configure(IEnumTypeDescriptor descriptor) - { - descriptor.Ignore(Foo.Bar2); - } + descriptor.Ignore(Foo.Bar2); } + } - public enum FooDeprecated - { - Bar1, - [GraphQLDeprecated("Baz.")] - Bar2 - } + public enum FooDeprecated + { + Bar1, + [GraphQLDeprecated("Baz.")] + Bar2 + } - [GraphQLName("Foo")] - public enum FooName - { - Bar1, - [GraphQLName("BAR_2")] - Bar2 - } + [GraphQLName("Foo")] + public enum FooName + { + Bar1, + [GraphQLName("BAR_2")] + Bar2 + } - public enum FooUnderline - { - Creating_Instance = 1 - } + public enum FooUnderline + { + Creating_Instance = 1 + } - public class SomeQueryType : ObjectType + public class SomeQueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("a").Type().Resolve("DEF"); - descriptor.Field("b").Type().Resolve("StringResolver"); - } + descriptor.Name("Query"); + descriptor.Field("a").Type().Resolve("DEF"); + descriptor.Field("b").Type().Resolve("StringResolver"); } + } - public class SomeEnumType - : EnumType + public class SomeEnumType + : EnumType + { + protected override void Configure(IEnumTypeDescriptor descriptor) { - protected override void Configure(IEnumTypeDescriptor descriptor) - { - descriptor.Name("Some"); - descriptor.Value("ABC").Name("DEF"); - } + descriptor.Name("Some"); + descriptor.Value("ABC").Name("DEF"); } + } - [GraphQLDescription("TestDescription")] - public enum DescriptionTestEnum - { - Foo, - Bar - } + [GraphQLDescription("TestDescription")] + public enum DescriptionTestEnum + { + Foo, + Bar } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeUnsafeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeUnsafeTests.cs index d94a274e17c..689059ba60f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeUnsafeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/EnumTypeUnsafeTests.cs @@ -6,72 +6,71 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class EnumTypeUnsafeTests { - public class EnumTypeUnsafeTests + [Fact] + public async Task Create_Enum_Unsafe_With_Two_Values() { - [Fact] - public async Task Create_Enum_Unsafe_With_Two_Values() - { - // arrange - // act - var enumType = EnumType.CreateUnsafe( - new("Simple") + // arrange + // act + var enumType = EnumType.CreateUnsafe( + new("Simple") + { + Values = { - Values = - { - new("ONE", runtimeValue: "One"), - new("TWO", runtimeValue: "Two") - } - }); + new("ONE", runtimeValue: "One"), + new("TWO", runtimeValue: "Two") + } + }); - var queryType = ObjectType.CreateUnsafe( - new("Query") + var queryType = ObjectType.CreateUnsafe( + new("Query") + { + Fields = { - Fields = - { - new("foo", type: TypeReference.Create(enumType), pureResolver: _ => "One") - } - }); + new("foo", type: TypeReference.Create(enumType), pureResolver: _ => "One") + } + }); - // assert - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(queryType) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + // assert + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(queryType) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Create_Enum_Unsafe_With_Descriptor() - { - // arrange - // act - var enumType = EnumType.CreateUnsafe( - new EnumTypeDefinition("Simple") + [Fact] + public async Task Create_Enum_Unsafe_With_Descriptor() + { + // arrange + // act + var enumType = EnumType.CreateUnsafe( + new EnumTypeDefinition("Simple") + { + Values = { - Values = - { - new("ONE", runtimeValue: "One"), - new("TWO", runtimeValue: "Two") - } - }); + new("ONE", runtimeValue: "One"), + new("TWO", runtimeValue: "Two") + } + }); - var queryType = ObjectType.CreateUnsafe( - new("Query") + var queryType = ObjectType.CreateUnsafe( + new("Query") + { + Fields = { - Fields = - { - new("foo", type: TypeReference.Create(enumType), pureResolver: _ => "One") - } - }); + new("foo", type: TypeReference.Create(enumType), pureResolver: _ => "One") + } + }); - // assert - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(queryType) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + // assert + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(queryType) + .BuildSchemaAsync() + .MatchSnapshotAsync(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputCoercionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputCoercionTests.cs index 6d678f7eb4f..aa76bc2b858 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputCoercionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputCoercionTests.cs @@ -5,235 +5,234 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputCoercionTests { - public class InputCoercionTests + /// + /// Converts according to input coercion rules. + /// + [Fact] + public void ConvertAccordingToInputCoercionRules() + { + InputIsCoercedCorrectly( + new BooleanValueNode(true), true); + InputIsCoercedCorrectly( + new BooleanValueNode(false), false); + InputIsCoercedCorrectly( + new IntValueNode(123), 123); + InputIsCoercedCorrectly( + new IntValueNode(123), 123d); + InputIsCoercedCorrectly( + new FloatValueNode(123.456d), 123.456d); + InputIsCoercedCorrectly( + new StringValueNode("abc123"), "abc123"); + InputIsCoercedCorrectly( + new StringValueNode("123456"), "123456"); + } + + /// + /// Does not convert when input coercion rules reject a value. + /// + [Fact] + public void ConvertAccordingToInputCoercionRules2() + { + InputCannotBeCoercedCorrectly( + new IntValueNode(123)); + InputCannotBeCoercedCorrectly( + new FloatValueNode(123.123d)); + InputCannotBeCoercedCorrectly( + new BooleanValueNode(true)); + InputCannotBeCoercedCorrectly( + new StringValueNode("123.123")); + InputCannotBeCoercedCorrectly( + new StringValueNode("123")); + InputCannotBeCoercedCorrectly( + new FloatValueNode(123.456d)); + InputCannotBeCoercedCorrectly( + new BooleanValueNode(false)); + InputIsCoercedCorrectly( + new StringValueNode("123456"), "123456"); + } + + [Fact] + public void ListCanBeCoercedFromListValue() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new BooleanType()); + var list = new ListValueNode(new BooleanValueNode(true), new BooleanValueNode(false)); + + // act + var coercedValue = + inputParser.ParseLiteral(list, type, PathFactory.Instance.New("root")); + + // assert + Assert.Collection(Assert.IsType>(coercedValue), Assert.True, Assert.False); + } + + /// + /// Expected Type: [[Boolean]] + /// Provided Value: [[true], [true, false]] + /// Coerced Value: [[true], [true, false]] + /// + [Fact] + public void Matrix_Can_Be_Coerced_From_Matrix() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new ListType(new BooleanType())); + var value = new ListValueNode( + new ListValueNode(new BooleanValueNode(true)), + new ListValueNode(new BooleanValueNode(true), new BooleanValueNode(false))); + + // act + var coercedValue = + inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); + + // assert + coercedValue.MatchSnapshot(); + } + + /// + /// Expected Type: [[Boolean]] + /// Provided Value: true + /// Coerced Value: [[true]] + /// + [Fact] + public void Matrix_Can_Be_Coerced_From_Single_Value() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new ListType(new BooleanType())); + var value = new BooleanValueNode(true); + + // act + var coercedValue = + inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); + + // assert + coercedValue.MatchSnapshot(); + } + + /// + /// Expected Type: [[Boolean]] + /// Provided Value: null + /// Coerced Value: null + /// + [Fact] + public void Matrix_Can_Be_Coerced_From_Null() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new ListType(new BooleanType())); + var value = NullValueNode.Default; + + // act + var coercedValue = + inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); + + // assert + Assert.Null(coercedValue); + } + + /// + /// Expected Type: [[Boolean]] + /// Provided Value: [true] + /// Coerced Value: Error: Incorrect item value + /// + [Fact] + public void Matrix_Cannot_Be_Coerced_From_List() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new ListType(new BooleanType())); + var value = new ListValueNode(new BooleanValueNode(true)); + + // act + void Action() => + inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void ListCanBeCoercedFromListElementValue() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new BooleanType()); + var element = new BooleanValueNode(true); + + // act + var coercedValue = + inputParser.ParseLiteral(element, type, PathFactory.Instance.New("root")); + + // assert + Assert.Collection(Assert.IsType>(coercedValue), Assert.True); + } + + [Fact] + public void ListCannotBeCoercedFromMixedList() + { + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new BooleanType()); + var list = new ListValueNode(new BooleanValueNode(true), new StringValueNode("foo")); + + // act + void Action() => + inputParser.ParseLiteral(list, type, PathFactory.Instance.New("root")); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void ListCannotBeCoercedIfElementTypeDoesNotMatch() { - /// - /// Converts according to input coercion rules. - /// - [Fact] - public void ConvertAccordingToInputCoercionRules() - { - InputIsCoercedCorrectly( - new BooleanValueNode(true), true); - InputIsCoercedCorrectly( - new BooleanValueNode(false), false); - InputIsCoercedCorrectly( - new IntValueNode(123), 123); - InputIsCoercedCorrectly( - new IntValueNode(123), 123d); - InputIsCoercedCorrectly( - new FloatValueNode(123.456d), 123.456d); - InputIsCoercedCorrectly( - new StringValueNode("abc123"), "abc123"); - InputIsCoercedCorrectly( - new StringValueNode("123456"), "123456"); - } - - /// - /// Does not convert when input coercion rules reject a value. - /// - [Fact] - public void ConvertAccordingToInputCoercionRules2() - { - InputCannotBeCoercedCorrectly( - new IntValueNode(123)); - InputCannotBeCoercedCorrectly( - new FloatValueNode(123.123d)); - InputCannotBeCoercedCorrectly( - new BooleanValueNode(true)); - InputCannotBeCoercedCorrectly( - new StringValueNode("123.123")); - InputCannotBeCoercedCorrectly( - new StringValueNode("123")); - InputCannotBeCoercedCorrectly( - new FloatValueNode(123.456d)); - InputCannotBeCoercedCorrectly( - new BooleanValueNode(false)); - InputIsCoercedCorrectly( - new StringValueNode("123456"), "123456"); - } - - [Fact] - public void ListCanBeCoercedFromListValue() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new BooleanType()); - var list = new ListValueNode(new BooleanValueNode(true), new BooleanValueNode(false)); - - // act - var coercedValue = - inputParser.ParseLiteral(list, type, PathFactory.Instance.New("root")); - - // assert - Assert.Collection(Assert.IsType>(coercedValue), Assert.True, Assert.False); - } - - /// - /// Expected Type: [[Boolean]] - /// Provided Value: [[true], [true, false]] - /// Coerced Value: [[true], [true, false]] - /// - [Fact] - public void Matrix_Can_Be_Coerced_From_Matrix() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new ListType(new BooleanType())); - var value = new ListValueNode( - new ListValueNode(new BooleanValueNode(true)), - new ListValueNode(new BooleanValueNode(true), new BooleanValueNode(false))); - - // act - var coercedValue = - inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); - - // assert - coercedValue.MatchSnapshot(); - } - - /// - /// Expected Type: [[Boolean]] - /// Provided Value: true - /// Coerced Value: [[true]] - /// - [Fact] - public void Matrix_Can_Be_Coerced_From_Single_Value() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new ListType(new BooleanType())); - var value = new BooleanValueNode(true); - - // act - var coercedValue = - inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); - - // assert - coercedValue.MatchSnapshot(); - } - - /// - /// Expected Type: [[Boolean]] - /// Provided Value: null - /// Coerced Value: null - /// - [Fact] - public void Matrix_Can_Be_Coerced_From_Null() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new ListType(new BooleanType())); - NullValueNode value = NullValueNode.Default; - - // act - var coercedValue = - inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); - - // assert - Assert.Null(coercedValue); - } - - /// - /// Expected Type: [[Boolean]] - /// Provided Value: [true] - /// Coerced Value: Error: Incorrect item value - /// - [Fact] - public void Matrix_Cannot_Be_Coerced_From_List() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new ListType(new BooleanType())); - var value = new ListValueNode(new BooleanValueNode(true)); - - // act - void Action() => - inputParser.ParseLiteral(value, type, PathFactory.Instance.New("root")); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void ListCanBeCoercedFromListElementValue() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new BooleanType()); - var element = new BooleanValueNode(true); - - // act - var coercedValue = - inputParser.ParseLiteral(element, type, PathFactory.Instance.New("root")); - - // assert - Assert.Collection(Assert.IsType>(coercedValue), Assert.True); - } - - [Fact] - public void ListCannotBeCoercedFromMixedList() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new BooleanType()); - var list = new ListValueNode(new BooleanValueNode(true), new StringValueNode("foo")); - - // act - void Action() => - inputParser.ParseLiteral(list, type, PathFactory.Instance.New("root")); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void ListCannotBeCoercedIfElementTypeDoesNotMatch() - { - // arrange - var inputParser = new InputParser(new DefaultTypeConverter()); - var type = (IInputType)new ListType(new BooleanType()); - var element = new StringValueNode("foo"); - - // act - void Action() => - inputParser.ParseLiteral(element, type, PathFactory.Instance.New("root")); - - // assert - Assert.Throws(Action); - } - - private void InputIsCoercedCorrectly( - TLiteral literal, TExpected expectedValue) - where TType : ScalarType, new() - where TLiteral : IValueNode - { - // arrange - var type = new TType(); - - // act - var coercedValue = type.ParseLiteral(literal); - - // assert - Assert.IsType(coercedValue); - Assert.Equal(expectedValue, coercedValue); - } - - private void InputCannotBeCoercedCorrectly( - TLiteral literal) - where TType : ScalarType, new() - where TLiteral : IValueNode - { - // arrange - var type = new TType(); - - // act - void Action() => type.ParseLiteral(literal); - - // assert - Assert.Throws(Action); - } + // arrange + var inputParser = new InputParser(new DefaultTypeConverter()); + var type = (IInputType)new ListType(new BooleanType()); + var element = new StringValueNode("foo"); + + // act + void Action() => + inputParser.ParseLiteral(element, type, PathFactory.Instance.New("root")); + + // assert + Assert.Throws(Action); + } + + private void InputIsCoercedCorrectly( + TLiteral literal, TExpected expectedValue) + where TType : ScalarType, new() + where TLiteral : IValueNode + { + // arrange + var type = new TType(); + + // act + var coercedValue = type.ParseLiteral(literal); + + // assert + Assert.IsType(coercedValue); + Assert.Equal(expectedValue, coercedValue); + } + + private void InputCannotBeCoercedCorrectly( + TLiteral literal) + where TType : ScalarType, new() + where TLiteral : IValueNode + { + // arrange + var type = new TType(); + + // act + void Action() => type.ParseLiteral(literal); + + // assert + Assert.Throws(Action); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeAttributeTests.cs index 361bf62c20e..17ccd877909 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeAttributeTests.cs @@ -8,186 +8,185 @@ using Xunit; using QueryRequestBuilder = HotChocolate.Execution.QueryRequestBuilder; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputObjectTypeAttributeTests { - public class InputObjectTypeAttributeTests + [Fact] + public void Change_Field_Name_With_Attribute() { - [Fact] - public void Change_Field_Name_With_Attribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.True( - schema.GetType("Object1Input") - .Fields - .ContainsField("bar")); - } + // act + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.True( + schema.GetType("Object1Input") + .Fields + .ContainsField("bar")); + } - [Fact] - public void Change_InputObjectType_Name_With_Attribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.True( - schema.GetType("Bar") - .Fields - .ContainsField("foo")); - } + [Fact] + public void Change_InputObjectType_Name_With_Attribute() + { + // act + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.True( + schema.GetType("Bar") + .Fields + .ContainsField("foo")); + } - [Fact] - public void Annotated_Struct1_With_InputObjectTypeAttribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.True( - schema.GetType("Foo") - .Fields - .ContainsField("foo")); - } + [Fact] + public void Annotated_Struct1_With_InputObjectTypeAttribute() + { + // act + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.True( + schema.GetType("Foo") + .Fields + .ContainsField("foo")); + } - [Fact] - public void Infer_Default_Values_From_Attribute() - { - SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Infer_Default_Values_From_Attribute() + { + SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public async Task Infer_Default_Values_From_Attribute_Execute() - { - await SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - - d.Field("foo") - .Argument("a", a => a.Type>()) - .Resolve(ctx => ctx.ArgumentValue("a")); - }) - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("{ foo(a: { }) { foo bar baz qux quux } }") - .Create()) - .MatchSnapshotAsync(); - } + [Fact] + public async Task Infer_Default_Values_From_Attribute_Execute() + { + await SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + + d.Field("foo") + .Argument("a", a => a.Type>()) + .Resolve(ctx => ctx.ArgumentValue("a")); + }) + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("{ foo(a: { }) { foo bar baz qux quux } }") + .Create()) + .MatchSnapshotAsync(); + } - [Fact] - public async Task Infer_Default_Values_From_Attribute_Execute_With_Variables() - { - await SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - - d.Field("foo") - .Argument("a", a => a.Type>()) - .Resolve(ctx => ctx.ArgumentValue("a")); - }) - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery(@" + [Fact] + public async Task Infer_Default_Values_From_Attribute_Execute_With_Variables() + { + await SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + + d.Field("foo") + .Argument("a", a => a.Type>()) + .Resolve(ctx => ctx.ArgumentValue("a")); + }) + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery(@" query($q: InputWithDefaultsInput) { foo(a: $q) { foo bar baz qux quux } }") - .SetVariableValue("q", new Dictionary()) - .Create()) - .MatchSnapshotAsync(); - } + .SetVariableValue("q", new Dictionary()) + .Create()) + .MatchSnapshotAsync(); + } - public class Object1 - { - [RenameField] - public string Foo { get; set; } - } + public class Object1 + { + [RenameField] + public string Foo { get; set; } + } - public class RenameFieldAttribute - : InputFieldDescriptorAttribute + public class RenameFieldAttribute + : InputFieldDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IInputFieldDescriptor descriptor, + MemberInfo member) { - public override void OnConfigure( - IDescriptorContext context, - IInputFieldDescriptor descriptor, - MemberInfo member) - { - descriptor.Name("bar"); - } + descriptor.Name("bar"); } + } - [RenameType] - public class Object2 - { - public string Foo { get; set; } - } + [RenameType] + public class Object2 + { + public string Foo { get; set; } + } - [InputObjectType(Name = "Foo")] - public struct Struct1 - { - public string Foo { get; set; } - } + [InputObjectType(Name = "Foo")] + public struct Struct1 + { + public string Foo { get; set; } + } - public class RenameTypeAttribute - : InputObjectTypeDescriptorAttribute + public class RenameTypeAttribute + : InputObjectTypeDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IInputObjectTypeDescriptor descriptor, + Type type) { - public override void OnConfigure( - IDescriptorContext context, - IInputObjectTypeDescriptor descriptor, - Type type) - { - descriptor.Name("Bar"); - } + descriptor.Name("Bar"); } + } - public class InputWithDefaults - { - [DefaultValue("DefaultValue123")] - public string Foo { get; set; } + public class InputWithDefaults + { + [DefaultValue("DefaultValue123")] + public string Foo { get; set; } - [DefaultValue(2)] - public int Bar { get; set; } + [DefaultValue(2)] + public int Bar { get; set; } - [DefaultValue(1.2)] - public double Baz { get; set; } + [DefaultValue(1.2)] + public double Baz { get; set; } - [DefaultValue(true)] - public bool Qux { get; set; } + [DefaultValue(true)] + public bool Qux { get; set; } - [DefaultValue(Quux.Corge)] - public Quux Quux { get; set; } - } + [DefaultValue(Quux.Corge)] + public Quux Quux { get; set; } + } - public enum Quux - { - Corge, - Grault - } + public enum Quux + { + Corge, + Grault } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeDictionaryTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeDictionaryTests.cs index 4627f63985e..217bc1fb954 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeDictionaryTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeDictionaryTests.cs @@ -8,61 +8,60 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputObjectTypeNonNullTests + : TypeTestBase { - public class InputObjectTypeNonNullTests - : TypeTestBase + [Fact] + public void Nullable_Dictionary_Is_Correctly_Detected() { - [Fact] - public void Nullable_Dictionary_Is_Correctly_Detected() - { - #if NETCOREAPP2_1 +#if NETCOREAPP2_1 SchemaBuilder.New() .AddQueryType() .Create() .ToString() .MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1")); - #else - SchemaBuilder.New() - .AddQueryType() - .Create() - .ToString() - .MatchSnapshot(); - #endif - } +#else + SchemaBuilder.New() + .AddQueryType() + .Create() + .ToString() + .MatchSnapshot(); +#endif + } - [Fact] - public async Task Dictionary_Is_Correctly_Deserialized() - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable(); + [Fact] + public async Task Dictionary_Is_Correctly_Deserialized() + { + // arrange + var executor = SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync( - "query { foo(input: { contextData: [ { key: \"abc\" value: \"abc\" } ] }) }"); + // act + var result = await executor.ExecuteAsync( + "query { foo(input: { contextData: [ { key: \"abc\" value: \"abc\" } ] }) }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - public class Query + public class Query + { + public string GetFoo(FooInput input) { - public string GetFoo(FooInput input) + if (input.ContextData is { Count: 1 }) { - if (input.ContextData is { Count: 1 }) - { - return input.ContextData.First().Value; - } - return "nothing"; + return input.ContextData.First().Value; } + return "nothing"; } + } - public class FooInput - { - public Dictionary? ContextData { get; set; } - } + public class FooInput + { + public Dictionary? ContextData { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeExtensionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeExtensionTests.cs index 4e5b6f9520e..92c7e7e7c08 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeExtensionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeExtensionTests.cs @@ -2,282 +2,281 @@ using HotChocolate.Language; using System.Linq; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputObjectTypeExtensionTests { - public class InputObjectTypeExtensionTests + [Fact] + public void InputObjectTypeExtension_AddField() { - [Fact] - public void InputObjectTypeExtension_AddField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - Assert.True(type.Fields.ContainsField("test")); - } + // assert + var type = schema.GetType("FooInput"); + Assert.True(type.Fields.ContainsField("test")); + } - [Fact] - public void InputObjectTypeExtension_SetTypeContextData() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .Create(); + [Fact] + public void InputObjectTypeExtension_SetTypeContextData() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - Assert.True(type.ContextData.ContainsKey("foo")); - } + // assert + var type = schema.GetType("FooInput"); + Assert.True(type.ContextData.ContainsKey("foo")); + } - [Fact] - public void InputObjectTypeExtension_SetFieldContextData() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Field("description") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .Create(); + [Fact] + public void InputObjectTypeExtension_SetFieldContextData() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Field("description") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - Assert.True(type.Fields["description"] - .ContextData.ContainsKey("foo")); - } + // assert + var type = schema.GetType("FooInput"); + Assert.True(type.Fields["description"] + .ContextData.ContainsKey("foo")); + } - [Fact] - public void InputObjectTypeExtension_SetDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Directive("dummy"))) - .AddDirectiveType() - .Create(); + [Fact] + public void InputObjectTypeExtension_SetDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Directive("dummy"))) + .AddDirectiveType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - Assert.True(type.Directives.Contains("dummy")); - } + // assert + var type = schema.GetType("FooInput"); + Assert.True(type.Directives.Contains("dummy")); + } - [Fact] - public void InputObjectTypeExtension_SetDirectiveOnField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Field("name") - .Directive("dummy"))) - .AddDirectiveType() - .Create(); + [Fact] + public void InputObjectTypeExtension_SetDirectiveOnField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Field("name") + .Directive("dummy"))) + .AddDirectiveType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - Assert.True(type.Fields["name"] - .Directives.Contains("dummy")); - } + // assert + var type = schema.GetType("FooInput"); + Assert.True(type.Fields["name"] + .Directives.Contains("dummy")); + } - [Fact] - public void InputObjectTypeExtension_ReplaceDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InputObjectType(t => t - .Directive("dummy_arg", new ArgumentNode("a", "a")))) - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Directive("dummy_arg", new ArgumentNode("a", "b")))) - .AddDirectiveType() - .Create(); + [Fact] + public void InputObjectTypeExtension_ReplaceDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InputObjectType(t => t + .Directive("dummy_arg", new ArgumentNode("a", "a")))) + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Directive("dummy_arg", new ArgumentNode("a", "b")))) + .AddDirectiveType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - string value = type.Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + // assert + var type = schema.GetType("FooInput"); + var value = type.Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void InputObjectTypeExtension_ReplaceDirectiveOnField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InputObjectType(t => t - .Field(f => f.Description) - .Directive("dummy_arg", new ArgumentNode("a", "a")))) - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Field("description") - .Directive("dummy_arg", new ArgumentNode("a", "b")))) - .AddDirectiveType() - .Create(); + [Fact] + public void InputObjectTypeExtension_ReplaceDirectiveOnField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InputObjectType(t => t + .Field(f => f.Description) + .Directive("dummy_arg", new ArgumentNode("a", "a")))) + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Field("description") + .Directive("dummy_arg", new ArgumentNode("a", "b")))) + .AddDirectiveType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - string value = type.Fields["description"].Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + // assert + var type = schema.GetType("FooInput"); + var value = type.Fields["description"].Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void InputObjectTypeExtension_RepeatableDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InputObjectType(t => t - .Directive("dummy_rep"))) - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Directive("dummy_rep"))) - .AddDirectiveType() - .Create(); + [Fact] + public void InputObjectTypeExtension_RepeatableDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InputObjectType(t => t + .Directive("dummy_rep"))) + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Directive("dummy_rep"))) + .AddDirectiveType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - int count = type.Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + // assert + var type = schema.GetType("FooInput"); + var count = type.Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - [Fact] - public void InputObjectTypeExtension_RepeatableDirectiveOnField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InputObjectType(t => t - .Field(f => f.Description) - .Directive("dummy_rep"))) - .AddType(new InputObjectTypeExtension(d => d - .Name("FooInput") - .Field("description") - .Directive("dummy_rep"))) - .AddDirectiveType() - .Create(); + [Fact] + public void InputObjectTypeExtension_RepeatableDirectiveOnField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InputObjectType(t => t + .Field(f => f.Description) + .Directive("dummy_rep"))) + .AddType(new InputObjectTypeExtension(d => d + .Name("FooInput") + .Field("description") + .Directive("dummy_rep"))) + .AddDirectiveType() + .Create(); - // assert - InputObjectType type = schema.GetType("FooInput"); - int count = type.Fields["description"] - .Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + // assert + var type = schema.GetType("FooInput"); + var count = type.Fields["description"] + .Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - public class QueryType - : ObjectType + public class QueryType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("description").Resolve("bar"); - } + descriptor.Name("Query"); + descriptor.Field("description").Resolve("bar"); } + } - public class FooType - : InputObjectType + public class FooType + : InputObjectType + { + protected override void Configure( + IInputObjectTypeDescriptor descriptor) { - protected override void Configure( - IInputObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Description); - } + descriptor.Field(t => t.Description); } + } - public class FooTypeExtension - : InputObjectTypeExtension + public class FooTypeExtension + : InputObjectTypeExtension + { + protected override void Configure( + IInputObjectTypeDescriptor descriptor) { - protected override void Configure( - IInputObjectTypeDescriptor descriptor) - { - descriptor.Name("FooInput"); - descriptor.Field("test") - .Type>(); - } + descriptor.Name("FooInput"); + descriptor.Field("test") + .Type>(); } + } - public class Foo + public class Foo + { + public Foo() { - public Foo() - { - } - - public Foo(string name, string description) - { - Name = name; - Description = description; - } + } - public string Name { get; } = "hello"; - public string Description { get; } = "hello"; + public Foo(string name, string description) + { + Name = name; + Description = description; } - public class DummyDirective - : DirectiveType + public string Name { get; } = "hello"; + public string Description { get; } = "hello"; + } + + public class DummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy"); - descriptor.Location(DirectiveLocation.InputObject); - descriptor.Location(DirectiveLocation.InputFieldDefinition); - } + descriptor.Name("dummy"); + descriptor.Location(DirectiveLocation.InputObject); + descriptor.Location(DirectiveLocation.InputFieldDefinition); } + } - public class DummyWithArgDirective - : DirectiveType + public class DummyWithArgDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_arg"); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.InputObject); - descriptor.Location(DirectiveLocation.InputFieldDefinition); - } + descriptor.Name("dummy_arg"); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.InputObject); + descriptor.Location(DirectiveLocation.InputFieldDefinition); } + } - public class RepeatableDummyDirective - : DirectiveType + public class RepeatableDummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_rep"); - descriptor.Repeatable(); - descriptor.Location(DirectiveLocation.InputObject); - descriptor.Location(DirectiveLocation.InputFieldDefinition); - } + descriptor.Name("dummy_rep"); + descriptor.Repeatable(); + descriptor.Location(DirectiveLocation.InputObject); + descriptor.Location(DirectiveLocation.InputFieldDefinition); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeTests.cs index 40e84da497f..6083b74231a 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputObjectTypeTests.cs @@ -14,955 +14,954 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputObjectTypeTests : TypeTestBase { - public class InputObjectTypeTests : TypeTestBase + [Fact] + public void InputObjectType_DynamicName() { - [Fact] - public void InputObjectType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn() - .Field("bar") - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InputObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void InputObjectType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType)) - .Field("bar") - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InputObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void GenericInputObjectType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InputObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void GenericInputObjectType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInputObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InputObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void Initialize_IgnoreProperty_PropertyIsNotInSchemaType() - { - // arrange - // act - var fooType = new InputObjectType( - d => d.Field(f => f.Id).Ignore()); - - // assert - fooType = CreateType(fooType); - Assert.Collection(fooType.Fields, - t => Assert.Equal("name", t.Name)); - } - - - [Fact] - public void Initialize_UnignoreProperty_PropertyIsInSchemaType() - { - // arrange - // act - var fooType = new InputObjectType(d => - { - d.Field(f => f.Id).Ignore(); - d.Field(f => f.Id).Ignore(false); - }); - - // assert - fooType = CreateType(fooType); - Assert.Collection(fooType.Fields, - t => Assert.Equal("id", t.Name), - t => Assert.Equal("name", t.Name)); - } - - [Fact] - public void EnsureInputObjectTypeKindIsCorrect() - { - // arrange - ISchema schema = Create(); - InputObjectType inputObjectType = - schema.GetType("Object1"); - - // act - TypeKind kind = inputObjectType.Kind; + // act + var schema = SchemaBuilder.New() + .AddInputObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn() + .Field("bar") + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - // assert - Assert.Equal(TypeKind.InputObject, kind); - } + [Fact] + public void InputObjectType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddInputObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType)) + .Field("bar") + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void GenericInputObject_AddDirectives_NameArgs() - { - // arrange - // act - var fooType = new InputObjectType( - d => d.Directive("foo").Field(f => f.Id).Directive("foo")); + [Fact] + public void GenericInputObjectType_DynamicName() + { + // act + var schema = SchemaBuilder.New() + .AddInputObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - // assert - fooType = CreateType(fooType, b => b.AddDirectiveType()); + [Fact] + public void GenericInputObjectType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddInputObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void Initialize_IgnoreProperty_PropertyIsNotInSchemaType() + { + // arrange + // act + var fooType = new InputObjectType( + d => d.Field(f => f.Id).Ignore()); + + // assert + fooType = CreateType(fooType); + Assert.Collection(fooType.Fields, + t => Assert.Equal("name", t.Name)); + } - [Fact] - public void GenericInputObject_AddDirectives_NameArgs2() - { - // arrange - // act - var fooType = new InputObjectType( - d => d.Directive(new NameString("foo")) - .Field(f => f.Id) - .Directive(new NameString("foo"))); - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); + [Fact] + public void Initialize_UnignoreProperty_PropertyIsInSchemaType() + { + // arrange + // act + var fooType = new InputObjectType(d => + { + d.Field(f => f.Id).Ignore(); + d.Field(f => f.Id).Ignore(false); + }); + + // assert + fooType = CreateType(fooType); + Assert.Collection(fooType.Fields, + t => Assert.Equal("id", t.Name), + t => Assert.Equal("name", t.Name)); + } + [Fact] + public void EnsureInputObjectTypeKindIsCorrect() + { + // arrange + var schema = Create(); + var inputObjectType = + schema.GetType("Object1"); - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + // act + var kind = inputObjectType.Kind; - [Fact] - public void GenericInputObject_AddDirectives_DirectiveNode() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive(new DirectiveNode("foo")) - .Field(f => f.Id) - .Directive(new DirectiveNode("foo"))); - - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); - - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + // assert + Assert.Equal(TypeKind.InputObject, kind); + } - [Fact] - public void GenericInputObject_AddDirectives_DirectiveClassInstance() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive(new FooDirective()) - .Field(f => f.Id) - .Directive(new FooDirective())); + [Fact] + public void GenericInputObject_AddDirectives_NameArgs() + { + // arrange + // act + var fooType = new InputObjectType( + d => d.Directive("foo").Field(f => f.Id).Directive("foo")); - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); + // assert + fooType = CreateType(fooType, b => b.AddDirectiveType()); - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void GenericInputObject_AddDirectives_DirectiveType() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive() + [Fact] + public void GenericInputObject_AddDirectives_NameArgs2() + { + // arrange + // act + var fooType = new InputObjectType( + d => d.Directive(new NameString("foo")) .Field(f => f.Id) - .Directive()); - - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); - - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } - - [Fact] - public void InputObject_AddDirectives_NameArgs() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive("foo") - .Field("id") - .Type() - .Directive("foo")); - - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); - - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } - - [Fact] - public void InputObject_AddDirectives_NameArgs2() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive(new NameString("foo")) - .Field("id") - .Type() .Directive(new NameString("foo"))); - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } - [Fact] - public void InputObject_AddDirectives_DirectiveNode() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive(new DirectiveNode("foo")) - .Field("id") - .Type() - .Directive(new DirectiveNode("foo"))); + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); + [Fact] + public void GenericInputObject_AddDirectives_DirectiveNode() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive(new DirectiveNode("foo")) + .Field(f => f.Id) + .Directive(new DirectiveNode("foo"))); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void GenericInputObject_AddDirectives_DirectiveClassInstance() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive(new FooDirective()) + .Field(f => f.Id) + .Directive(new FooDirective())); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void InputObject_AddDirectives_DirectiveClassInstance() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive(new FooDirective()) - .Field("id") - .Type() - .Directive(new FooDirective())); + [Fact] + public void GenericInputObject_AddDirectives_DirectiveType() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive() + .Field(f => f.Id) + .Directive()); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); + [Fact] + public void InputObject_AddDirectives_NameArgs() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive("foo") + .Field("id") + .Type() + .Directive("foo")); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void InputObject_AddDirectives_NameArgs2() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive(new NameString("foo")) + .Field("id") + .Type() + .Directive(new NameString("foo"))); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void InputObject_AddDirectives_DirectiveType() - { - // arrange - // act - var fooType = new InputObjectType(d => d - .Name("Bar") - .Directive() - .Field("id") - .Type() - .Directive()); + [Fact] + public void InputObject_AddDirectives_DirectiveNode() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive(new DirectiveNode("foo")) + .Field("id") + .Type() + .Directive(new DirectiveNode("foo"))); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - // assert - fooType = CreateType(fooType, - b => b.AddDirectiveType()); + [Fact] + public void InputObject_AddDirectives_DirectiveClassInstance() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive(new FooDirective()) + .Field("id") + .Type() + .Directive(new FooDirective())); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void InputObject_AddDirectives_DirectiveType() + { + // arrange + // act + var fooType = new InputObjectType(d => d + .Name("Bar") + .Directive() + .Field("id") + .Type() + .Directive()); + + // assert + fooType = CreateType(fooType, + b => b.AddDirectiveType()); + + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - private ISchema Create() - { - return SchemaBuilder.New() - .ModifyOptions(o => o.StrictValidation = false) - .AddInputObjectType(d => - { - d.Name("Object1"); - d.Field(t => t.Foo).Type>(); - d.Field(t => t.Bar).Type(); - }) - .AddInputObjectType(d => - { - d.Name("Object2"); - d.Field(t => t.FooList) - .Type>>>(); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - } + private ISchema Create() + { + return SchemaBuilder.New() + .ModifyOptions(o => o.StrictValidation = false) + .AddInputObjectType(d => + { + d.Name("Object1"); + d.Field(t => t.Foo).Type>(); + d.Field(t => t.Bar).Type(); + }) + .AddInputObjectType(d => + { + d.Name("Object2"); + d.Field(t => t.FooList) + .Type>>>(); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + } - [Fact] - public void DoNotAllow_InputTypes_OnFields() - { - // arrange - // act - void Action() => SchemaBuilder.New() + [Fact] + public void DoNotAllow_InputTypes_OnFields() + { + // arrange + // act + void Action() => SchemaBuilder.New() + .AddType(new InputObjectType(t => t.Name("Foo") + .Field("bar") + .Type>>())) + .Create(); + + // assert + Assert.Throws(Action).Errors[0].Message.MatchSnapshot(); + } + + [Fact] + public void DoNotAllow_DynamicInputTypes_OnFields() + { + // arrange + // act + void Action() => + SchemaBuilder.New() .AddType(new InputObjectType(t => t.Name("Foo") .Field("bar") - .Type>>())) + .Type(new NonNullType(new ObjectType())))) .Create(); - // assert - Assert.Throws(Action).Errors[0].Message.MatchSnapshot(); - } - - [Fact] - public void DoNotAllow_DynamicInputTypes_OnFields() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddType(new InputObjectType(t => t.Name("Foo") - .Field("bar") - .Type(new NonNullType(new ObjectType())))) - .Create(); - - // assert - Exception? ex = Assert.Throws(Action).Errors.First().Exception; - Assert.Equal("inputType", Assert.IsType(ex).ParamName); - } - - [Fact] - public void Ignore_DescriptorIsNull_ArgumentNullException() - { - // arrange - // act - void Action() - => InputObjectTypeDescriptorExtensions.Ignore(null, t => t.Id); - - // assert - Assert.Throws(Action); - } + // assert + var ex = Assert.Throws(Action).Errors.First().Exception; + Assert.Equal("inputType", Assert.IsType(ex).ParamName); + } - [Fact] - public void Ignore_ExpressionIsNull_ArgumentNullException() - { - // arrange - var descriptor = - InputObjectTypeDescriptor.New( - DescriptorContext.Create()); + [Fact] + public void Ignore_DescriptorIsNull_ArgumentNullException() + { + // arrange + // act + void Action() + => InputObjectTypeDescriptorExtensions.Ignore(null, t => t.Id); - // act - void Action() => descriptor.Ignore(null); + // assert + Assert.Throws(Action); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void Ignore_ExpressionIsNull_ArgumentNullException() + { + // arrange + var descriptor = + InputObjectTypeDescriptor.New( + DescriptorContext.Create()); - [Fact] - public void Ignore_Id_Property() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new InputObjectType(d => d - .Ignore(t => t.Id))) - .Create(); + // act + void Action() => descriptor.Ignore(null); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void Unignore_Id_Property() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new InputObjectType(d => - { - d.Ignore(t => t.Id); - d.Field(t => t.Id).Ignore(false); - })) - .Create(); + [Fact] + public void Ignore_Id_Property() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new InputObjectType(d => d + .Ignore(t => t.Id))) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task Convert_Parts_Of_The_Input_Graph() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeConverter(from => new Bar { Text = from.Text }) - .AddTypeConverter(from => new Baz { Text = from.Text }) - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = executor.Execute( - "{ foo(a: { bar: { text: \"abc\" } }) }"); - - // assert - result.ToJson().MatchSnapshot(); - } + [Fact] + public void Unignore_Id_Property() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new InputObjectType(d => + { + d.Ignore(t => t.Id); + d.Field(t => t.Id).Ignore(false); + })) + .Create(); - [Fact] - public void Ignore_Fields_With_GraphQLIgnoreAttribute() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType>() - .Create(); + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public async Task Convert_Parts_Of_The_Input_Graph() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeConverter(from => new Bar { Text = from.Text }) + .AddTypeConverter(from => new Baz { Text = from.Text }) + .BuildRequestExecutorAsync(); + + // act + var result = executor.Execute( + "{ foo(a: { bar: { text: \"abc\" } }) }"); + + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task Input_With_Optionals_Not_Set() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public void Ignore_Fields_With_GraphQLIgnoreAttribute() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType>() + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + // assert + schema.ToString().MatchSnapshot(); + } - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ do(input: { baz: \"abc\" }) { isBarSet bar baz } }"); + [Fact] + public async Task Input_With_Optionals_Not_Set() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert - result.ToJson().MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [InlineData("null")] - [InlineData("\"abc\"")] - [Theory] - public async Task Input_With_Optionals_Set(string value) - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + // act + var result = await executor.ExecuteAsync( + "{ do(input: { baz: \"abc\" }) { isBarSet bar baz } }"); - IRequestExecutor executor = schema.MakeExecutable(); + // assert + result.ToJson().MatchSnapshot(); + } - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ do(input: { bar: " + value + " }) { isBarSet } }"); + [InlineData("null")] + [InlineData("\"abc\"")] + [Theory] + public async Task Input_With_Optionals_Set(string value) + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert - result.ToJson().MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [Fact] - public async Task Input_With_Immutable_ClrType() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + // act + var result = await executor.ExecuteAsync( + "{ do(input: { bar: " + value + " }) { isBarSet } }"); - IRequestExecutor executor = schema.MakeExecutable(); + // assert + result.ToJson().MatchSnapshot(); + } - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ do(input: { bar: \"abc\" baz: \"def\" qux: \"ghi\" }) { bar baz qux } }"); + [Fact] + public async Task Input_With_Immutable_ClrType() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert - result.ToJson().MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [Fact] - public void Input_Infer_Default_Values() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("abc") - .Argument("def", a => a.Type>()) - .Resolve("ghi")) - .Create(); + // act + var result = await executor.ExecuteAsync( + "{ do(input: { bar: \"abc\" baz: \"def\" qux: \"ghi\" }) { bar baz qux } }"); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task Input_IgnoreField() - { - // arrange - // act - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType() - .BuildSchemaAsync(); + [Fact] + public void Input_Infer_Default_Values() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("abc") + .Argument("def", a => a.Type>()) + .Resolve("ghi")) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + [Fact] + public async Task Input_IgnoreField() + { + // arrange + // act + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .BuildSchemaAsync(); - // assert - schema.ToString().MatchSnapshot(); - } - [Fact] - public void Specify_Argument_Type_With_SDL_Syntax() - { - SchemaBuilder.New() - .AddInputObjectType(d => - { - d.Name("Bar"); - d.Field("Foo").Type("String"); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .Print() - .MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - public class InputWithInterfaceType : InputObjectType - { - protected override void Configure( - IInputObjectTypeDescriptor descriptor) + [Fact] + public void Specify_Argument_Type_With_SDL_Syntax() + { + SchemaBuilder.New() + .AddInputObjectType(d => { - descriptor.Field(x => x.Works); - descriptor.Field(x => x.DoesNotWork).Ignore(); - } - } + d.Name("Bar"); + d.Field("Foo").Type("String"); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void InputObjectType_InInputObjectType_ThrowsSchemaException() + public class InputWithInterfaceType : InputObjectType + { + protected override void Configure( + IInputObjectTypeDescriptor descriptor) { - // arrange - // act - void Fail() - => SchemaBuilder - .New() - .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) - .AddType>>() - .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) - .Create(); - - // assert - Assert.Throws(Fail).Message.MatchSnapshot(); + descriptor.Field(x => x.Works); + descriptor.Field(x => x.DoesNotWork).Ignore(); } + } - [Fact] - public async Task Input_Casing_Is_Recognized() - { - // arrange - // act - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .BuildSchemaAsync(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void InputObjectType_InInputObjectType_ThrowsSchemaException() + { + // arrange + // act + void Fail() + => SchemaBuilder + .New() + .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) + .AddType>>() + .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) + .Create(); - [Fact] - public async Task AnnotationBased_DepreactedInputTypes_NullableFields_Valid() - { - // arrange - // act - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddInputObjectType() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) - .BuildSchemaAsync(); - - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(Fail).Message.MatchSnapshot(); + } - [Fact] - public async Task AnnotationBased_DepreactedInputTypes_NonNullableField_Invalid() - { - // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) - .AddInputObjectType() - .BuildSchemaAsync(); - - // assert - SchemaException exception = await Assert.ThrowsAsync(call); - exception.Errors.Single().ToString().MatchSnapshot(); - } + [Fact] + public async Task Input_Casing_Is_Recognized() + { + // arrange + // act + var schema = await new ServiceCollection() + .AddGraphQL() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .BuildSchemaAsync(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DepreactedInputTypes_NullableFields_Valid() - { - // arrange - // act - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) - .AddInputObjectType(x => x.Name("Foo").Field("bar").Type().Deprecated("b")) - .BuildSchemaAsync(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public async Task AnnotationBased_DepreactedInputTypes_NullableFields_Valid() + { + // arrange + // act + var schema = await new ServiceCollection() + .AddGraphQL() + .AddInputObjectType() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) + .BuildSchemaAsync(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DepreactedInputTypes_NonNullableField_Invalid() - { - // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) - .AddInputObjectType(x => x - .Name("Foo") - .Field("bar") - .Type>() - .Deprecated("b")) - .BuildSchemaAsync(); + [Fact] + public async Task AnnotationBased_DepreactedInputTypes_NonNullableField_Invalid() + { + // arrange + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) + .AddInputObjectType() + .BuildSchemaAsync(); + + // assert + var exception = await Assert.ThrowsAsync(call); + exception.Errors.Single().ToString().MatchSnapshot(); + } - // assert - SchemaException exception = await Assert.ThrowsAsync(call); - exception.Errors.Single().ToString().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_DepreactedInputTypes_NullableFields_Valid() + { + // arrange + // act + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) + .AddInputObjectType(x => x.Name("Foo").Field("bar").Type().Deprecated("b")) + .BuildSchemaAsync(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DepreactedInputTypes_NullableFields_Valid() - { - // arrange - // act - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) - .AddDocumentFromString(@" + [Fact] + public async Task CodeFirst_DepreactedInputTypes_NonNullableField_Invalid() + { + // arrange + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) + .AddInputObjectType(x => x + .Name("Foo") + .Field("bar") + .Type>() + .Deprecated("b")) + .BuildSchemaAsync(); + + // assert + var exception = await Assert.ThrowsAsync(call); + exception.Errors.Single().ToString().MatchSnapshot(); + } + + [Fact] + public async Task SchemaFirst_DepreactedInputTypes_NullableFields_Valid() + { + // arrange + // act + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) + .AddDocumentFromString(@" input Foo { bar: String @deprecated(reason: ""reason"") } ") - .BuildSchemaAsync(); + .BuildSchemaAsync(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DepreactedInputTypes_NonNullableField_Invalid() - { - // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) - .AddDocumentFromString(@" + [Fact] + public async Task SchemaFirst_DepreactedInputTypes_NonNullableField_Invalid() + { + // arrange + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("bar").Resolve("asd")) + .AddDocumentFromString(@" input Foo { bar: String! @deprecated(reason: ""reason"") } ") - .BuildSchemaAsync(); + .BuildSchemaAsync(); - // assert - SchemaException exception = await Assert.ThrowsAsync(call); - exception.Errors.Single().ToString().MatchSnapshot(); - } + // assert + var exception = await Assert.ThrowsAsync(call); + exception.Errors.Single().ToString().MatchSnapshot(); + } - [Fact] - public void OneOf_descriptor_is_null() - { - void Fail() => InputObjectTypeDescriptorExtensions.OneOf(null); + [Fact] + public void OneOf_descriptor_is_null() + { + void Fail() => InputObjectTypeDescriptorExtensions.OneOf(null); - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void OneOf_generic_descriptor_is_null() - { - void Fail() => InputObjectTypeDescriptorExtensions.OneOf(null); + [Fact] + public void OneOf_generic_descriptor_is_null() + { + void Fail() => InputObjectTypeDescriptorExtensions.OneOf(null); - Assert.Throws(Fail); - } + Assert.Throws(Fail); + } - [Fact] - public void Deprecate_fields_with_attribute() - { - SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Deprecate_fields_with_attribute() + { + SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .Print() + .MatchSnapshot(); + } - public class FieldNameInput - { - public string? YourFieldName { get; set; } + public class FieldNameInput + { + public string? YourFieldName { get; set; } - public string YourFieldname { get; set; } = default!; - } + public string YourFieldname { get; set; } = default!; + } - public class DeprecatedInputFields - { - [Obsolete("reason")] - public int? ObsoleteWithReason { get; set; } + public class DeprecatedInputFields + { + [Obsolete("reason")] + public int? ObsoleteWithReason { get; set; } - [Obsolete] - public int? Obsolete { get; set; } + [Obsolete] + public int? Obsolete { get; set; } - [GraphQLDeprecated("reason")] - public int? Deprecated { get; set; } - } + [GraphQLDeprecated("reason")] + public int? Deprecated { get; set; } + } - public class DeprecatedNonNull - { - [Obsolete("reason")] - public int ObsoleteWithReason { get; set; } - } + public class DeprecatedNonNull + { + [Obsolete("reason")] + public int ObsoleteWithReason { get; set; } + } - public class QueryWithInterfaceInput - { - public string? Test(InputWithInterface? input) => "Foo"; - } + public class QueryWithInterfaceInput + { + public string? Test(InputWithInterface? input) => "Foo"; + } - public class InputWithInterface - { - public string? Works { get; set; } - public IDoesNotWork? DoesNotWork { get; set; } - } + public class InputWithInterface + { + public string? Works { get; set; } + public IDoesNotWork? DoesNotWork { get; set; } + } - public interface IDoesNotWork - { - public double? Member { get; set; } - } + public interface IDoesNotWork + { + public double? Member { get; set; } + } - public class SimpleInput - { - public int Id { get; set; } - public string? Name { get; set; } - } + public class SimpleInput + { + public int Id { get; set; } + public string? Name { get; set; } + } - public class SerializationInputObject1 - { - public SerializationInputObject2? Foo { get; set; } - public string? Bar { get; set; } = "Bar"; - } + public class SerializationInputObject1 + { + public SerializationInputObject2? Foo { get; set; } + public string? Bar { get; set; } = "Bar"; + } - public class SerializationInputObject2 - { - public List? FooList { get; set; } = - new() { new SerializationInputObject1() }; - } + public class SerializationInputObject2 + { + public List? FooList { get; set; } = + new() { new SerializationInputObject1() }; + } - public class FooDirectiveType : DirectiveType + public class FooDirectiveType : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor - .Name("foo") - .Location(DirectiveLocation.InputObject) - .Location(DirectiveLocation.InputFieldDefinition); - } + descriptor + .Name("foo") + .Location(DirectiveLocation.InputObject) + .Location(DirectiveLocation.InputFieldDefinition); } + } - public class FooDirective { } + public class FooDirective { } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Name("Query") - .Field("foo") - .Argument("a", a => a.Type()) - .Type() - .Resolve(ctx => ctx.ArgumentValue("a").Bar?.Text); - } + descriptor + .Name("Query") + .Field("foo") + .Argument("a", a => a.Type()) + .Type() + .Resolve(ctx => ctx.ArgumentValue("a").Bar?.Text); } + } - public class FooInputType : InputObjectType + public class FooInputType : InputObjectType + { + protected override void Configure( + IInputObjectTypeDescriptor descriptor) { - protected override void Configure( - IInputObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Bar).Type(); - } + descriptor.Field(t => t.Bar).Type(); } + } - public class BazInputType : InputObjectType - { - } + public class BazInputType : InputObjectType + { + } - public class Foo - { - public Bar? Bar { get; set; } - } + public class Foo + { + public Bar? Bar { get; set; } + } - public class FooIgnored - { - [GraphQLIgnore] - public Bar? Bar { get; set; } + public class FooIgnored + { + [GraphQLIgnore] + public Bar? Bar { get; set; } - public Bar? Baz { get; set; } - } + public Bar? Baz { get; set; } + } - public class Bar - { - public string? Text { get; set; } - } + public class Bar + { + public string? Text { get; set; } + } - public class Baz - { - public string? Text { get; set; } - } + public class Baz + { + public string? Text { get; set; } + } - public class QueryWithOptionals + public class QueryWithOptionals + { + public FooPayload Do(FooInput input) { - public FooPayload Do(FooInput input) + return new FooPayload { - return new FooPayload - { - IsBarSet = input.Bar.HasValue, - Bar = input.Bar, - Baz = input.Baz - }; - } + IsBarSet = input.Bar.HasValue, + Bar = input.Bar, + Baz = input.Baz + }; } + } - public class FooInput - { - public Optional Bar { get; set; } - public string? Baz { get; set; } - } + public class FooInput + { + public Optional Bar { get; set; } + public string? Baz { get; set; } + } - public class FooPayload + public class FooPayload + { + public bool IsBarSet { get; set; } + public string? Bar { get; set; } + public string? Baz { get; set; } + } + + public class QueryWithImmutables + { + public FooImmutable? Do(FooImmutable? input) { - public bool IsBarSet { get; set; } - public string? Bar { get; set; } - public string? Baz { get; set; } + return input; } + } - public class QueryWithImmutables + public class FooImmutable + { + public FooImmutable() { - public FooImmutable? Do(FooImmutable? input) - { - return input; - } + Bar = "default"; } - public class FooImmutable + public FooImmutable(string? bar, string? baz) { - public FooImmutable() - { - Bar = "default"; - } - - public FooImmutable(string? bar, string? baz) - { - Bar = bar; - Baz = baz; - } + Bar = bar; + Baz = baz; + } - public string? Bar { get; } + public string? Bar { get; } - public string? Baz { get; set; } + public string? Baz { get; set; } - public string? Qux { get; private set; } - } + public string? Qux { get; private set; } + } - public class InputWithDefault - { - [DefaultValue("abc")] - public string? WithStringDefault { get; set; } + public class InputWithDefault + { + [DefaultValue("abc")] + public string? WithStringDefault { get; set; } - [DefaultValue(null)] - public string? WithNullDefault { get; set; } + [DefaultValue(null)] + public string? WithNullDefault { get; set; } - [DefaultValue(FooEnum.Bar)] - public FooEnum Enum { get; set; } + [DefaultValue(FooEnum.Bar)] + public FooEnum Enum { get; set; } - public string? WithoutDefault { get; set; } - } + public string? WithoutDefault { get; set; } + } - public class InputWithDeprecatedField - { - [Obsolete] - public string? A { get; set; } + public class InputWithDeprecatedField + { + [Obsolete] + public string? A { get; set; } - [GraphQLDeprecated("Foo Bar")] - public string? B { get; set; } - } + [GraphQLDeprecated("Foo Bar")] + public string? B { get; set; } + } - public enum FooEnum - { - Bar, - Baz - } + public enum FooEnum + { + Bar, + Baz } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputParserTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputParserTests.cs index 2edea41eded..32b1bb3d7c6 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputParserTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputParserTests.cs @@ -11,500 +11,499 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputParserTests { - public class InputParserTests + [Fact] + public void Deserialize_InputObject_AllIsSet() { - [Fact] - public void Deserialize_InputObject_AllIsSet() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - InputObjectType type = schema.GetType("TestInput"); + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - var fieldData = new Dictionary - { - { "field1", "abc" }, - { "field2", 123 } - }; - - // act - var parser = new InputParser(new DefaultTypeConverter()); - var runtimeValue = parser.ParseResult(fieldData, type, Path.Root); - - // assert - Assert.IsType(runtimeValue).MatchSnapshot(); - } + var type = schema.GetType("TestInput"); - [Fact] - public void Parse_InputObject_AllIsSet() + var fieldData = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + { "field1", "abc" }, + { "field2", 123 } + }; - InputObjectType type = schema.GetType("TestInput"); + // act + var parser = new InputParser(new DefaultTypeConverter()); + var runtimeValue = parser.ParseResult(fieldData, type, Path.Root); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("field1", "abc"), - new ObjectFieldNode("field2", 123)); + // assert + Assert.IsType(runtimeValue).MatchSnapshot(); + } - // act - var parser = new InputParser(new DefaultTypeConverter()); - var runtimeValue = parser.ParseLiteral(fieldData, type, Path.Root); + [Fact] + public void Parse_InputObject_AllIsSet() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.IsType(runtimeValue).MatchSnapshot(); - } + var type = schema.GetType("TestInput"); - [Fact] - public void Deserialize_InputObject_AllIsSet_ConstructorInit() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + var fieldData = new ObjectValueNode( + new ObjectFieldNode("field1", "abc"), + new ObjectFieldNode("field2", 123)); - InputObjectType type = schema.GetType("Test2Input"); + // act + var parser = new InputParser(new DefaultTypeConverter()); + var runtimeValue = parser.ParseLiteral(fieldData, type, Path.Root); - var fieldData = new Dictionary - { - { "field1", "abc" }, - { "field2", 123 } - }; + // assert + Assert.IsType(runtimeValue).MatchSnapshot(); + } - // act - var parser = new InputParser(new DefaultTypeConverter()); - var runtimeValue = parser.ParseResult(fieldData, type, Path.Root); + [Fact] + public void Deserialize_InputObject_AllIsSet_ConstructorInit() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.IsType(runtimeValue).MatchSnapshot(); - } + var type = schema.GetType("Test2Input"); - [Fact] - public void Parse_InputObject_AllIsSet_ConstructorInit() + var fieldData = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + { "field1", "abc" }, + { "field2", 123 } + }; - InputObjectType type = schema.GetType("Test2Input"); + // act + var parser = new InputParser(new DefaultTypeConverter()); + var runtimeValue = parser.ParseResult(fieldData, type, Path.Root); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("field1", "abc"), - new ObjectFieldNode("field2", 123)); + // assert + Assert.IsType(runtimeValue).MatchSnapshot(); + } - // act - var parser = new InputParser(new DefaultTypeConverter()); - var runtimeValue = parser.ParseLiteral(fieldData, type, Path.Root); + [Fact] + public void Parse_InputObject_AllIsSet_ConstructorInit() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.IsType(runtimeValue).MatchSnapshot(); - } + var type = schema.GetType("Test2Input"); - [Fact] - public void Deserialize_InputObject_AllIsSet_MissingRequired() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + var fieldData = new ObjectValueNode( + new ObjectFieldNode("field1", "abc"), + new ObjectFieldNode("field2", 123)); - InputObjectType type = schema.GetType("Test2Input"); + // act + var parser = new InputParser(new DefaultTypeConverter()); + var runtimeValue = parser.ParseLiteral(fieldData, type, Path.Root); - var fieldData = new Dictionary - { - { "field2", 123 } - }; + // assert + Assert.IsType(runtimeValue).MatchSnapshot(); + } - // act - var parser = new InputParser(new DefaultTypeConverter()); - void Action() => parser.ParseResult(fieldData, type, Path.Root); + [Fact] + public void Deserialize_InputObject_AllIsSet_MissingRequired() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Throws(Action).MatchSnapshot(); - } + var type = schema.GetType("Test2Input"); - [Fact] - public void Parse_InputObject_AllIsSet_MissingRequired() + var fieldData = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + { "field2", 123 } + }; - InputObjectType type = schema.GetType("Test2Input"); + // act + var parser = new InputParser(new DefaultTypeConverter()); + void Action() => parser.ParseResult(fieldData, type, Path.Root); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("field2", 123)); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - // act - var parser = new InputParser(new DefaultTypeConverter()); - void Action() => parser.ParseLiteral(fieldData, type, Path.Root); + [Fact] + public void Parse_InputObject_AllIsSet_MissingRequired() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Throws(Action).MatchSnapshot(); - } + var type = schema.GetType("Test2Input"); - [Fact] - public void Deserialize_InputObject_AllIsSet_OneInvalidField() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - InputObjectType type = schema.GetType("TestInput"); + var fieldData = new ObjectValueNode( + new ObjectFieldNode("field2", 123)); - var fieldData = new Dictionary - { - { "field2", 123 }, - { "field3", 123 } - }; + // act + var parser = new InputParser(new DefaultTypeConverter()); + void Action() => parser.ParseLiteral(fieldData, type, Path.Root); - // act - var parser = new InputParser(new DefaultTypeConverter()); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - void Action() - => parser.ParseResult(fieldData, type, PathFactory.Instance.New("root")); + [Fact] + public void Deserialize_InputObject_AllIsSet_OneInvalidField() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Throws(Action).MatchSnapshot(); - } + var type = schema.GetType("TestInput"); - [Fact] - public void Parse_InputObject_AllIsSet_OneInvalidField() + var fieldData = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + { "field2", 123 }, + { "field3", 123 } + }; - InputObjectType type = schema.GetType("TestInput"); + // act + var parser = new InputParser(new DefaultTypeConverter()); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("field2", 123), - new ObjectFieldNode("field3", 123)); + void Action() + => parser.ParseResult(fieldData, type, PathFactory.Instance.New("root")); - // act - var parser = new InputParser(new DefaultTypeConverter()); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - void Action() - => parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); + [Fact] + public void Parse_InputObject_AllIsSet_OneInvalidField() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Throws(Action).MatchSnapshot(); - } + var type = schema.GetType("TestInput"); - [Fact] - public void Deserialize_InputObject_AllIsSet_TwoInvalidFields() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + var fieldData = new ObjectValueNode( + new ObjectFieldNode("field2", 123), + new ObjectFieldNode("field3", 123)); - InputObjectType type = schema.GetType("TestInput"); + // act + var parser = new InputParser(new DefaultTypeConverter()); - var fieldData = new Dictionary - { - { "field2", 123 }, - { "field3", 123 }, - { "field4", 123 } - }; + void Action() + => parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); - // act - var parser = new InputParser(new DefaultTypeConverter()); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - void Action() - => parser.ParseResult(fieldData, type, PathFactory.Instance.New("root")); + [Fact] + public void Deserialize_InputObject_AllIsSet_TwoInvalidFields() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Throws(Action).MatchSnapshot(); - } + var type = schema.GetType("TestInput"); - [Fact] - public void Parse_InputObject_AllIsSet_TwoInvalidFields() + var fieldData = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + { "field2", 123 }, + { "field3", 123 }, + { "field4", 123 } + }; - InputObjectType type = schema.GetType("TestInput"); + // act + var parser = new InputParser(new DefaultTypeConverter()); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("field2", 123), - new ObjectFieldNode("field3", 123), - new ObjectFieldNode("field4", 123)); + void Action() + => parser.ParseResult(fieldData, type, PathFactory.Instance.New("root")); - // act - var parser = new InputParser(new DefaultTypeConverter()); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - void Action() - => parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); + [Fact] + public void Parse_InputObject_AllIsSet_TwoInvalidFields() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Throws(Action).MatchSnapshot(); - } + var type = schema.GetType("TestInput"); - [Fact] - public void Parse_InputObject_WithDefault_Values() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + var fieldData = new ObjectValueNode( + new ObjectFieldNode("field2", 123), + new ObjectFieldNode("field3", 123), + new ObjectFieldNode("field4", 123)); - InputObjectType type = schema.GetType("Test3Input"); + // act + var parser = new InputParser(new DefaultTypeConverter()); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("field2", 123)); + void Action() + => parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); - // act - var parser = new InputParser(); - var obj = parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - // assert - Assert.Equal("DefaultAbc", Assert.IsType(obj).Field1); - } + [Fact] + public void Parse_InputObject_WithDefault_Values() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public void Parse_InputObject_NonNullViolation() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + var type = schema.GetType("Test3Input"); - var type = new NonNullType(schema.GetType("Test3Input")); + var fieldData = new ObjectValueNode( + new ObjectFieldNode("field2", 123)); - // act - var parser = new InputParser(); + // act + var parser = new InputParser(); + var obj = parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); - void Action() - => parser.ParseLiteral( - NullValueNode.Default, - type, - PathFactory.Instance.New("root")); + // assert + Assert.Equal("DefaultAbc", Assert.IsType(obj).Field1); + } - // assert - Assert.Throws(Action).MatchSnapshot(); - } + [Fact] + public void Parse_InputObject_NonNullViolation() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public void Parse_InputObject_NullableEnumList() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddInputObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + var type = new NonNullType(schema.GetType("Test3Input")); - var type = new NonNullType(schema.GetType("FooInput")); + // act + var parser = new InputParser(); - var listData = new ListValueNode( + void Action() + => parser.ParseLiteral( NullValueNode.Default, - new EnumValueNode("BAZ")); + type, + PathFactory.Instance.New("root")); - var fieldData = new ObjectValueNode( - new ObjectFieldNode("bars", listData)); - - // act - var parser = new InputParser(); - var runtimeData = - parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); + // assert + Assert.Throws(Action).MatchSnapshot(); + } - // assert - Assert.Collection( - Assert.IsType(runtimeData).Bars, - t => Assert.Null(t), - t => Assert.Equal(Bar.Baz, t)); - } + [Fact] + public void Parse_InputObject_NullableEnumList() + { + // arrange + var schema = SchemaBuilder.New() + .AddInputObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + var type = new NonNullType(schema.GetType("FooInput")); + + var listData = new ListValueNode( + NullValueNode.Default, + new EnumValueNode("BAZ")); + + var fieldData = new ObjectValueNode( + new ObjectFieldNode("bars", listData)); + + // act + var parser = new InputParser(); + var runtimeData = + parser.ParseLiteral(fieldData, type, PathFactory.Instance.New("root")); + + // assert + Assert.Collection( + Assert.IsType(runtimeData).Bars, + t => Assert.Null(t), + t => Assert.Equal(Bar.Baz, t)); + } - [Fact] - public async Task Integration_InputObjectDefaultValue_ValueIsInitialized() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IReadOnlyQueryRequest query = QueryRequestBuilder.Create(@" + [Fact] + public async Task Integration_InputObjectDefaultValue_ValueIsInitialized() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var query = QueryRequestBuilder.Create(@" { loopback(input: {field2: 1}) { field1 field2 } }"); - IExecutionResult result = await executor.ExecuteAsync(query, CancellationToken.None); + var result = await executor.ExecuteAsync(query, CancellationToken.None); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public void OneOf_A_and_B_Are_Set() - { - // arrange - ISchema schema = - SchemaBuilder.New() - .AddInputObjectType() - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void OneOf_A_and_B_Are_Set() + { + // arrange + var schema = + SchemaBuilder.New() + .AddInputObjectType() + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - InputObjectType oneOfInput = schema.GetType(nameof(OneOfInput)); + var oneOfInput = schema.GetType(nameof(OneOfInput)); - var parser = new InputParser(); + var parser = new InputParser(); - var data = new ObjectValueNode( - new ObjectFieldNode("a", "abc"), - new ObjectFieldNode("b", 123)); + var data = new ObjectValueNode( + new ObjectFieldNode("a", "abc"), + new ObjectFieldNode("b", 123)); - // act - void Fail() - => parser.ParseLiteral(data, oneOfInput, PathFactory.Instance.New("root")); + // act + void Fail() + => parser.ParseLiteral(data, oneOfInput, PathFactory.Instance.New("root")); - // assert - Assert.Throws(Fail).Errors.MatchSnapshot(); - } + // assert + Assert.Throws(Fail).Errors.MatchSnapshot(); + } - [Fact] - public void OneOf_A_is_Null_and_B_has_Value() - { - // arrange - ISchema schema = - SchemaBuilder.New() - .AddInputObjectType() - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void OneOf_A_is_Null_and_B_has_Value() + { + // arrange + var schema = + SchemaBuilder.New() + .AddInputObjectType() + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - InputObjectType oneOfInput = schema.GetType(nameof(OneOfInput)); + var oneOfInput = schema.GetType(nameof(OneOfInput)); - var parser = new InputParser(); + var parser = new InputParser(); - var data = new ObjectValueNode( - new ObjectFieldNode("a", NullValueNode.Default), - new ObjectFieldNode("b", 123)); + var data = new ObjectValueNode( + new ObjectFieldNode("a", NullValueNode.Default), + new ObjectFieldNode("b", 123)); - // act - void Fail() - => parser.ParseLiteral(data, oneOfInput, PathFactory.Instance.New("root")); + // act + void Fail() + => parser.ParseLiteral(data, oneOfInput, PathFactory.Instance.New("root")); - // assert - Assert.Throws(Fail).Errors.MatchSnapshot(); - } + // assert + Assert.Throws(Fail).Errors.MatchSnapshot(); + } - [Fact] - public void OneOf_only_B_has_Value() - { - // arrange - ISchema schema = - SchemaBuilder.New() - .AddInputObjectType() - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void OneOf_only_B_has_Value() + { + // arrange + var schema = + SchemaBuilder.New() + .AddInputObjectType() + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - InputObjectType oneOfInput = schema.GetType(nameof(OneOfInput)); + var oneOfInput = schema.GetType(nameof(OneOfInput)); - var parser = new InputParser(); + var parser = new InputParser(); - var data = new ObjectValueNode( - new ObjectFieldNode("b", 123)); + var data = new ObjectValueNode( + new ObjectFieldNode("b", 123)); - // act - var runtimeValue = - parser.ParseLiteral(data, oneOfInput, PathFactory.Instance.New("root")); + // act + var runtimeValue = + parser.ParseLiteral(data, oneOfInput, PathFactory.Instance.New("root")); - // assert - runtimeValue.MatchSnapshot(); - } + // assert + runtimeValue.MatchSnapshot(); + } - public class TestInput - { - public string? Field1 { get; set; } + public class TestInput + { + public string? Field1 { get; set; } - public int? Field2 { get; set; } - } + public int? Field2 { get; set; } + } - public class Test2Input + public class Test2Input + { + public Test2Input(string field1) { - public Test2Input(string field1) - { - Field1 = field1; - } + Field1 = field1; + } - public string Field1 { get; } + public string Field1 { get; } - public int? Field2 { get; set; } - } + public int? Field2 { get; set; } + } - public class Test3Input + public class Test3Input + { + public Test3Input(string field1) { - public Test3Input(string field1) - { - Field1 = field1; - } + Field1 = field1; + } - [DefaultValue("DefaultAbc")] - public string Field1 { get; } + [DefaultValue("DefaultAbc")] + public string Field1 { get; } - public int? Field2 { get; set; } - } + public int? Field2 { get; set; } + } - public class FooInput - { - public List Bars { get; set; } = new(); - } + public class FooInput + { + public List Bars { get; set; } = new(); + } - public class Query4 - { - public Test4 Loopback(Test4 input) => input; - } + public class Query4 + { + public Test4 Loopback(Test4 input) => input; + } - public class Test4 - { - [DefaultValue("DefaultAbc")] - public string? Field1 { get; set; } + public class Test4 + { + [DefaultValue("DefaultAbc")] + public string? Field1 { get; set; } - public int? Field2 { get; set; } - } + public int? Field2 { get; set; } + } - public enum Bar - { - Baz - } + public enum Bar + { + Baz + } - [OneOf] - public class OneOfInput - { - public string? A { get; set; } + [OneOf] + public class OneOfInput + { + public string? A { get; set; } - public int? B { get; set; } + public int? B { get; set; } - public string? C { get; set; } - } + public string? C { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InputValueFormatterTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InputValueFormatterTests.cs index a4c06f2ebba..65909703dac 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InputValueFormatterTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InputValueFormatterTests.cs @@ -4,137 +4,136 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InputValueFormatterTests { - public class InputValueFormatterTests + [Fact] + public async Task Add_Input_Formatter_To_Argument() { - [Fact] - public async Task Add_Input_Formatter_To_Argument() - { - Snapshot.FullName(); - - await SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .ExecuteAsync("{ one(arg: \"abc\") }") - .MatchSnapshotAsync(); - } + Snapshot.FullName(); + + await SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .ExecuteAsync("{ one(arg: \"abc\") }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Add_Chained_Input_Formatter_To_Argument() - { - Snapshot.FullName(); - - await SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .ExecuteAsync("{ two(arg: \"abc\") }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Add_Chained_Input_Formatter_To_Argument() + { + Snapshot.FullName(); + + await SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .ExecuteAsync("{ two(arg: \"abc\") }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Add_Input_Formatter_To_Field() - { - Snapshot.FullName(); - - await SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .ExecuteAsync("{ one_input(arg: { bar: \"abc\" }) }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Add_Input_Formatter_To_Field() + { + Snapshot.FullName(); + + await SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .ExecuteAsync("{ one_input(arg: { bar: \"abc\" }) }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Add_Chained_Input_Formatter_To_Field() - { - Snapshot.FullName(); - - await SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .ExecuteAsync("{ two_input(arg: { baz: \"abc\" }) }") - .MatchSnapshotAsync(); - } + [Fact] + public async Task Add_Chained_Input_Formatter_To_Field() + { + Snapshot.FullName(); + + await SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .ExecuteAsync("{ two_input(arg: { baz: \"abc\" }) }") + .MatchSnapshotAsync(); + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - - descriptor.Field("one") - .Argument("arg", a => a.Type() - .Extend() - .OnBeforeCreate(d => d.Formatters.Add(new UpperCaseInputValueFormatter()))) - .Type() - .Resolve(c => c.ArgumentValue("arg")); - - descriptor.Field("two") - .Argument("arg", a => a.Type() - .Extend() - .OnBeforeCreate(d => - { - d.Formatters.Add(new UpperCaseInputValueFormatter()); - d.Formatters.Add(new AddTwoInputValueFormatter()); - })) - .Type() - .Resolve(c => c.ArgumentValue("arg")); - - descriptor.Field("one_input") - .Argument("arg", a => a.Type()) - .Type() - .Resolve(c => c.ArgumentValue("arg").Bar); - - descriptor.Field("two_input") - .Argument("arg", a => a.Type()) - .Type() - .Resolve(c => c.ArgumentValue("arg").Baz); - } - } + descriptor.Name("Query"); - public class FooInputType : InputObjectType - { - protected override void Configure(IInputObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Bar) + descriptor.Field("one") + .Argument("arg", a => a.Type() .Extend() - .OnBeforeCreate(d => d.Formatters.Add(new UpperCaseInputValueFormatter())); + .OnBeforeCreate(d => d.Formatters.Add(new UpperCaseInputValueFormatter()))) + .Type() + .Resolve(c => c.ArgumentValue("arg")); - descriptor.Field(t => t.Baz) + descriptor.Field("two") + .Argument("arg", a => a.Type() .Extend() .OnBeforeCreate(d => { d.Formatters.Add(new UpperCaseInputValueFormatter()); d.Formatters.Add(new AddTwoInputValueFormatter()); - }); - } + })) + .Type() + .Resolve(c => c.ArgumentValue("arg")); + + descriptor.Field("one_input") + .Argument("arg", a => a.Type()) + .Type() + .Resolve(c => c.ArgumentValue("arg").Bar); + + descriptor.Field("two_input") + .Argument("arg", a => a.Type()) + .Type() + .Resolve(c => c.ArgumentValue("arg").Baz); } + } - public class Foo + public class FooInputType : InputObjectType + { + protected override void Configure(IInputObjectTypeDescriptor descriptor) { - public string Bar { get; set; } - - public string Baz { get; set; } + descriptor.Field(t => t.Bar) + .Extend() + .OnBeforeCreate(d => d.Formatters.Add(new UpperCaseInputValueFormatter())); + + descriptor.Field(t => t.Baz) + .Extend() + .OnBeforeCreate(d => + { + d.Formatters.Add(new UpperCaseInputValueFormatter()); + d.Formatters.Add(new AddTwoInputValueFormatter()); + }); } + } - public class UpperCaseInputValueFormatter : IInputValueFormatter + public class Foo + { + public string Bar { get; set; } + + public string Baz { get; set; } + } + + public class UpperCaseInputValueFormatter : IInputValueFormatter + { + public object OnAfterDeserialize(object runtimeValue) { - public object OnAfterDeserialize(object runtimeValue) - { - return runtimeValue is string s ? s.ToUpperInvariant() : runtimeValue; - } + return runtimeValue is string s ? s.ToUpperInvariant() : runtimeValue; } + } - public class AddTwoInputValueFormatter : IInputValueFormatter + public class AddTwoInputValueFormatter : IInputValueFormatter + { + public object OnAfterDeserialize(object runtimeValue) { - public object OnAfterDeserialize(object runtimeValue) - { - return runtimeValue is string s ? s + "2" : runtimeValue; - } + return runtimeValue is string s ? s + "2" : runtimeValue; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeAttributeTests.cs index 8f50838cb2c..1d320e3696a 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeAttributeTests.cs @@ -5,160 +5,159 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InterfaceTypeAttributeTests + : TypeTestBase { - public class InterfaceTypeAttributeTests - : TypeTestBase + [Fact] + public void ArgumentDescriptorAttribute_Changes_DefaultValue() { - [Fact] - public void ArgumentDescriptorAttribute_Changes_DefaultValue() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.Equal( - "abc", - schema.GetType("Interface1") - .Fields["field"] - .Arguments["argument"] - .DefaultValue! - .Value); - } + // act + var schema = SchemaBuilder.New() + .AddInterfaceType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.Equal( + "abc", + schema.GetType("Interface1") + .Fields["field"] + .Arguments["argument"] + .DefaultValue! + .Value); + } - [Fact] - public void InterfaceFieldDescriptorAttribute_Adds_ContextData() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.Equal( - "def", - schema.GetType("Interface2") - .Fields["field"] - .ContextData["abc"]); - } + [Fact] + public void InterfaceFieldDescriptorAttribute_Adds_ContextData() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.Equal( + "def", + schema.GetType("Interface2") + .Fields["field"] + .ContextData["abc"]); + } - [Fact] - public void InterfaceFieldDescriptorAttribute_Updated_FieldDefinition() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType(d => - d.Field(t => t.GetField()).Name("foo")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.Equal( - "def", - schema.GetType("Interface2") - .Fields["foo"] - .ContextData["abc"]); - } + [Fact] + public void InterfaceFieldDescriptorAttribute_Updated_FieldDefinition() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType(d => + d.Field(t => t.GetField()).Name("foo")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.Equal( + "def", + schema.GetType("Interface2") + .Fields["foo"] + .ContextData["abc"]); + } - [Fact] - public void InterfaceTypeDescriptorAttribute_Add_FieldDefinition() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.True( - schema.GetType("Interface3") - .Fields.ContainsField("abc")); - } + [Fact] + public void InterfaceTypeDescriptorAttribute_Add_FieldDefinition() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.True( + schema.GetType("Interface3") + .Fields.ContainsField("abc")); + } - [Fact] - public void Annotated_Class_With_InterfaceTypeAttribute() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.True( - schema.GetType("Foo") - .Fields.ContainsField("bar")); - } + [Fact] + public void Annotated_Class_With_InterfaceTypeAttribute() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.True( + schema.GetType("Foo") + .Fields.ContainsField("bar")); + } - public interface Interface1 - { - string GetField([ArgumentDefaultValue("abc")]string argument); - } + public interface Interface1 + { + string GetField([ArgumentDefaultValue("abc")]string argument); + } - public class ArgumentDefaultValueAttribute - : ArgumentDescriptorAttribute + public class ArgumentDefaultValueAttribute + : ArgumentDescriptorAttribute + { + public ArgumentDefaultValueAttribute(object defaultValue) { - public ArgumentDefaultValueAttribute(object defaultValue) - { - DefaultValue = defaultValue; - } - - public object DefaultValue { get; } - - public override void OnConfigure( - IDescriptorContext context, - IArgumentDescriptor descriptor, - ParameterInfo parameter) - { - descriptor.DefaultValue(DefaultValue); - } + DefaultValue = defaultValue; } - public interface Interface2 - { - [PropertyAddContextData] - string GetField(); - } + public object DefaultValue { get; } - public class PropertyAddContextDataAttribute - : InterfaceFieldDescriptorAttribute + public override void OnConfigure( + IDescriptorContext context, + IArgumentDescriptor descriptor, + ParameterInfo parameter) { - public override void OnConfigure( - IDescriptorContext context, - IInterfaceFieldDescriptor descriptor, - MemberInfo member) - { - descriptor.Extend().OnBeforeCompletion( - (c, d) => d.ContextData.Add("abc", "def")); - } + descriptor.DefaultValue(DefaultValue); } + } - [InterfaceAddField] - public interface Interface3 - { - string GetField(); - } + public interface Interface2 + { + [PropertyAddContextData] + string GetField(); + } - public class InterfaceAddFieldAttribute - : InterfaceTypeDescriptorAttribute + public class PropertyAddContextDataAttribute + : InterfaceFieldDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IInterfaceFieldDescriptor descriptor, + MemberInfo member) { - public override void OnConfigure( - IDescriptorContext context, - IInterfaceTypeDescriptor descriptor, - Type type) - { - descriptor.Field("abc").Type(); - } + descriptor.Extend().OnBeforeCompletion( + (c, d) => d.ContextData.Add("abc", "def")); } + } + + [InterfaceAddField] + public interface Interface3 + { + string GetField(); + } - [InterfaceType(Name = "Foo")] - public class Object1 + public class InterfaceAddFieldAttribute + : InterfaceTypeDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IInterfaceTypeDescriptor descriptor, + Type type) { - public string? Bar { get; set; } + descriptor.Field("abc").Type(); } } + + [InterfaceType(Name = "Foo")] + public class Object1 + { + public string? Bar { get; set; } + } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeExtensionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeExtensionTests.cs index e1d214a9749..a252d144746 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeExtensionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeExtensionTests.cs @@ -6,535 +6,534 @@ using HotChocolate.Language; using HotChocolate.Resolvers; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InterfaceTypeExtensionTests { - public class InterfaceTypeExtensionTests + [Fact] + public void InterfaceTypeExtension_AddField() { - [Fact] - public void InterfaceTypeExtension_AddField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields.ContainsField("test")); - } - - [Obsolete] - [Fact] - public void InterfaceTypeExtension_DepricateField() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .DeprecationReason("Foo"))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"].IsDeprecated); - Assert.Equal("Foo", type.Fields["description"].DeprecationReason); - } - - [Fact] - public void InterfaceTypeExtension_Deprecate_With_Reason() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .Deprecated("Foo"))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"].IsDeprecated); - Assert.Equal("Foo", type.Fields["description"].DeprecationReason); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields.ContainsField("test")); + } - [Fact] - public void InterfaceTypeExtension_Deprecate_Without_Reason() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .Deprecated())) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"].IsDeprecated); - Assert.Equal( - WellKnownDirectives.DeprecationDefaultReason, - type.Fields["description"].DeprecationReason); - } + [Obsolete] + [Fact] + public void InterfaceTypeExtension_DepricateField() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .DeprecationReason("Foo"))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"].IsDeprecated); + Assert.Equal("Foo", type.Fields["description"].DeprecationReason); + } - [Fact] - public void InterfaceTypeExtension_Deprecated_Directive_Is_Serialized() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .Deprecated())) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void InterfaceTypeExtension_Deprecate_With_Reason() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Deprecated("Foo"))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"].IsDeprecated); + Assert.Equal("Foo", type.Fields["description"].DeprecationReason); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void InterfaceTypeExtension_Deprecate_Without_Reason() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Deprecated())) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"].IsDeprecated); + Assert.Equal( + WellKnownDirectives.DeprecationDefaultReason, + type.Fields["description"].DeprecationReason); + } - [Fact] - public void InterfaceTypeExtension_SetTypeContextData() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + [Fact] + public void InterfaceTypeExtension_Deprecated_Directive_Is_Serialized() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Deprecated())) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.ContextData.ContainsKey("foo")); - } + [Fact] + public void InterfaceTypeExtension_SetTypeContextData() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.ContextData.ContainsKey("foo")); + } - [Fact] - public void InterfaceTypeExtension_SetFieldContextData() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"] - .ContextData.ContainsKey("foo")); - } + [Fact] + public void InterfaceTypeExtension_SetFieldContextData() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"] + .ContextData.ContainsKey("foo")); + } - [Fact] - public void InterfaceTypeExtension_SetArgumentContextData() - { - // arrange - FieldResolverDelegate resolver = - ctx => new ValueTask(null); - - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("name") + [Fact] + public void InterfaceTypeExtension_SetArgumentContextData() + { + // arrange + FieldResolverDelegate resolver = + ctx => new ValueTask(null); + + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("name") + .Type() + .Argument("a", a => a .Type() - .Argument("a", a => a - .Type() - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar")))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"].Arguments["a"] - .ContextData.ContainsKey("foo")); - } + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar")))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"].Arguments["a"] + .ContextData.ContainsKey("foo")); + } - [Fact] - public void InterfaceTypeExtension_SetDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Directive("dummy"))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Directives.Contains("dummy")); - } + [Fact] + public void InterfaceTypeExtension_SetDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Directive("dummy"))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Directives.Contains("dummy")); + } - [Fact] - public void InterfaceTypeExtension_SetDirectiveOnField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("name") - .Directive("dummy"))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"] - .Directives.Contains("dummy")); - } + [Fact] + public void InterfaceTypeExtension_SetDirectiveOnField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("name") + .Directive("dummy"))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"] + .Directives.Contains("dummy")); + } - [Fact] - public void InterfaceTypeExtension_SetDirectiveOnArgument() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => a.Directive("dummy")))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"].Arguments["a"] - .Directives.Contains("dummy")); - } + [Fact] + public void InterfaceTypeExtension_SetDirectiveOnArgument() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => a.Directive("dummy")))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"].Arguments["a"] + .Directives.Contains("dummy")); + } - [Fact] - public void InterfaceTypeExtension_ReplaceDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Directive("dummy_arg", new ArgumentNode("a", "a")))) - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Directive("dummy_arg", new ArgumentNode("a", "b")))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - string value = type.Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public void InterfaceTypeExtension_ReplaceDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Directive("dummy_arg", new ArgumentNode("a", "a")))) + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Directive("dummy_arg", new ArgumentNode("a", "b")))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var value = type.Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void InterfaceTypeExtension_ReplaceDirectiveOnField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Field(f => f.Description) - .Directive("dummy_arg", new ArgumentNode("a", "a")))) - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Directive("dummy_arg", new ArgumentNode("a", "b")))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - string value = type.Fields["description"].Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public void InterfaceTypeExtension_ReplaceDirectiveOnField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Field(f => f.Description) + .Directive("dummy_arg", new ArgumentNode("a", "a")))) + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Directive("dummy_arg", new ArgumentNode("a", "b")))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var value = type.Fields["description"].Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void InterfaceTypeExtension_ReplaceDirectiveOnArgument() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Field(f => f.GetName(default)) - .Argument("a", a => a - .Type() - .Directive("dummy_arg", new ArgumentNode("a", "a"))))) - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => - a.Directive("dummy_arg", new ArgumentNode("a", "b"))))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - string value = type.Fields["name"].Arguments["a"] - .Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public void InterfaceTypeExtension_ReplaceDirectiveOnArgument() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Field(f => f.GetName(default)) + .Argument("a", a => a + .Type() + .Directive("dummy_arg", new ArgumentNode("a", "a"))))) + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => + a.Directive("dummy_arg", new ArgumentNode("a", "b"))))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var value = type.Fields["name"].Arguments["a"] + .Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void InterfaceTypeExtension_CopyDependencies_ToType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => - a.Directive("dummy_arg", new ArgumentNode("a", "b"))))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - string value = type.Fields["name"].Arguments["a"] - .Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public void InterfaceTypeExtension_CopyDependencies_ToType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => + a.Directive("dummy_arg", new ArgumentNode("a", "b"))))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var value = type.Fields["name"].Arguments["a"] + .Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void InterfaceTypeExtension_RepeatableDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Directive("dummy_rep"))) - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Directive("dummy_rep"))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - int count = type.Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + [Fact] + public void InterfaceTypeExtension_RepeatableDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Directive("dummy_rep"))) + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Directive("dummy_rep"))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var count = type.Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - [Fact] - public void InterfaceTypeExtension_RepeatableDirectiveOnField() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Field(f => f.Description) - .Directive("dummy_rep"))) - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("description") - .Directive("dummy_rep"))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - int count = type.Fields["description"] - .Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + [Fact] + public void InterfaceTypeExtension_RepeatableDirectiveOnField() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Field(f => f.Description) + .Directive("dummy_rep"))) + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("description") + .Directive("dummy_rep"))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var count = type.Fields["description"] + .Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - [Fact] - public void InterfaceTypeExtension_RepeatableDirectiveOnArgument() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Field(f => f.GetName(default)) - .Argument("a", a => a - .Type() - .Directive("dummy_rep", new ArgumentNode("a", "a"))))) - .AddType(new InterfaceTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => - a.Directive("dummy_rep", new ArgumentNode("a", "b"))))) - .AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Foo"); - int count = type.Fields["name"].Arguments["a"] - .Directives["dummy_rep"] - .Count(); - Assert.Equal(2, count); - } + [Fact] + public void InterfaceTypeExtension_RepeatableDirectiveOnArgument() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Field(f => f.GetName(default)) + .Argument("a", a => a + .Type() + .Directive("dummy_rep", new ArgumentNode("a", "a"))))) + .AddType(new InterfaceTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => + a.Directive("dummy_rep", new ArgumentNode("a", "b"))))) + .AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Foo"); + var count = type.Fields["name"].Arguments["a"] + .Directives["dummy_rep"] + .Count(); + Assert.Equal(2, count); + } - public class DummyQuery - { - public string Foo { get; set; } - } + public class DummyQuery + { + public string Foo { get; set; } + } - public class FooType - : InterfaceType + public class FooType + : InterfaceType + { + protected override void Configure( + IInterfaceTypeDescriptor descriptor) { - protected override void Configure( - IInterfaceTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Field(t => t.Description); - } + descriptor.Name("Foo"); + descriptor.Field(t => t.Description); } + } - public class FooTypeExtension - : InterfaceTypeExtension + public class FooTypeExtension + : InterfaceTypeExtension + { + protected override void Configure( + IInterfaceTypeDescriptor descriptor) { - protected override void Configure( - IInterfaceTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Field("test") - .Type>(); - } + descriptor.Name("Foo"); + descriptor.Field("test") + .Type>(); } + } - public interface IFoo - { - string Description { get; } + public interface IFoo + { + string Description { get; } - string GetName(string a); - } + string GetName(string a); + } - public class FooResolver + public class FooResolver + { + public string GetName2() { - public string GetName2() - { - return "FooResolver.GetName2"; - } + return "FooResolver.GetName2"; } + } - public class DummyDirective - : DirectiveType + public class DummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy"); - descriptor.Location(DirectiveLocation.Interface); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } + descriptor.Name("dummy"); + descriptor.Location(DirectiveLocation.Interface); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class DummyWithArgDirective - : DirectiveType + public class DummyWithArgDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_arg"); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.Interface); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } + descriptor.Name("dummy_arg"); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.Interface); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class RepeatableDummyDirective - : DirectiveType + public class RepeatableDummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_rep"); - descriptor.Repeatable(); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.Interface); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } + descriptor.Name("dummy_rep"); + descriptor.Repeatable(); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.Interface); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeTests.cs index c742aed468a..a7b19c89b7f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/InterfaceTypeTests.cs @@ -12,682 +12,682 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class InterfaceTypeTests : TypeTestBase { - public class InterfaceTypeTests : TypeTestBase + [Fact] + public void InterfaceType_DynamicName() { - [Fact] - public void InterfaceType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn() - .Field("bar") - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + // act + var schema = SchemaBuilder.New() + .AddInterfaceType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn() + .Field("bar") + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void InterfaceType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType)) - .Field("bar") - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + [Fact] + public void InterfaceType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType)) + .Field("bar") + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void GenericInterfaceType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + [Fact] + public void GenericInterfaceType_DynamicName() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void GenericInterfaceType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddInterfaceType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + [Fact] + public void GenericInterfaceType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddInterfaceType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void InferFieldsFromClrInterface() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(), - b => b.ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.Collection( - fooType.Fields.Where(t => !t.IsIntrospectionField).OrderBy(t => t.Name), - t => - { - Assert.Equal("bar", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - }, - t => - { - Assert.Equal("baz", t.Name); - Assert.IsType(t.Type); - }, - t => - { - Assert.Equal("qux", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - Assert.Collection(t.Arguments, - a => Assert.Equal("a", a.Name)); - }); - } + [Fact] + public void InferFieldsFromClrInterface() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(), + b => b.ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.Collection( + fooType.Fields.Where(t => !t.IsIntrospectionField).OrderBy(t => t.Name), + t => + { + Assert.Equal("bar", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + }, + t => + { + Assert.Equal("baz", t.Name); + Assert.IsType(t.Type); + }, + t => + { + Assert.Equal("qux", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + Assert.Collection(t.Arguments, + a => Assert.Equal("a", a.Name)); + }); + } - [Fact] - public void InferSchemaInterfaceTypeFromClrInterface() - { - // arrange && act - ISchema schema = SchemaBuilder.New() - .AddType() - .AddQueryType() - .Create(); - - // assert - ObjectType type = schema.GetType("FooImpl"); - Assert.Collection(type.Implements, t => Assert.Equal("IFoo", t.Name)); - } + [Fact] + public void InferSchemaInterfaceTypeFromClrInterface() + { + // arrange && act + var schema = SchemaBuilder.New() + .AddType() + .AddQueryType() + .Create(); + + // assert + var type = schema.GetType("FooImpl"); + Assert.Collection(type.Implements, t => Assert.Equal("IFoo", t.Name)); + } - [Fact] - public void IgnoreFieldsFromClrInterface() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(t => t.Ignore(p => p.Bar)), - b => b.ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.Collection( - fooType.Fields.Where(t => !t.IsIntrospectionField), - t => - { - Assert.Equal("baz", t.Name); - Assert.IsType(t.Type); - }, - t => - { - Assert.Equal("qux", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - Assert.Collection(t.Arguments, - a => Assert.Equal("a", a.Name)); - }); - } + [Fact] + public void IgnoreFieldsFromClrInterface() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(t => t.Ignore(p => p.Bar)), + b => b.ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.Collection( + fooType.Fields.Where(t => !t.IsIntrospectionField), + t => + { + Assert.Equal("baz", t.Name); + Assert.IsType(t.Type); + }, + t => + { + Assert.Equal("qux", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + Assert.Collection(t.Arguments, + a => Assert.Equal("a", a.Name)); + }); + } - [Fact] - public void UnIgnoreFieldsFromClrInterface() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(t => - { - t.Ignore(p => p.Bar); - t.Field(p => p.Bar).Ignore(false); - }), - b => b.ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.Collection( - fooType.Fields.Where(t => !t.IsIntrospectionField), - t => - { - Assert.Equal("bar", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - }, - t => - { - Assert.Equal("baz", t.Name); - Assert.IsType(t.Type); - }, - t => - { - Assert.Equal("qux", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - Assert.Collection(t.Arguments, - a => Assert.Equal("a", a.Name)); - }); - } + [Fact] + public void UnIgnoreFieldsFromClrInterface() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(t => + { + t.Ignore(p => p.Bar); + t.Field(p => p.Bar).Ignore(false); + }), + b => b.ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.Collection( + fooType.Fields.Where(t => !t.IsIntrospectionField), + t => + { + Assert.Equal("bar", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + }, + t => + { + Assert.Equal("baz", t.Name); + Assert.IsType(t.Type); + }, + t => + { + Assert.Equal("qux", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + Assert.Collection(t.Arguments, + a => Assert.Equal("a", a.Name)); + }); + } - [Fact] - public void ExplicitInterfaceFieldDeclaration() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(t => t - .BindFields(BindingBehavior.Explicit) - .Field(p => p.Bar)), - b => b.ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.Collection( - fooType.Fields.Where(t => !t.IsIntrospectionField), - t => - { - Assert.Equal("bar", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - }); - } + [Fact] + public void ExplicitInterfaceFieldDeclaration() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(t => t + .BindFields(BindingBehavior.Explicit) + .Field(p => p.Bar)), + b => b.ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.Collection( + fooType.Fields.Where(t => !t.IsIntrospectionField), + t => + { + Assert.Equal("bar", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + }); + } - [Fact] - public void GenericInterfaceType_AddDirectives_NameArgs() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(d => d - .Directive("foo") - .Field(f => f.Bar) - .Directive("foo")), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); - } + [Fact] + public void GenericInterfaceType_AddDirectives_NameArgs() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(d => d + .Directive("foo") + .Field(f => f.Bar) + .Directive("foo")), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); + } - [Fact] - public void GenericInterfaceType_AddDirectives_NameArgs2() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(d => d - .Directive(new NameString("foo")) - .Field(f => f.Bar) - .Directive(new NameString("foo"))), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); - } + [Fact] + public void GenericInterfaceType_AddDirectives_NameArgs2() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(d => d + .Directive(new NameString("foo")) + .Field(f => f.Bar) + .Directive(new NameString("foo"))), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); + } - [Fact] - public void GenericInterfaceType_AddDirectives_DirectiveNode() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(d => d - .Directive(new DirectiveNode("foo")) - .Field(f => f.Bar) - .Directive(new DirectiveNode("foo"))), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); - } + [Fact] + public void GenericInterfaceType_AddDirectives_DirectiveNode() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(d => d + .Directive(new DirectiveNode("foo")) + .Field(f => f.Bar) + .Directive(new DirectiveNode("foo"))), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); + } - [Fact] - public void GenericInterfaceType_AddDirectives_DirectiveClassInstance() - { - // arrange - // act - InterfaceType fooType = CreateType( - new InterfaceType(d => d - .Directive(new FooDirective()) - .Field(f => f.Bar) - .Directive(new FooDirective())), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); - } + [Fact] + public void GenericInterfaceType_AddDirectives_DirectiveClassInstance() + { + // arrange + // act + var fooType = CreateType( + new InterfaceType(d => d + .Directive(new FooDirective()) + .Field(f => f.Bar) + .Directive(new FooDirective())), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); + } - [Fact] - public void GenericInterfaceType_AddDirectives_DirectiveType() - { - // arrange - // act - InterfaceType fooType = CreateType(new InterfaceType(d => d - .Directive() - .Field(f => f.Bar) - .Directive()), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); - } + [Fact] + public void GenericInterfaceType_AddDirectives_DirectiveType() + { + // arrange + // act + var fooType = CreateType(new InterfaceType(d => d + .Directive() + .Field(f => f.Bar) + .Directive()), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); + } - [Fact] - public void InterfaceType_AddDirectives_NameArgs() - { - // arrange - // act - InterfaceType fooType = CreateType(new InterfaceType(d => d - .Name("FooInt") - .Directive("foo") - .Field("id") - .Type() - .Directive("foo")), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void InterfaceType_AddDirectives_NameArgs() + { + // arrange + // act + var fooType = CreateType(new InterfaceType(d => d + .Name("FooInt") + .Directive("foo") + .Field("id") + .Type() + .Directive("foo")), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void InterfaceType_AddDirectives_NameArgs2() - { - // arrange - // act - InterfaceType fooType = CreateType(new InterfaceType(d => d - .Name("FooInt") - .Directive(new NameString("foo")) - .Field("bar") - .Type() - .Directive(new NameString("foo"))), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); - } + [Fact] + public void InterfaceType_AddDirectives_NameArgs2() + { + // arrange + // act + var fooType = CreateType(new InterfaceType(d => d + .Name("FooInt") + .Directive(new NameString("foo")) + .Field("bar") + .Type() + .Directive(new NameString("foo"))), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["bar"].Directives["foo"]); + } - [Fact] - public void InterfaceType_AddDirectives_DirectiveNode() - { - // arrange - // act - InterfaceType fooType = CreateType(new InterfaceType(d => d - .Name("FooInt") - .Directive(new DirectiveNode("foo")) - .Field("id") - .Type() - .Directive(new DirectiveNode("foo"))), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void InterfaceType_AddDirectives_DirectiveNode() + { + // arrange + // act + var fooType = CreateType(new InterfaceType(d => d + .Name("FooInt") + .Directive(new DirectiveNode("foo")) + .Field("id") + .Type() + .Directive(new DirectiveNode("foo"))), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void InterfaceType_AddDirectives_DirectiveClassInstance() - { - // arrange - // act - InterfaceType fooType = CreateType(new InterfaceType(d => d - .Name("FooInt") - .Directive(new FooDirective()) - .Field("id") - .Type() - .Directive(new FooDirective())), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void InterfaceType_AddDirectives_DirectiveClassInstance() + { + // arrange + // act + var fooType = CreateType(new InterfaceType(d => d + .Name("FooInt") + .Directive(new FooDirective()) + .Field("id") + .Type() + .Directive(new FooDirective())), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void InterfaceType_AddDirectives_DirectiveType() - { - // arrange - // act - InterfaceType fooType = CreateType(new InterfaceType(d => d - .Name("FooInt") - .Directive() - .Field("id") - .Type() - .Directive()), - b => b.AddDirectiveType() - .ModifyOptions(o => o.StrictValidation = false)); - - // assert - Assert.NotEmpty(fooType.Directives["foo"]); - Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); - } + [Fact] + public void InterfaceType_AddDirectives_DirectiveType() + { + // arrange + // act + var fooType = CreateType(new InterfaceType(d => d + .Name("FooInt") + .Directive() + .Field("id") + .Type() + .Directive()), + b => b.AddDirectiveType() + .ModifyOptions(o => o.StrictValidation = false)); + + // assert + Assert.NotEmpty(fooType.Directives["foo"]); + Assert.NotEmpty(fooType.Fields["id"].Directives["foo"]); + } - [Fact] - public void DoNotAllow_InputTypes_OnFields() - { - // arrange - // act - Action a = () => SchemaBuilder.New() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Field("bar") - .Type>>())) - .Create(); - - // assert - Assert.Throws(a) - .Errors.First().Message.MatchSnapshot(); - } + [Fact] + public void DoNotAllow_InputTypes_OnFields() + { + // arrange + // act + Action a = () => SchemaBuilder.New() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Field("bar") + .Type>>())) + .Create(); + + // assert + Assert.Throws(a) + .Errors.First().Message.MatchSnapshot(); + } - [Fact] - public void DoNotAllow_DynamicInputTypes_OnFields() - { - // arrange - // act - Action a = () => SchemaBuilder.New() - .AddType(new InterfaceType(t => t - .Name("Foo") - .Field("bar") - .Type(new NonNullType(new InputObjectType())))) - .Create(); - - // assert - Assert.Throws(a) - .Errors.First().Message.MatchSnapshot(); - } + [Fact] + public void DoNotAllow_DynamicInputTypes_OnFields() + { + // arrange + // act + Action a = () => SchemaBuilder.New() + .AddType(new InterfaceType(t => t + .Name("Foo") + .Field("bar") + .Type(new NonNullType(new InputObjectType())))) + .Create(); + + // assert + Assert.Throws(a) + .Errors.First().Message.MatchSnapshot(); + } - [Fact] - public void Ignore_DescriptorIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => InterfaceTypeDescriptorExtensions.Ignore(null, t => t.Bar); + [Fact] + public void Ignore_DescriptorIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => InterfaceTypeDescriptorExtensions.Ignore(null, t => t.Bar); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void Ignore_ExpressionIsNull_ArgumentNullException() - { - // arrange - var descriptor = InterfaceTypeDescriptor.New(DescriptorContext.Create()); + [Fact] + public void Ignore_ExpressionIsNull_ArgumentNullException() + { + // arrange + var descriptor = InterfaceTypeDescriptor.New(DescriptorContext.Create()); - // act - void Action() => descriptor.Ignore(null); + // act + void Action() => descriptor.Ignore(null); - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void Ignore_Bar_Property() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new InterfaceType(d => d - .Ignore(t => t.Bar))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Ignore_Bar_Property() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new InterfaceType(d => d + .Ignore(t => t.Bar))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Deprecate_Obsolete_Fields() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new InterfaceType()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Deprecate_Obsolete_Fields() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new InterfaceType()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Deprecate_Fields_With_Deprecated_Attribute() - { - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c.Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new InterfaceType()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Deprecate_Fields_With_Deprecated_Attribute() + { + var schema = SchemaBuilder.New() + .AddQueryType(c => c.Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new InterfaceType()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + schema.ToString().MatchSnapshot(); + } - [Fact] - public void AnnotationBased_Interface_Issue_3577() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void AnnotationBased_Interface_Issue_3577() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void AnnotationBased_Interface_Issue_3577_Inheritance_Control() - { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void AnnotationBased_Interface_Issue_3577_Inheritance_Control() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void InterfaceType_InInterfaceType_ThrowsSchemaException() - { - // arrange - // act - Exception ex = Record.Exception( - () => SchemaBuilder - .New() - .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) - .AddType>>() - .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) - .Create()); - - // assert - Assert.IsType(ex); - ex.Message.MatchSnapshot(); - } + [Fact] + public void InterfaceType_InInterfaceType_ThrowsSchemaException() + { + // arrange + // act + var ex = Record.Exception( + () => SchemaBuilder + .New() + .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) + .AddType>>() + .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) + .Create()); + + // assert + Assert.IsType(ex); + ex.Message.MatchSnapshot(); + } - [Fact] - public void Specify_Field_Type_With_SDL_Syntax() - { - SchemaBuilder.New() - .AddInterfaceType(d => - { - d.Name("Bar"); - d.Field("Foo").Type("String"); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Specify_Field_Type_With_SDL_Syntax() + { + SchemaBuilder.New() + .AddInterfaceType(d => + { + d.Name("Bar"); + d.Field("Foo").Type("String"); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void Specify_Argument_Type_With_SDL_Syntax() - { - SchemaBuilder.New() - .AddInterfaceType(d => - { - d.Name("Bar"); - d.Field("Foo") - .Argument("a", t => t.Type("Int")) - .Type("String"); - }) - .ModifyOptions(o => o.StrictValidation = false) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Specify_Argument_Type_With_SDL_Syntax() + { + SchemaBuilder.New() + .AddInterfaceType(d => + { + d.Name("Bar"); + d.Field("Foo") + .Argument("a", t => t.Type("Int")) + .Type("String"); + }) + .ModifyOptions(o => o.StrictValidation = false) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public async Task AnnotationBased_DeprecatedArguments_Valid() - { - // arrange - - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) - .AddInterfaceType() - .AddType() - .BuildRequestExecutorAsync(); - - // assert - executor.Schema.Print().MatchSnapshot(); - } + [Fact] + public async Task AnnotationBased_DeprecatedArguments_Valid() + { + // arrange + + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) + .AddInterfaceType() + .AddType() + .BuildRequestExecutorAsync(); + + // assert + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task AnnotationBased_DeprecatedArgumentsWithNonNullType_Invalid() - { - // arrange - - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) - .AddInterfaceType() - .AddType() - .BuildRequestExecutorAsync(); - - // assert - SchemaException ex = await Assert.ThrowsAsync(call); - ex.Errors[0].ToString().MatchSnapshot(); - } + [Fact] + public async Task AnnotationBased_DeprecatedArgumentsWithNonNullType_Invalid() + { + // arrange + + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) + .AddInterfaceType() + .AddType() + .BuildRequestExecutorAsync(); + + // assert + var ex = await Assert.ThrowsAsync(call); + ex.Errors[0].ToString().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DeprecatedArguments_Valid() - { - // arrange - - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) - .AddInterfaceType(x => x - .Name("Interface") - .Field("bar") - .Type() - .Argument("baz", y => y.Type().Deprecated("b"))) - .AddObjectType(x => x - .Name("Foo") - .Implements("Interface") - .Field("bar") - .Resolve("asd") - .Type() - .Argument("baz", y => y.Type().Deprecated("b"))) - .BuildRequestExecutorAsync(); - - // assert - executor.Schema.Print().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_DeprecatedArguments_Valid() + { + // arrange + + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) + .AddInterfaceType(x => x + .Name("Interface") + .Field("bar") + .Type() + .Argument("baz", y => y.Type().Deprecated("b"))) + .AddObjectType(x => x + .Name("Foo") + .Implements("Interface") + .Field("bar") + .Resolve("asd") + .Type() + .Argument("baz", y => y.Type().Deprecated("b"))) + .BuildRequestExecutorAsync(); + + // assert + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DeprecatedArgumentsWithNonNullType_Invalid() - { - // arrange - - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) - .AddInterfaceType(x => x - .Name("Interface") - .Field("bar") - .Type() - .Argument("baz", y => y.Type>().Deprecated("b"))) - .AddObjectType(x => x - .Name("Foo") - .Implements("Interface") - .Field("bar") - .Resolve("asd") - .Type() - .Argument("baz", y => y.Type>().Deprecated("b"))) - .BuildRequestExecutorAsync(); - - // assert - SchemaException ex = await Assert.ThrowsAsync(call); - ex.Errors[0].ToString().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_DeprecatedArgumentsWithNonNullType_Invalid() + { + // arrange + + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) + .AddInterfaceType(x => x + .Name("Interface") + .Field("bar") + .Type() + .Argument("baz", y => y.Type>().Deprecated("b"))) + .AddObjectType(x => x + .Name("Foo") + .Implements("Interface") + .Field("bar") + .Resolve("asd") + .Type() + .Argument("baz", y => y.Type>().Deprecated("b"))) + .BuildRequestExecutorAsync(); + + // assert + var ex = await Assert.ThrowsAsync(call); + ex.Errors[0].ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DeprecatedArguments_Valid() - { - // arrange + [Fact] + public async Task SchemaFirst_DeprecatedArguments_Valid() + { + // arrange - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) - .AddDocumentFromString(@" + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) + .AddDocumentFromString(@" interface Interface { bar(a: String @deprecated(reason:""reason"")): Int! } @@ -696,23 +696,23 @@ type Foo implements Interface { bar(a: String @deprecated(reason:""reason"")): Int! } ") - .AddResolver("Foo", "bar", x => 1) - .BuildRequestExecutorAsync(); + .AddResolver("Foo", "bar", x => 1) + .BuildRequestExecutorAsync(); - // assert - executor.Schema.Print().MatchSnapshot(); - } + // assert + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DeprecatedArgumentsWithNonNullType_Invalid() - { - // arrange + [Fact] + public async Task SchemaFirst_DeprecatedArgumentsWithNonNullType_Invalid() + { + // arrange - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) - .AddDocumentFromString(@" + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x.Name("Query").Field("foo").Resolve(1)) + .AddDocumentFromString(@" interface Interface { bar(a: String! @deprecated(reason:""reason"")): Int! } @@ -721,161 +721,160 @@ type Foo implements Interface { bar(a: String! @deprecated(reason:""reason"")): Int! } ") - .AddResolver("Foo", "bar", x => 1) - .BuildRequestExecutorAsync(); + .AddResolver("Foo", "bar", x => 1) + .BuildRequestExecutorAsync(); - // assert - SchemaException ex = await Assert.ThrowsAsync(call); - ex.Errors[0].ToString().MatchSnapshot(); - } + // assert + var ex = await Assert.ThrowsAsync(call); + ex.Errors[0].ToString().MatchSnapshot(); + } - [Fact] - public async Task Ensure_Interface_Field_Is_Requested_When_Applying_NamingConvention() - { - await new ServiceCollection() - .AddGraphQL() - .AddConvention() - .AddQueryType(x => x - .Name("Query") - .Field("foo") - .Type>() - .Resolve(() => null)) - .AddResolver("Foo", "bar", x => 1) - .ModifyOptions(o => o.StrictValidation = false) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Ensure_Interface_Field_Is_Requested_When_Applying_NamingConvention() + { + await new ServiceCollection() + .AddGraphQL() + .AddConvention() + .AddQueryType(x => x + .Name("Query") + .Field("foo") + .Type>() + .Resolve(() => null)) + .AddResolver("Foo", "bar", x => 1) + .ModifyOptions(o => o.StrictValidation = false) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - private sealed class SnakeCaseNamingConventions : DefaultNamingConventions + private sealed class SnakeCaseNamingConventions : DefaultNamingConventions + { + public override NameString GetMemberName(MemberInfo member, MemberKind kind) { - public override NameString GetMemberName(MemberInfo member, MemberKind kind) + if (kind == MemberKind.InterfaceField) { - if (kind == MemberKind.InterfaceField) - { - var pattern = new Regex( - @"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+"); - return string.Join("_", pattern.Matches(member.Name)).ToLower(); - } - - return base.GetMemberName(member, kind); + var pattern = new Regex( + @"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+"); + return string.Join("_", pattern.Matches(member.Name)).ToLower(); } - } - private interface IFooNaming - { - string FooBarBaz { get; } + return base.GetMemberName(member, kind); } + } - public interface IFoo - { - bool Bar { get; } - string Baz(); - int Qux(string a); - } + private interface IFooNaming + { + string FooBarBaz { get; } + } - public class FooImpl : IFoo - { - public bool Bar => throw new NotImplementedException(); + public interface IFoo + { + bool Bar { get; } + string Baz(); + int Qux(string a); + } - public string Baz() => throw new NotImplementedException(); + public class FooImpl : IFoo + { + public bool Bar => throw new NotImplementedException(); - public int Qux(string a) => throw new NotImplementedException(); - } + public string Baz() => throw new NotImplementedException(); - public class FooDirectiveType - : DirectiveType - { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor - .Name("foo") - .Location(DirectiveLocation.Interface) - .Location(DirectiveLocation.FieldDefinition); - } - } + public int Qux(string a) => throw new NotImplementedException(); + } - public class FooDirective + public class FooDirectiveType + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { + descriptor + .Name("foo") + .Location(DirectiveLocation.Interface) + .Location(DirectiveLocation.FieldDefinition); } + } - public class FooObsolete - { - [Obsolete("Baz")] - public string Bar() => "foo"; - } + public class FooDirective + { + } - public class FooDeprecated - { - [GraphQLDeprecated("Use Bar2.")] - public string Bar() => "foo"; + public class FooObsolete + { + [Obsolete("Baz")] + public string Bar() => "foo"; + } - public string Bar2() => "Foo 2: Electric foo-galoo"; - } + public class FooDeprecated + { + [GraphQLDeprecated("Use Bar2.")] + public string Bar() => "foo"; - public class Query - { - public string Hello => "World!"; + public string Bar2() => "Foo 2: Electric foo-galoo"; + } - public IEnumerable GetFruits() => new Fruit[] { new Orange(), new Pineapple() }; - } + public class Query + { + public string Hello => "World!"; - [InterfaceType] - public class DeprecatedInterface - { - public int? Deprecated([GraphQLDeprecated("reason")] int? deprecated) => deprecated; - } + public IEnumerable GetFruits() => new Fruit[] { new Orange(), new Pineapple() }; + } - [InterfaceType] - public class DeprecatedImplementation : DeprecatedInterface - { - } + [InterfaceType] + public class DeprecatedInterface + { + public int? Deprecated([GraphQLDeprecated("reason")] int? deprecated) => deprecated; + } - [InterfaceType] - public class DeprecatedNonNullInterface - { - public int Deprecated([GraphQLDeprecated("reason")] int deprecated) => deprecated; - } + [InterfaceType] + public class DeprecatedImplementation : DeprecatedInterface + { + } - [InterfaceType] - public class DeprecatedNonNullImplementation : DeprecatedInterface - { - } + [InterfaceType] + public class DeprecatedNonNullInterface + { + public int Deprecated([GraphQLDeprecated("reason")] int deprecated) => deprecated; + } - [InterfaceType] - public class Fruit - { - public string Taste => "Sweet"; - } + [InterfaceType] + public class DeprecatedNonNullImplementation : DeprecatedInterface + { + } - public class Orange : Fruit - { - public string Color => "Orange"; - } + [InterfaceType] + public class Fruit + { + public string Taste => "Sweet"; + } - public class Pineapple : Fruit - { - public string Shape => "Strange"; - } + public class Orange : Fruit + { + public string Color => "Orange"; + } - public class PetQuery - { - public Pet GetDog() => new Dog { Name = "Foo" }; - } + public class Pineapple : Fruit + { + public string Shape => "Strange"; + } - [InterfaceType(Inherited = true)] - public class Pet - { - public string Name { get; set; } - } + public class PetQuery + { + public Pet GetDog() => new Dog { Name = "Foo" }; + } - public class Canina : Pet - { - } + [InterfaceType(Inherited = true)] + public class Pet + { + public string Name { get; set; } + } - [ObjectType] - public class Dog : Canina - { - } + public class Canina : Pet + { + } + + [ObjectType] + public class Dog : Canina + { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/ListTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/ListTypeTests.cs index 6d45078ee6f..6223dfe9048 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/ListTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/ListTypeTests.cs @@ -9,141 +9,140 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ListTypeTests { - public class ListTypeTests + [Fact] + public void EnsureElementTypeIsCorrectlySet() + { + // arrange + var innerType = new StringType(); + + // act + var type = new ListType(innerType); + + // assert + Assert.Equal(innerType, type.ElementType); + } + + + [Fact] + public void EnsureNonNullElementTypeIsCorrectlySet() + { + // arrange + var innerType = new NonNullType(new StringType()); + + // act + var type = new ListType(innerType); + + // assert + Assert.Equal(innerType, type.ElementType); + } + + [Fact] + public void EnsureNativeTypeIsCorrectlyDetected() + { + // arrange + var innerType = new NonNullType(new StringType()); + var type = new ListType(innerType); + + // act + var clrType = type.RuntimeType; + + // assert + Assert.Equal(typeof(List), clrType); + } + + [Fact] + public async Task Integration_List_ListValues_Scalars() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ scalars(values: [1,2]) }") + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Integration_List_ScalarValue_Scalars() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ scalars(values: 1) }") + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Integration_List_ListValues_Object() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ objects(values: [{ bar: 1 }, { bar: 2 }]) { bar } }") + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Integration_List_ScalarValue_Object() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder + .New() + .SetQuery("{ objects(values: { bar: 1 }) { bar } }") + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + public class Query + { + public int[] Scalars(int[] values) => values; + + public Foo[] Objects(Foo[] values) => values; + } + + public class Foo { - [Fact] - public void EnsureElementTypeIsCorrectlySet() - { - // arrange - var innerType = new StringType(); - - // act - var type = new ListType(innerType); - - // assert - Assert.Equal(innerType, type.ElementType); - } - - - [Fact] - public void EnsureNonNullElementTypeIsCorrectlySet() - { - // arrange - var innerType = new NonNullType(new StringType()); - - // act - var type = new ListType(innerType); - - // assert - Assert.Equal(innerType, type.ElementType); - } - - [Fact] - public void EnsureNativeTypeIsCorrectlyDetected() - { - // arrange - var innerType = new NonNullType(new StringType()); - var type = new ListType(innerType); - - // act - Type clrType = type.RuntimeType; - - // assert - Assert.Equal(typeof(List), clrType); - } - - [Fact] - public async Task Integration_List_ListValues_Scalars() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ scalars(values: [1,2]) }") - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Integration_List_ScalarValue_Scalars() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ scalars(values: 1) }") - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Integration_List_ListValues_Object() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ objects(values: [{ bar: 1 }, { bar: 2 }]) { bar } }") - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Integration_List_ScalarValue_Object() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder - .New() - .SetQuery("{ objects(values: { bar: 1 }) { bar } }") - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - public class Query - { - public int[] Scalars(int[] values) => values; - - public Foo[] Objects(Foo[] values) => values; - } - - public class Foo - { - public int Bar { get; set; } - } + public int Bar { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/NativeTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/NativeTypeTests.cs index 2e653c59da2..37c2daf4996 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/NativeTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/NativeTypeTests.cs @@ -2,36 +2,35 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class NativeTypeTests { - public class NativeTypeTests + [Fact] + public void Kind_NotSupportedException() { - [Fact] - public void Kind_NotSupportedException() - { - // arrange - var type = new NativeType(); + // arrange + var type = new NativeType(); - // act - TypeKind kind; - void Action() => kind = ((IInputType)type).Kind; + // act + TypeKind kind; + void Action() => kind = ((IInputType)type).Kind; - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void ClrType_NotSupportedException() - { - // arrange - var type = new NativeType(); + [Fact] + public void ClrType_NotSupportedException() + { + // arrange + var type = new NativeType(); - // act - Type clrType; - void Action() => clrType = ((IInputType)type).RuntimeType; + // act + Type clrType; + void Action() => clrType = ((IInputType)type).RuntimeType; - // assert - Assert.Throws(Action); - } + // assert + Assert.Throws(Action); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/NonNullTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/NonNullTypeTests.cs index 127abf96ff0..f0b344692c8 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/NonNullTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/NonNullTypeTests.cs @@ -2,42 +2,41 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class NonNullTypeTests { - public class NonNullTypeTests + [Fact] + public void EnsureInnerTypeIsCorrectlySet() + { + // arrange + var innerType = new StringType(); + + // act + var type = new NonNullType(innerType); + + // assert + Assert.Equal(innerType, type.Type); + } + + + [Fact] + public void EnsureNativeTypeIsCorrectlyDetected() + { + // act + var type = new NonNullType(new StringType()); + + // assert + Assert.Equal(typeof(string), type.RuntimeType); + } + + [Fact] + public void InnerType_Cannot_Be_A_NonNullType() { - [Fact] - public void EnsureInnerTypeIsCorrectlySet() - { - // arrange - var innerType = new StringType(); - - // act - var type = new NonNullType(innerType); - - // assert - Assert.Equal(innerType, type.Type); - } - - - [Fact] - public void EnsureNativeTypeIsCorrectlyDetected() - { - // act - var type = new NonNullType(new StringType()); - - // assert - Assert.Equal(typeof(string), type.RuntimeType); - } - - [Fact] - public void InnerType_Cannot_Be_A_NonNullType() - { - // act - void Action() => new NonNullType(new NonNullType(new StringType())); - - // assert - Assert.Throws(Action); - } + // act + void Action() => new NonNullType(new NonNullType(new StringType())); + + // assert + Assert.Throws(Action); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectFieldExpressionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectFieldExpressionTests.cs index dc4e1107661..aae90583f36 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectFieldExpressionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectFieldExpressionTests.cs @@ -8,79 +8,78 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ObjectFieldExpressionTests { - public class ObjectFieldExpressionTests + [Fact] + public void Infer_Field_Types_From_Expression() { - [Fact] - public void Infer_Field_Types_From_Expression() - { - SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - d.Field(t => t.Bar.Text); + SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + d.Field(t => t.Bar.Text); #if !NETCOREAPP2_1 && !NETCOREAPP3_1 - d.Field(t => t.Bars.Select(t => t.Text)).Name("texts"); + d.Field(t => t.Bars.Select(t => t.Text)).Name("texts"); #endif - }) - .Create() - .ToString() + }) + .Create() + .ToString() #if NETCOREAPP2_1 || NETCOREAPP3_1 .MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1")); #else - .MatchSnapshot(); + .MatchSnapshot(); #endif - } + } - [Fact] - public void Execute_Expression_Fields() - { - SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - d.Field(t => t.Bar.Text); - d.Field(t => t.Bars.Select(b => b.Text)).Name("texts"); - d.Field(t => t.Bars.Select(b => b.Text).FirstOrDefault()).Name("firstText"); - }) - .Create() - .MakeExecutable() - .Execute("{ text texts firstText }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void Execute_Expression_Fields() + { + SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + d.Field(t => t.Bar.Text); + d.Field(t => t.Bars.Select(b => b.Text)).Name("texts"); + d.Field(t => t.Bars.Select(b => b.Text).FirstOrDefault()).Name("firstText"); + }) + .Create() + .MakeExecutable() + .Execute("{ text texts firstText }") + .ToJson() + .MatchSnapshot(); + } - [Fact] - public void Execute_Complex_Expression_Fields() - { - SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - d.Field(t => t.Bar.Count + t.Bar.Text.Length).Name("calc"); - }) - .Create() - .MakeExecutable() - .Execute("{ calc }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void Execute_Complex_Expression_Fields() + { + SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + d.Field(t => t.Bar.Count + t.Bar.Text.Length).Name("calc"); + }) + .Create() + .MakeExecutable() + .Execute("{ calc }") + .ToJson() + .MatchSnapshot(); + } - public class Foo - { - public IEnumerable Bars => new[] { new Bar() }; + public class Foo + { + public IEnumerable Bars => new[] { new Bar() }; - public Bar Bar => new Bar(); + public Bar Bar => new Bar(); - public string Field = "ABC"; - } + public string Field = "ABC"; + } - public class Bar - { - public string Text { get; } = "Hello"; + public class Bar + { + public string Text { get; } = "Hello"; - public int Count { get; } = 1; - } + public int Count { get; } = 1; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeAttributeTests.cs index 3ab76a13277..b6b9698d0d1 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeAttributeTests.cs @@ -9,204 +9,203 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ObjectTypeAttributeTests + : TypeTestBase { - public class ObjectTypeAttributeTests - : TypeTestBase + [Fact] + public void ArgumentDescriptorAttribute_Changes_DefaultValue() { - [Fact] - public void ArgumentDescriptorAttribute_Changes_DefaultValue() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - Assert.Equal( - "abc", - schema.QueryType.Fields["field"].Arguments["argument"].DefaultValue!.Value); - } + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + Assert.Equal( + "abc", + schema.QueryType.Fields["field"].Arguments["argument"].DefaultValue!.Value); + } - [Fact] - public void ObjectFieldDescriptorAttribute_Adds_ContextData() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - Assert.Equal( - "def", - schema.QueryType.Fields["field"].ContextData["abc"]); - } + [Fact] + public void ObjectFieldDescriptorAttribute_Adds_ContextData() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + Assert.Equal( + "def", + schema.QueryType.Fields["field"].ContextData["abc"]); + } - [Fact] - public void ObjectFieldDescriptorAttribute_Updated_FieldDefinition() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => - d.Field(t => t.GetField()).Name("foo")) - .Create(); - - // assert - Assert.Equal( - "def", - schema.QueryType.Fields["foo"].ContextData["abc"]); - } + [Fact] + public void ObjectFieldDescriptorAttribute_Updated_FieldDefinition() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType(d => + d.Field(t => t.GetField()).Name("foo")) + .Create(); + + // assert + Assert.Equal( + "def", + schema.QueryType.Fields["foo"].ContextData["abc"]); + } - [Fact] - public void ObjectTypeDescriptorAttribute_Add_FieldDefinition() - { - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public void ObjectTypeDescriptorAttribute_Add_FieldDefinition() + { + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert - Assert.True(schema.QueryType.Fields.ContainsField("abc")); - } + // assert + Assert.True(schema.QueryType.Fields.ContainsField("abc")); + } - [Fact] - public void ObjectTypeDescriptorAttribute_Add_FieldDefinition_2() - { - // act - ISchema schema = SchemaBuilder.New() - .AddObjectType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.True(schema.GetType("Object3").Fields.ContainsField("abc")); - } + [Fact] + public void ObjectTypeDescriptorAttribute_Add_FieldDefinition_2() + { + // act + var schema = SchemaBuilder.New() + .AddObjectType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.True(schema.GetType("Object3").Fields.ContainsField("abc")); + } - [Fact] - public void ObjectTypeAttribute_Mark_Struct_As_ObjectType() - { - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + [Fact] + public void ObjectTypeAttribute_Mark_Struct_As_ObjectType() + { + // act + var schema = SchemaBuilder.New() + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void ExtendObjectTypeAttribute_Extend_Query_Type() + { + // act + var schema = SchemaBuilder.New() + .AddType() + .AddType() + .ModifyOptions(o => o.RemoveUnreachableTypes = true) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void ExtendObjectTypeAttribute_Extend_Query_Type() - { - // act - ISchema schema = SchemaBuilder.New() + [Fact] + public async Task ExtendObjectTypeAttribute_Extend_Query_Type_2() + { + // act + var schema = + await new ServiceCollection() + .AddGraphQL() .AddType() .AddType() - .ModifyOptions(o => o.RemoveUnreachableTypes = true) - .Create(); + .TrimTypes() + .BuildSchemaAsync(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task ExtendObjectTypeAttribute_Extend_Query_Type_2() + public class Object1 + { + public string GetField([ArgumentDefaultValue("abc")] string argument) { - // act - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddType() - .AddType() - .TrimTypes() - .BuildSchemaAsync(); - - // assert - schema.ToString().MatchSnapshot(); + throw new NotImplementedException(); } + } - public class Object1 + public class ArgumentDefaultValueAttribute + : ArgumentDescriptorAttribute + { + public ArgumentDefaultValueAttribute(object defaultValue) { - public string GetField([ArgumentDefaultValue("abc")] string argument) - { - throw new NotImplementedException(); - } + DefaultValue = defaultValue; } - public class ArgumentDefaultValueAttribute - : ArgumentDescriptorAttribute + public object DefaultValue { get; } + + public override void OnConfigure( + IDescriptorContext context, + IArgumentDescriptor descriptor, + ParameterInfo parameterInfo) { - public ArgumentDefaultValueAttribute(object defaultValue) - { - DefaultValue = defaultValue; - } - - public object DefaultValue { get; } - - public override void OnConfigure( - IDescriptorContext context, - IArgumentDescriptor descriptor, - ParameterInfo parameterInfo) - { - descriptor.DefaultValue(DefaultValue); - } + descriptor.DefaultValue(DefaultValue); } + } - public class Object2 + public class Object2 + { + [PropertyAddContextData] + public string GetField() { - [PropertyAddContextData] - public string GetField() - { - throw new NotImplementedException(); - } + throw new NotImplementedException(); } + } - public class PropertyAddContextDataAttribute - : ObjectFieldDescriptorAttribute + public class PropertyAddContextDataAttribute + : ObjectFieldDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IObjectFieldDescriptor descriptor, + MemberInfo member) { - public override void OnConfigure( - IDescriptorContext context, - IObjectFieldDescriptor descriptor, - MemberInfo member) - { - descriptor.Extend().OnBeforeCompletion( - (c, d) => d.ContextData.Add("abc", "def")); - } + descriptor.Extend().OnBeforeCompletion( + (c, d) => d.ContextData.Add("abc", "def")); } + } - [ObjectAddField] - public class Object3 + [ObjectAddField] + public class Object3 + { + public string GetField() { - public string GetField() - { - throw new NotImplementedException(); - } + throw new NotImplementedException(); } + } - public class ObjectAddFieldAttribute - : ObjectTypeDescriptorAttribute + public class ObjectAddFieldAttribute + : ObjectTypeDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IObjectTypeDescriptor descriptor, + Type type) { - public override void OnConfigure( - IDescriptorContext context, - IObjectTypeDescriptor descriptor, - Type type) - { #pragma warning disable CS0618 - descriptor.Field("abc").Resolver("def"); + descriptor.Field("abc").Resolver("def"); #pragma warning restore CS0618 - } } + } - [ObjectType("Query")] - public struct StructQuery - { - public string? Foo { get; } - } + [ObjectType("Query")] + public struct StructQuery + { + public string? Foo { get; } + } - [ExtendObjectType("Query")] - public class StructQueryExtension - { - public string? Bar { get; } - } + [ExtendObjectType("Query")] + public class StructQueryExtension + { + public string? Bar { get; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeExtensionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeExtensionTests.cs index 1477b798ffd..7fc56d8c9dd 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeExtensionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeExtensionTests.cs @@ -17,927 +17,926 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ObjectTypeExtensionTests { - public class ObjectTypeExtensionTests + [Fact] + public async Task ObjectTypeExtension_AddField() { - [Fact] - public async Task ObjectTypeExtension_AddField() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields.ContainsField("test")); - } - - [Fact] - public async Task ObjectTypeExtension_Infer_Field() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields.ContainsField("test")); - } - - [Fact] - public async Task ObjectTypeExtension_Declare_Field() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => - { - d.Name("Foo"); - d.Field(t => t.Test).Type(); - })) - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields.ContainsField("test")); - Assert.IsType(type.Fields["test"].Type); - } - - [Fact] - public async Task ObjectTypeExtension_Remove_Field_By_Name() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") - .Ignore(true))) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task ObjectTypeExtension_Remove_Field() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Ignore(f => f.Description))) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task ObjectTypeExtension_Execute_Infer_Field() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .ExecuteRequestAsync("{ test }") - .MatchSnapshotAsync(); - } - - [Fact] - public async Task ObjectTypeExtension_OverrideResolver() - { - ValueTask Resolver(IResolverContext ctx) => new(null!); + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields.ContainsField("test")); + } - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .Resolve(Resolver))) - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_Infer_Field() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields.ContainsField("test")); + } - ObjectType type = schema.GetType("Foo"); - Assert.Equal(Resolver, type.Fields["description"].Resolver); - } + [Fact] + public async Task ObjectTypeExtension_Declare_Field() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => + { + d.Name("Foo"); + d.Field(t => t.Test).Type(); + })) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields.ContainsField("test")); + Assert.IsType(type.Fields["test"].Type); + } - [Fact] - public async Task ObjectTypeExtension_AddResolverType() - { - var context = new Mock(MockBehavior.Strict); - context.Setup(t => t.Resolver()) - .Returns(new FooResolver()); - context.Setup(t => t.RequestAborted) - .Returns(CancellationToken.None); + [Fact] + public async Task ObjectTypeExtension_Remove_Field_By_Name() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Ignore(true))) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field(t => t.GetName2()) - .Type())) - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_Remove_Field() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Ignore(f => f.Description))) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - ObjectType type = schema.GetType("Foo"); - var value = await type.Fields["name2"].Resolver!.Invoke(context.Object); - Assert.Equal("FooResolver.GetName2", value); - } + [Fact] + public async Task ObjectTypeExtension_Execute_Infer_Field() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .ExecuteRequestAsync("{ test }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task ObjectTypeExtension_AddMiddleware() - { - Snapshot.FullName(); + [Fact] + public async Task ObjectTypeExtension_OverrideResolver() + { + ValueTask Resolver(IResolverContext ctx) => new(null!); + + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Resolve(Resolver))) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.Equal(Resolver, type.Fields["description"].Resolver); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .Use(_ => context => - { - context.Result = "BAR"; - return default; - }))) - .ExecuteRequestAsync("{ description }") - .ToJsonAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task ObjectTypeExtension_AddResolverType() + { + var context = new Mock(MockBehavior.Strict); + context.Setup(t => t.Resolver()) + .Returns(new FooResolver()); + context.Setup(t => t.RequestAborted) + .Returns(CancellationToken.None); + + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field(t => t.GetName2()) + .Type())) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + var value = await type.Fields["name2"].Resolver!.Invoke(context.Object); + Assert.Equal("FooResolver.GetName2", value); + } - [Obsolete] - [Fact] - public async Task ObjectTypeExtension_DeprecateField_Obsolete() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .DeprecationReason("Foo"))) - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_AddMiddleware() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Use(_ => context => + { + context.Result = "BAR"; + return default; + }))) + .ExecuteRequestAsync("{ description }") + .ToJsonAsync() + .MatchSnapshotAsync(); + } - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"].IsDeprecated); - Assert.Equal("Foo", type.Fields["description"].DeprecationReason); - } + [Obsolete] + [Fact] + public async Task ObjectTypeExtension_DeprecateField_Obsolete() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .DeprecationReason("Foo"))) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"].IsDeprecated); + Assert.Equal("Foo", type.Fields["description"].DeprecationReason); + } - [Fact] - public async Task ObjectTypeExtension_DeprecateField_With_Reason() - { - Snapshot.FullName(); + [Fact] + public async Task ObjectTypeExtension_DeprecateField_With_Reason() + { + Snapshot.FullName(); + + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Deprecated("Foo"))) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"].IsDeprecated); + Assert.Equal("Foo", type.Fields["description"].DeprecationReason); + schema.ToString().MatchSnapshot(); + } - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") - .Type() - .Deprecated("Foo"))) - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_DeprecateField_Without_Reason() + { + Snapshot.FullName(); + + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Type() + .Deprecated())) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"].IsDeprecated); + Assert.Equal( + WellKnownDirectives.DeprecationDefaultReason, + type.Fields["description"].DeprecationReason); + schema.ToString().MatchSnapshot(); + } - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"].IsDeprecated); - Assert.Equal("Foo", type.Fields["description"].DeprecationReason); - schema.ToString().MatchSnapshot(); - } + [Fact] + public async Task ObjectTypeExtension_SetTypeContextData() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.ContextData.ContainsKey("foo")); + } - [Fact] - public async Task ObjectTypeExtension_DeprecateField_Without_Reason() - { - Snapshot.FullName(); + [Fact] + public async Task ObjectTypeExtension_SetFieldContextData() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields["description"] + .ContextData.ContainsKey("foo")); + } - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") + [Fact] + public async Task ObjectTypeExtension_SetArgumentContextData() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("name") + .Type() + .Argument("a", a => a .Type() - .Deprecated())) - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"].IsDeprecated); - Assert.Equal( - WellKnownDirectives.DeprecationDefaultReason, - type.Fields["description"].DeprecationReason); - schema.ToString().MatchSnapshot(); - } - - [Fact] - public async Task ObjectTypeExtension_SetTypeContextData() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.ContextData.ContainsKey("foo")); - } - - [Fact] - public async Task ObjectTypeExtension_SetFieldContextData() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["description"] - .ContextData.ContainsKey("foo")); - } - - [Fact] - public async Task ObjectTypeExtension_SetArgumentContextData() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("name") - .Type() - .Argument("a", a => a - .Type() - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar")))) - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"].Arguments["a"] - .ContextData.ContainsKey("foo")); - } - - [Fact] - public async Task ObjectTypeExtension_SetDirectiveOnType() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Directive("dummy"))) - .AddDirectiveType() - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Directives.Contains("dummy")); - } - - [Fact] - public async Task ObjectTypeExtension_SetDirectiveOnField() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("name") - .Directive("dummy"))) - .AddDirectiveType() - .BuildSchemaAsync(); + .OnBeforeCreate(c => c.ContextData["foo"] = "bar")))) + .BuildSchemaAsync(); - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"] - .Directives.Contains("dummy")); - } - - [Fact] - public async Task ObjectTypeExtension_SetDirectiveOnArgument() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => a.Directive("dummy")))) - .AddDirectiveType() - .BuildSchemaAsync(); - - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"].Arguments["a"] - .Directives.Contains("dummy")); - } - - [Fact] - public async Task ObjectTypeExtension_CopyDependencies_ToType() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => a.Directive("dummy_arg", new ArgumentNode("a", "b"))))) - .AddDirectiveType() - .BuildSchemaAsync(); + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"].Arguments["a"] + .ContextData.ContainsKey("foo")); + } - ObjectType type = schema.GetType("Foo"); - var value = type.Fields["name"].Arguments["a"] - .Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public async Task ObjectTypeExtension_SetDirectiveOnType() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Directive("dummy"))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Directives.Contains("dummy")); + } - [Fact] - public async Task ObjectTypeExtension_RepeatableDirectiveOnType() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(new ObjectType(t => t - .Directive("dummy_rep"))) - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Directive("dummy_rep"))) - .AddDirectiveType() - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_SetDirectiveOnField() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("name") + .Directive("dummy"))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"] + .Directives.Contains("dummy")); + } - ObjectType type = schema.GetType("Foo"); - var count = type.Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + [Fact] + public async Task ObjectTypeExtension_SetDirectiveOnArgument() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => a.Directive("dummy")))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"].Arguments["a"] + .Directives.Contains("dummy")); + } - [Fact] - public async Task ObjectTypeExtension_RepeatableDirectiveOnField() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(new ObjectType(t => t - .Field(f => f.Description) - .Directive("dummy_rep"))) - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("description") - .Directive("dummy_rep"))) - .AddDirectiveType() - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_CopyDependencies_ToType() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => a.Directive("dummy_arg", new ArgumentNode("a", "b"))))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + var value = type.Fields["name"].Arguments["a"] + .Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - ObjectType type = schema.GetType("Foo"); - var count = type.Fields["description"].Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + [Fact] + public async Task ObjectTypeExtension_RepeatableDirectiveOnType() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(new ObjectType(t => t + .Directive("dummy_rep"))) + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Directive("dummy_rep"))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + var count = type.Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - [Fact] - public async Task ObjectTypeExtension_RepeatableDirectiveOnArgument() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(new ObjectType(t => t - .Field(f => f.GetName(default!)) - .Argument("a", a => a - .Type() - .Directive("dummy_rep", new ArgumentNode("a", "a"))))) - .AddTypeExtension(new ObjectTypeExtension(d => d - .Name("Foo") - .Field("name") - .Argument("a", a => - a.Directive("dummy_rep", new ArgumentNode("a", "b"))))) - .AddDirectiveType() - .BuildSchemaAsync(); + [Fact] + public async Task ObjectTypeExtension_RepeatableDirectiveOnField() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(new ObjectType(t => t + .Field(f => f.Description) + .Directive("dummy_rep"))) + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("description") + .Directive("dummy_rep"))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + var count = type.Fields["description"].Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - ObjectType type = schema.GetType("Foo"); - var count = type.Fields["name"].Arguments["a"] - .Directives["dummy_rep"] - .Count(); - Assert.Equal(2, count); - } + [Fact] + public async Task ObjectTypeExtension_RepeatableDirectiveOnArgument() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(new ObjectType(t => t + .Field(f => f.GetName(default!)) + .Argument("a", a => a + .Type() + .Directive("dummy_rep", new ArgumentNode("a", "a"))))) + .AddTypeExtension(new ObjectTypeExtension(d => d + .Name("Foo") + .Field("name") + .Argument("a", a => + a.Directive("dummy_rep", new ArgumentNode("a", "b"))))) + .AddDirectiveType() + .BuildSchemaAsync(); + + var type = schema.GetType("Foo"); + var count = type.Fields["name"].Arguments["a"] + .Directives["dummy_rep"] + .Count(); + Assert.Equal(2, count); + } - [Fact] - public async Task ObjectTypeExtension_SetDirectiveOnArgument_Sdl_First() - { - ISchema schema = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddDocumentFromString( - @"extend type Foo { + [Fact] + public async Task ObjectTypeExtension_SetDirectiveOnArgument_Sdl_First() + { + var schema = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddDocumentFromString( + @"extend type Foo { name(a: String @dummy): String }") - .AddDirectiveType() - .BuildSchemaAsync(); + .AddDirectiveType() + .BuildSchemaAsync(); - ObjectType type = schema.GetType("Foo"); - Assert.True(type.Fields["name"].Arguments["a"].Directives.Contains("dummy")); - } - - [Fact] - public async Task BindByType() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + var type = schema.GetType("Foo"); + Assert.True(type.Fields["name"].Arguments["a"].Directives.Contains("dummy")); + } - [Fact] - public async Task BindResolver_With_Property() - { - Snapshot.FullName(); + [Fact] + public async Task BindByType() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task BindResolver_With_Property() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task BindResolver_With_Field() - { - Snapshot.FullName(); + [Fact] + public async Task BindResolver_With_Field() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Remove_Properties_Globally() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Remove_Properties_Globally() - { - Snapshot.FullName(); + [Fact] + public async Task Remove_Fields_Globally() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Remove_Fields() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Remove_Fields_Globally() - { - Snapshot.FullName(); + [Fact] + public async Task Remove_Fields_BindField() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Replace_Field() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Fact] - public async Task Remove_Fields() - { - Snapshot.FullName(); + [Fact] + public async Task Replace_Field_With_The_Same_Name() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task Replace_Field_With_The_Same_Name_Execute() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .AddTypeExtension() + .ExecuteRequestAsync("{ person { someId(arg: \"efg\") } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Remove_Fields_BindField() - { - Snapshot.FullName(); + [Fact] + public async Task Extended_Field_Overwrites_Extended_Field() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .AddTypeExtension() + .ExecuteRequestAsync("{ foo }") + .MatchSnapshotAsync(); + } + [Fact] + public async Task Ensure_Member_And_ResolverMember_Are_Correctly_Set_When_Extending() + { + var schema = await new ServiceCollection() .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync(); - [Fact] - public async Task Replace_Field() - { - Snapshot.FullName(); + IObjectField field = schema.QueryType.Fields["foo1"]; + Assert.Equal("GetFoo", field.Member?.Name); + Assert.Equal("GetFoo1", field.ResolverMember?.Name); + } + [Fact] + public async Task Ensure_Member_And_ResolverMember_Are_The_Same_When_Not_Extending() + { + var schema = await new ServiceCollection() .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task Replace_Field_With_The_Same_Name() - { - Snapshot.FullName(); + .AddQueryType() + .BuildSchemaAsync(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + IObjectField field = schema.QueryType.Fields["foo"]; + Assert.Equal("GetFoo", field.Member?.Name); + Assert.Equal("GetFoo", field.ResolverMember?.Name); + } - [Fact] - public async Task Replace_Field_With_The_Same_Name_Execute() - { - Snapshot.FullName(); + [Fact] + public async Task Descriptor_Attributes_Are_Applied_On_Resolvers() + { + Snapshot.FullName(); - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .AddTypeExtension() - .ExecuteRequestAsync("{ person { someId(arg: \"efg\") } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .ExecuteRequestAsync("{ sayHello }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Extended_Field_Overwrites_Extended_Field() + public class FooType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .AddTypeExtension() - .ExecuteRequestAsync("{ foo }") - .MatchSnapshotAsync(); + descriptor.Field(t => t.Description); } + } - [Fact] - public async Task Ensure_Member_And_ResolverMember_Are_Correctly_Set_When_Extending() + public class FooTypeExtension : ObjectTypeExtension + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync(); - - IObjectField field = schema.QueryType.Fields["foo1"]; - Assert.Equal("GetFoo", field.Member?.Name); - Assert.Equal("GetFoo1", field.ResolverMember?.Name); + descriptor.Name("Foo"); + descriptor.Field("test") + .Resolve(() => new List()) + .Type>(); } + } - [Fact] - public async Task Ensure_Member_And_ResolverMember_Are_The_Same_When_Not_Extending() + public class GenericFooTypeExtension + : ObjectTypeExtension + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - ISchema schema = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync(); - - IObjectField field = schema.QueryType.Fields["foo"]; - Assert.Equal("GetFoo", field.Member?.Name); - Assert.Equal("GetFoo", field.ResolverMember?.Name); + descriptor.Name("Foo"); } + } - [Fact] - public async Task Descriptor_Attributes_Are_Applied_On_Resolvers() - { - Snapshot.FullName(); + public class Foo + { + public string? Description { get; } = "hello"; - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .ExecuteRequestAsync("{ sayHello }") - .MatchSnapshotAsync(); - } + public string? GetName(string? a) => default!; + } - public class FooType : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Description); - } - } + public class FooExtension + { + public string Test { get; set; } = "Test123"; + } - public class FooTypeExtension : ObjectTypeExtension + public class FooResolver + { + public string GetName2() { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Field("test") - .Resolve(() => new List()) - .Type>(); - } + return "FooResolver.GetName2"; } + } - public class GenericFooTypeExtension - : ObjectTypeExtension + public class DummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - } + descriptor.Name("dummy"); + descriptor.Location(DirectiveLocation.Object); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class Foo + public class DummyWithArgDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - public string? Description { get; } = "hello"; - - public string? GetName(string? a) => default!; + descriptor.Name("dummy_arg"); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.Object); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class FooExtension + public class RepeatableDummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - public string Test { get; set; } = "Test123"; + descriptor.Name("dummy_rep"); + descriptor.Repeatable(); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.Object); + descriptor.Location(DirectiveLocation.FieldDefinition); + descriptor.Location(DirectiveLocation.ArgumentDefinition); } + } - public class FooResolver - { - public string GetName2() - { - return "FooResolver.GetName2"; - } - } + public class Query : IMarker + { + public string? Foo { get; } = "abc"; + } - public class DummyDirective - : DirectiveType - { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy"); - descriptor.Location(DirectiveLocation.Object); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); - } - } + public class Bar : IMarker + { + public string? Baz { get; } = "def"; + } - public class DummyWithArgDirective - : DirectiveType + [ExtendObjectType( + // extends all types that inherit this type. + extendsType: typeof(IMarker))] + public class Extensions + { + // introduces a new field on all types that apply the parent + public string? Any([Parent] object parent) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) + if (parent is Query q) { - descriptor.Name("dummy_arg"); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.Object); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); + return q.Foo; } - } - public class RepeatableDummyDirective - : DirectiveType - { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) + if (parent is Bar b) { - descriptor.Name("dummy_rep"); - descriptor.Repeatable(); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.Object); - descriptor.Location(DirectiveLocation.FieldDefinition); - descriptor.Location(DirectiveLocation.ArgumentDefinition); + return b.Baz; } - } - public class Query : IMarker - { - public string? Foo { get; } = "abc"; + return null; } - public class Bar : IMarker + // replaces the original field baz on bar + [GraphQLName("baz")] + public string? BazEx([Parent] Bar bar) { - public string? Baz { get; } = "def"; + return bar.Baz; } - [ExtendObjectType( - // extends all types that inherit this type. - extendsType: typeof(IMarker))] - public class Extensions + // introduces a new field to query + public Bar? FooEx([Parent] Query query) { - // introduces a new field on all types that apply the parent - public string? Any([Parent] object parent) - { - if (parent is Query q) - { - return q.Foo; - } - - if (parent is Bar b) - { - return b.Baz; - } - - return null; - } - - // replaces the original field baz on bar - [GraphQLName("baz")] - public string? BazEx([Parent] Bar bar) - { - return bar.Baz; - } - - // introduces a new field to query - public Bar? FooEx([Parent] Query query) - { - return new(); - } + return new(); } + } - public interface IMarker - { + public interface IMarker + { - } + } - public class BindResolver_With_Property_PersonDto - { - public int FriendId => 1; - } + public class BindResolver_With_Property_PersonDto + { + public int FriendId => 1; + } - [ExtendObjectType(typeof(BindResolver_With_Property_PersonDto))] - public class BindResolver_With_Property_PersonResolvers - { - [BindMember(nameof(BindResolver_With_Property_PersonDto.FriendId))] - public List Friends() => new(); - } + [ExtendObjectType(typeof(BindResolver_With_Property_PersonDto))] + public class BindResolver_With_Property_PersonResolvers + { + [BindMember(nameof(BindResolver_With_Property_PersonDto.FriendId))] + public List Friends() => new(); + } - [ExtendObjectType(typeof(BindResolver_With_Property_PersonDto))] - public class BindResolver_With_Field_PersonResolvers - { - [BindFieldAttribute("friendId")] - public List Friends() => new(); - } + [ExtendObjectType(typeof(BindResolver_With_Property_PersonDto))] + public class BindResolver_With_Field_PersonResolvers + { + [BindFieldAttribute("friendId")] + public List Friends() => new(); + } - public class Remove_Properties_Globally_PersonDto - { - public int FriendId { get; } = 1; + public class Remove_Properties_Globally_PersonDto + { + public int FriendId { get; } = 1; - public int InternalId { get; } = 1; - } + public int InternalId { get; } = 1; + } - [ExtendObjectType( - typeof(Remove_Properties_Globally_PersonDto), - IgnoreProperties = new[] { nameof(Remove_Properties_Globally_PersonDto.InternalId) })] - public class Remove_Properties_Globally_PersonResolvers - { - } + [ExtendObjectType( + typeof(Remove_Properties_Globally_PersonDto), + IgnoreProperties = new[] { nameof(Remove_Properties_Globally_PersonDto.InternalId) })] + public class Remove_Properties_Globally_PersonResolvers + { + } - public class Remove_Fields_Globally_PersonDto - { - public int FriendId { get; } = 1; + public class Remove_Fields_Globally_PersonDto + { + public int FriendId { get; } = 1; - public int InternalId { get; } = 1; - } + public int InternalId { get; } = 1; + } - [ExtendObjectType( - typeof(Remove_Fields_Globally_PersonDto), - IgnoreProperties = new[] { "internalId" })] - public class Remove_Fields_Globally_PersonResolvers - { - } + [ExtendObjectType( + typeof(Remove_Fields_Globally_PersonDto), + IgnoreProperties = new[] { "internalId" })] + public class Remove_Fields_Globally_PersonResolvers + { + } - public class Remove_Fields_PersonDto - { - public int FriendId { get; } = 1; + public class Remove_Fields_PersonDto + { + public int FriendId { get; } = 1; - public int InternalId { get; } = 1; - } + public int InternalId { get; } = 1; + } - [ExtendObjectType(typeof(Remove_Fields_PersonDto))] - public class Remove_Fields_PersonResolvers - { - [GraphQLIgnore] - public int InternalId { get; } = 1; - } + [ExtendObjectType(typeof(Remove_Fields_PersonDto))] + public class Remove_Fields_PersonResolvers + { + [GraphQLIgnore] + public int InternalId { get; } = 1; + } - public class Remove_Fields_BindProperty_PersonDto - { - public int FriendId { get; } = 1; + public class Remove_Fields_BindProperty_PersonDto + { + public int FriendId { get; } = 1; - public int InternalId { get; } = 1; - } + public int InternalId { get; } = 1; + } - [ExtendObjectType(typeof(Remove_Fields_BindProperty_PersonDto))] - public class Remove_Fields_BindProperty_PersonResolvers - { - [GraphQLIgnore] - [BindMember(nameof(Remove_Fields_BindProperty_PersonDto.InternalId))] - public int SomeId { get; } = 1; - } + [ExtendObjectType(typeof(Remove_Fields_BindProperty_PersonDto))] + public class Remove_Fields_BindProperty_PersonResolvers + { + [GraphQLIgnore] + [BindMember(nameof(Remove_Fields_BindProperty_PersonDto.InternalId))] + public int SomeId { get; } = 1; + } - public class Replace_Field_PersonDto - { - public int FriendId { get; } = 1; + public class Replace_Field_PersonDto + { + public int FriendId { get; } = 1; - public int InternalId { get; } = 1; - } + public int InternalId { get; } = 1; + } - [ExtendObjectType(typeof(Replace_Field_PersonDto))] - public class Replace_Field_PersonResolvers - { - [BindMember(nameof(Replace_Field_PersonDto.InternalId))] - public string? SomeId { get; } = "abc"; - } + [ExtendObjectType(typeof(Replace_Field_PersonDto))] + public class Replace_Field_PersonResolvers + { + [BindMember(nameof(Replace_Field_PersonDto.InternalId))] + public string? SomeId { get; } = "abc"; + } - public interface IPersonDto - { - string SomeId(); - } + public interface IPersonDto + { + string SomeId(); + } - [ExtendObjectType("Query")] - public class Replace_Field_PersonDto_2_Query - { - public Replace_Field_PersonDto_2? GetPerson() => new(); - } + [ExtendObjectType("Query")] + public class Replace_Field_PersonDto_2_Query + { + public Replace_Field_PersonDto_2? GetPerson() => new(); + } - public class Replace_Field_PersonDto_2 : IPersonDto - { - public string SomeId() => "1"; - } + public class Replace_Field_PersonDto_2 : IPersonDto + { + public string SomeId() => "1"; + } - [ExtendObjectType(typeof(IPersonDto))] - public class Replace_Field_PersonResolvers_2 - { - [BindMember(nameof(Replace_Field_PersonDto_2.SomeId))] - public string? SomeId([Parent] IPersonDto dto, string? arg = "abc") => - dto.SomeId() + arg; - } + [ExtendObjectType(typeof(IPersonDto))] + public class Replace_Field_PersonResolvers_2 + { + [BindMember(nameof(Replace_Field_PersonDto_2.SomeId))] + public string? SomeId([Parent] IPersonDto dto, string? arg = "abc") => + dto.SomeId() + arg; + } - [ExtendObjectType(OperationTypeNames.Query)] - public class ExtensionA - { - public string Foo() => "abc"; - } + [ExtendObjectType(OperationTypeNames.Query)] + public class ExtensionA + { + public string Foo() => "abc"; + } - [ExtendObjectType(OperationTypeNames.Query)] - public class ExtensionB - { - public string Foo() => "def"; - } + [ExtendObjectType(OperationTypeNames.Query)] + public class ExtensionB + { + public string Foo() => "def"; + } - public class ObjectField_Test_Query - { - public string GetFoo() => null!; - } + public class ObjectField_Test_Query + { + public string GetFoo() => null!; + } - [ExtendObjectType(typeof(ObjectField_Test_Query))] - public class ObjectField_Test_Query_Extension - { - [BindMember(nameof(ObjectField_Test_Query.GetFoo))] - public string GetFoo1() => null!; - } + [ExtendObjectType(typeof(ObjectField_Test_Query))] + public class ObjectField_Test_Query_Extension + { + [BindMember(nameof(ObjectField_Test_Query.GetFoo))] + public string GetFoo1() => null!; + } - public class FooQueryType : ObjectType + public class FooQueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("sayHello").ResolveWith(t => t.SayHello()); - } + descriptor.Name("Query"); + descriptor.Field("sayHello").ResolveWith(t => t.SayHello()); } + } - public class FooBar - { - [Foo] - public string SayHello() => "Huhu"; - } + public class FooBar + { + [Foo] + public string SayHello() => "Huhu"; + } - public class FooAttribute : ObjectFieldDescriptorAttribute + public class FooAttribute : ObjectFieldDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IObjectFieldDescriptor descriptor, + MemberInfo member) { - public override void OnConfigure( - IDescriptorContext context, - IObjectFieldDescriptor descriptor, - MemberInfo member) + descriptor.Use(_ => ctx => { - descriptor.Use(_ => ctx => - { - ctx.Result = "Hello"; - return default; - }); - } + ctx.Result = "Hello"; + return default; + }); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeTests.cs index af939959047..19f00868dc9 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeTests.cs @@ -19,323 +19,323 @@ using Xunit; using Xunit.Sdk; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ObjectTypeTests : TypeTestBase { - public class ObjectTypeTests : TypeTestBase + [Fact] + public void ObjectType_DynamicName() { - [Fact] - public void ObjectType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn() - .Field("bar") - .Type() - .Resolve("foo")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - ObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void ObjectType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType)) - .Field("bar") - .Type() - .Resolve("foo")) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - ObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void GenericObjectType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - ObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void GenericObjectType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddObjectType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType))) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - ObjectType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } - - [Fact] - public void InitializeExplicitFieldWithImplicitResolver() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType(d => d - .Field(f => f.Description) - .Name("a"))); - - // assert - Assert.NotNull(fooType.Fields["a"].Resolver); - } - - [Fact] - public void IntArgumentIsInferredAsNonNullType() - { - // arrange - // act - ObjectType fooType = - CreateType(new ObjectType()); - - // assert - IType argumentType = fooType.Fields["bar"] - .Arguments.First() - .Type; - - Assert.NotNull(argumentType); - Assert.True(argumentType.IsNonNullType()); - Assert.Equal("Int", argumentType.NamedType().Name.Value); - } + // act + var schema = SchemaBuilder.New() + .AddObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn() + .Field("bar") + .Type() + .Resolve("foo")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public async Task FieldMiddlewareIsIntegrated() - { - // arrange - var resolverContext = new Mock(); - resolverContext.SetupAllProperties(); + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - // act - ObjectType fooType = CreateType(new ObjectType(c => c - .Name("Foo") - .Field("bar") - .Resolve(() => "baz")), - b => b.Use(next => async context => - { - await next(context); + [Fact] + public void ObjectType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType)) + .Field("bar") + .Type() + .Resolve("foo")) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - if (context.Result is string s) - { - context.Result = s.ToUpperInvariant(); - } - })); + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - // assert - await fooType.Fields["bar"].Middleware(resolverContext.Object); - Assert.Equal("BAZ", resolverContext.Object.Result); - } + [Fact] + public void GenericObjectType_DynamicName() + { + // act + var schema = SchemaBuilder.New() + .AddObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Obsolete("DeprecationReason is obsolete.")] - [Fact] - public void DeprecationReason_Obsolete() - { - // arrange - var resolverContext = new Mock(); - resolverContext.SetupAllProperties(); + [Fact] + public void GenericObjectType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddObjectType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType))) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - // act - ObjectType fooType = CreateType(new ObjectType(c => c - .Name("Foo") - .Field("bar") - .DeprecationReason("fooBar") - .Resolve(() => "baz"))); + [Fact] + public void InitializeExplicitFieldWithImplicitResolver() + { + // arrange + // act + var fooType = CreateType(new ObjectType(d => d + .Field(f => f.Description) + .Name("a"))); + + // assert + Assert.NotNull(fooType.Fields["a"].Resolver); + } - // assert - Assert.Equal("fooBar", fooType.Fields["bar"].DeprecationReason); - Assert.True(fooType.Fields["bar"].IsDeprecated); - } + [Fact] + public void IntArgumentIsInferredAsNonNullType() + { + // arrange + // act + var fooType = + CreateType(new ObjectType()); + + // assert + IType argumentType = fooType.Fields["bar"] + .Arguments.First() + .Type; + + Assert.NotNull(argumentType); + Assert.True(argumentType.IsNonNullType()); + Assert.Equal("Int", argumentType.NamedType().Name.Value); + } - [Fact] - public void Deprecated_Field_With_Reason() - { - // arrange - var resolverContext = new Mock(); - resolverContext.SetupAllProperties(); + [Fact] + public async Task FieldMiddlewareIsIntegrated() + { + // arrange + var resolverContext = new Mock(); + resolverContext.SetupAllProperties(); - // act - ObjectType fooType = CreateType(new ObjectType(c => c + // act + var fooType = CreateType(new ObjectType(c => c .Name("Foo") .Field("bar") - .Deprecated("fooBar") - .Resolve(() => "baz"))); - - // assert - Assert.Equal("fooBar", fooType.Fields["bar"].DeprecationReason); - Assert.True(fooType.Fields["bar"].IsDeprecated); - } - - [Fact] - public void Deprecated_Field_With_Reason_Is_Serialized() - { - // arrange - var resolverContext = new Mock(); - resolverContext.SetupAllProperties(); + .Resolve(() => "baz")), + b => b.Use(next => async context => + { + await next(context); - // act - ISchema schema = CreateSchema(new ObjectType(c => c - .Name("Foo") - .Field("bar") - .Deprecated("fooBar") - .Resolve(() => "baz"))); + if (context.Result is string s) + { + context.Result = s.ToUpperInvariant(); + } + })); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + await fooType.Fields["bar"].Middleware(resolverContext.Object); + Assert.Equal("BAZ", resolverContext.Object.Result); + } - [Fact] - public void Deprecated_Field_Without_Reason() - { - // arrange - var resolverContext = new Mock(); - resolverContext.SetupAllProperties(); + [Obsolete("DeprecationReason is obsolete.")] + [Fact] + public void DeprecationReason_Obsolete() + { + // arrange + var resolverContext = new Mock(); + resolverContext.SetupAllProperties(); + + // act + var fooType = CreateType(new ObjectType(c => c + .Name("Foo") + .Field("bar") + .DeprecationReason("fooBar") + .Resolve(() => "baz"))); + + // assert + Assert.Equal("fooBar", fooType.Fields["bar"].DeprecationReason); + Assert.True(fooType.Fields["bar"].IsDeprecated); + } - // act - ObjectType fooType = CreateType(new ObjectType(c => c - .Name("Foo") - .Field("bar") - .Deprecated() - .Resolve(() => "baz"))); - - // assert - Assert.Equal( - WellKnownDirectives.DeprecationDefaultReason, - fooType.Fields["bar"].DeprecationReason); - Assert.True(fooType.Fields["bar"].IsDeprecated); - } + [Fact] + public void Deprecated_Field_With_Reason() + { + // arrange + var resolverContext = new Mock(); + resolverContext.SetupAllProperties(); + + // act + var fooType = CreateType(new ObjectType(c => c + .Name("Foo") + .Field("bar") + .Deprecated("fooBar") + .Resolve(() => "baz"))); + + // assert + Assert.Equal("fooBar", fooType.Fields["bar"].DeprecationReason); + Assert.True(fooType.Fields["bar"].IsDeprecated); + } - [Fact] - public void Deprecated_Field_Without_Reason_Is_Serialized() - { - // arrange - var resolverContext = new Mock(); - resolverContext.SetupAllProperties(); + [Fact] + public void Deprecated_Field_With_Reason_Is_Serialized() + { + // arrange + var resolverContext = new Mock(); + resolverContext.SetupAllProperties(); + + // act + var schema = CreateSchema(new ObjectType(c => c + .Name("Foo") + .Field("bar") + .Deprecated("fooBar") + .Resolve(() => "baz"))); + + // assert + schema.ToString().MatchSnapshot(); + } - // act - ISchema schema = CreateSchema(new ObjectType(c => c - .Name("Foo") - .Field("bar") - .Deprecated() - .Resolve(() => "baz"))); + [Fact] + public void Deprecated_Field_Without_Reason() + { + // arrange + var resolverContext = new Mock(); + resolverContext.SetupAllProperties(); + + // act + var fooType = CreateType(new ObjectType(c => c + .Name("Foo") + .Field("bar") + .Deprecated() + .Resolve(() => "baz"))); + + // assert + Assert.Equal( + WellKnownDirectives.DeprecationDefaultReason, + fooType.Fields["bar"].DeprecationReason); + Assert.True(fooType.Fields["bar"].IsDeprecated); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Deprecated_Field_Without_Reason_Is_Serialized() + { + // arrange + var resolverContext = new Mock(); + resolverContext.SetupAllProperties(); + + // act + var schema = CreateSchema(new ObjectType(c => c + .Name("Foo") + .Field("bar") + .Deprecated() + .Resolve(() => "baz"))); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void InitializesImplicitFieldWithImplicitResolver() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType()); + [Fact] + public void InitializesImplicitFieldWithImplicitResolver() + { + // arrange + // act + var fooType = CreateType(new ObjectType()); - // assert - Assert.NotNull(fooType.Fields.First().Resolver); - } + // assert + Assert.NotNull(fooType.Fields.First().Resolver); + } - [Fact] - public void EnsureObjectTypeKindIsCorrect() - { - // arrange - // act - ObjectType someObject = CreateType(new ObjectType()); + [Fact] + public void EnsureObjectTypeKindIsCorrect() + { + // arrange + // act + var someObject = CreateType(new ObjectType()); - // assert - Assert.Equal(TypeKind.Object, someObject.Kind); - } + // assert + Assert.Equal(TypeKind.Object, someObject.Kind); + } - /// - /// For the type detection the order of the resolver or type descriptor function should not matter. - /// - /// descriptor.Field("test") - /// .Resolver{List{string}}(() => new List{string}()) - /// .Type{ListType{StringType}}(); - /// - /// descriptor.Field("test") - /// .Type{ListType{StringType}}(); - /// .Resolver{List{string}}(() => new List{string}()) - /// - [Fact] - public void ObjectTypeWithDynamicField_TypeDeclareOrderShouldNotMatter() - { - // act - FooType fooType = CreateType(new FooType()); + /// + /// For the type detection the order of the resolver or type descriptor function should not matter. + /// + /// descriptor.Field("test") + /// .Resolver{List{string}}(() => new List{string}()) + /// .Type{ListType{StringType}}(); + /// + /// descriptor.Field("test") + /// .Type{ListType{StringType}}(); + /// .Resolver{List{string}}(() => new List{string}()) + /// + [Fact] + public void ObjectTypeWithDynamicField_TypeDeclareOrderShouldNotMatter() + { + // act + var fooType = CreateType(new FooType()); - // assert - Assert.True(fooType.Fields.TryGetField("test", out ObjectField field)); - Assert.IsType(field.Type); - Assert.IsType(((ListType)field.Type).ElementType); - } + // assert + Assert.True(fooType.Fields.TryGetField("test", out var field)); + Assert.IsType(field.Type); + Assert.IsType(((ListType)field.Type).ElementType); + } - [Fact] - public void GenericObjectTypes() - { - // arrange - // act - ObjectType> genericType = - CreateType(new ObjectType>()); + [Fact] + public void GenericObjectTypes() + { + // arrange + // act + var genericType = + CreateType(new ObjectType>()); - // assert - Assert.Equal("GenericFooOfString", genericType.Name); - } + // assert + Assert.Equal("GenericFooOfString", genericType.Name); + } - [Fact] - public void NestedGenericObjectTypes() - { - // arrange - // act - ObjectType>> genericType = - CreateType(new ObjectType>>()); + [Fact] + public void NestedGenericObjectTypes() + { + // arrange + // act + var genericType = + CreateType(new ObjectType>>()); - // assert - Assert.Equal("GenericFooOfGenericFooOfString", genericType.Name); - } + // assert + Assert.Equal("GenericFooOfGenericFooOfString", genericType.Name); + } - [Fact] - public void BindFieldToResolverTypeField() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType(d => d - .Field(t => t.GetBar(default)))); - - // assert - Assert.Equal("foo", fooType.Fields["bar"].Arguments.First().Name); - Assert.NotNull(fooType.Fields["bar"].Resolver); - Assert.IsType(fooType.Fields["bar"].Type); - } + [Fact] + public void BindFieldToResolverTypeField() + { + // arrange + // act + var fooType = CreateType(new ObjectType(d => d + .Field(t => t.GetBar(default)))); + + // assert + Assert.Equal("foo", fooType.Fields["bar"].Arguments.First().Name); + Assert.NotNull(fooType.Fields["bar"].Resolver); + Assert.IsType(fooType.Fields["bar"].Type); + } - [Fact] - public void TwoInterfacesProvideFieldAWithDifferentOutputType() - { - // arrange - var source = @" + [Fact] + public void TwoInterfacesProvideFieldAWithDifferentOutputType() + { + // arrange + var source = @" interface A { a: String } @@ -348,28 +348,28 @@ type C implements A & B { a: String }"; - // act - try - { - SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - } - catch (SchemaException ex) - { - ex.Message.MatchSnapshot(); - return; - } - - Assert.True(false, "Schema exception was not thrown."); + // act + try + { + SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); } - - [Fact] - public void TwoInterfacesProvideFieldAWithDifferentArguments1() + catch (SchemaException ex) { - // arrange - var source = @" + ex.Message.MatchSnapshot(); + return; + } + + Assert.True(false, "Schema exception was not thrown."); + } + + [Fact] + public void TwoInterfacesProvideFieldAWithDifferentArguments1() + { + // arrange + var source = @" interface A { a(a: String): String } @@ -382,28 +382,28 @@ type C implements A & B { a(a: String): String }"; - // act - try - { - SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - } - catch (SchemaException ex) - { - ex.Message.MatchSnapshot(); - return; - } - - Assert.True(false, "Schema exception was not thrown."); + // act + try + { + SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); } - - [Fact] - public void TwoInterfacesProvideFieldAWithDifferentArguments2() + catch (SchemaException ex) { - // arrange - var source = @" + ex.Message.MatchSnapshot(); + return; + } + + Assert.True(false, "Schema exception was not thrown."); + } + + [Fact] + public void TwoInterfacesProvideFieldAWithDifferentArguments2() + { + // arrange + var source = @" interface A { a(a: String): String } @@ -416,28 +416,28 @@ type C implements A & B { a(a: String): String }"; - // act - try - { - SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - } - catch (SchemaException ex) - { - ex.Message.MatchSnapshot(); - return; - } - - Assert.True(false, "Schema exception was not thrown."); + // act + try + { + SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); } - - [Fact] - public void TwoInterfacesProvideFieldAWithDifferentArguments3() + catch (SchemaException ex) { - // arrange - var source = @" + ex.Message.MatchSnapshot(); + return; + } + + Assert.True(false, "Schema exception was not thrown."); + } + + [Fact] + public void TwoInterfacesProvideFieldAWithDifferentArguments3() + { + // arrange + var source = @" interface A { a(a: String): String } @@ -450,28 +450,28 @@ type C implements A & B { a(a: String): String }"; - // act - try - { - SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - } - catch (SchemaException ex) - { - ex.Message.MatchSnapshot(); - return; - } - - Assert.True(false, "Schema exception was not thrown."); + // act + try + { + SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); } - - [Fact] - public void SpecifyQueryTypeNameInSchemaFirst() + catch (SchemaException ex) { - // arrange - var source = @" + ex.Message.MatchSnapshot(); + return; + } + + Assert.True(false, "Schema exception was not thrown."); + } + + [Fact] + public void SpecifyQueryTypeNameInSchemaFirst() + { + // arrange + var source = @" type A { field: String } type B { field: String } type C { field: String } @@ -483,64 +483,64 @@ public void SpecifyQueryTypeNameInSchemaFirst() } "; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .Use(_ => _) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .Use(_ => _) + .Create(); - Assert.Equal("A", schema.QueryType.Name.Value); - Assert.Equal("B", schema.MutationType?.Name.Value); - Assert.Equal("C", schema.SubscriptionType?.Name.Value); - } + Assert.Equal("A", schema.QueryType.Name.Value); + Assert.Equal("B", schema.MutationType?.Name.Value); + Assert.Equal("C", schema.SubscriptionType?.Name.Value); + } - [Fact] - public void SpecifyQueryTypeNameInSchemaFirstWithOptions() - { - // arrange - var source = @" + [Fact] + public void SpecifyQueryTypeNameInSchemaFirstWithOptions() + { + // arrange + var source = @" type A { field: String } type B { field: String } type C { field: String }"; - // act - ISchema schema = SchemaBuilder.New() + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .Use(_ => _) + .ModifyOptions(o => + { + o.QueryTypeName = "A"; + o.MutationTypeName = "B"; + o.SubscriptionTypeName = "C"; + }) + .Create(); + + Assert.Equal("A", schema.QueryType.Name.Value); + Assert.Equal("B", schema.MutationType?.Name.Value); + Assert.Equal("C", schema.SubscriptionType?.Name.Value); + } + + [Fact] + public void NoQueryType() + { + // arrange + var source = @"type A { field: String }"; + + // act + void Action() + => SchemaBuilder.New() .AddDocumentFromString(source) .Use(_ => _) - .ModifyOptions(o => - { - o.QueryTypeName = "A"; - o.MutationTypeName = "B"; - o.SubscriptionTypeName = "C"; - }) .Create(); - Assert.Equal("A", schema.QueryType.Name.Value); - Assert.Equal("B", schema.MutationType?.Name.Value); - Assert.Equal("C", schema.SubscriptionType?.Name.Value); - } - - [Fact] - public void NoQueryType() - { - // arrange - var source = @"type A { field: String }"; - - // act - void Action() - => SchemaBuilder.New() - .AddDocumentFromString(source) - .Use(_ => _) - .Create(); - - Assert.Throws(Action).Errors.MatchSnapshot(); - } + Assert.Throws(Action).Errors.MatchSnapshot(); + } - [Fact] - public void ObjectFieldDoesNotMatchInterfaceDefinitionArgTypeInvalid() - { - // arrange - var source = @" + [Fact] + public void ObjectFieldDoesNotMatchInterfaceDefinitionArgTypeInvalid() + { + // arrange + var source = @" interface A { a(a: String): String } @@ -553,28 +553,28 @@ type C implements A & B { a(a: [String]): String }"; - // act - try - { - SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - } - catch (SchemaException ex) - { - ex.Message.MatchSnapshot(); - return; - } - - Assert.True(false, "Schema exception was not thrown."); + // act + try + { + SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); } - - [Fact] - public void ObjectFieldDoesNotMatchInterfaceDefinitionReturnTypeInvalid() + catch (SchemaException ex) { - // arrange - var source = @" + ex.Message.MatchSnapshot(); + return; + } + + Assert.True(false, "Schema exception was not thrown."); + } + + [Fact] + public void ObjectFieldDoesNotMatchInterfaceDefinitionReturnTypeInvalid() + { + // arrange + var source = @" interface A { a(a: String): String } @@ -587,28 +587,28 @@ type C implements A & B { a(a: String): Int }"; - // act - try - { - SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - } - catch (SchemaException ex) - { - ex.Message.MatchSnapshot(); - return; - } - - Assert.True(false, "Schema exception was not thrown."); + // act + try + { + SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); } - - [Fact] - public void ObjectTypeImplementsAllFields() + catch (SchemaException ex) { - // arrange - var source = @" + ex.Message.MatchSnapshot(); + return; + } + + Assert.True(false, "Schema exception was not thrown."); + } + + [Fact] + public void ObjectTypeImplementsAllFields() + { + // arrange + var source = @" interface A { a(a: String): String } @@ -626,22 +626,22 @@ type C implements A & B { } "; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); - // assert - ObjectType type = schema.GetType("C"); - Assert.Equal(2, type.Implements.Count); - } + // assert + var type = schema.GetType("C"); + Assert.Equal(2, type.Implements.Count); + } - [Fact] - public void ObjectTypeImplementsAllFieldsWithWrappedTypes() - { - // arrange - var source = @" + [Fact] + public void ObjectTypeImplementsAllFieldsWithWrappedTypes() + { + // arrange + var source = @" interface A { a(a: String!): String! } @@ -659,1569 +659,1568 @@ type C implements A & B { } "; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddResolver("C.a", _ => new("foo")) - .Create(); - - // assert - ObjectType type = schema.GetType("C"); - Assert.Equal(2, type.Implements.Count); - } + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddResolver("C.a", _ => new("foo")) + .Create(); - [Fact] - public void NonNullAttribute_StringIsRewritten_NonNullStringType() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType()); + // assert + var type = schema.GetType("C"); + Assert.Equal(2, type.Implements.Count); + } - // assert - Assert.True(fooType.Fields["baz"].Type.IsNonNullType()); - Assert.Equal("String", fooType.Fields["baz"].Type.NamedType().Name); - } + [Fact] + public void NonNullAttribute_StringIsRewritten_NonNullStringType() + { + // arrange + // act + var fooType = CreateType(new ObjectType()); - [Fact] - public void ObjectType_FieldDefaultValue_SerializesCorrectly() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve(() => "") - .Argument("_456", - a => a.Type>() - .DefaultValue(new Foo()))); + // assert + Assert.True(fooType.Fields["baz"].Type.IsNonNullType()); + Assert.Equal("String", fooType.Fields["baz"].Type.NamedType().Name); + } - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(objectType) - .Create(); + [Fact] + public void ObjectType_FieldDefaultValue_SerializesCorrectly() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve(() => "") + .Argument("_456", + a => a.Type>() + .DefaultValue(new Foo()))); + + // act + var schema = SchemaBuilder.New() + .AddQueryType(objectType) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void ObjectType_ResolverOverrides_FieldMember() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Resolve("World")); - [Fact] - public void ObjectType_ResolverOverrides_FieldMember() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Resolve("World")); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void ObjectType_FuncString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve(() => "fooBar")); + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_FuncString_ResolverInferType() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Resolve(() => "fooBar")); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_ConstantString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve("fooBar")); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_ConstantString_ResolverInferType() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Resolve("fooBar")); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_FuncCtxString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve(ctx => ctx.Selection.Field.Name.Value)); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_FuncCtxString_ResolverInferType() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Resolve(ctx => ctx.Selection.Field.Name.Value)); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_FuncCtxCtString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve((ctx, _) => ctx.Selection.Field.Name.Value)); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_FuncCtxCtString_ResolverInferType() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Resolve((ctx, _) => ctx.Selection.Field.Name.Value)); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_FuncObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve(() => (object)"fooBar")); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } - - [Fact] - public void ObjectType_ConstantObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve((object)"fooBar")); - - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); - - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectType_FuncString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve(() => "fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void ObjectType_FuncCtxObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve(ctx => (object)ctx.Selection.Field.Name.Value)); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + [Fact] + public void ObjectType_FuncString_ResolverInferType() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Resolve(() => "fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - [Fact] - public void ObjectType_FuncCtxCtObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Name("Bar") - .Field("_123") - .Type() - .Resolve((ctx, _) => (object)ctx.Selection.Field.Name.Value)); + [Fact] + public void ObjectType_ConstantString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve("fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // assert - executor.Execute("{ _123 }").ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectType_ConstantString_ResolverInferType() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Resolve("fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void ObjectTypeOfFoo_FuncString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve(() => "fooBar")); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + [Fact] + public void ObjectType_FuncCtxString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve(ctx => ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - [Fact] - public void ObjectTypeOfFoo_ConstantString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve("fooBar")); + [Fact] + public void ObjectType_FuncCtxString_ResolverInferType() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Resolve(ctx => ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectType_FuncCtxCtString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve((ctx, _) => ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void ObjectTypeOfFoo_FuncCtxString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve(ctx => ctx.Selection.Field.Name.Value)); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + [Fact] + public void ObjectType_FuncCtxCtString_ResolverInferType() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Resolve((ctx, _) => ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - [Fact] - public void ObjectTypeOfFoo_FuncCtxCtString_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve((ctx, _) => ctx.Selection.Field.Name.Value)); + [Fact] + public void ObjectType_FuncObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve(() => (object)"fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectType_ConstantObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve((object)"fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void ObjectTypeOfFoo_FuncObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve(() => (object)"fooBar")); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + [Fact] + public void ObjectType_FuncCtxObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve(ctx => (object)ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - [Fact] - public void ObjectTypeOfFoo_ConstantObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve((object)"fooBar")); + [Fact] + public void ObjectType_FuncCtxCtObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Name("Bar") + .Field("_123") + .Type() + .Resolve((ctx, _) => (object)ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + // assert + executor.Execute("{ _123 }").ToJson().MatchSnapshot(); + } - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectTypeOfFoo_FuncString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve(() => "fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void ObjectTypeOfFoo_FuncCtxObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve(ctx => (object)ctx.Selection.Field.Name.Value)); + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + [Fact] + public void ObjectTypeOfFoo_ConstantString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve("fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - [Fact] - public void ObjectTypeOfFoo_FuncCtxCtObject_Resolver() - { - // arrange - var objectType = new ObjectType(t => t - .Field(f => f.Description) - .Type() - .Resolve((ctx, _) => (object)ctx.Selection.Field.Name.Value)); + [Fact] + public void ObjectTypeOfFoo_FuncCtxString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve(ctx => ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // act - IRequestExecutor executor = - SchemaBuilder.New() - .AddQueryType(objectType) - .Create() - .MakeExecutable(); + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - // assert - executor.Execute("{ description }").ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectTypeOfFoo_FuncCtxCtString_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve((ctx, _) => ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public async Task ObjectType_SourceTypeObject_BindsResolverCorrectly() - { - // arrange - var objectType = new ObjectType(t => t.Name("Bar") - .Field(f => f.GetDescription(default)) - .Name("desc") - .Type()); + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - ISchema schema = SchemaBuilder.New() + [Fact] + public void ObjectTypeOfFoo_FuncObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve(() => (object)"fooBar")); + + // act + var executor = + SchemaBuilder.New() .AddQueryType(objectType) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); + .Create() + .MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("{ desc }") - .SetInitialValue(new Foo()) - .Create()); + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - // assert - result.ToJson().MatchSnapshot(); - } + [Fact] + public void ObjectTypeOfFoo_ConstantObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve((object)"fooBar")); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - [Fact] - public void InferInterfaceImplementation() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType(), - b => b.AddType(new InterfaceType())); - - // assert - Assert.IsType>( - fooType.Implements[0]); - } + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - [Fact] - public void IgnoreFieldWithShortcut() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType(d => - { - d.Ignore(t => t.Description); - d.Field("foo").Type().Resolve("abc"); - })); + [Fact] + public void ObjectTypeOfFoo_FuncCtxObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve(ctx => (object)ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - Assert.Collection( - fooType.Fields.Where(t => !t.IsIntrospectionField), - t => Assert.Equal("foo", t.Name)); - } + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - [Fact] - public void UnIgnoreFieldWithShortcut() - { - // arrange - // act - ObjectType fooType = CreateType(new ObjectType(d => - { - d.Ignore(t => t.Description); - d.Field("foo").Type().Resolve("abc"); - d.Field(t => t.Description).Ignore(false); - })); + [Fact] + public void ObjectTypeOfFoo_FuncCtxCtObject_Resolver() + { + // arrange + var objectType = new ObjectType(t => t + .Field(f => f.Description) + .Type() + .Resolve((ctx, _) => (object)ctx.Selection.Field.Name.Value)); + + // act + var executor = + SchemaBuilder.New() + .AddQueryType(objectType) + .Create() + .MakeExecutable(); - // assert - Assert.Collection( - fooType.Fields.Where(t => !t.IsIntrospectionField), - t => Assert.Equal("description", t.Name), - t => Assert.Equal("foo", t.Name)); - } + // assert + executor.Execute("{ description }").ToJson().MatchSnapshot(); + } - [Fact] - public void IgnoreField_DescriptorIsNull_ArgumentNullException() - { - // arrange - // act - void Action() => ObjectTypeDescriptorExtensions.Ignore(null, t => t.Description); + [Fact] + public async Task ObjectType_SourceTypeObject_BindsResolverCorrectly() + { + // arrange + var objectType = new ObjectType(t => t.Name("Bar") + .Field(f => f.GetDescription(default)) + .Name("desc") + .Type()); + + var schema = SchemaBuilder.New() + .AddQueryType(objectType) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("{ desc }") + .SetInitialValue(new Foo()) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void InferInterfaceImplementation() + { + // arrange + // act + var fooType = CreateType(new ObjectType(), + b => b.AddType(new InterfaceType())); + + // assert + Assert.IsType>( + fooType.Implements[0]); + } - [Fact] - public void IgnoreField_ExpressionIsNull_ArgumentNullException() - { - // arrange - var descriptor = new Mock>(); + [Fact] + public void IgnoreFieldWithShortcut() + { + // arrange + // act + var fooType = CreateType(new ObjectType(d => + { + d.Ignore(t => t.Description); + d.Field("foo").Type().Resolve("abc"); + })); + + // assert + Assert.Collection( + fooType.Fields.Where(t => !t.IsIntrospectionField), + t => Assert.Equal("foo", t.Name)); + } - // act - Action a = () => descriptor.Object.Ignore(null); + [Fact] + public void UnIgnoreFieldWithShortcut() + { + // arrange + // act + var fooType = CreateType(new ObjectType(d => + { + d.Ignore(t => t.Description); + d.Field("foo").Type().Resolve("abc"); + d.Field(t => t.Description).Ignore(false); + })); + + // assert + Assert.Collection( + fooType.Fields.Where(t => !t.IsIntrospectionField), + t => Assert.Equal("description", t.Name), + t => Assert.Equal("foo", t.Name)); + } - // assert - Assert.Throws(a); - } + [Fact] + public void IgnoreField_DescriptorIsNull_ArgumentNullException() + { + // arrange + // act + void Action() => ObjectTypeDescriptorExtensions.Ignore(null, t => t.Description); - [Fact] - public void DoNotAllow_InputTypes_OnFields() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddType(new ObjectType(t => t.Name("Foo") - .Field("bar") - .Type>>())) - .Create(); - - // assert - Assert.Throws(Action) - .Errors[0] - .Message.MatchSnapshot(); - } + // assert + Assert.Throws(Action); + } - [Fact] - public void DoNotAllow_DynamicInputTypes_OnFields() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddType(new ObjectType(t => t.Name("Foo") - .Field("bar") - .Type(new NonNullType(new InputObjectType())))) - .Create(); - - // assert - Assert.Throws(Action) - .Errors[0] - .Message.MatchSnapshot(); - } + [Fact] + public void IgnoreField_ExpressionIsNull_ArgumentNullException() + { + // arrange + var descriptor = new Mock>(); - [Fact] - public void Support_Argument_Attributes() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + // act + Action a = () => descriptor.Object.Ignore(null); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(a); + } - [Fact] - public void Argument_Type_IsInferred_From_Parameter() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Field(f => f.GetBar(1)) - .Argument("foo", a => a.DefaultValue(default))) + [Fact] + public void DoNotAllow_InputTypes_OnFields() + { + // arrange + // act + void Action() => + SchemaBuilder.New() + .AddType(new ObjectType(t => t.Name("Foo") + .Field("bar") + .Type>>())) .Create(); - // assert - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void Argument_Type_Cannot_Be_Inferred() - { - // arrange - // act - void Action() => - SchemaBuilder.New() - .AddQueryType(t => t.Field(f => f.GetBar(1)) - .Argument("bar", a => a.DefaultValue(default))) - .Create(); - - // assert - Assert.Throws(Action) - .Errors[0] - .Message.MatchSnapshot(); - } + // assert + Assert.Throws(Action) + .Errors[0] + .Message.MatchSnapshot(); + } - [Fact] - public void CreateObjectTypeWithXmlDocumentation() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() + [Fact] + public void DoNotAllow_DynamicInputTypes_OnFields() + { + // arrange + // act + void Action() => + SchemaBuilder.New() + .AddType(new ObjectType(t => t.Name("Foo") + .Field("bar") + .Type(new NonNullType(new InputObjectType())))) .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(Action) + .Errors[0] + .Message.MatchSnapshot(); + } - [Fact] - public void CreateObjectTypeWithXmlDocumentation_IgnoreXmlDocs() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .ModifyOptions(options => options.UseXmlDocumentation = false) - .Create(); + [Fact] + public void Support_Argument_Attributes() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Argument_Type_IsInferred_From_Parameter() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Field(f => f.GetBar(1)) + .Argument("foo", a => a.DefaultValue(default))) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void CreateObjectTypeWithXmlDocumentation_IgnoreXmlDocs_SchemaCreate() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .ModifyOptions(o => o.UseXmlDocumentation = false) + [Fact] + public void Argument_Type_Cannot_Be_Inferred() + { + // arrange + // act + void Action() => + SchemaBuilder.New() + .AddQueryType(t => t.Field(f => f.GetBar(1)) + .Argument("bar", a => a.DefaultValue(default))) .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + Assert.Throws(Action) + .Errors[0] + .Message.MatchSnapshot(); + } - [Fact] - public void Field_Is_Missing_Type_Throws_SchemaException() - { - // arrange - // act - Action action = () => SchemaBuilder.New() - .AddObjectType(t => t - .Name("abc") - .Field("def") - .Resolve((object)"ghi")) - .Create(); + [Fact] + public void CreateObjectTypeWithXmlDocumentation() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - Assert.Throws(action) - .Errors.Select(t => new { t.Message, t.Code }) - .MatchSnapshot(); - } + [Fact] + public void CreateObjectTypeWithXmlDocumentation_IgnoreXmlDocs() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .ModifyOptions(options => options.UseXmlDocumentation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Deprecate_Obsolete_Fields() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new ObjectType()) - .Create(); + [Fact] + public void CreateObjectTypeWithXmlDocumentation_IgnoreXmlDocs_SchemaCreate() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .ModifyOptions(o => o.UseXmlDocumentation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Field_Is_Missing_Type_Throws_SchemaException() + { + // arrange + // act + Action action = () => SchemaBuilder.New() + .AddObjectType(t => t + .Name("abc") + .Field("def") + .Resolve((object)"ghi")) + .Create(); + + // assert + Assert.Throws(action) + .Errors.Select(t => new { t.Message, t.Code }) + .MatchSnapshot(); + } - [Fact] - public void Deprecate_Fields_With_Deprecated_Attribute() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(c => c - .Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(new ObjectType()) - .Create(); + [Fact] + public void Deprecate_Obsolete_Fields() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new ObjectType()) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void ObjectType_From_Struct() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(new ObjectType()) - .Create(); + [Fact] + public void Deprecate_Fields_With_Deprecated_Attribute() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(c => c + .Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(new ObjectType()) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public async Task Execute_With_Query_As_Struct() - { - // arrange - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType(new ObjectType()) - .Create() - .MakeExecutable(); + [Fact] + public void ObjectType_From_Struct() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(new ObjectType()) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("{ bar baz }") - .SetInitialValue(new FooStruct { Qux = "Qux_Value", Baz = "Baz_Value" }) - .Create()); - // assert - result.ToJson().MatchSnapshot(); - } + [Fact] + public async Task Execute_With_Query_As_Struct() + { + // arrange + var executor = SchemaBuilder.New() + .AddQueryType(new ObjectType()) + .Create() + .MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("{ bar baz }") + .SetInitialValue(new FooStruct { Qux = "Qux_Value", Baz = "Baz_Value" }) + .Create()); + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public void ObjectType_From_Dictionary() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public void ObjectType_From_Dictionary() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert + // assert #if NETCOREAPP2_1 schema.ToString().MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1")); #else - schema.ToString().MatchSnapshot(); + schema.ToString().MatchSnapshot(); #endif - } + } - [Fact] - public void Infer_List_From_Queryable() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public void Infer_List_From_Queryable() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert + // assert #if NETCOREAPP2_1 schema.ToString().MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1")); #else - schema.ToString().MatchSnapshot(); + schema.ToString().MatchSnapshot(); #endif - } - - [Fact] - public void NonNull_Attribute_With_Explicit_Nullability_Definition() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void NonNull_Attribute_With_Explicit_Nullability_Definition() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Infer_Non_Null_Filed() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + [Fact] + public void Infer_Non_Null_Filed() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); - // assert + // assert #if NETCOREAPP2_1 schema.ToString().MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1")); #else - schema.ToString().MatchSnapshot(); + schema.ToString().MatchSnapshot(); #endif - } - - [Fact] - public void Ignore_Fields_With_GraphQLIgnoreAttribute() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void Declare_Resolver_With_Result_Type_String() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("test") - .Resolve( - _ => new ValueTask("abc"), - typeof(string))) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void Declare_Resolver_With_Result_Type_NativeTypeListOfInt() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("test") - .Resolve( - _ => new ValueTask("abc"), - typeof(NativeType>))) - .Create(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Ignore_Fields_With_GraphQLIgnoreAttribute() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Declare_Resolver_With_Result_Type_ListTypeOfIntType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("test") - .Resolve( - _ => new ValueTask("abc"), - typeof(ListType))) - .Create(); + [Fact] + public void Declare_Resolver_With_Result_Type_String() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("test") + .Resolve( + _ => new ValueTask("abc"), + typeof(string))) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Declare_Resolver_With_Result_Type_NativeTypeListOfInt() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("test") + .Resolve( + _ => new ValueTask("abc"), + typeof(NativeType>))) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void Declare_Resolver_With_Result_Type_Override_ListTypeOfIntType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("test") - .Type() - .Resolve( - _ => new ValueTask("abc"), - typeof(ListType))) - .Create(); + [Fact] + public void Declare_Resolver_With_Result_Type_ListTypeOfIntType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("test") + .Resolve( + _ => new ValueTask("abc"), + typeof(ListType))) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Declare_Resolver_With_Result_Type_Override_ListTypeOfIntType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("test") + .Type() + .Resolve( + _ => new ValueTask("abc"), + typeof(ListType))) + .Create(); - [Fact] - public void Declare_Resolver_With_Result_Type_Weak_Override_ListTypeOfIntType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("test") - .Type() - .Resolve(_ => new ValueTask("abc"), typeof(int))) - .Create(); + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Declare_Resolver_With_Result_Type_Weak_Override_ListTypeOfIntType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("test") + .Type() + .Resolve(_ => new ValueTask("abc"), typeof(int))) + .Create(); - [Fact] - public void Declare_Resolver_With_Result_Type_Is_Null() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType(t => t - .Name("Query") - .Field("test") - .Type() - .Resolve(_ => new ValueTask("abc"), null)) - .Create(); + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Declare_Resolver_With_Result_Type_Is_Null() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType(t => t + .Name("Query") + .Field("test") + .Type() + .Resolve(_ => new ValueTask("abc"), null)) + .Create(); - [Fact] - public void Infer_Argument_Default_Values() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); + // assert + schema.ToString().MatchSnapshot(); + } - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void Infer_Argument_Default_Values() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Obsolete] - [Fact] - public void Inferred_Interfaces_From_Type_Extensions_Are_Merged() - { - SchemaBuilder.New() - .AddDocumentFromString( - @"type Query { + [Obsolete] + [Fact] + public void Inferred_Interfaces_From_Type_Extensions_Are_Merged() + { + SchemaBuilder.New() + .AddDocumentFromString( + @"type Query { some: Some } type Some { foo: String }") - .AddType() - .Use(_ => _ => default) - .EnableRelaySupport() - .Create() - .ToString() - .MatchSnapshot(); - } + .AddType() + .Use(_ => _ => default) + .EnableRelaySupport() + .Create() + .ToString() + .MatchSnapshot(); + } - [Obsolete] - [Fact] - public void Interfaces_From_Type_Extensions_Are_Merged() - { - SchemaBuilder.New() - .AddDocumentFromString("type Query { some: Some } type Some { foo: String }") - .AddDocumentFromString("extend type Some implements Node { id: ID! }") - .Use(_ => _ => default) - .EnableRelaySupport() - .Create() - .ToString() - .MatchSnapshot(); - } + [Obsolete] + [Fact] + public void Interfaces_From_Type_Extensions_Are_Merged() + { + SchemaBuilder.New() + .AddDocumentFromString("type Query { some: Some } type Some { foo: String }") + .AddDocumentFromString("extend type Some implements Node { id: ID! }") + .Use(_ => _ => default) + .EnableRelaySupport() + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Nested_Lists_With_Sdl_First() - { - SchemaBuilder.New() - .AddDocumentFromString("type Query { some: [[Some]] } type Some { foo: String }") - .Use(_ => _ => default) - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void Nested_Lists_With_Sdl_First() + { + SchemaBuilder.New() + .AddDocumentFromString("type Query { some: [[Some]] } type Some { foo: String }") + .Use(_ => _ => default) + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Nested_Lists_With_Code_First() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void Nested_Lists_With_Code_First() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .ToString() + .MatchSnapshot(); + } - [Fact] - public void Execute_Nested_Lists_With_Code_First() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .Execute("{ fooMatrix { baz } }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void Execute_Nested_Lists_With_Code_First() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .Execute("{ fooMatrix { baz } }") + .ToJson() + .MatchSnapshot(); + } - [Fact] - public void ResolveWith() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .Execute("{ foo baz }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void ResolveWith() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .Execute("{ foo baz }") + .ToJson() + .MatchSnapshot(); + } - [Fact] - public void ResolveWithAsync() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .Execute("{ foo baz qux quux quuz }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void ResolveWithAsync() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .Execute("{ foo baz qux quux quuz }") + .ToJson() + .MatchSnapshot(); + } - [Fact] - public void ResolveWith_NonGeneric() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .MakeExecutable() - .Execute("{ foo }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void ResolveWith_NonGeneric() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .MakeExecutable() + .Execute("{ foo }") + .ToJson() + .MatchSnapshot(); + } - [Fact] - public void IgnoreIndexers() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void IgnoreIndexers() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void ObjectType_InObjectType_ThrowsSchemaException() - { - // arrange - // act - Exception ex = Record.Exception( - () => SchemaBuilder - .New() - .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) - .AddType>>() - .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) - .Create()); - - // assert - Assert.IsType(ex); - ex.Message.MatchSnapshot(); - } + [Fact] + public void ObjectType_InObjectType_ThrowsSchemaException() + { + // arrange + // act + var ex = Record.Exception( + () => SchemaBuilder + .New() + .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) + .AddType>>() + .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) + .Create()); + + // assert + Assert.IsType(ex); + ex.Message.MatchSnapshot(); + } - [Fact] - public void Specify_Field_Type_With_SDL_Syntax() - { - SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - d.Field("Foo").Type("String").Resolve(_ => null); - }) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Specify_Field_Type_With_SDL_Syntax() + { + SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + d.Field("Foo").Type("String").Resolve(_ => null); + }) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void Specify_Argument_Type_With_SDL_Syntax() - { - SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - d.Field("Foo") - .Argument("a", t => t.Type("Int")) - .Type("String") - .Resolve(_ => null); - }) - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Specify_Argument_Type_With_SDL_Syntax() + { + SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + d.Field("Foo") + .Argument("a", t => t.Type("Int")) + .Type("String") + .Resolve(_ => null); + }) + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public void Infer_Types_Correctly_When_Using_ResolveWith() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .Print() - .MatchSnapshot(); - } + [Fact] + public void Infer_Types_Correctly_When_Using_ResolveWith() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .Print() + .MatchSnapshot(); + } - [Fact] - public async Task Override_Instance_Check_With_Options() - { - Snapshot.FullName(); + [Fact] + public async Task Override_Instance_Check_With_Options() + { + Snapshot.FullName(); - var globalCheck = false; + var globalCheck = false; - await new ServiceCollection() - .AddGraphQL() - .ModifyOptions(o => o.DefaultIsOfTypeCheck = (objectType, context, value) => - { - globalCheck = true; - return true; - }) - .AddQueryType(t => t.Field("abc").Type("Foo").Resolve(new object())) - .AddInterfaceType(t => t.Name("Foo").Field("abc").Type("String")) - .AddObjectType(t => t.Name("Bar").Implements("Foo").Field("abc").Type("String").Resolve("abc")) - .ExecuteRequestAsync("{ abc { abc } }") - .MatchSnapshotAsync(); - - Assert.True(globalCheck); - } + await new ServiceCollection() + .AddGraphQL() + .ModifyOptions(o => o.DefaultIsOfTypeCheck = (objectType, context, value) => + { + globalCheck = true; + return true; + }) + .AddQueryType(t => t.Field("abc").Type("Foo").Resolve(new object())) + .AddInterfaceType(t => t.Name("Foo").Field("abc").Type("String")) + .AddObjectType(t => t.Name("Bar").Implements("Foo").Field("abc").Type("String").Resolve("abc")) + .ExecuteRequestAsync("{ abc { abc } }") + .MatchSnapshotAsync(); + + Assert.True(globalCheck); + } - [Fact] - public async Task AnotationBased_DeprecatedArgument_Should_BeDeprecated() - { - // arrangt - Snapshot.FullName(); + [Fact] + public async Task AnotationBased_DeprecatedArgument_Should_BeDeprecated() + { + // arrangt + Snapshot.FullName(); - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); - // assert - executor.Schema.Print().MatchSnapshot(); - } + // assert + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task AnotationBased_DeprecatedArgument_NonNullableIsDeprecated_Throw() - { - // arrange - Snapshot.FullName(); - - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // assert - SchemaException ex = await Assert.ThrowsAsync(call); - ex.Errors.Single().ToString().MatchSnapshot(); - } + [Fact] + public async Task AnotationBased_DeprecatedArgument_NonNullableIsDeprecated_Throw() + { + // arrange + Snapshot.FullName(); + + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // assert + var ex = await Assert.ThrowsAsync(call); + ex.Errors.Single().ToString().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DeprecatedArgument_Should_BeDeprecated() - { - // arrange - Snapshot.FullName(); - - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Field("foo") - .Argument("bar", x => x.Type().Deprecated("Is deprecated")) - .Resolve("")) - .BuildRequestExecutorAsync(); - - // assert - executor.Schema.Print().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_DeprecatedArgument_Should_BeDeprecated() + { + // arrange + Snapshot.FullName(); + + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Field("foo") + .Argument("bar", x => x.Type().Deprecated("Is deprecated")) + .Resolve("")) + .BuildRequestExecutorAsync(); + + // assert + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task CodeFirst_DeprecatedArgument_NonNullableIsDeprecated_Throw() - { - // arrange - Snapshot.FullName(); - - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddQueryType(x => x - .Field("foo") - .Argument( - "bar", - x => x.Type>().Deprecated("Is deprecated")) - .Resolve("")) - .BuildRequestExecutorAsync(); - - // assert - SchemaException ex = await Assert.ThrowsAsync(call); - ex.Errors.Single().ToString().MatchSnapshot(); - } + [Fact] + public async Task CodeFirst_DeprecatedArgument_NonNullableIsDeprecated_Throw() + { + // arrange + Snapshot.FullName(); + + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddQueryType(x => x + .Field("foo") + .Argument( + "bar", + x => x.Type>().Deprecated("Is deprecated")) + .Resolve("")) + .BuildRequestExecutorAsync(); + + // assert + var ex = await Assert.ThrowsAsync(call); + ex.Errors.Single().ToString().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DeprecatedArgument_Should_BeDeprecated() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task SchemaFirst_DeprecatedArgument_Should_BeDeprecated() + { + // arrange + Snapshot.FullName(); - // act - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(@" + // act + var executor = await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(@" type Query { foo(bar: String @deprecated(reason:""reason"")): Int! } ") - .AddResolver("Query", "foo", x => 1) - .BuildRequestExecutorAsync(); + .AddResolver("Query", "foo", x => 1) + .BuildRequestExecutorAsync(); - // assert - executor.Schema.Print().MatchSnapshot(); - } + // assert + executor.Schema.Print().MatchSnapshot(); + } - [Fact] - public async Task SchemaFirst_DeprecatedArgument_NonNullableIsDeprecated_Throw() - { - // arrange - Snapshot.FullName(); + [Fact] + public async Task SchemaFirst_DeprecatedArgument_NonNullableIsDeprecated_Throw() + { + // arrange + Snapshot.FullName(); - // act - Func call = async () => await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(@" + // act + Func call = async () => await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(@" type Query { foo(bar: String! @deprecated(reason:""reason"")): Int! } ") - .AddResolver("Query", "foo", x => 1) - .BuildRequestExecutorAsync(); + .AddResolver("Query", "foo", x => 1) + .BuildRequestExecutorAsync(); - // assert - SchemaException ex = await Assert.ThrowsAsync(call); - ex.Errors.Single().ToString().MatchSnapshot(); - } - - public class GenericFoo - { - public T Value { get; } - } - - public class Foo - : IFoo - { - public Foo() { } + // assert + var ex = await Assert.ThrowsAsync(call); + ex.Errors.Single().ToString().MatchSnapshot(); + } - public Foo(string description) - { - Description = description; - } + public class GenericFoo + { + public T Value { get; } + } - public string Description { get; } = "hello"; - } + public class Foo + : IFoo + { + public Foo() { } - public interface IFoo + public Foo(string description) { - string Description { get; } + Description = description; } - public class FooResolver - { - public string GetBar(string foo) => "hello foo"; + public string Description { get; } = "hello"; + } - public string GetDescription([Parent] Foo foo) => foo.Description; - } + public interface IFoo + { + string Description { get; } + } - public class QueryWithIntArg - { - public string GetBar(int foo) => "hello foo"; - } + public class FooResolver + { + public string GetBar(string foo) => "hello foo"; + + public string GetDescription([Parent] Foo foo) => foo.Description; + } + + public class QueryWithIntArg + { + public string GetBar(int foo) => "hello foo"; + } #nullable enable - public class Bar - { - [GraphQLNonNullType] - public string Baz { get; set; } = default!; - } + public class Bar + { + [GraphQLNonNullType] + public string Baz { get; set; } = default!; + } #nullable disable - public class Baz - { - public string Qux( - [GraphQLName("arg2")] [GraphQLDescription("argdesc")] [GraphQLNonNullType] - string arg) => arg; - - public string Quux([GraphQLType(typeof(ListType))] string arg) => arg; - } + public class Baz + { + public string Qux( + [GraphQLName("arg2")] [GraphQLDescription("argdesc")] [GraphQLNonNullType] + string arg) => arg; - public class FooType - : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Description); - descriptor.Field("test") - .Resolve(() => new List()) - .Type>(); - } - } + public string Quux([GraphQLType(typeof(ListType))] string arg) => arg; + } - public class FooObsolete + public class FooType + : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - [Obsolete("Baz")] - public string Bar() => "foo"; + descriptor.Field(t => t.Description); + descriptor.Field("test") + .Resolve(() => new List()) + .Type>(); } + } - public class FooIgnore - { - [GraphQLIgnore] - public string Bar() => "foo"; + public class FooObsolete + { + [Obsolete("Baz")] + public string Bar() => "foo"; + } - public string Baz() => "foo"; - } + public class FooIgnore + { + [GraphQLIgnore] + public string Bar() => "foo"; - public class FooDeprecated - { - [GraphQLDeprecated("Use Bar2.")] - public string Bar() => "foo"; + public string Baz() => "foo"; + } - public string Bar2() => "Foo 2: Electric foo-galoo"; - } + public class FooDeprecated + { + [GraphQLDeprecated("Use Bar2.")] + public string Bar() => "foo"; - public struct FooStruct - { - // should be ignored by the automatic field - // inference. - public string Qux; - - // should be included by the automatic field - // inference. - public string Baz { get; set; } - - // should be ignored by the automatic field - // inference since we cannot determine what object means - // in the graphql context. - // This field has to be included explicitly. - public object Quux { get; set; } - - // should be included by the automatic field - // inference. - public string GetBar() => Qux + "_Bar_Value"; - } + public string Bar2() => "Foo 2: Electric foo-galoo"; + } - public class FooWithDict - { - public Dictionary Map { get; set; } - } + public struct FooStruct + { + // should be ignored by the automatic field + // inference. + public string Qux; + + // should be included by the automatic field + // inference. + public string Baz { get; set; } + + // should be ignored by the automatic field + // inference since we cannot determine what object means + // in the graphql context. + // This field has to be included explicitly. + public object Quux { get; set; } + + // should be included by the automatic field + // inference. + public string GetBar() => Qux + "_Bar_Value"; + } - public class MyList - : MyListBase - { - } + public class FooWithDict + { + public Dictionary Map { get; set; } + } - public class MyListBase - : IQueryable - { - public Type ElementType => throw new NotImplementedException(); + public class MyList + : MyListBase + { + } - public Expression Expression => throw new NotImplementedException(); + public class MyListBase + : IQueryable + { + public Type ElementType => throw new NotImplementedException(); - public IQueryProvider Provider => throw new NotImplementedException(); + public Expression Expression => throw new NotImplementedException(); - public IEnumerator GetEnumerator() - { - throw new NotImplementedException(); - } + public IQueryProvider Provider => throw new NotImplementedException(); - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); } - public class MyListQuery + IEnumerator IEnumerable.GetEnumerator() { - public MyList List { get; set; } + throw new NotImplementedException(); } + } - public class FooWithNullable - { - public bool? Bar { get; set; } + public class MyListQuery + { + public MyList List { get; set; } + } - public List Bars { get; set; } - } + public class FooWithNullable + { + public bool? Bar { get; set; } - public class QueryWithArgumentDefaults - { - public string Field1( - string a = null, - string b = "abc") => null; + public List Bars { get; set; } + } - public string Field2( - [DefaultValue(null)] string a, - [DefaultValue("abc")] string b) => null; - } + public class QueryWithArgumentDefaults + { + public string Field1( + string a = null, + string b = "abc") => null; - [ExtendObjectType("Some")] - public class SomeTypeExtensionWithInterface : INode - { - [GraphQLType(typeof(NonNullType))] - public string Id { get; } - } + public string Field2( + [DefaultValue(null)] string a, + [DefaultValue("abc")] string b) => null; + } - public class QueryWithNestedList - { - public List> FooMatrix => - new() { new() { new() } }; - } + [ExtendObjectType("Some")] + public class SomeTypeExtensionWithInterface : INode + { + [GraphQLType(typeof(NonNullType))] + public string Id { get; } + } - public class ResolveWithQuery - { - public int Foo { get; set; } = 123; - } + public class QueryWithNestedList + { + public List> FooMatrix => + new() { new() { new() } }; + } - public class ResolveWithQueryResolver - { - public string Bar { get; set; } = "Bar"; + public class ResolveWithQuery + { + public int Foo { get; set; } = 123; + } - public Task FooAsync() => Task.FromResult("Foo"); + public class ResolveWithQueryResolver + { + public string Bar { get; set; } = "Bar"; - public Task BarAsync(IResolverContext context) - => Task.FromResult(context is not null); - } + public Task FooAsync() => Task.FromResult("Foo"); - public class ResolveWithQueryType : ObjectType + public Task BarAsync(IResolverContext context) + => Task.FromResult(context is not null); + } + + public class ResolveWithQueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Foo).ResolveWith(t => t.Bar); - descriptor.Field("baz").ResolveWith(t => t.Bar); - } + descriptor.Field(t => t.Foo).ResolveWith(t => t.Bar); + descriptor.Field("baz").ResolveWith(t => t.Bar); } + } - public class ResolveWithQueryTypeAsync : ObjectType + public class ResolveWithQueryTypeAsync : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Field(t => t.Foo).ResolveWith(t => t.FooAsync()); - descriptor.Field("baz").ResolveWith(t => t.FooAsync()); + descriptor.Field(t => t.Foo).ResolveWith(t => t.FooAsync()); + descriptor.Field("baz").ResolveWith(t => t.FooAsync()); - descriptor.Field("qux").ResolveWith(t => t.Bar); - descriptor.Field("quux").ResolveWith(t => t.FooAsync()); + descriptor.Field("qux").ResolveWith(t => t.Bar); + descriptor.Field("quux").ResolveWith(t => t.FooAsync()); - descriptor.Field("quuz").ResolveWith(t => t.BarAsync(default)); - } + descriptor.Field("quuz").ResolveWith(t => t.BarAsync(default)); } + } - public class ResolveWithNonGenericObjectType : ObjectType + public class ResolveWithNonGenericObjectType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - Type type = typeof(ResolveWithQuery); + var type = typeof(ResolveWithQuery); - descriptor.Name("ResolveWithQuery"); + descriptor.Name("ResolveWithQuery"); - descriptor.Field("foo") - .Type() - .ResolveWith(type.GetProperty("Foo")); - } + descriptor.Field("foo") + .Type() + .ResolveWith(type.GetProperty("Foo")); } + } - public class AnnotatedNestedList - { - [GraphQLNonNullType(true, false, false)] - public List> NestedList { get; set; } - } + public class AnnotatedNestedList + { + [GraphQLNonNullType(true, false, false)] + public List> NestedList { get; set; } + } - public class QueryWithIndexer + public class QueryWithIndexer + { + public string this[int i] { - public string this[int i] - { - get => throw new NotImplementedException(); - } - - public string GetFoo() => throw new NotImplementedException(); + get => throw new NotImplementedException(); } + public string GetFoo() => throw new NotImplementedException(); + } + #nullable enable - public class InferNonNullTypesWithResolveWith : ObjectType + public class InferNonNullTypesWithResolveWith : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); + descriptor.Name("Query"); - descriptor - .Field("foo") - .ResolveWith(t => t.Foo); + descriptor + .Field("foo") + .ResolveWith(t => t.Foo); - descriptor - .Field("bar") - .ResolveWith(t => t.Bar); - } + descriptor + .Field("bar") + .ResolveWith(t => t.Bar); } + } - public class InferNonNullTypesWithResolveWithResolvers - { - public string? Foo => "Foo"; + public class InferNonNullTypesWithResolveWithResolvers + { + public string? Foo => "Foo"; - public string Bar => "Bar"; - } + public string Bar => "Bar"; + } - public class QueryWithDeprecatedArguments - { - public string Field([GraphQLDeprecated("Not longer allowed")] string? deprecated) => ""; - } + public class QueryWithDeprecatedArguments + { + public string Field([GraphQLDeprecated("Not longer allowed")] string? deprecated) => ""; + } - public class QueryWithDeprecatedArgumentsIllegal - { - public string Field([GraphQLDeprecated("Not longer allowed")] int deprecated) => ""; - } + public class QueryWithDeprecatedArgumentsIllegal + { + public string Field([GraphQLDeprecated("Not longer allowed")] int deprecated) => ""; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/PaginationTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/PaginationTests.cs index 48ff41c2335..94f04a87137 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/PaginationTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/PaginationTests.cs @@ -9,26 +9,26 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class PaginationTests { - public class PaginationTests + [Fact(Skip = "Test is flaky")] + public async Task Execute_NestedOffsetPaging_NoCyclicDependencies() { - [Fact(Skip = "Test is flaky")] - public async Task Execute_NestedOffsetPaging_NoCyclicDependencies() + await TryTest(async ct => { - await TryTest(async ct => - { - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { DefaultPageSize = 50 }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(cancellationToken: ct); - - IExecutionResult executionResult = await executor - .ExecuteAsync(@" + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { DefaultPageSize = 50 }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(cancellationToken: ct); + + var executionResult = await executor + .ExecuteAsync(@" { users { items { @@ -40,28 +40,28 @@ await TryTest(async ct => } } }", - ct); + ct); - executionResult.ToJson().MatchSnapshot(); - }); - } + executionResult.ToJson().MatchSnapshot(); + }); + } - [Fact(Skip = "Flaky test.")] - public async Task Execute_NestedOffsetPaging_With_Indirect_Cycles() + [Fact(Skip = "Flaky test.")] + public async Task Execute_NestedOffsetPaging_With_Indirect_Cycles() + { + await TryTest(async ct => { - await TryTest(async ct => - { - IRequestExecutor executor = - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .SetPagingOptions(new PagingOptions { DefaultPageSize = 50 }) - .Services - .BuildServiceProvider() - .GetRequestExecutorAsync(cancellationToken: ct); - - IExecutionResult executionResult = await executor - .ExecuteAsync(@" + var executor = + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .SetPagingOptions(new PagingOptions { DefaultPageSize = 50 }) + .Services + .BuildServiceProvider() + .GetRequestExecutorAsync(cancellationToken: ct); + + var executionResult = await executor + .ExecuteAsync(@" { users { items { @@ -79,77 +79,76 @@ await TryTest(async ct => }", ct); - executionResult.ToJson().MatchSnapshot(); - }); - } + executionResult.ToJson().MatchSnapshot(); + }); + } - public class User - { - public string? FirstName { get; set; } + public class User + { + public string? FirstName { get; set; } - public List Parents { get; set; } = default!; + public List Parents { get; set; } = default!; - public List Groups { get; set; } = default!; - } + public List Groups { get; set; } = default!; + } - public class Group - { - public string? FirstName { get; set; } + public class Group + { + public string? FirstName { get; set; } - public List Members { get; set; } = default!; - } + public List Members { get; set; } = default!; + } - public class UserType : ObjectType + public class UserType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(i => i.Parents) - .UseOffsetPaging() - .Resolve(() => new[] - { - new User { FirstName = "Mother" }, - new User { FirstName = "Father" } - }); - - descriptor - .Field(i => i.Groups) - .UseOffsetPaging() - .Resolve(() => new[] - { - new Group { FirstName = "Admin" } - }); - } + descriptor + .Field(i => i.Parents) + .UseOffsetPaging() + .Resolve(() => new[] + { + new User { FirstName = "Mother" }, + new User { FirstName = "Father" } + }); + + descriptor + .Field(i => i.Groups) + .UseOffsetPaging() + .Resolve(() => new[] + { + new Group { FirstName = "Admin" } + }); } + } - public class GroupType : ObjectType + public class GroupType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(i => i.Members) - .UseOffsetPaging() - .Resolve(() => new[] - { - new User { FirstName = "Mother" }, - new User { FirstName = "Father" } - }); - } + descriptor + .Field(i => i.Members) + .UseOffsetPaging() + .Resolve(() => new[] + { + new User { FirstName = "Mother" }, + new User { FirstName = "Father" } + }); } + } - public class Query - { - public List Users => new() { new User() }; - } + public class Query + { + public List Users => new() { new User() }; + } - public class QueryType : ObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(t => t.Users) - .UseOffsetPaging(); - } + descriptor + .Field(t => t.Users) + .UseOffsetPaging(); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdAttributeTests.cs index 12a22e6741b..f27e8fcc239 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdAttributeTests.cs @@ -13,32 +13,32 @@ #nullable enable -namespace HotChocolate.Types.Relay +namespace HotChocolate.Types.Relay; + +public class IdAttributeTests { - public class IdAttributeTests + [Fact] + public async Task Id_On_Arguments() { - [Fact] - public async Task Id_On_Arguments() - { - // arrange - var idSerializer = new IdSerializer(); - var intId = idSerializer.Serialize("Query", 1); - var stringId = idSerializer.Serialize("Query", "abc"); - var guidId = idSerializer.Serialize( - "Query", - new Guid("26a2dc8f-4dab-408c-88c6-523a0a89a2b5")); - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery(@"query foo ( + // arrange + var idSerializer = new IdSerializer(); + var intId = idSerializer.Serialize("Query", 1); + var stringId = idSerializer.Serialize("Query", "abc"); + var guidId = idSerializer.Serialize( + "Query", + new Guid("26a2dc8f-4dab-408c-88c6-523a0a89a2b5")); + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery(@"query foo ( $intId: ID! $nullIntId: ID = null $stringId: ID! @@ -62,59 +62,59 @@ await SchemaBuilder.New() guidIdList(id: [$guidId $guidId]) nullableGuidIdList(id: [$guidId $nullGuidId $guidId]) }") - .SetVariableValue("intId", intId) - .SetVariableValue("stringId", stringId) - .SetVariableValue("guidId", guidId) - .Create()); + .SetVariableValue("intId", intId) + .SetVariableValue("stringId", stringId) + .SetVariableValue("guidId", guidId) + .Create()); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task InterceptedId_On_Arguments() - { - // arrange - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery(@"query foo { + [Fact] + public async Task InterceptedId_On_Arguments() + { + // arrange + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery(@"query foo { interceptedId(id: 1) interceptedIds(id: [1, 2]) }") - .Create()); + .Create()); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task Id_On_Objects() - { - // arrange - var idSerializer = new IdSerializer(); - var someId = idSerializer.Serialize("Some", "1"); - var someIntId = idSerializer.Serialize("Some", 1); - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo ($someId: ID! $someIntId: ID!) { + [Fact] + public async Task Id_On_Objects() + { + // arrange + var idSerializer = new IdSerializer(); + var someId = idSerializer.Serialize("Some", "1"); + var someIntId = idSerializer.Serialize("Some", 1); + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo ($someId: ID! $someIntId: ID!) { foo(input: { someId: $someId someIds: [$someIntId] someNullableId: $someId someNullableIds: [$someIntId] }) @@ -127,41 +127,41 @@ ... on FooPayload { } } }") - .SetVariableValue("someId", someId) - .SetVariableValue("someNullableId", null) - .SetVariableValue("someIntId", someIntId) - .SetVariableValue("someNullableIntId", null) - .Create()); - - // assert - new - { - result = result.ToJson(), - someId, - someIntId - }.MatchSnapshot(); - } + .SetVariableValue("someId", someId) + .SetVariableValue("someNullableId", null) + .SetVariableValue("someIntId", someIntId) + .SetVariableValue("someNullableIntId", null) + .Create()); - [Fact] - public async Task Id_On_Objects_Given_Nulls() + // assert + new { - // arrange - var idSerializer = new IdSerializer(); - var someId = idSerializer.Serialize("Some", "1"); - var someIntId = idSerializer.Serialize("Some", 1); - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo ( + result = result.ToJson(), + someId, + someIntId + }.MatchSnapshot(); + } + + [Fact] + public async Task Id_On_Objects_Given_Nulls() + { + // arrange + var idSerializer = new IdSerializer(); + var someId = idSerializer.Serialize("Some", "1"); + var someIntId = idSerializer.Serialize("Some", 1); + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo ( $someId: ID! $someIntId: ID! $someNullableId: ID $someNullableIntId: ID) { @@ -178,42 +178,42 @@ ... on FooPayload { } } }") - .SetVariableValue("someId", someId) - .SetVariableValue("someNullableId", null) - .SetVariableValue("someIntId", someIntId) - .SetVariableValue("someNullableIntId", null) - .Create()); - - // assert - new - { - result = result.ToJson(), - someId, - someIntId - }.MatchSnapshot(); - } + .SetVariableValue("someId", someId) + .SetVariableValue("someNullableId", null) + .SetVariableValue("someIntId", someIntId) + .SetVariableValue("someNullableIntId", null) + .Create()); - [Fact] - public async Task InterceptedId_On_Objects() + // assert + new { - // arrange - var idSerializer = new IdSerializer(); - var someId = idSerializer.Serialize("Some", "1"); - var someIntId = idSerializer.Serialize("Some", 1); - - IRequestExecutor executor = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable(); + result = result.ToJson(), + someId, + someIntId + }.MatchSnapshot(); + } - // act - IExecutionResult result = await executor - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo($someId: ID! $someIntId: ID!) { + [Fact] + public async Task InterceptedId_On_Objects() + { + // arrange + var idSerializer = new IdSerializer(); + var someId = idSerializer.Serialize("Some", "1"); + var someIntId = idSerializer.Serialize("Some", 1); + + var executor = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable(); + + // act + var result = await executor + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo($someId: ID! $someIntId: ID!) { foo(input: { someId: $someId someIds: [$someIntId] @@ -226,33 +226,33 @@ public async Task InterceptedId_On_Objects() interceptedIds } }") - .SetVariableValue("someId", someId) - .SetVariableValue("someIntId", someIntId) - .Create()); + .SetVariableValue("someId", someId) + .SetVariableValue("someIntId", someIntId) + .Create()); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task Id_On_Objects_InvalidType() - { - // arrange - var idSerializer = new IdSerializer(); - var someId = idSerializer.Serialize("Some", Guid.Empty); - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo ($someId: ID!) { + [Fact] + public async Task Id_On_Objects_InvalidType() + { + // arrange + var idSerializer = new IdSerializer(); + var someId = idSerializer.Serialize("Some", Guid.Empty); + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo ($someId: ID!) { foo(input: { someId: $someId someIds: [$someId] }) { someId ... on FooPayload { @@ -260,35 +260,35 @@ ... on FooPayload { } } }") - .SetVariableValue("someId", someId) - .Create()); - - // assert - new - { - result = result.ToJson(), - someId - }.MatchSnapshot(); - } + .SetVariableValue("someId", someId) + .Create()); - [Fact] - public async Task Id_On_Objects_InvalidId() + // assert + new { - // arrange - var someId = "abc"; - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo ($someId: ID!) { + result = result.ToJson(), + someId + }.MatchSnapshot(); + } + + [Fact] + public async Task Id_On_Objects_InvalidId() + { + // arrange + var someId = "abc"; + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo ($someId: ID!) { foo(input: { someId: $someId someIds: [$someId] }) { someId ... on FooPayload { @@ -296,231 +296,230 @@ ... on FooPayload { } } }") - .SetVariableValue("someId", someId) - .Create()); - - // assert - new - { - result = result.ToJson(), - someId - }.MatchSnapshot(); - } + .SetVariableValue("someId", someId) + .Create()); - [Fact] - public void Id_Type_Is_Correctly_Inferred() + // assert + new { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .ToString() - .MatchSnapshot(); - } + result = result.ToJson(), + someId + }.MatchSnapshot(); + } - [Fact] - public void EnsureIdIsOnlyAppliedOnce() - { - var inspector = new TestTypeInterceptor(); - - SchemaBuilder.New() - .AddQueryType(d => - { - d.Name("Query"); - d.Field("abc").ID().ID().ID().ID().Resolve("abc"); - }) - .AddGlobalObjectIdentification(false) - .TryAddTypeInterceptor(inspector) - .Create(); + [Fact] + public void Id_Type_Is_Correctly_Inferred() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .ToString() + .MatchSnapshot(); + } - Assert.Equal(1, inspector.Count); - } + [Fact] + public void EnsureIdIsOnlyAppliedOnce() + { + var inspector = new TestTypeInterceptor(); - [SuppressMessage("Performance", "CA1822:Mark members as static")] - public class Query - { - public string IntId([ID] int id) => id.ToString(); - public string IntIdList([ID] int[] id) => - string.Join(", ", id.Select(t => t.ToString())); - - public string NullableIntId([ID] int? id) => id?.ToString() ?? "null"; - public string NullableIntIdList([ID] int?[] id) => - string.Join(", ", id.Select(t => t?.ToString() ?? "null")); - - public string StringId([ID] string id) => id; - public string StringIdList([ID] string[] id) => - string.Join(", ", id.Select(t => t.ToString())); - - public string NullableStringId([ID] string? id) => id ?? "null"; - public string NullableStringIdList([ID] string?[] id) => - string.Join(", ", id.Select(t => t?.ToString() ?? "null")); - - public string GuidId([ID] Guid id) => id.ToString(); - public string GuidIdList([ID] IReadOnlyList id) => - string.Join(", ", id.Select(t => t.ToString())); - - public string NullableGuidId([ID] Guid? id) => id?.ToString() ?? "null"; - public string NullableGuidIdList([ID] IReadOnlyList id) => - string.Join(", ", id.Select(t => t?.ToString() ?? "null")); - - public string InterceptedId([InterceptedID] [ID] int id) => id.ToString(); - - public string InterceptedIds([InterceptedID] [ID] int[] id) => - string.Join(", ", id.Select(t => t.ToString())); - - public IFooPayload Foo(FooInput input) => - new FooPayload( - input.SomeId, - input.SomeNullableId, - input.SomeIds, - input.SomeNullableIds, - input.InterceptedId, - input.InterceptedIds); - } + SchemaBuilder.New() + .AddQueryType(d => + { + d.Name("Query"); + d.Field("abc").ID().ID().ID().ID().Resolve("abc"); + }) + .AddGlobalObjectIdentification(false) + .TryAddTypeInterceptor(inspector) + .Create(); + + Assert.Equal(1, inspector.Count); + } + + [SuppressMessage("Performance", "CA1822:Mark members as static")] + public class Query + { + public string IntId([ID] int id) => id.ToString(); + public string IntIdList([ID] int[] id) => + string.Join(", ", id.Select(t => t.ToString())); + + public string NullableIntId([ID] int? id) => id?.ToString() ?? "null"; + public string NullableIntIdList([ID] int?[] id) => + string.Join(", ", id.Select(t => t?.ToString() ?? "null")); + + public string StringId([ID] string id) => id; + public string StringIdList([ID] string[] id) => + string.Join(", ", id.Select(t => t.ToString())); + + public string NullableStringId([ID] string? id) => id ?? "null"; + public string NullableStringIdList([ID] string?[] id) => + string.Join(", ", id.Select(t => t?.ToString() ?? "null")); + + public string GuidId([ID] Guid id) => id.ToString(); + public string GuidIdList([ID] IReadOnlyList id) => + string.Join(", ", id.Select(t => t.ToString())); + + public string NullableGuidId([ID] Guid? id) => id?.ToString() ?? "null"; + public string NullableGuidIdList([ID] IReadOnlyList id) => + string.Join(", ", id.Select(t => t?.ToString() ?? "null")); + + public string InterceptedId([InterceptedID] [ID] int id) => id.ToString(); + + public string InterceptedIds([InterceptedID] [ID] int[] id) => + string.Join(", ", id.Select(t => t.ToString())); + + public IFooPayload Foo(FooInput input) => + new FooPayload( + input.SomeId, + input.SomeNullableId, + input.SomeIds, + input.SomeNullableIds, + input.InterceptedId, + input.InterceptedIds); + } - public class FooInput + public class FooInput + { + public FooInput( + string someId, + string? someNullableId, + IReadOnlyList someIds, + IReadOnlyList? someNullableIds, + int? interceptedId, + IReadOnlyList? interceptedIds) { - public FooInput( - string someId, - string? someNullableId, - IReadOnlyList someIds, - IReadOnlyList? someNullableIds, - int? interceptedId, - IReadOnlyList? interceptedIds) - { - SomeId = someId; - SomeNullableId = someNullableId; - SomeIds = someIds; - SomeNullableIds = someNullableIds; - InterceptedId = interceptedId; - InterceptedIds = interceptedIds; - } + SomeId = someId; + SomeNullableId = someNullableId; + SomeIds = someIds; + SomeNullableIds = someNullableIds; + InterceptedId = interceptedId; + InterceptedIds = interceptedIds; + } - [ID("Some")] public string SomeId { get; } + [ID("Some")] public string SomeId { get; } - [ID("Some")] public string? SomeNullableId { get; } + [ID("Some")] public string? SomeNullableId { get; } - [ID("Some")] public IReadOnlyList SomeIds { get; } + [ID("Some")] public IReadOnlyList SomeIds { get; } - [ID("Some")] public IReadOnlyList? SomeNullableIds { get; } + [ID("Some")] public IReadOnlyList? SomeNullableIds { get; } - [ID, InterceptedID] - public int? InterceptedId { get; } + [ID, InterceptedID] + public int? InterceptedId { get; } - [ID, InterceptedID] - public IReadOnlyList? InterceptedIds { get; } - } + [ID, InterceptedID] + public IReadOnlyList? InterceptedIds { get; } + } - public class FooPayload : IFooPayload + public class FooPayload : IFooPayload + { + public FooPayload( + string someId, + string? someNullableId, + IReadOnlyList someIds, + IReadOnlyList? someNullableIds, + int? interceptedId, + IReadOnlyList? interceptedIds) { - public FooPayload( - string someId, - string? someNullableId, - IReadOnlyList someIds, - IReadOnlyList? someNullableIds, - int? interceptedId, - IReadOnlyList? interceptedIds) - { - SomeId = someId; - SomeNullableId = someNullableId; - SomeIds = someIds; - SomeNullableIds = someNullableIds; - InterceptedId = interceptedId; - InterceptedIds = interceptedIds; - } + SomeId = someId; + SomeNullableId = someNullableId; + SomeIds = someIds; + SomeNullableIds = someNullableIds; + InterceptedId = interceptedId; + InterceptedIds = interceptedIds; + } - [ID("Bar")] public string SomeId { get; } + [ID("Bar")] public string SomeId { get; } - [ID("Bar")] public IReadOnlyList SomeIds { get; } + [ID("Bar")] public IReadOnlyList SomeIds { get; } - [ID("Bar")] public string? SomeNullableId { get; } + [ID("Bar")] public string? SomeNullableId { get; } - [ID("Bar")] public IReadOnlyList? SomeNullableIds { get; } + [ID("Bar")] public IReadOnlyList? SomeNullableIds { get; } - public int? InterceptedId { get; } + public int? InterceptedId { get; } - public IReadOnlyList? InterceptedIds { get; } + public IReadOnlyList? InterceptedIds { get; } - public string Raw => - $"{nameof(SomeId)}: {SomeId}, " + - $"{nameof(SomeIds)}: [{string.Join(", ", SomeIds)}], " + - $"{nameof(SomeNullableId)}: {SomeNullableId}, " + - $"{nameof(SomeNullableIds)}: [{string.Join(", ", SomeNullableIds ?? Array.Empty())}]" + - $"{nameof(InterceptedId)}: {InterceptedId}" + - $"{nameof(InterceptedIds)}: [{string.Join(", ", InterceptedIds ?? Array.Empty())}]"; - } + public string Raw => + $"{nameof(SomeId)}: {SomeId}, " + + $"{nameof(SomeIds)}: [{string.Join(", ", SomeIds)}], " + + $"{nameof(SomeNullableId)}: {SomeNullableId}, " + + $"{nameof(SomeNullableIds)}: [{string.Join(", ", SomeNullableIds ?? Array.Empty())}]" + + $"{nameof(InterceptedId)}: {InterceptedId}" + + $"{nameof(InterceptedIds)}: [{string.Join(", ", InterceptedIds ?? Array.Empty())}]"; + } - public interface IFooPayload - { - [ID] string SomeId { get; } + public interface IFooPayload + { + [ID] string SomeId { get; } - [ID] public string? SomeNullableId { get; } + [ID] public string? SomeNullableId { get; } - [ID] IReadOnlyList SomeIds { get; } + [ID] IReadOnlyList SomeIds { get; } - [ID] IReadOnlyList? SomeNullableIds { get; } + [ID] IReadOnlyList? SomeNullableIds { get; } - int? InterceptedId { get; } + int? InterceptedId { get; } - IReadOnlyList? InterceptedIds { get; } + IReadOnlyList? InterceptedIds { get; } - string Raw { get; } - } + string Raw { get; } + } - [AttributeUsage( - AttributeTargets.Parameter | - AttributeTargets.Property | - AttributeTargets.Method)] - public class InterceptedIDAttribute : DescriptorAttribute + [AttributeUsage( + AttributeTargets.Parameter | + AttributeTargets.Property | + AttributeTargets.Method)] + public class InterceptedIDAttribute : DescriptorAttribute + { + protected internal override void TryConfigure( + IDescriptorContext context, + IDescriptor descriptor, + ICustomAttributeProvider element) { - protected internal override void TryConfigure( - IDescriptorContext context, - IDescriptor descriptor, - ICustomAttributeProvider element) + switch (descriptor) { - switch (descriptor) - { - case IInputFieldDescriptor dc when element is PropertyInfo: - dc.Extend().OnBeforeCompletion((_, d) => AddInterceptingSerializer(d)); - break; - case IArgumentDescriptor dc when element is ParameterInfo: - dc.Extend().OnBeforeCompletion((_, d) => AddInterceptingSerializer(d)); - break; - } + case IInputFieldDescriptor dc when element is PropertyInfo: + dc.Extend().OnBeforeCompletion((_, d) => AddInterceptingSerializer(d)); + break; + case IArgumentDescriptor dc when element is ParameterInfo: + dc.Extend().OnBeforeCompletion((_, d) => AddInterceptingSerializer(d)); + break; } + } - private static void AddInterceptingSerializer(ArgumentDefinition definition) => - definition.Formatters.Insert(0, new InterceptingFormatter()); + private static void AddInterceptingSerializer(ArgumentDefinition definition) => + definition.Formatters.Insert(0, new InterceptingFormatter()); - private sealed class InterceptingFormatter : IInputValueFormatter - { - public object? OnAfterDeserialize(object? runtimeValue) => - runtimeValue is IEnumerable list - ? list - .Select(x => new IdValue("x", "y", int.Parse(x))) - .ToArray() - : new IdValue("x", "y", int.Parse((string)runtimeValue!)); - } + private sealed class InterceptingFormatter : IInputValueFormatter + { + public object? OnAfterDeserialize(object? runtimeValue) => + runtimeValue is IEnumerable list + ? list + .Select(x => new IdValue("x", "y", int.Parse(x))) + .ToArray() + : new IdValue("x", "y", int.Parse((string)runtimeValue!)); } + } - public class TestTypeInterceptor : TypeInterceptor - { - public int Count { get; set; } + public class TestTypeInterceptor : TypeInterceptor + { + public int Count { get; set; } - public override void OnValidateType( - ITypeSystemObjectContext validationContext, - DefinitionBase? definition, - IDictionary contextData) + public override void OnValidateType( + ITypeSystemObjectContext validationContext, + DefinitionBase? definition, + IDictionary contextData) + { + if (validationContext.Type.Name.Equals("Query") && + definition is ObjectTypeDefinition typeDef) { - if (validationContext.Type.Name.Equals("Query") && - definition is ObjectTypeDefinition typeDef) - { - Count = typeDef.Fields - .Single(t => t.Name.Equals("abc")) - .GetResultConverters() - .Count; - } + Count = typeDef.Fields + .Single(t => t.Name.Equals("abc")) + .GetResultConverters() + .Count; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdDescriptorTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdDescriptorTests.cs index 7514b18228b..6df562558d8 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdDescriptorTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdDescriptorTests.cs @@ -4,165 +4,164 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Relay +namespace HotChocolate.Types.Relay; + +public class IdDescriptorTests { - public class IdDescriptorTests + [Fact] + public async Task Id_On_Arguments() { - [Fact] - public async Task Id_On_Arguments() - { - // arrange - var idSerializer = new IdSerializer(); - var intId = idSerializer.Serialize("Query", 1); - var stringId = idSerializer.Serialize("Query", "abc"); - var guidId = idSerializer.Serialize("Query", Guid.Empty); - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo ($intId: ID! $stringId: ID! $guidId: ID!) { + // arrange + var idSerializer = new IdSerializer(); + var intId = idSerializer.Serialize("Query", 1); + var stringId = idSerializer.Serialize("Query", "abc"); + var guidId = idSerializer.Serialize("Query", Guid.Empty); + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo ($intId: ID! $stringId: ID! $guidId: ID!) { intId(id: $intId) stringId(id: $stringId) guidId(id: $guidId) }") - .SetVariableValue("intId", intId) - .SetVariableValue("stringId", stringId) - .SetVariableValue("guidId", guidId) - .Create()); + .SetVariableValue("intId", intId) + .SetVariableValue("stringId", stringId) + .SetVariableValue("guidId", guidId) + .Create()); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task Id_On_Objects() - { - // arrange - var idSerializer = new IdSerializer(); - var someId = idSerializer.Serialize("Some", 1); - - // act - IExecutionResult result = - await SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddGlobalObjectIdentification(false) - .Create() - .MakeExecutable() - .ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery( - @"query foo ($someId: ID!) { + [Fact] + public async Task Id_On_Objects() + { + // arrange + var idSerializer = new IdSerializer(); + var someId = idSerializer.Serialize("Some", 1); + + // act + var result = + await SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddGlobalObjectIdentification(false) + .Create() + .MakeExecutable() + .ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery( + @"query foo ($someId: ID!) { foo(input: { someId: $someId }) { someId } }") - .SetVariableValue("someId", someId) - .Create()); - - // assert - new - { - result = result.ToJson(), - someId - }.MatchSnapshot(); - } + .SetVariableValue("someId", someId) + .Create()); - [Fact] - public void Id_Type_Is_Correctly_Inferred() + // assert + new { - SchemaBuilder.New() - .AddQueryType() - .AddType() - .Create() - .ToString() - .MatchSnapshot(); - } + result = result.ToJson(), + someId + }.MatchSnapshot(); + } - public class QueryType : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field(t => t.IntId(default)) - .Argument("id", a => a.ID()); - - descriptor - .Field(t => t.StringId(default)) - .Argument("id", a => a.ID()); - - descriptor - .Field(t => t.GuidId(default)) - .Argument("id", a => a.ID()); - - descriptor - .Field(t => t.Foo(default)) - .Argument("input", a => a.Type()) - .Type(); - } - } + [Fact] + public void Id_Type_Is_Correctly_Inferred() + { + SchemaBuilder.New() + .AddQueryType() + .AddType() + .Create() + .ToString() + .MatchSnapshot(); + } - public class FooInputType : InputObjectType + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IInputObjectTypeDescriptor descriptor) - { - descriptor - .Field(t => t.SomeId) - .ID("Some"); - } + descriptor + .Field(t => t.IntId(default)) + .Argument("id", a => a.ID()); + + descriptor + .Field(t => t.StringId(default)) + .Argument("id", a => a.ID()); + + descriptor + .Field(t => t.GuidId(default)) + .Argument("id", a => a.ID()); + + descriptor + .Field(t => t.Foo(default)) + .Argument("input", a => a.Type()) + .Type(); } + } - public class FooPayloadType : ObjectType + public class FooInputType : InputObjectType + { + protected override void Configure(IInputObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor.Implements(); - - descriptor - .Field(t => t.SomeId) - .ID("Bar"); - } + descriptor + .Field(t => t.SomeId) + .ID("Some"); } + } - public class FooPayloadInterfaceType : InterfaceType + public class FooPayloadType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IInterfaceTypeDescriptor descriptor) - { - descriptor - .Field(t => t.SomeId) - .ID(); - } - } + descriptor.Implements(); - public class Query - { - public string IntId(int id) => id.ToString(); - public string StringId(string id) => id; - public string GuidId(Guid id) => id.ToString(); - public IFooPayload Foo(FooInput input) => new FooPayload { SomeId = input.SomeId }; + descriptor + .Field(t => t.SomeId) + .ID("Bar"); } + } - public class FooInput + public class FooPayloadInterfaceType : InterfaceType + { + protected override void Configure(IInterfaceTypeDescriptor descriptor) { - public string SomeId { get; set; } + descriptor + .Field(t => t.SomeId) + .ID(); } + } - public class FooPayload : IFooPayload - { - public string SomeId { get; set; } - } + public class Query + { + public string IntId(int id) => id.ToString(); + public string StringId(string id) => id; + public string GuidId(Guid id) => id.ToString(); + public IFooPayload Foo(FooInput input) => new FooPayload { SomeId = input.SomeId }; + } - public interface IFooPayload - { - string SomeId { get; set; } - } + public class FooInput + { + public string SomeId { get; set; } + } + + public class FooPayload : IFooPayload + { + public string SomeId { get; set; } + } + + public interface IFooPayload + { + string SomeId { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdMiddlewareTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdMiddlewareTests.cs index 046be51c939..9ea9b1212fb 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdMiddlewareTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdMiddlewareTests.cs @@ -3,34 +3,33 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Relay +namespace HotChocolate.Types.Relay; + +public class IdMiddlewareTests { - public class IdMiddlewareTests + [Fact] + public async Task ExecuteQueryThatReturnsId_IdShouldBeOpaque() { - [Fact] - public async Task ExecuteQueryThatReturnsId_IdShouldBeOpaque() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddGlobalObjectIdentification(false) - .Create(); + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .AddGlobalObjectIdentification(false) + .Create(); - IRequestExecutor executor = schema.MakeExecutable(); + var executor = schema.MakeExecutable(); - // act - IExecutionResult result = await executor.ExecuteAsync("{ id string }"); + // act + var result = await executor.ExecuteAsync("{ id string }"); - // assert - result.ToJson().MatchSnapshot(); - } + // assert + result.ToJson().MatchSnapshot(); + } - public class SomeQuery - { - [ID] - public string GetId() => "Hello"; + public class SomeQuery + { + [ID] + public string GetId() => "Hello"; - public string GetString() => "Hello"; - } + public string GetString() => "Hello"; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdSerializerTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdSerializerTests.cs index a11da1a5ff9..7b03df50ab2 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdSerializerTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/IdSerializerTests.cs @@ -2,211 +2,210 @@ using System.Text; using Xunit; -namespace HotChocolate.Types.Relay +namespace HotChocolate.Types.Relay; + +public class IdSerializerTests { - public class IdSerializerTests + [Fact] + public void Serialize_TypeNameIsEmpty_ArgumentException() + { + // arrange + var serializer = new IdSerializer(); + + // act + Action a = () => serializer.Serialize("", 123); + + // assert + Assert.Throws(a); + } + + [Fact] + public void Serialize_IdIsNull_Null() + { + // arrange + var serializer = new IdSerializer(); + + // act + var s = serializer.Serialize("Foo", default(object)); + + // assert + Assert.Null(s); + } + + [Fact] + public void Deserialize_SerializedIsNull_ArgumentNullException() + { + // arrange + var serializer = new IdSerializer(); + + // act + Action a = () => serializer.Deserialize(null); + + // assert + Assert.Throws(a); + } + + [Fact] + public void IsPossibleBase64String_sIsNull_ArgumentNullException() + { + // arrange + var serializer = new IdSerializer(); + + // act + Action a = () => IdSerializer.IsPossibleBase64String(null); + + // assert + Assert.Throws(a); + } + + [InlineData("123", "\0Bar\nFoo\nd123")] + [Theory] + public void SerializeIdValueWithSchemaName(object id, string expected) + { + // arrange + NameString schema = "Bar"; + NameString typeName = "Foo"; + var serializer = new IdSerializer(includeSchemaName: true); + + // act + var serializedId = serializer.Serialize(schema, typeName, id); + + // assert + var unwrapped = Encoding.UTF8.GetString( + Convert.FromBase64String(serializedId)); + Assert.Equal(expected, unwrapped); + } + + [InlineData("AEJhcgpGb28KZDEyMw==", "123", typeof(string))] + [Theory] + public void DeserializeIdValueWithSchemaName( + string serialized, object id, Type idType) + { + // arrange + var serializer = new IdSerializer(); + + // act + var value = serializer.Deserialize(serialized); + + // assert + Assert.IsType(idType, value.Value); + Assert.Equal(id, value.Value); + Assert.Equal("Foo", value.TypeName); + Assert.Equal("Bar", value.SchemaName); + } + + + [InlineData((short)123, "Foo\ns123")] + [InlineData(123, "Foo\ni123")] + [InlineData((long)123, "Foo\nl123")] + [InlineData("123456", "Foo\nd123456")] + [Theory] + public void SerializeIdValue(object id, string expected) + { + // arrange + NameString typeName = "Foo"; + var serializer = new IdSerializer(); + + // act + var serializedId = serializer.Serialize(typeName, id); + + // assert + var unwrapped = Encoding.UTF8.GetString( + Convert.FromBase64String(serializedId)); + Assert.Equal(expected, unwrapped); + } + + [Fact] + public void SerializeMaxLongIdValue() + { + // arrange + object id = long.MaxValue; + var expected = "Foo\nl" + id; + NameString typeName = "Foo"; + var serializer = new IdSerializer(); + + // act + var serializedId = serializer.Serialize(typeName, id); + + // assert + var unwrapped = Encoding.UTF8.GetString( + Convert.FromBase64String(serializedId)); + Assert.Equal(expected, unwrapped); + } + + + [Fact] + public void SerializeGuidValue() { - [Fact] - public void Serialize_TypeNameIsEmpty_ArgumentException() - { - // arrange - var serializer = new IdSerializer(); - - // act - Action a = () => serializer.Serialize("", 123); - - // assert - Assert.Throws(a); - } - - [Fact] - public void Serialize_IdIsNull_Null() - { - // arrange - var serializer = new IdSerializer(); - - // act - var s = serializer.Serialize("Foo", default(object)); - - // assert - Assert.Null(s); - } - - [Fact] - public void Deserialize_SerializedIsNull_ArgumentNullException() - { - // arrange - var serializer = new IdSerializer(); - - // act - Action a = () => serializer.Deserialize(null); - - // assert - Assert.Throws(a); - } - - [Fact] - public void IsPossibleBase64String_sIsNull_ArgumentNullException() - { - // arrange - var serializer = new IdSerializer(); - - // act - Action a = () => IdSerializer.IsPossibleBase64String(null); - - // assert - Assert.Throws(a); - } - - [InlineData("123", "\0Bar\nFoo\nd123")] - [Theory] - public void SerializeIdValueWithSchemaName(object id, string expected) - { - // arrange - NameString schema = "Bar"; - NameString typeName = "Foo"; - var serializer = new IdSerializer(includeSchemaName: true); - - // act - string serializedId = serializer.Serialize(schema, typeName, id); - - // assert - string unwrapped = Encoding.UTF8.GetString( - Convert.FromBase64String(serializedId)); - Assert.Equal(expected, unwrapped); - } - - [InlineData("AEJhcgpGb28KZDEyMw==", "123", typeof(string))] - [Theory] - public void DeserializeIdValueWithSchemaName( - string serialized, object id, Type idType) - { - // arrange - var serializer = new IdSerializer(); - - // act - IdValue value = serializer.Deserialize(serialized); - - // assert - Assert.IsType(idType, value.Value); - Assert.Equal(id, value.Value); - Assert.Equal("Foo", value.TypeName); - Assert.Equal("Bar", value.SchemaName); - } - - - [InlineData((short)123, "Foo\ns123")] - [InlineData(123, "Foo\ni123")] - [InlineData((long)123, "Foo\nl123")] - [InlineData("123456", "Foo\nd123456")] - [Theory] - public void SerializeIdValue(object id, string expected) - { - // arrange - NameString typeName = "Foo"; - var serializer = new IdSerializer(); - - // act - string serializedId = serializer.Serialize(typeName, id); - - // assert - string unwrapped = Encoding.UTF8.GetString( - Convert.FromBase64String(serializedId)); - Assert.Equal(expected, unwrapped); - } - - [Fact] - public void SerializeMaxLongIdValue() - { - // arrange - object id = long.MaxValue; - string expected = "Foo\nl" + id; - NameString typeName = "Foo"; - var serializer = new IdSerializer(); - - // act - string serializedId = serializer.Serialize(typeName, id); - - // assert - string unwrapped = Encoding.UTF8.GetString( - Convert.FromBase64String(serializedId)); - Assert.Equal(expected, unwrapped); - } - - - [Fact] - public void SerializeGuidValue() - { - // arrange - NameString typeName = "Foo"; - var id = new Guid("dad4f33d303345d7b7541d9ac23974d9"); - var serializer = new IdSerializer(); - - // act - string serializedId = serializer.Serialize(typeName, id); - - // assert - string unwrapped = Encoding.UTF8.GetString( - Convert.FromBase64String(serializedId)); - Assert.Equal("Foo\ngdad4f33d303345d7b7541d9ac23974d9", unwrapped); - } - - [InlineData("Rm9vCnMxMjM=", (short)123, typeof(short))] - [InlineData("Rm9vCmkxMjM=", 123, typeof(int))] - [InlineData("Rm9vCmwxMjM=", (long)123, typeof(long))] - [InlineData("Rm9vCmQxMjM0NTY=", "123456", typeof(string))] - [Theory] - public void DeserializeIdValue( - string serialized, object id, Type idType) - { - // arrange - var serializer = new IdSerializer(); - - // act - IdValue value = serializer.Deserialize(serialized); - - // assert - Assert.IsType(idType, value.Value); - Assert.Equal(id, value.Value); - Assert.Equal("Foo", value.TypeName); - } - - [Fact] - public void DeserializeGuidValue() - { - // arrange - var serialized = "Rm9vCmdkYWQ0ZjMzZDMwMzM0NWQ3Yjc1NDFkOWFjMjM5NzRkOQ=="; - var serializer = new IdSerializer(); - - // act - IdValue value = serializer.Deserialize(serialized); - - // assert - Assert.Equal( - new Guid("dad4f33d303345d7b7541d9ac23974d9"), - Assert.IsType(value.Value)); - Assert.Equal("Foo", value.TypeName); - } - - [InlineData("Rm9vLXN7===", false)] - [InlineData("Rm9vLXN7====", false)] - [InlineData("====", false)] - [InlineData("=Rm9=vLXN7AA", false)] - [InlineData("Rm9=vLXN7AA=", false)] - [InlineData("Rm9vLXN7AA==", true)] - [InlineData("Rm9vLWc989TaMzDXRbdUHZrCOXT", false)] - [InlineData("Rm9vLWc989TaMzDXRbdUHZrCOXTZ", true)] - [Theory] - public void IsPossibleBase64String(string serialized, bool valid) - { - // arrange - var serializer = new IdSerializer(); - - // act - bool result = IdSerializer.IsPossibleBase64String(serialized); - - // assert - Assert.Equal(valid, result); - } + // arrange + NameString typeName = "Foo"; + var id = new Guid("dad4f33d303345d7b7541d9ac23974d9"); + var serializer = new IdSerializer(); + + // act + var serializedId = serializer.Serialize(typeName, id); + + // assert + var unwrapped = Encoding.UTF8.GetString( + Convert.FromBase64String(serializedId)); + Assert.Equal("Foo\ngdad4f33d303345d7b7541d9ac23974d9", unwrapped); + } + + [InlineData("Rm9vCnMxMjM=", (short)123, typeof(short))] + [InlineData("Rm9vCmkxMjM=", 123, typeof(int))] + [InlineData("Rm9vCmwxMjM=", (long)123, typeof(long))] + [InlineData("Rm9vCmQxMjM0NTY=", "123456", typeof(string))] + [Theory] + public void DeserializeIdValue( + string serialized, object id, Type idType) + { + // arrange + var serializer = new IdSerializer(); + + // act + var value = serializer.Deserialize(serialized); + + // assert + Assert.IsType(idType, value.Value); + Assert.Equal(id, value.Value); + Assert.Equal("Foo", value.TypeName); + } + + [Fact] + public void DeserializeGuidValue() + { + // arrange + var serialized = "Rm9vCmdkYWQ0ZjMzZDMwMzM0NWQ3Yjc1NDFkOWFjMjM5NzRkOQ=="; + var serializer = new IdSerializer(); + + // act + var value = serializer.Deserialize(serialized); + + // assert + Assert.Equal( + new Guid("dad4f33d303345d7b7541d9ac23974d9"), + Assert.IsType(value.Value)); + Assert.Equal("Foo", value.TypeName); + } + + [InlineData("Rm9vLXN7===", false)] + [InlineData("Rm9vLXN7====", false)] + [InlineData("====", false)] + [InlineData("=Rm9=vLXN7AA", false)] + [InlineData("Rm9=vLXN7AA=", false)] + [InlineData("Rm9vLXN7AA==", true)] + [InlineData("Rm9vLWc989TaMzDXRbdUHZrCOXT", false)] + [InlineData("Rm9vLWc989TaMzDXRbdUHZrCOXTZ", true)] + [Theory] + public void IsPossibleBase64String(string serialized, bool valid) + { + // arrange + var serializer = new IdSerializer(); + + // act + var result = IdSerializer.IsPossibleBase64String(serialized); + + // assert + Assert.Equal(valid, result); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs index da949881827..4e961d20d2c 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs @@ -5,533 +5,532 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Relay +namespace HotChocolate.Types.Relay; + +public class NodeFieldSupportTests { - public class NodeFieldSupportTests - { - [Obsolete] - [Fact] - public async Task NodeId_Is_Correctly_Formatted() - { - // arrange - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddQueryType() - .AddObjectType(d => d - .AsNode() - .IdField(t => t.Id) - .NodeResolver((_, id) => Task.FromResult(new Bar { Id = id }))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ bar { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Obsolete] - [Fact] - public async Task Node_Type_Is_Correctly_In_Context() - { - // arrange - string type = null; - - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddQueryType() - .AddObjectType(d => d - .AsNode() - .IdField(t => t.Id) - .NodeResolver((_, id) => Task.FromResult(new Bar { Id = id }))) - .Use(next => async ctx => + [Obsolete] + [Fact] + public async Task NodeId_Is_Correctly_Formatted() + { + // arrange + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddQueryType() + .AddObjectType(d => d + .AsNode() + .IdField(t => t.Id) + .NodeResolver((_, id) => Task.FromResult(new Bar { Id = id }))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ bar { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Obsolete] + [Fact] + public async Task Node_Type_Is_Correctly_In_Context() + { + // arrange + string type = null; + + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddQueryType() + .AddObjectType(d => d + .AsNode() + .IdField(t => t.Id) + .NodeResolver((_, id) => Task.FromResult(new Bar { Id = id }))) + .Use(next => async ctx => + { + await next(ctx); + + if (ctx.LocalContextData.TryGetValue( + WellKnownContextData.InternalType, + out var value)) { - await next(ctx); - - if (ctx.LocalContextData.TryGetValue( - WellKnownContextData.InternalType, - out var value)) - { - type = (NameString)value; - } - }) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - Assert.Equal("Bar", type); - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Separated_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .AddObjectType(d => d - .ImplementsNode() - .IdField(t => t.Id) - .ResolveNodeWith(t => t.GetBarAsync(default))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Nodes_Get_Single() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .AddObjectType(d => d - .ImplementsNode() - .IdField(t => t.Id) - .ResolveNodeWith(t => t.GetBarAsync(default))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ nodes(ids: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Nodes_Get_Many() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .AddObjectType(d => d - .ImplementsNode() - .IdField(t => t.Id) - .ResolveNodeWith(t => t.GetBarAsync(default))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ nodes(ids: [\"QmFyCmQxMjM=\", \"QmFyCmQxMjM=\"]) { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Parent_Id() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType( - x => x.Name("Query") - .Field("childs") - .Resolve(new Child { Id = "123" })) - .AddObjectType(d => d - .ImplementsNode() - .IdField(t => t.Id) - .ResolveNode((_, id) => Task.FromResult(new Child { Id = id }))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ childs { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Separated_Resolver_ImplicitId() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .AddObjectType(d => d - .ImplementsNode() - .ResolveNodeWith(t => t.GetBarAsync(default))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - var json = result.ToJson(); - json.MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_Named_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_Inherited_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_External_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_ExternalInheritedStatic_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_ExternalInheritedInstance_Resolver() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_ExternalDefinedOnInterface_Resolver() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddSingleton() - .AddGraphQL() - .AddGlobalObjectIdentification() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Node_Resolve_Implicit_Custom_IdField() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddGlobalObjectIdentification() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"QmFyCmQxMjM=\") { id } }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - public class Foo - { - public Bar Bar { get; set; } = new() { Id = "123" }; - } - - public class Bar - { - public string Id { get; set; } - } - - public class BarResolver - { - public Task GetBarAsync(string id) => Task.FromResult(new Bar { Id = id }); - } - - public class Foo1 - { - public Bar1 Bar { get; set; } = new() { Id = "123" }; - } - - [ObjectType("Bar")] - [Node] - public class Bar1 - { - public string Id { get; set; } - - public static Bar1 GetBar1(string id) => new() { Id = id }; - } - - public class Foo2 - { - public Bar2 Bar { get; set; } = new() { Id = "123" }; - } - - [ObjectType("Bar")] - [Node(NodeResolver = nameof(GetFoo))] - public class Bar2 - { - public string Id { get; set; } - - public static Bar2 GetFoo(string id) => new() { Id = id }; - } - - public class Foo3 - { - public Bar3 Bar { get; set; } = new() { Id = "123" }; - } - - [ObjectType("Bar")] - [Node(NodeResolverType = typeof(Bar3Resolver))] - public class Bar3 - { - public string Id { get; set; } - } - - public static class Bar3Resolver - { - public static Bar3 GetBar3(string id) => new() { Id = id }; - } - - public class Foo4 - { - public Bar4 Bar { get; set; } = new() { Id1 = "123" }; - } - - [ObjectType("Bar")] - [Node( - IdField = nameof(Id1), - NodeResolver = nameof(GetFoo))] - public class Bar4 - { - public string Id1 { get; set; } - - public static Bar2 GetFoo(string id) => new() { Id = id }; - } - - [ObjectType("Bar")] - [Node] - public class Bar5 - { - public string Id { get; set; } - - public static Bar5 Get(string id) => new() { Id = id }; - } - - public class Foo6 - { - public Bar6 Bar { get; set; } = new() { Id = "123" }; - } - - public abstract class Bar6Base where T : Bar6Base, new() - { - public string Id { get; set; } - - public static T Get(string id) => new() { Id = id }; - } - - [ObjectType("Bar")] - [Node] - public class Bar6 : Bar6Base - { - } - - public class Foo7 - { - public Bar7 Bar { get; set; } = new() { Id = "123" }; - } - - [ObjectType("Bar")] - [Node(NodeResolverType = typeof(Bar7Resolver))] - public class Bar7 - { - public string Id { get; set; } - } - - public abstract class Bar7ResolverBase - { - public static Bar7 GetBar7(string id) => new() { Id = id }; - } - - public class Bar7Resolver : Bar7ResolverBase - { - } - - public class Foo8 - { - public Bar8 Bar { get; set; } = new() { Id = "123" }; - } - - [ObjectType("Bar")] - [Node(NodeResolverType = typeof(Bar8Resolver))] - public class Bar8 - { - public string Id { get; set; } - } - - public class Bar8ResolverBase - { - public Bar8 GetBar8(string id) => new() { Id = id }; - } - - public class Bar8Resolver : Bar8ResolverBase - { - } - - public class Foo9 - { - public Bar9 Bar { get; set; } = new() { Id = "123" }; - } - - [ObjectType("Bar")] - [Node(NodeResolverType = typeof(IBar9Resolver))] - public class Bar9 - { - public string Id { get; set; } - } - - public interface IBar9Resolver - { - public Bar9 GetBar9(string id); - } - - public class Bar9Resolver : IBar9Resolver - { - public Bar9 GetBar9(string id) => new() { Id = id }; - } - - public class Parent - { - public string Id { get; set; } - } - - public class Child : Parent - { - } + type = (NameString)value; + } + }) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + Assert.Equal("Bar", type); + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Separated_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .AddObjectType(d => d + .ImplementsNode() + .IdField(t => t.Id) + .ResolveNodeWith(t => t.GetBarAsync(default))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Nodes_Get_Single() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .AddObjectType(d => d + .ImplementsNode() + .IdField(t => t.Id) + .ResolveNodeWith(t => t.GetBarAsync(default))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ nodes(ids: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Nodes_Get_Many() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .AddObjectType(d => d + .ImplementsNode() + .IdField(t => t.Id) + .ResolveNodeWith(t => t.GetBarAsync(default))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ nodes(ids: [\"QmFyCmQxMjM=\", \"QmFyCmQxMjM=\"]) { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Parent_Id() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType( + x => x.Name("Query") + .Field("childs") + .Resolve(new Child { Id = "123" })) + .AddObjectType(d => d + .ImplementsNode() + .IdField(t => t.Id) + .ResolveNode((_, id) => Task.FromResult(new Child { Id = id }))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ childs { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Separated_Resolver_ImplicitId() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .AddObjectType(d => d + .ImplementsNode() + .ResolveNodeWith(t => t.GetBarAsync(default))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + var json = result.ToJson(); + json.MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_Named_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_Inherited_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_External_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_ExternalInheritedStatic_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_ExternalInheritedInstance_Resolver() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_ExternalDefinedOnInterface_Resolver() + { + // arrange + var executor = await new ServiceCollection() + .AddSingleton() + .AddGraphQL() + .AddGlobalObjectIdentification() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Node_Resolve_Implicit_Custom_IdField() + { + // arrange + var schema = SchemaBuilder.New() + .AddGlobalObjectIdentification() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"QmFyCmQxMjM=\") { id } }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + public class Foo + { + public Bar Bar { get; set; } = new() { Id = "123" }; + } + + public class Bar + { + public string Id { get; set; } + } + + public class BarResolver + { + public Task GetBarAsync(string id) => Task.FromResult(new Bar { Id = id }); + } + + public class Foo1 + { + public Bar1 Bar { get; set; } = new() { Id = "123" }; + } + + [ObjectType("Bar")] + [Node] + public class Bar1 + { + public string Id { get; set; } + + public static Bar1 GetBar1(string id) => new() { Id = id }; + } + + public class Foo2 + { + public Bar2 Bar { get; set; } = new() { Id = "123" }; + } + + [ObjectType("Bar")] + [Node(NodeResolver = nameof(GetFoo))] + public class Bar2 + { + public string Id { get; set; } + + public static Bar2 GetFoo(string id) => new() { Id = id }; + } + + public class Foo3 + { + public Bar3 Bar { get; set; } = new() { Id = "123" }; + } + + [ObjectType("Bar")] + [Node(NodeResolverType = typeof(Bar3Resolver))] + public class Bar3 + { + public string Id { get; set; } + } + + public static class Bar3Resolver + { + public static Bar3 GetBar3(string id) => new() { Id = id }; + } + + public class Foo4 + { + public Bar4 Bar { get; set; } = new() { Id1 = "123" }; + } + + [ObjectType("Bar")] + [Node( + IdField = nameof(Id1), + NodeResolver = nameof(GetFoo))] + public class Bar4 + { + public string Id1 { get; set; } + + public static Bar2 GetFoo(string id) => new() { Id = id }; + } + + [ObjectType("Bar")] + [Node] + public class Bar5 + { + public string Id { get; set; } + + public static Bar5 Get(string id) => new() { Id = id }; + } + + public class Foo6 + { + public Bar6 Bar { get; set; } = new() { Id = "123" }; + } + + public abstract class Bar6Base where T : Bar6Base, new() + { + public string Id { get; set; } + + public static T Get(string id) => new() { Id = id }; + } + + [ObjectType("Bar")] + [Node] + public class Bar6 : Bar6Base + { + } + + public class Foo7 + { + public Bar7 Bar { get; set; } = new() { Id = "123" }; + } + + [ObjectType("Bar")] + [Node(NodeResolverType = typeof(Bar7Resolver))] + public class Bar7 + { + public string Id { get; set; } + } + + public abstract class Bar7ResolverBase + { + public static Bar7 GetBar7(string id) => new() { Id = id }; + } + + public class Bar7Resolver : Bar7ResolverBase + { + } + + public class Foo8 + { + public Bar8 Bar { get; set; } = new() { Id = "123" }; + } + + [ObjectType("Bar")] + [Node(NodeResolverType = typeof(Bar8Resolver))] + public class Bar8 + { + public string Id { get; set; } + } + + public class Bar8ResolverBase + { + public Bar8 GetBar8(string id) => new() { Id = id }; + } + + public class Bar8Resolver : Bar8ResolverBase + { + } + + public class Foo9 + { + public Bar9 Bar { get; set; } = new() { Id = "123" }; + } + + [ObjectType("Bar")] + [Node(NodeResolverType = typeof(IBar9Resolver))] + public class Bar9 + { + public string Id { get; set; } + } + + public interface IBar9Resolver + { + public Bar9 GetBar9(string id); + } + + public class Bar9Resolver : IBar9Resolver + { + public Bar9 GetBar9(string id) => new() { Id = id }; + } + + public class Parent + { + public string Id { get; set; } + } + + public class Child : Parent + { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeResolverTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeResolverTests.cs index 2c2974e895d..092b7956117 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeResolverTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeResolverTests.cs @@ -8,301 +8,300 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class NodeResolverTests { - public class NodeResolverTests + [Obsolete] + [Fact] + public async Task NodeResolver_ResolveNode() { - [Obsolete] - [Fact] - public async Task NodeResolver_ResolveNode() - { - // arrange - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddType() - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"RW50aXR5CmRmb28=\") " + - "{ ... on Entity { id name } } }"); - - // assert - result.ToJson().MatchSnapshot(); - } + // arrange + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddType() + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"RW50aXR5CmRmb28=\") " + + "{ ... on Entity { id name } } }"); + + // assert + result.ToJson().MatchSnapshot(); + } - [Obsolete] - [Fact] - public async Task NodeResolver_ResolveNode_DynamicField() - { - // arrange - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddObjectType(d => - { - d.AsNode() - .NodeResolver((ctx, id) => - Task.FromResult(new Entity { Name = id })) - .Resolve(ctx => ctx.Parent().Id); - }) - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"RW50aXR5CmRmb28=\") " + - "{ ... on Entity { id name } } }"); - - // assert - result.ToJson().MatchSnapshot(); - } + [Obsolete] + [Fact] + public async Task NodeResolver_ResolveNode_DynamicField() + { + // arrange + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddObjectType(d => + { + d.AsNode() + .NodeResolver((ctx, id) => + Task.FromResult(new Entity { Name = id })) + .Resolve(ctx => ctx.Parent().Id); + }) + .AddQueryType() + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"RW50aXR5CmRmb28=\") " + + "{ ... on Entity { id name } } }"); + + // assert + result.ToJson().MatchSnapshot(); + } - [Obsolete] - [Fact] - public async Task NodeResolver_ResolveNode_DynamicFieldObject() - { - // arrange - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddObjectType(d => - { - d.AsNode() - .NodeResolver((ctx, id) => - Task.FromResult(new Entity { Name = (string)id })) - .Resolve(ctx => ctx.Parent().Id); - }) - .AddQueryType() - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"RW50aXR5CmRmb28=\") " + - "{ ... on Entity { id name } } }"); - - // assert - result.ToJson().MatchSnapshot(); - } + [Obsolete] + [Fact] + public async Task NodeResolver_ResolveNode_DynamicFieldObject() + { + // arrange + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddObjectType(d => + { + d.AsNode() + .NodeResolver((ctx, id) => + Task.FromResult(new Entity { Name = (string)id })) + .Resolve(ctx => ctx.Parent().Id); + }) + .AddQueryType() + .Create(); - [Obsolete] - [Fact] - public async Task NodeResolverObject_ResolveNode_DynamicField() - { - // arrange - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddObjectType(d => - { - d.Name("Entity"); - d.AsNode() - .NodeResolver((ctx, id) => - Task.FromResult(new Entity { Name = id })) - .Resolve(ctx => ctx.Parent().Id); - d.Field("name") - .Type() - .Resolve(t => t.Parent().Name); - }) - .AddQueryType(d => - { - d.Name("Query") - .Field("entity") - .Type(new NamedTypeNode("Entity")) - .Resolve(new Entity { Name = "foo" }); - }) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"RW50aXR5CmRmb28=\") " + - "{ ... on Entity { id name } } }"); - - // assert - result.ToJson().MatchSnapshot(); - } + var executor = schema.MakeExecutable(); - [Obsolete] - [Fact] - public async Task NodeResolverObject_ResolveNode_DynamicFieldObject() - { - // arrange - ISchema schema = SchemaBuilder.New() - .EnableRelaySupport() - .AddObjectType(d => - { - d.Name("Entity"); - d.AsNode() - .NodeResolver((ctx, id) => - Task.FromResult(new Entity { Name = (string)id })) - .Resolve(ctx => ctx.Parent().Id); - d.Field("name") - .Type() - .Resolve(t => t.Parent().Name); - }) - .AddQueryType(d => - { - d.Name("Query") - .Field("entity") - .Type(new NamedTypeNode("Entity")) - .Resolve(new Entity { Name = "foo" }); - }) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ node(id: \"RW50aXR5CmRmb28=\") " + - "{ ... on Entity { id name } } }"); - - // assert - result.ToJson().MatchSnapshot(); - } + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"RW50aXR5CmRmb28=\") " + + "{ ... on Entity { id name } } }"); - [Fact] - public async Task NodeAttribute_On_Extension() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task NodeAttribute_On_Extension2() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task NodeResolverObject_ResolveNode_DynamicField() + { + // arrange + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddObjectType(d => + { + d.Name("Entity"); + d.AsNode() + .NodeResolver((ctx, id) => + Task.FromResult(new Entity { Name = id })) + .Resolve(ctx => ctx.Parent().Id); + d.Field("name") + .Type() + .Resolve(t => t.Parent().Name); + }) + .AddQueryType(d => + { + d.Name("Query") + .Field("entity") + .Type(new NamedTypeNode("Entity")) + .Resolve(new Entity { Name = "foo" }); + }) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"RW50aXR5CmRmb28=\") " + + "{ ... on Entity { id name } } }"); + + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task NodeAttribute_On_Extension3() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task NodeResolverObject_ResolveNode_DynamicFieldObject() + { + // arrange + var schema = SchemaBuilder.New() + .EnableRelaySupport() + .AddObjectType(d => + { + d.Name("Entity"); + d.AsNode() + .NodeResolver((ctx, id) => + Task.FromResult(new Entity { Name = (string)id })) + .Resolve(ctx => ctx.Parent().Id); + d.Field("name") + .Type() + .Resolve(t => t.Parent().Name); + }) + .AddQueryType(d => + { + d.Name("Query") + .Field("entity") + .Type(new NamedTypeNode("Entity")) + .Resolve(new Entity { Name = "foo" }); + }) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ node(id: \"RW50aXR5CmRmb28=\") " + + "{ ... on Entity { id name } } }"); + + // assert + result.ToJson().MatchSnapshot(); + } - [Fact] - public async Task NodeAttribute_On_Extension4() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Fact] + public async Task NodeAttribute_On_Extension() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Obsolete] - [Fact] - public async Task NodeAttribute_On_Extension_Fetch_Through_Node_Field() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddTypeExtension() - .EnableRelaySupport() - .ExecuteRequestAsync( - @"{ + [Fact] + public async Task NodeAttribute_On_Extension2() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + [Fact] + public async Task NodeAttribute_On_Extension3() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + [Fact] + public async Task NodeAttribute_On_Extension4() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + [Obsolete] + [Fact] + public async Task NodeAttribute_On_Extension_Fetch_Through_Node_Field() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddTypeExtension() + .EnableRelaySupport() + .ExecuteRequestAsync( + @"{ node(id: ""RW50aXR5CmRhYmM="") { ... on Entity { name } } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - public class Query - { - public Entity GetEntity(string name) => new Entity { Name = name }; + public class Query + { + public Entity GetEntity(string name) => new Entity { Name = name }; - public Entity2 GetEntity2(string name) => new Entity2 { Name = name }; - } + public Entity2 GetEntity2(string name) => new Entity2 { Name = name }; + } - [Obsolete] - public class EntityType - : ObjectType + [Obsolete] + public class EntityType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.AsNode() - .IdField(t => t.Id) - .NodeResolver((ctx, id) => - Task.FromResult(new Entity { Name = id })); - } + descriptor.AsNode() + .IdField(t => t.Id) + .NodeResolver((ctx, id) => + Task.FromResult(new Entity { Name = id })); } + } - public class Entity - { - public string Id => Name; - public string Name { get; set; } - } + public class Entity + { + public string Id => Name; + public string Name { get; set; } + } - public class Entity2 - { - public string Id => Name; - public string Name { get; set; } + public class Entity2 + { + public string Id => Name; + public string Name { get; set; } - public static Entity2 Get(string id) => new() { Name = id }; - } + public static Entity2 Get(string id) => new() { Name = id }; + } - [Node] - [ExtendObjectType(typeof(Entity))] - public class EntityExtension - { - public static Entity GetEntity(string id) => new() { Name = id }; - } + [Node] + [ExtendObjectType(typeof(Entity))] + public class EntityExtension + { + public static Entity GetEntity(string id) => new() { Name = id }; + } - [Node] - [ExtendObjectType(typeof(Entity))] - public class EntityExtension2 - { - [NodeResolver] - public static Entity Foo(string id) => new() { Name = id }; - } + [Node] + [ExtendObjectType(typeof(Entity))] + public class EntityExtension2 + { + [NodeResolver] + public static Entity Foo(string id) => new() { Name = id }; + } - [Node] - [ExtendObjectType(typeof(Entity))] - public class EntityExtension3 - { - [NodeResolver] - public Entity Foo(string id) => new() { Name = id }; - } + [Node] + [ExtendObjectType(typeof(Entity))] + public class EntityExtension3 + { + [NodeResolver] + public Entity Foo(string id) => new() { Name = id }; + } - [Node] - [ExtendObjectType(typeof(Entity))] - public class EntityExtension4 - { - public Entity GetEntity(string id) => new() { Name = id }; - } + [Node] + [ExtendObjectType(typeof(Entity))] + public class EntityExtension4 + { + public Entity GetEntity(string id) => new() { Name = id }; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeTypeTests.cs index cdd5291c1aa..3020fda4e4e 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeTypeTests.cs @@ -1,37 +1,36 @@ using HotChocolate.Types.Relay; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class NodeTypeTests + : TypeTestBase { - public class NodeTypeTests - : TypeTestBase + [Fact] + public void InitializeExplicitFieldWithImplicitResolver() { - [Fact] - public void InitializeExplicitFieldWithImplicitResolver() - { - // arrange - // act - NodeType nodeInterface = CreateType( - new NodeType(), - b => b.ModifyOptions(o => o.StrictValidation = false)); + // arrange + // act + var nodeInterface = CreateType( + new NodeType(), + b => b.ModifyOptions(o => o.StrictValidation = false)); - // assert - Assert.Equal( - "Node", - nodeInterface.Name); + // assert + Assert.Equal( + "Node", + nodeInterface.Name); - Assert.Equal( - "The node interface is implemented by entities that have " + - "a global unique identifier.", - nodeInterface.Description); + Assert.Equal( + "The node interface is implemented by entities that have " + + "a global unique identifier.", + nodeInterface.Description); - Assert.Collection(nodeInterface.Fields, - t => - { - Assert.Equal("id", t.Name); - Assert.IsType( - Assert.IsType(t.Type).Type); - }); - } + Assert.Collection(nodeInterface.Fields, + t => + { + Assert.Equal("id", t.Name); + Assert.IsType( + Assert.IsType(t.Type).Type); + }); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/RelaySchemaTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/RelaySchemaTests.cs index ae7e6e79999..5b5a56bc37b 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Relay/RelaySchemaTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Relay/RelaySchemaTests.cs @@ -7,234 +7,233 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.Relay +namespace HotChocolate.Types.Relay; + +public class RelaySchemaTests { - public class RelaySchemaTests + [Obsolete] + [Fact] + public void EnableRelay_Node_Field_On_Query_Exists() { - [Obsolete] - [Fact] - public void EnableRelay_Node_Field_On_Query_Exists() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .EnableRelaySupport() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } - - [Obsolete] - [Fact] - public async Task EnableRelay_AddQueryToMutationPayloads() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .EnableRelaySupport() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [Obsolete] - [Fact] - public async Task EnableRelay_AddQueryToMutationPayloads_With_Extensions() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType(d => d.Name("Mutation")) - .AddTypeExtension() - .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task EnableRelay_AddQueryToMutationPayloads() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Obsolete] - [Fact] - public async Task EnableRelay_AddQueryToMutationPayloads_With_Different_FieldName() - { - Snapshot.FullName(); + [Obsolete] + [Fact] + public async Task EnableRelay_AddQueryToMutationPayloads_With_Extensions() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType(d => d.Name("Mutation")) + .AddTypeExtension() + .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .EnableRelaySupport(new RelayOptions - { - AddQueryFieldToMutationPayloads = true, - QueryFieldName = "rootQuery" - }) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task EnableRelay_AddQueryToMutationPayloads_With_Different_FieldName() + { + Snapshot.FullName(); - [Obsolete] - [Fact] - public async Task EnableRelay_AddQueryToMutationPayloads_With_Different_PayloadPredicate() - { - Snapshot.FullName(); + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .EnableRelaySupport(new RelayOptions + { + AddQueryFieldToMutationPayloads = true, + QueryFieldName = "rootQuery" + }) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .EnableRelaySupport(new RelayOptions - { - AddQueryFieldToMutationPayloads = true, - MutationPayloadPredicate = type => type.Name.Value.EndsWith("Result") - }) - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task EnableRelay_AddQueryToMutationPayloads_With_Different_PayloadPredicate() + { + Snapshot.FullName(); - [Obsolete] - [Fact] - public async Task EnableRelay_AddQueryToMutationPayloads_Refetch_SomeId() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) - .ExecuteRequestAsync("mutation { foo { query { some { id } } } }") - .MatchSnapshotAsync(); - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .EnableRelaySupport(new RelayOptions + { + AddQueryFieldToMutationPayloads = true, + MutationPayloadPredicate = type => type.Name.Value.EndsWith("Result") + }) + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } - [Obsolete] - [Fact] - public async Task EnableRelay_AddQueryToMutationPayloads_Refetch_SomeId_With_Query_Inst() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddMutationType() - .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) - .ExecuteRequestAsync("mutation { foo { query { some { id } } } }") - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task EnableRelay_AddQueryToMutationPayloads_Refetch_SomeId() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) + .ExecuteRequestAsync("mutation { foo { query { some { id } } } }") + .MatchSnapshotAsync(); + } - [Fact] - public async Task Relay_ShouldReturnNonNullError_When_IdIsNull() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType(d => d.Field("user") - .Type() - .Resolve(c => new User - { - Name = "TEST" - })) - .AddGlobalObjectIdentification() - .ExecuteRequestAsync("query { user { id name } } ") - .MatchSnapshotAsync(); - } + [Obsolete] + [Fact] + public async Task EnableRelay_AddQueryToMutationPayloads_Refetch_SomeId_With_Query_Inst() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddMutationType() + .EnableRelaySupport(new RelayOptions { AddQueryFieldToMutationPayloads = true }) + .ExecuteRequestAsync("mutation { foo { query { some { id } } } }") + .MatchSnapshotAsync(); + } - public class User - { - public string Id { get; set; } + [Fact] + public async Task Relay_ShouldReturnNonNullError_When_IdIsNull() + { + Snapshot.FullName(); - public string Name { get; set; } - } + await new ServiceCollection() + .AddGraphQL() + .AddQueryType(d => d.Field("user") + .Type() + .Resolve(c => new User + { + Name = "TEST" + })) + .AddGlobalObjectIdentification() + .ExecuteRequestAsync("query { user { id name } } ") + .MatchSnapshotAsync(); + } - public class UserType : ObjectType - { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .ImplementsNode() - .IdField(f => f.Id) - .ResolveNode(ResolveNode); - } + public class User + { + public string Id { get; set; } - private Task ResolveNode(IResolverContext context, string id) - { - return Task.FromResult(new User { Name = "TEST" }); - } - } + public string Name { get; set; } + } - public class QueryType : ObjectType + public class UserType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Field("some") - .Type() - .Resolve(new object()); - } + descriptor + .ImplementsNode() + .IdField(f => f.Id) + .ResolveNode(ResolveNode); } - public class SomeType : ObjectType + private Task ResolveNode(IResolverContext context, string id) { - protected override void Configure(IObjectTypeDescriptor descriptor) - { - descriptor - .Name("Some") - .ImplementsNode() - .ResolveNode((_, _) => Task.FromResult(new object())); - - descriptor - .Field("id") - .Type>() - .Resolve("bar"); - } + return Task.FromResult(new User { Name = "TEST" }); } + } - public class Query + public class QueryType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - public Some GetSome() => new(); + descriptor + .Field("some") + .Type() + .Resolve(new object()); } + } - [Node] - public class Some + public class SomeType : ObjectType + { + protected override void Configure(IObjectTypeDescriptor descriptor) { - public string Id => "some"; + descriptor + .Name("Some") + .ImplementsNode() + .ResolveNode((_, _) => Task.FromResult(new object())); - public static Some GetSome(string id) => new(); + descriptor + .Field("id") + .Type>() + .Resolve("bar"); } + } - public class Mutation - { - public FooPayload Foo() => new(); - } + public class Query + { + public Some GetSome() => new(); + } - public class Mutation2 - { - public BazPayload Baz() => new(); + [Node] + public class Some + { + public string Id => "some"; - public BarResult Bar() => new(); - } + public static Some GetSome(string id) => new(); + } - [ExtendObjectType("Mutation")] - public class MutationExtension - { - public FooPayload Foo() => new(); - } + public class Mutation + { + public FooPayload Foo() => new(); + } - public class FooPayload - { - } + public class Mutation2 + { + public BazPayload Baz() => new(); - public class BazPayload - { - public string Some { get; set; } - } + public BarResult Bar() => new(); + } - public class BarResult - { - } + [ExtendObjectType("Mutation")] + public class MutationExtension + { + public FooPayload Foo() => new(); + } + + public class FooPayload + { + } + + public class BazPayload + { + public string Some { get; set; } + } + + public class BarResult + { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/SDL/EnumTypeSchemaFirstTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/SDL/EnumTypeSchemaFirstTests.cs index 2e976463c22..9df905b3682 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/SDL/EnumTypeSchemaFirstTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/SDL/EnumTypeSchemaFirstTests.cs @@ -6,16 +6,16 @@ using System.Threading.Tasks; using Snapshooter; -namespace HotChocolate.Types.SDL +namespace HotChocolate.Types.SDL; + +public class EnumTypeSchemaFirstTests { - public class EnumTypeSchemaFirstTests + [Fact] + public void Declare_EnumType_With_Explicit_Value_Binding() { - [Fact] - public void Declare_EnumType_With_Explicit_Value_Binding() - { - // arrange - var sdl = - @"type Query { + // arrange + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -23,24 +23,24 @@ enum Greetings { GOOD @bind(to: ""GoodMorning"") }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .MakeExecutable() - .Execute("{ hello(greetings: GOOD) }") - .ToJson() - .MatchSnapshot(); - } - - [Fact] - public void Declare_EnumType_With_Implicit_Value_Binding() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .MakeExecutable() + .Execute("{ hello(greetings: GOOD) }") + .ToJson() + .MatchSnapshot(); + } + + [Fact] + public void Declare_EnumType_With_Implicit_Value_Binding() + { + // arrange + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -48,24 +48,24 @@ enum Greetings { GOOD_MORNING }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .MakeExecutable() - .Execute("{ hello(greetings: GOOD_MORNING) }") - .ToJson() - .MatchSnapshot(); - } - - [Fact] - public void Declare_EnumType_With_Type_Extension() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .MakeExecutable() + .Execute("{ hello(greetings: GOOD_MORNING) }") + .ToJson() + .MatchSnapshot(); + } + + [Fact] + public void Declare_EnumType_With_Type_Extension() + { + // arrange + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -77,26 +77,26 @@ extend enum Greetings { GOOD_EVENING }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .MakeExecutable() - .Execute("{ hello(greetings: GOOD_EVENING) }") - .ToJson() - .MatchSnapshot(); - } - - [Fact] - public async Task RequestBuilder_Declare_EnumType_With_Explicit_Value_Binding() - { - // arrange - Snapshot.FullName(); - - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .MakeExecutable() + .Execute("{ hello(greetings: GOOD_EVENING) }") + .ToJson() + .MatchSnapshot(); + } + + [Fact] + public async Task RequestBuilder_Declare_EnumType_With_Explicit_Value_Binding() + { + // arrange + Snapshot.FullName(); + + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -104,24 +104,24 @@ enum Greetings { GOOD @bind(to: ""GoodMorning"") }"; - // act - // assert - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .ExecuteRequestAsync("{ hello(greetings: GOOD) }") - .MatchSnapshotAsync(); - } - - [Fact] - public async Task RequestBuilder_Declare_EnumType_With_Implicit_Value_Binding() - { - // arrange - Snapshot.FullName(); - - var sdl = - @"type Query { + // act + // assert + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .ExecuteRequestAsync("{ hello(greetings: GOOD) }") + .MatchSnapshotAsync(); + } + + [Fact] + public async Task RequestBuilder_Declare_EnumType_With_Implicit_Value_Binding() + { + // arrange + Snapshot.FullName(); + + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -129,24 +129,24 @@ enum Greetings { GOOD_MORNING }"; - // act - // assert - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .ExecuteRequestAsync("{ hello(greetings: GOOD_MORNING) }") - .MatchSnapshotAsync(); - } - - [Fact] - public async Task RequestBuilder_Declare_EnumType_With_Type_Extension() - { - // arrange - Snapshot.FullName(); - - var sdl = - @"type Query { + // act + // assert + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .ExecuteRequestAsync("{ hello(greetings: GOOD_MORNING) }") + .MatchSnapshotAsync(); + } + + [Fact] + public async Task RequestBuilder_Declare_EnumType_With_Type_Extension() + { + // arrange + Snapshot.FullName(); + + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -158,27 +158,27 @@ extend enum Greetings { GOOD_EVENING }"; - // act - // assert - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .ExecuteRequestAsync("{ hello(greetings: GOOD_EVENING) }") - .MatchSnapshotAsync(); - } - - // https://github.com/ChilliCream/hotchocolate/issues/833 - [InlineData("GOOD_EVENING")] - [InlineData("GOODEVENING")] - [Theory] - public async Task Try_Using_A_Enum_Value_That_Is_Not_Bound(string value) - { - // arrange - Snapshot.FullName(new SnapshotNameExtension(value)); - - var sdl = - @"type Query { + // act + // assert + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .ExecuteRequestAsync("{ hello(greetings: GOOD_EVENING) }") + .MatchSnapshotAsync(); + } + + // https://github.com/ChilliCream/hotchocolate/issues/833 + [InlineData("GOOD_EVENING")] + [InlineData("GOODEVENING")] + [Theory] + public async Task Try_Using_A_Enum_Value_That_Is_Not_Bound(string value) + { + // arrange + Snapshot.FullName(new SnapshotNameExtension(value)); + + var sdl = + @"type Query { hello(greetings: Greetings): Greetings } @@ -186,26 +186,25 @@ enum Greetings { GOOD_MORNING }"; - // act - // assert - await new ServiceCollection() - .AddGraphQL() - .AddDocumentFromString(sdl) - .AddResolver() - .BindRuntimeType() - .ExecuteRequestAsync($"{{ hello(greetings: \"{value}\") }}") - .MatchSnapshotAsync(); - } - - public class Query - { - public Greetings Hello(Greetings greetings) => greetings; - } - - public enum Greetings - { - GoodMorning, - GoodEvening - } + // act + // assert + await new ServiceCollection() + .AddGraphQL() + .AddDocumentFromString(sdl) + .AddResolver() + .BindRuntimeType() + .ExecuteRequestAsync($"{{ hello(greetings: \"{value}\") }}") + .MatchSnapshotAsync(); + } + + public class Query + { + public Greetings Hello(Greetings greetings) => greetings; + } + + public enum Greetings + { + GoodMorning, + GoodEvening } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/SDL/InputObjectTypeSchemaFirstTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/SDL/InputObjectTypeSchemaFirstTests.cs index 334c4cd1e4d..36d60dc975d 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/SDL/InputObjectTypeSchemaFirstTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/SDL/InputObjectTypeSchemaFirstTests.cs @@ -1,16 +1,16 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.SDL +namespace HotChocolate.Types.SDL; + +public class InputObjectTypeSchemaFirstTests { - public class InputObjectTypeSchemaFirstTests + [Fact] + public void Declare_Simple_Input_Type() { - [Fact] - public void Declare_Simple_Input_Type() - { - // arrange - var sdl = - @"type Query { + // arrange + var sdl = + @"type Query { hello(input: HelloInput): String } @@ -18,22 +18,22 @@ input HelloInput { hello: String }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Declare_Input_Type_With_Type_Extension() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Declare_Input_Type_With_Type_Extension() + { + // arrange + var sdl = + @"type Query { hello(input: HelloInput): String } @@ -45,22 +45,22 @@ extend input HelloInput { world: String }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Field() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Field() + { + // arrange + var sdl = + @"type Query { hello(input: HelloInput): String } @@ -74,22 +74,22 @@ extend input HelloInput { directive @foo on INPUT_FIELD_DEFINITION"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Type() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Type() + { + // arrange + var sdl = + @"type Query { hello(input: HelloInput): String } @@ -101,25 +101,24 @@ extend input HelloInput @foo directive @foo on INPUT_OBJECT"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - public class Query - { - public string Hello(HelloInput input) => "Hello"; - } - - public class HelloInput - { - public string Hello { get; set; } - public string World { get; set; } - } + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + public class Query + { + public string Hello(HelloInput input) => "Hello"; + } + + public class HelloInput + { + public string Hello { get; set; } + public string World { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/SDL/ObjectTypeSchemaFirstTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/SDL/ObjectTypeSchemaFirstTests.cs index a5c8c07bde9..7cfd6e44ba7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/SDL/ObjectTypeSchemaFirstTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/SDL/ObjectTypeSchemaFirstTests.cs @@ -1,35 +1,35 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types.SDL +namespace HotChocolate.Types.SDL; + +public class ObjectTypeSchemaFirstTests { - public class ObjectTypeSchemaFirstTests + [Fact] + public void Declare_Simple_Query_Type() { - [Fact] - public void Declare_Simple_Query_Type() - { - // arrange - var sdl = - @"type Query { + // arrange + var sdl = + @"type Query { hello: String }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Declare_Query_Type_With_Type_Extension() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Declare_Query_Type_With_Type_Extension() + { + // arrange + var sdl = + @"type Query { hello: String } @@ -37,22 +37,22 @@ extend type Query { world: String }"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Field() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Field() + { + // arrange + var sdl = + @"type Query { hello: String } @@ -62,22 +62,22 @@ extend type Query { directive @foo on FIELD_DEFINITION"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - [Fact] - public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Type() - { - // arrange - var sdl = - @"type Query { + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + [Fact] + public void Declare_Query_Type_With_Type_Extension_Add_Directive_To_Type() + { + // arrange + var sdl = + @"type Query { hello: String } @@ -85,21 +85,20 @@ extend type Query @foo directive @foo on OBJECT"; - // act - // assert - SchemaBuilder.New() - .AddDocumentFromString(sdl) - .BindRuntimeType() - .Create() - .Print() - .MatchSnapshot(); - } - - public class Query - { - public string Hello() => "Hello"; - - public string World() => "World"; - } + // act + // assert + SchemaBuilder.New() + .AddDocumentFromString(sdl) + .BindRuntimeType() + .Create() + .Print() + .MatchSnapshot(); + } + + public class Query + { + public string Hello() => "Hello"; + + public string World() => "World"; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/AnyTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/AnyTypeTests.cs index c83cf1b41b2..6a1fae95808 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/AnyTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/AnyTypeTests.cs @@ -10,1122 +10,1121 @@ using Xunit; using static HotChocolate.Tests.TestHelper; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class AnyTypeTests { - public class AnyTypeTests + [Fact] + public async Task Output_Return_Object() { - [Fact] - public async Task Output_Return_Object() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => new Foo())) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Output_Return_List() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => new List { new() })) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Output_Return_DateTime() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => new DateTimeOffset( - new DateTime(2016, 01, 01), - TimeSpan.Zero))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Output_Return_String() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => "abc")) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Output_Return_Int() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => 123)) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Output_Return_Float() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => 1.2)) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Output_Return_Boolean() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Resolve(_ => true)) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync("{ foo }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Object() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: { a: \"foo\" }) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_List() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: [ \"foo\" ]) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Object_List() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: [ { a: \"foo\" } ]) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Object_To_Foo() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: { bar: { baz: \"FooBar\" } }) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_String() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: \"foo\") }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Int() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: 123) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Float() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: 1.2) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Boolean() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: true) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Null() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - "{ foo(input: null) }"); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_List_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", new List { "abc" }) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Object_List_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", new List + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => new Foo())) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Output_Return_List() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => new List { new() })) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Output_Return_DateTime() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => new DateTimeOffset( + new DateTime(2016, 01, 01), + TimeSpan.Zero))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Output_Return_String() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => "abc")) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Output_Return_Int() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => 123)) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Output_Return_Float() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => 1.2)) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Output_Return_Boolean() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Resolve(_ => true)) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync("{ foo }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Object() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: { a: \"foo\" }) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_List() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: [ \"foo\" ]) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Object_List() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: [ { a: \"foo\" } ]) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Object_To_Foo() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: { bar: { baz: \"FooBar\" } }) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_String() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: \"foo\") }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Int() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: 123) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Float() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: 1.2) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Boolean() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: true) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Null() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + "{ foo(input: null) }"); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_List_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", new List { "abc" }) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Object_List_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", new List + { + new Dictionary { - new Dictionary - { - { "abc", "def" } - } - }) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_String_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", "bar") - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Int_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", 123) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Float_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", 1.2) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Object_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentLiteral("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", new { a = "b" }) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_ObjectDict_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentLiteral("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", new Dictionary { { "a", "b" } }) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_ArgumentKind() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentKind("input").ToString())) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", new Dictionary { { "a", "b" } }) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Boolean_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor executor = schema.MakeExecutable(); - - // act - IExecutionResult result = await executor.ExecuteAsync( - QueryRequestBuilder.New() - .SetQuery("query ($foo: Any) { foo(input: $foo) }") - .SetVariableValue("foo", false) - .Create()); - - // assert - result.ToJson().MatchSnapshot(); - } - - [Fact] - public async Task Input_Value_Null_As_Variable() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - IRequestExecutor 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(); - } - - [Fact] - public void IsInstanceOfType_EnumValue_False() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new EnumValueNode("foo")); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_ObjectValue_True() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new ObjectValueNode(Array.Empty())); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_ListValue_False() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new ListValueNode(Array.Empty())); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringValue_False() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new StringValueNode("foo")); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_IntValue_False() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new IntValueNode(123)); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_FloatValue_False() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new FloatValueNode(1.2)); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_BooleanValue_False() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(new BooleanValueNode(true)); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullValue_True() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_Null_ArgumentNullException() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - void Action() => type.IsInstanceOfType(null!); - - // assert - Assert.Throws(Action); - } - - [InlineData("abc", typeof(StringValueNode))] - [InlineData((short)1, typeof(IntValueNode))] - [InlineData((int)1, typeof(IntValueNode))] - [InlineData((long)1, typeof(IntValueNode))] - [InlineData((float)1, typeof(FloatValueNode))] - [InlineData((double)1, typeof(FloatValueNode))] - [InlineData(true, typeof(BooleanValueNode))] - [InlineData(false, typeof(BooleanValueNode))] - [Theory] - public void ParseValue_ScalarValues(object value, Type expectedType) - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue(value); - - // assert - Assert.IsType(expectedType, literal); - } - - [Fact] - public void ParseValue_Decimal() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue((decimal)1); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void ParseValue_List_Of_Object() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue(new List()); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void ParseValue_List_Of_String() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue(new List()); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void ParseValue_List_Of_Foo() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue(new List()); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void ParseValue_Foo() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue(new Foo()); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void ParseValue_Dictionary() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - IValueNode literal = type.ParseValue( - new Dictionary()); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void Deserialize_ValueNode() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - // act - var value = type.Deserialize(new StringValueNode("Foo")); - - // assert - Assert.Equal("Foo", value); - } - - [Fact] - public void Deserialize_Dictionary() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - var toDeserialize = new Dictionary - { - {"Foo", new StringValueNode("Bar")} - }; - - // act - var value = type.Deserialize(toDeserialize); - - // assert - Assert.Equal("Bar", Assert.IsType>(value)["Foo"]); - } - - [Fact] - public void Deserialize_NestedDictionary() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - - var toDeserialize = new Dictionary - { - {"Foo",new Dictionary{{"Bar",new StringValueNode("Baz")}}} - }; - - // act - var value = type.Deserialize(toDeserialize); - - // assert - var innerDictionary = Assert.IsType>(value)["Foo"]; - Assert.Equal("Baz", Assert.IsType>(innerDictionary)["Bar"]); - } - - [Fact] - public void Deserialize_List() + { "abc", "def" } + } + }) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_String_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", "bar") + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Int_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", 123) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Float_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", 1.2) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Object_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentLiteral("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", new { a = "b" }) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_ObjectDict_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentLiteral("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", new Dictionary { { "a", "b" } }) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_ArgumentKind() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentKind("input").ToString())) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", new Dictionary { { "a", "b" } }) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Boolean_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", false) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public async Task Input_Value_Null_As_Variable() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var executor = schema.MakeExecutable(); + + // act + var result = await executor.ExecuteAsync( + QueryRequestBuilder.New() + .SetQuery("query ($foo: Any) { foo(input: $foo) }") + .SetVariableValue("foo", null) + .Create()); + + // assert + result.ToJson().MatchSnapshot(); + } + + [Fact] + public void IsInstanceOfType_EnumValue_False() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new EnumValueNode("foo")); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_ObjectValue_True() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new ObjectValueNode(Array.Empty())); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_ListValue_False() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new ListValueNode(Array.Empty())); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringValue_False() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new StringValueNode("foo")); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_IntValue_False() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new IntValueNode(123)); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_FloatValue_False() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new FloatValueNode(1.2)); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_BooleanValue_False() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(new BooleanValueNode(true)); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullValue_True() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_Null_ArgumentNullException() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + void Action() => type.IsInstanceOfType(null!); + + // assert + Assert.Throws(Action); + } + + [InlineData("abc", typeof(StringValueNode))] + [InlineData((short)1, typeof(IntValueNode))] + [InlineData((int)1, typeof(IntValueNode))] + [InlineData((long)1, typeof(IntValueNode))] + [InlineData((float)1, typeof(FloatValueNode))] + [InlineData((double)1, typeof(FloatValueNode))] + [InlineData(true, typeof(BooleanValueNode))] + [InlineData(false, typeof(BooleanValueNode))] + [Theory] + public void ParseValue_ScalarValues(object value, Type expectedType) + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue(value); + + // assert + Assert.IsType(expectedType, literal); + } + + [Fact] + public void ParseValue_Decimal() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue((decimal)1); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void ParseValue_List_Of_Object() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue(new List()); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void ParseValue_List_Of_String() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue(new List()); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void ParseValue_List_Of_Foo() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue(new List()); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void ParseValue_Foo() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue(new Foo()); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void ParseValue_Dictionary() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var literal = type.ParseValue( + new Dictionary()); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void Deserialize_ValueNode() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + // act + var value = type.Deserialize(new StringValueNode("Foo")); + + // assert + Assert.Equal("Foo", value); + } + + [Fact] + public void Deserialize_Dictionary() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + var toDeserialize = new Dictionary { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType(d => d - .Name("Query") - .Field("foo") - .Type() - .Argument("input", a => a.Type()) - .Resolve(ctx => ctx.ArgumentValue("input"))) - .Create(); - - AnyType type = schema.GetType("Any"); - var toDeserialize = - new List { new StringValueNode("Foo"), new StringValueNode("Bar") }; - - // act - var value = type.Deserialize(toDeserialize); - - // assert - Assert.Collection( - Assert.IsType(value)!, - x => Assert.Equal("Foo",x), - x => Assert.Equal("Bar",x)); - } - - [Fact] - public async Task Dictionary_Is_Handled_As_Object() + {"Foo", new StringValueNode("Bar")} + }; + + // act + var value = type.Deserialize(toDeserialize); + + // assert + Assert.Equal("Bar", Assert.IsType>(value)["Foo"]); + } + + [Fact] + public void Deserialize_NestedDictionary() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + + var toDeserialize = new Dictionary { - Snapshot.FullName(); - await ExpectValid( + {"Foo",new Dictionary{{"Bar",new StringValueNode("Baz")}}} + }; + + // act + var value = type.Deserialize(toDeserialize); + + // assert + var innerDictionary = Assert.IsType>(value)["Foo"]; + Assert.Equal("Baz", Assert.IsType>(innerDictionary)["Bar"]); + } + + [Fact] + public void Deserialize_List() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType(d => d + .Name("Query") + .Field("foo") + .Type() + .Argument("input", a => a.Type()) + .Resolve(ctx => ctx.ArgumentValue("input"))) + .Create(); + + var type = schema.GetType("Any"); + var toDeserialize = + new List { new StringValueNode("Foo"), new StringValueNode("Bar") }; + + // act + var value = type.Deserialize(toDeserialize); + + // assert + Assert.Collection( + Assert.IsType(value)!, + x => Assert.Equal("Foo",x), + x => Assert.Equal("Bar",x)); + } + + [Fact] + public async Task Dictionary_Is_Handled_As_Object() + { + Snapshot.FullName(); + await ExpectValid( "{ someObject }", configure: c => c.AddQueryType()) - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } - public class Foo - { - public Bar Bar { get; set; } = new Bar(); - } + public class Foo + { + public Bar Bar { get; set; } = new Bar(); + } - public class Bar - { - public string Baz { get; set; } = "Baz"; - } + public class Bar + { + public string Baz { get; set; } = "Baz"; + } - public class QueryWithDictionary - { - [GraphQLType(typeof(AnyType))] - public IDictionary SomeObject => - new Dictionary { { "a", "b" } }; - } + public class QueryWithDictionary + { + [GraphQLType(typeof(AnyType))] + public IDictionary SomeObject => + new Dictionary { { "a", "b" } }; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/BooleanTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/BooleanTypeTests.cs index 1a8b3a6ba98..11804ad5289 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/BooleanTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/BooleanTypeTests.cs @@ -2,136 +2,135 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class BooleanTypeTests { - public class BooleanTypeTests + [Fact] + public void ParseLiteral() + { + // arrange + var literal = new BooleanValueNode(null, true); + + // act + var booleanType = new BooleanType(); + var result = booleanType.ParseLiteral(literal); + + // assert + Assert.IsType(result); + Assert.True((bool)result); + } + + [Fact] + public void IsInstanceOfType() { - [Fact] - public void ParseLiteral() - { - // arrange - var literal = new BooleanValueNode(null, true); - - // act - var booleanType = new BooleanType(); - object result = booleanType.ParseLiteral(literal); - - // assert - Assert.IsType(result); - Assert.True((bool)result); - } - - [Fact] - public void IsInstanceOfType() - { - // arrange - var boolLiteral = new BooleanValueNode(null, true); - var stringLiteral = new StringValueNode(null, "12345", false); - NullValueNode nullLiteral = NullValueNode.Default; - - // act - var booleanType = new BooleanType(); - bool isIntLiteralInstanceOf = booleanType.IsInstanceOfType(boolLiteral); - bool isStringLiteralInstanceOf = booleanType.IsInstanceOfType(stringLiteral); - bool isNullLiteralInstanceOf = booleanType.IsInstanceOfType(nullLiteral); - - // assert - Assert.True(isIntLiteralInstanceOf); - Assert.False(isStringLiteralInstanceOf); - Assert.True(isNullLiteralInstanceOf); - } - - [Fact] - public void EnsureBooleanTypeKindIsCorret() - { - // arrange - var type = new BooleanType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [Fact] - public void Serialize_Null_Null() - { - // arrange - var booleanType = new BooleanType(); - - // act - object result = booleanType.Serialize(null); - - // assert - Assert.Null(result); - } - - [Fact] - public void Serialize_True_True() - { - // arrange - var booleanType = new BooleanType(); - - // act - object result = booleanType.Serialize(true); - - // assert - Assert.IsType(result); - Assert.True((bool)result); - } - - [Fact] - public void Serialize_String_Exception() - { - // arrange - var booleanType = new BooleanType(); - - // act - Action a = () => booleanType.Serialize("foo"); - - // assert - Assert.Throws(a); - } - - [Fact] - public void Deserialize_Null_Null() - { - // arrange - var booleanType = new BooleanType(); - - // act - object result = booleanType.Serialize(null); - - // assert - Assert.Null(result); - } - - [Fact] - public void Deserialize_True_True() - { - // arrange - var booleanType = new BooleanType(); - - // act - object result = booleanType.Serialize(true); - - // assert - Assert.IsType(result); - Assert.True((bool)result); - } - - [Fact] - public void Deserialize_String_Exception() - { - // arrange - var booleanType = new BooleanType(); - - // act - Action a = () => booleanType.Serialize("foo"); - - // assert - Assert.Throws(a); - } + // arrange + var boolLiteral = new BooleanValueNode(null, true); + var stringLiteral = new StringValueNode(null, "12345", false); + var nullLiteral = NullValueNode.Default; + + // act + var booleanType = new BooleanType(); + var isIntLiteralInstanceOf = booleanType.IsInstanceOfType(boolLiteral); + var isStringLiteralInstanceOf = booleanType.IsInstanceOfType(stringLiteral); + var isNullLiteralInstanceOf = booleanType.IsInstanceOfType(nullLiteral); + + // assert + Assert.True(isIntLiteralInstanceOf); + Assert.False(isStringLiteralInstanceOf); + Assert.True(isNullLiteralInstanceOf); + } + + [Fact] + public void EnsureBooleanTypeKindIsCorret() + { + // arrange + var type = new BooleanType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [Fact] + public void Serialize_Null_Null() + { + // arrange + var booleanType = new BooleanType(); + + // act + var result = booleanType.Serialize(null); + + // assert + Assert.Null(result); + } + + [Fact] + public void Serialize_True_True() + { + // arrange + var booleanType = new BooleanType(); + + // act + var result = booleanType.Serialize(true); + + // assert + Assert.IsType(result); + Assert.True((bool)result); + } + + [Fact] + public void Serialize_String_Exception() + { + // arrange + var booleanType = new BooleanType(); + + // act + Action a = () => booleanType.Serialize("foo"); + + // assert + Assert.Throws(a); + } + + [Fact] + public void Deserialize_Null_Null() + { + // arrange + var booleanType = new BooleanType(); + + // act + var result = booleanType.Serialize(null); + + // assert + Assert.Null(result); + } + + [Fact] + public void Deserialize_True_True() + { + // arrange + var booleanType = new BooleanType(); + + // act + var result = booleanType.Serialize(true); + + // assert + Assert.IsType(result); + Assert.True((bool)result); + } + + [Fact] + public void Deserialize_String_Exception() + { + // arrange + var booleanType = new BooleanType(); + + // act + Action a = () => booleanType.Serialize("foo"); + + // assert + Assert.Throws(a); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteArrayTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteArrayTypeTests.cs index 8498b23b043..019c5bacaee 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteArrayTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteArrayTypeTests.cs @@ -3,297 +3,296 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ByteArrayTypeTests { - public class ByteArrayTypeTests + [Fact] + public void IsInstanceOfType_StringLiteral() + { + // arrange + var byteArrayType = new ByteArrayType(); + var byteArray = Encoding.ASCII.GetBytes("value"); + + // act + var isOfType = byteArrayType.IsInstanceOfType(byteArray); + + // assert + Assert.True(isOfType); + } + + [Fact] + public void IsInstanceOfType_NullLiteral() + { + // arrange + var byteArrayType = new ByteArrayType(); + var literal = new NullValueNode(null); + + // act + var isOfType = byteArrayType.IsInstanceOfType(literal); + + // assert + Assert.True(isOfType); + } + + [Fact] + public void IsInstanceOfType_IntLiteral() + { + // arrange + var byteArrayType = new ByteArrayType(); + + var literal = new IntValueNode(123); + + // act + var isOfType = byteArrayType.IsInstanceOfType(literal); + + // assert + Assert.False(isOfType); + } + + [Fact] + public void IsInstanceOfType_Null() + { + // arrange + var byteArrayType = new ByteArrayType(); + var guid = Guid.NewGuid(); + + // act + Action action = () => byteArrayType.IsInstanceOfType(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Serialize_Base64() + { + // arrange + var byteArrayType = new ByteArrayType(); + + var value = Encoding.ASCII.GetBytes("value"); + + // act + var serializedValue = byteArrayType.Serialize(value); + + // assert + Assert.Equal( + Convert.ToBase64String(value), + Assert.IsType(serializedValue)); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var byteArrayType = new ByteArrayType(); + + // act + var serializedValue = byteArrayType.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Int() + { + // arrange + var byteArrayType = new ByteArrayType(); + var value = 123; + + // act + Action action = () => byteArrayType.Serialize(value); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Deserialize_Null() { - [Fact] - public void IsInstanceOfType_StringLiteral() - { - // arrange - var byteArrayType = new ByteArrayType(); - var byteArray = Encoding.ASCII.GetBytes("value"); - - // act - bool isOfType = byteArrayType.IsInstanceOfType(byteArray); - - // assert - Assert.True(isOfType); - } - - [Fact] - public void IsInstanceOfType_NullLiteral() - { - // arrange - var byteArrayType = new ByteArrayType(); - var literal = new NullValueNode(null); - - // act - bool isOfType = byteArrayType.IsInstanceOfType(literal); - - // assert - Assert.True(isOfType); - } - - [Fact] - public void IsInstanceOfType_IntLiteral() - { - // arrange - var byteArrayType = new ByteArrayType(); - - var literal = new IntValueNode(123); - - // act - bool isOfType = byteArrayType.IsInstanceOfType(literal); - - // assert - Assert.False(isOfType); - } - - [Fact] - public void IsInstanceOfType_Null() - { - // arrange - var byteArrayType = new ByteArrayType(); - var guid = Guid.NewGuid(); - - // act - Action action = () => byteArrayType.IsInstanceOfType(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Serialize_Base64() - { - // arrange - var byteArrayType = new ByteArrayType(); - - var value = Encoding.ASCII.GetBytes("value"); - - // act - var serializedValue = byteArrayType.Serialize(value); - - // assert - Assert.Equal( - Convert.ToBase64String(value), - Assert.IsType(serializedValue)); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var byteArrayType = new ByteArrayType(); - - // act - var serializedValue = byteArrayType.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Int() - { - // arrange - var byteArrayType = new ByteArrayType(); - var value = 123; - - // act - Action action = () => byteArrayType.Serialize(value); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Deserialize_Null() - { - // arrange - var byteArrayType = new ByteArrayType(); - - // act - var success = byteArrayType.TryDeserialize(null, out object o); - - // assert - Assert.True(success); - Assert.Null(o); - } - - [Fact] - public void Deserialize_String() - { - // arrange - var byteArrayType = new ByteArrayType(); - byte[] bytes = Encoding.ASCII.GetBytes("value"); - - // act - var success = byteArrayType.TryDeserialize( - Convert.ToBase64String(bytes), out object o); - - // assert - Assert.True(success); - Assert.Equal(bytes, o); - } - - [Fact] - public void Deserialize_Bytes() - { - // arrange - var byteArrayType = new ByteArrayType(); - byte[] bytes = Encoding.ASCII.GetBytes("value"); - - // act - var success = byteArrayType.TryDeserialize( - bytes, out object o); - - // assert - Assert.True(success); - Assert.Equal(bytes, o); - } - - [Fact] - public void Deserialize_Guid() - { - // arrange - var byteArrayType = new ByteArrayType(); - byte[] bytes = Encoding.ASCII.GetBytes("value"); - - // act - var success = byteArrayType.TryDeserialize(bytes, out object o); - - // assert - Assert.True(success); - Assert.Equal(bytes, o); - } - - [Fact] - public void Deserialize_Int() - { - // arrange - var byteArrayType = new ByteArrayType(); - var value = 123; - - // act - var success = byteArrayType.TryDeserialize(value, out _); - - // assert - Assert.False(success); - } - - [Fact] - public void ParseLiteral_StringValueNode() - { - // arrange - var byteArrayType = new ByteArrayType(); - byte[] expected = Encoding.ASCII.GetBytes("value"); - var literal = new StringValueNode(Convert.ToBase64String(expected)); - - // act - var actual = (byte[])byteArrayType - .ParseLiteral(literal); - - // assert - Assert.Equal(expected, actual); - } - - [Fact] - public void ParseLiteral_IntValueNode() - { - // arrange - var byteArrayType = new ByteArrayType(); - var literal = new IntValueNode(123); - - // act - Action action = () => byteArrayType.ParseLiteral(literal); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var byteArrayType = new ByteArrayType(); - NullValueNode literal = NullValueNode.Default; - - // act - var value = byteArrayType.ParseLiteral(literal); - - // assert - Assert.Null(value); - } - - [Fact] - public void ParseLiteral_Null() - { - // arrange - var byteArrayType = new ByteArrayType(); - - // act - Action action = () => byteArrayType.ParseLiteral(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_Guid() - { - // arrange - var byteArrayType = new ByteArrayType(); - byte[] expected = Encoding.ASCII.GetBytes("value"); - var expectedLiteralValue = Convert.ToBase64String(expected); - - // act - var stringLiteral = - (StringValueNode)byteArrayType.ParseValue(expected); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var byteArrayType = new ByteArrayType(); - Guid? guid = null; - - // act - IValueNode stringLiteral = - byteArrayType.ParseValue(guid); - - // assert - Assert.True(stringLiteral is NullValueNode); - Assert.Null(((NullValueNode)stringLiteral).Value); - } - - [Fact] - public void ParseValue_Int() - { - // arrange - var byteArrayType = new ByteArrayType(); - int value = 123; - - // act - Action action = () => byteArrayType.ParseValue(value); - - // assert - Assert.Throws(action); - } - - [Fact] - public void EnsureDateTypeKindIsCorret() - { - // arrange - var type = new ByteArrayType(); - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } + // arrange + var byteArrayType = new ByteArrayType(); + + // act + var success = byteArrayType.TryDeserialize(null, out var o); + + // assert + Assert.True(success); + Assert.Null(o); + } + + [Fact] + public void Deserialize_String() + { + // arrange + var byteArrayType = new ByteArrayType(); + var bytes = Encoding.ASCII.GetBytes("value"); + + // act + var success = byteArrayType.TryDeserialize( + Convert.ToBase64String(bytes), out var o); + + // assert + Assert.True(success); + Assert.Equal(bytes, o); + } + + [Fact] + public void Deserialize_Bytes() + { + // arrange + var byteArrayType = new ByteArrayType(); + var bytes = Encoding.ASCII.GetBytes("value"); + + // act + var success = byteArrayType.TryDeserialize( + bytes, out var o); + + // assert + Assert.True(success); + Assert.Equal(bytes, o); + } + + [Fact] + public void Deserialize_Guid() + { + // arrange + var byteArrayType = new ByteArrayType(); + var bytes = Encoding.ASCII.GetBytes("value"); + + // act + var success = byteArrayType.TryDeserialize(bytes, out var o); + + // assert + Assert.True(success); + Assert.Equal(bytes, o); + } + + [Fact] + public void Deserialize_Int() + { + // arrange + var byteArrayType = new ByteArrayType(); + var value = 123; + + // act + var success = byteArrayType.TryDeserialize(value, out _); + + // assert + Assert.False(success); + } + + [Fact] + public void ParseLiteral_StringValueNode() + { + // arrange + var byteArrayType = new ByteArrayType(); + var expected = Encoding.ASCII.GetBytes("value"); + var literal = new StringValueNode(Convert.ToBase64String(expected)); + + // act + var actual = (byte[])byteArrayType + .ParseLiteral(literal); + + // assert + Assert.Equal(expected, actual); + } + + [Fact] + public void ParseLiteral_IntValueNode() + { + // arrange + var byteArrayType = new ByteArrayType(); + var literal = new IntValueNode(123); + + // act + Action action = () => byteArrayType.ParseLiteral(literal); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var byteArrayType = new ByteArrayType(); + var literal = NullValueNode.Default; + + // act + var value = byteArrayType.ParseLiteral(literal); + + // assert + Assert.Null(value); + } + + [Fact] + public void ParseLiteral_Null() + { + // arrange + var byteArrayType = new ByteArrayType(); + + // act + Action action = () => byteArrayType.ParseLiteral(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_Guid() + { + // arrange + var byteArrayType = new ByteArrayType(); + var expected = Encoding.ASCII.GetBytes("value"); + var expectedLiteralValue = Convert.ToBase64String(expected); + + // act + var stringLiteral = + (StringValueNode)byteArrayType.ParseValue(expected); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var byteArrayType = new ByteArrayType(); + Guid? guid = null; + + // act + var stringLiteral = + byteArrayType.ParseValue(guid); + + // assert + Assert.True(stringLiteral is NullValueNode); + Assert.Null(((NullValueNode)stringLiteral).Value); + } + + [Fact] + public void ParseValue_Int() + { + // arrange + var byteArrayType = new ByteArrayType(); + var value = 123; + + // act + Action action = () => byteArrayType.ParseValue(value); + + // assert + Assert.Throws(action); + } + + [Fact] + public void EnsureDateTypeKindIsCorret() + { + // arrange + var type = new ByteArrayType(); + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteTypeTests.cs index fd6848d6553..1e73dc87ba6 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ByteTypeTests.cs @@ -2,278 +2,277 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ByteTypeTests { - public class ByteTypeTests + [Fact] + public void IsInstanceOfType_FloatLiteral_True() + { + // arrange + var type = new ByteType(); + var literal = new IntValueNode(1); + + // act + var result = type.IsInstanceOfType(literal); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullLiteral_True() { - [Fact] - public void IsInstanceOfType_FloatLiteral_True() - { - // arrange - var type = new ByteType(); - var literal = new IntValueNode(1); - - // act - var result = type.IsInstanceOfType(literal); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullLiteral_True() - { - // arrange - var type = new ByteType(); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringLiteral_False() - { - // arrange - var type = new ByteType(); - - // act - var result = type.IsInstanceOfType(new FloatValueNode(1M)); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new ByteType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new ByteType(); - byte value = 123; - - // act - var serializedValue = type.Serialize(value); - - // assert - Assert.IsType(serializedValue); - Assert.Equal(value, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new ByteType(); - - // act - var serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new ByteType(); - var input = "abc"; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void Serialize_MaxValue_Violation() - { - // arrange - var type = new ByteType(0, 100); - byte value = 200; - - // act - // assert - Assert.Throws( - () => type.Serialize(value)); - } - - [Fact] - public void ParseLiteral_IntLiteral() - { - // arrange - var type = new ByteType(); - var literal = new IntValueNode(1); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToByte(), value); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new ByteType(); - - // act - var output = type.ParseLiteral(NullValueNode.Default); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new ByteType(); - var input = new StringValueNode("abc"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new ByteType(); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_MaxValue() - { - // arrange - var type = new ByteType(1, 100); - byte input = 100; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(100, literal.ToByte()); - } - - [Fact] - public void ParseValue_MaxValue_Violation() - { - // arrange - var type = new ByteType(1, 100); - byte input = 101; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_MinValue() - { - // arrange - var type = new ByteType(1, 100); - byte input = 1; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(1, literal.ToByte()); - } - - [Fact] - public void ParseValue_MinValue_Violation() - { - // arrange - var type = new ByteType(1, 100); - byte input = 0; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new ByteType(); - var value = "123"; - - // act - // assert - Assert.Throws( - () => type.ParseValue(value)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new ByteType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_Nullable() - { - // arrange - var type = new ByteType(); - byte? input = 123; - - // act - IntValueNode output = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(123, output.ToDouble()); - } - - [Fact] - public void Ensure_TypeKind_is_Scalar() - { - // arrange - var type = new ByteType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } + // arrange + var type = new ByteType(); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringLiteral_False() + { + // arrange + var type = new ByteType(); + + // act + var result = type.IsInstanceOfType(new FloatValueNode(1M)); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new ByteType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new ByteType(); + byte value = 123; + + // act + var serializedValue = type.Serialize(value); + + // assert + Assert.IsType(serializedValue); + Assert.Equal(value, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new ByteType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new ByteType(); + var input = "abc"; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void Serialize_MaxValue_Violation() + { + // arrange + var type = new ByteType(0, 100); + byte value = 200; + + // act + // assert + Assert.Throws( + () => type.Serialize(value)); + } + + [Fact] + public void ParseLiteral_IntLiteral() + { + // arrange + var type = new ByteType(); + var literal = new IntValueNode(1); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToByte(), value); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new ByteType(); + + // act + var output = type.ParseLiteral(NullValueNode.Default); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new ByteType(); + var input = new StringValueNode("abc"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new ByteType(); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_MaxValue() + { + // arrange + var type = new ByteType(1, 100); + byte input = 100; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(100, literal.ToByte()); + } + + [Fact] + public void ParseValue_MaxValue_Violation() + { + // arrange + var type = new ByteType(1, 100); + byte input = 101; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_MinValue() + { + // arrange + var type = new ByteType(1, 100); + byte input = 1; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(1, literal.ToByte()); + } + + [Fact] + public void ParseValue_MinValue_Violation() + { + // arrange + var type = new ByteType(1, 100); + byte input = 0; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new ByteType(); + var value = "123"; + + // act + // assert + Assert.Throws( + () => type.ParseValue(value)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new ByteType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_Nullable() + { + // arrange + var type = new ByteType(); + byte? input = 123; + + // act + var output = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(123, output.ToDouble()); + } + + [Fact] + public void Ensure_TypeKind_is_Scalar() + { + // arrange + var type = new ByteType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTimeTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTimeTypeTests.cs index d19cfec1881..10c48291759 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTimeTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTimeTypeTests.cs @@ -8,386 +8,385 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DateTimeTypeTests { - public class DateTimeTypeTests + [Fact] + public void Serialize_Utc_DateTimeOffset() + { + // arrange + var dateTimeType = new DateTimeType(); + DateTimeOffset dateTime = new DateTime( + 2018, + 6, + 11, + 8, + 46, + 14, + DateTimeKind.Utc); + + var expectedValue = "2018-06-11T08:46:14.000Z"; + + // act + var serializedValue = (string)dateTimeType.Serialize(dateTime); + + // assert + Assert.Equal(expectedValue, serializedValue); + } + + [Fact] + public void Serialize_DateTimeOffset() + { + // arrange + var dateTimeType = new DateTimeType(); + var dateTime = new DateTimeOffset( + new DateTime(2018, 6, 11, 8, 46, 14), + new TimeSpan(4, 0, 0)); + var expectedValue = "2018-06-11T08:46:14.000+04:00"; + + // act + var serializedValue = (string)dateTimeType.Serialize(dateTime); + + // assert + Assert.Equal(expectedValue, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var dateTimeType = new DateTimeType(); + + // act + var serializedValue = dateTimeType.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_String_Exception() + { + // arrange + var dateTimeType = new DateTimeType(); + + // act + Action a = () => dateTimeType.Serialize("foo"); + + // assert + Assert.Throws(a); + } + + [Fact] + public void ParseLiteral_StringValueNode() + { + // arrange + var dateTimeType = new DateTimeType(); + var literal = new StringValueNode( + "2018-06-29T08:46:14+04:00"); + var expectedDateTime = new DateTimeOffset( + new DateTime(2018, 6, 29, 8, 46, 14), + new TimeSpan(4, 0, 0)); + + // act + var dateTime = (DateTimeOffset)dateTimeType + .ParseLiteral(literal); + + // assert + Assert.Equal(expectedDateTime, dateTime); + } + + [InlineData("en-US")] + [InlineData("en-AU")] + [InlineData("en-GB")] + [InlineData("de-CH")] + [InlineData("de-de")] + [Theory] + public void ParseLiteral_StringValueNode_DifferentCulture(string cultureName) + { + // arrange + Thread.CurrentThread.CurrentCulture = + CultureInfo.GetCultureInfo(cultureName); + + var dateTimeType = new DateTimeType(); + var literal = new StringValueNode( + "2018-06-29T08:46:14+04:00"); + var expectedDateTime = new DateTimeOffset( + new DateTime(2018, 6, 29, 8, 46, 14), + new TimeSpan(4, 0, 0)); + + // act + var dateTime = (DateTimeOffset)dateTimeType + .ParseLiteral(literal); + + // assert + Assert.Equal(expectedDateTime, dateTime); + } + + [Fact] + public void Deserialize_IsoString_DateTimeOffset() + { + // arrange + var dateTimeType = new DateTimeType(); + var dateTime = new DateTimeOffset( + new DateTime(2018, 6, 11, 8, 46, 14), + new TimeSpan(4, 0, 0)); + + // act + var deserializedValue = (DateTimeOffset)dateTimeType + .Deserialize("2018-06-11T08:46:14+04:00"); + + // assert + Assert.Equal(dateTime, deserializedValue); + } + + [Fact] + public void Deserialize_ZuluString_DateTimeOffset() + { + // arrange + var dateTimeType = new DateTimeType(); + var dateTime = new DateTimeOffset( + new DateTime(2018, 6, 11, 8, 46, 14), + new TimeSpan(0, 0, 0)); + + // act + var deserializedValue = (DateTimeOffset)dateTimeType + .Deserialize("2018-06-11T08:46:14.000Z"); + + // assert + Assert.Equal(dateTime, deserializedValue); + } + + [Fact] + public void Deserialize_IsoString_DateTime() + { + // arrange + var dateTimeType = new DateTimeType(); + var dateTime = new DateTime( + 2018, + 6, + 11, + 8, + 46, + 14, + DateTimeKind.Unspecified); + + // act + var deserializedValue = ((DateTimeOffset)dateTimeType + .Deserialize("2018-06-11T08:46:14+04:00")).DateTime; + + // assert + Assert.Equal(dateTime, deserializedValue); + Assert.Equal(DateTimeKind.Unspecified, deserializedValue.Kind); + } + + [Fact] + public void Deserialize_ZuluString_DateTime() + { + // arrange + var dateTimeType = new DateTimeType(); + DateTimeOffset dateTime = new DateTime( + 2018, + 6, + 11, + 8, + 46, + 14, + DateTimeKind.Utc); + + // act + var deserializedValue = ((DateTimeOffset)dateTimeType + .Deserialize("2018-06-11T08:46:14.000Z")); + + // assert + Assert.Equal(dateTime, deserializedValue.UtcDateTime); + } + + [Fact] + public void Deserialize_InvalidString_To_DateTimeOffset() + { + // arrange + var type = new DateTimeType(); + + // act + var success = type.TryDeserialize("abc", out var deserialized); + + // assert + Assert.False(success); + } + + [Fact] + public void Deserialize_DateTimeOffset_To_DateTimeOffset() + { + // arrange + var type = new DateTimeType(); + var time = new DateTimeOffset( + new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc)); + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Equal(time, deserialized); + } + + [Fact] + public void Deserialize_DateTime_To_DateTimeOffset() + { + // arrange + var type = new DateTimeType(); + var time = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Equal(time, + Assert.IsType(deserialized).UtcDateTime); + } + + [Fact] + public void Deserialize_NullableDateTime_To_DateTimeOffset() + { + // arrange + var type = new DateTimeType(); + DateTime? time = + new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Equal(time, + Assert.IsType(deserialized).UtcDateTime); + } + + [Fact] + public void Deserialize_NullableDateTime_To_DateTimeOffset_2() + { + // arrange + var type = new DateTimeType(); + DateTime? time = null; + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Null(deserialized); + } + + [Fact] + public void Deserialize_Null_To_Null() + { + // arrange + var type = new DateTimeType(); + + // act + var success = type.TryDeserialize(null, out var deserialized); + + // assert + Assert.True(success); + Assert.Null(deserialized); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var dateTimeType = new DateTimeType(); + var literal = NullValueNode.Default; + + // act + var value = dateTimeType.ParseLiteral(literal); + + // assert + Assert.Null(value); + } + + [Fact] + public void ParseValue_DateTimeOffset() + { + // arrange + var dateTimeType = new DateTimeType(); + var dateTime = new DateTimeOffset( + new DateTime(2018, 6, 11, 8, 46, 14), + new TimeSpan(4, 0, 0)); + var expectedLiteralValue = "2018-06-11T08:46:14.000+04:00"; + + // act + var stringLiteral = + (StringValueNode)dateTimeType.ParseValue(dateTime); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void ParseValue_Utc_DateTimeOffset() + { + // arrange + var dateTimeType = new DateTimeType(); + DateTimeOffset dateTime = + new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + var expectedLiteralValue = "2018-06-11T08:46:14.000Z"; + + // act + var stringLiteral = + (StringValueNode)dateTimeType.ParseValue(dateTime); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var dateTimeType = new DateTimeType(); + + // act + var literal = dateTimeType.ParseValue(null); + + // assert + Assert.IsType(literal); + } + + [Fact] + public void EnsureDateTimeTypeKindIsCorrect() + { + // arrange + var type = new DateTimeType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [Fact] + public async Task Integration_DefaultDateTime() + { + // arrange + var executor = await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildRequestExecutorAsync(); + + // act + var res = await executor.ExecuteAsync("{ test }"); + + // assert + res.ToJson().MatchSnapshot(); + } + + public class DefaultDateTime { - [Fact] - public void Serialize_Utc_DateTimeOffset() - { - // arrange - var dateTimeType = new DateTimeType(); - DateTimeOffset dateTime = new DateTime( - 2018, - 6, - 11, - 8, - 46, - 14, - DateTimeKind.Utc); - - string expectedValue = "2018-06-11T08:46:14.000Z"; - - // act - string serializedValue = (string)dateTimeType.Serialize(dateTime); - - // assert - Assert.Equal(expectedValue, serializedValue); - } - - [Fact] - public void Serialize_DateTimeOffset() - { - // arrange - var dateTimeType = new DateTimeType(); - var dateTime = new DateTimeOffset( - new DateTime(2018, 6, 11, 8, 46, 14), - new TimeSpan(4, 0, 0)); - string expectedValue = "2018-06-11T08:46:14.000+04:00"; - - // act - string serializedValue = (string)dateTimeType.Serialize(dateTime); - - // assert - Assert.Equal(expectedValue, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var dateTimeType = new DateTimeType(); - - // act - object serializedValue = dateTimeType.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_String_Exception() - { - // arrange - var dateTimeType = new DateTimeType(); - - // act - Action a = () => dateTimeType.Serialize("foo"); - - // assert - Assert.Throws(a); - } - - [Fact] - public void ParseLiteral_StringValueNode() - { - // arrange - var dateTimeType = new DateTimeType(); - var literal = new StringValueNode( - "2018-06-29T08:46:14+04:00"); - var expectedDateTime = new DateTimeOffset( - new DateTime(2018, 6, 29, 8, 46, 14), - new TimeSpan(4, 0, 0)); - - // act - var dateTime = (DateTimeOffset)dateTimeType - .ParseLiteral(literal); - - // assert - Assert.Equal(expectedDateTime, dateTime); - } - - [InlineData("en-US")] - [InlineData("en-AU")] - [InlineData("en-GB")] - [InlineData("de-CH")] - [InlineData("de-de")] - [Theory] - public void ParseLiteral_StringValueNode_DifferentCulture(string cultureName) - { - // arrange - Thread.CurrentThread.CurrentCulture = - CultureInfo.GetCultureInfo(cultureName); - - var dateTimeType = new DateTimeType(); - var literal = new StringValueNode( - "2018-06-29T08:46:14+04:00"); - var expectedDateTime = new DateTimeOffset( - new DateTime(2018, 6, 29, 8, 46, 14), - new TimeSpan(4, 0, 0)); - - // act - var dateTime = (DateTimeOffset)dateTimeType - .ParseLiteral(literal); - - // assert - Assert.Equal(expectedDateTime, dateTime); - } - - [Fact] - public void Deserialize_IsoString_DateTimeOffset() - { - // arrange - var dateTimeType = new DateTimeType(); - var dateTime = new DateTimeOffset( - new DateTime(2018, 6, 11, 8, 46, 14), - new TimeSpan(4, 0, 0)); - - // act - var deserializedValue = (DateTimeOffset)dateTimeType - .Deserialize("2018-06-11T08:46:14+04:00"); - - // assert - Assert.Equal(dateTime, deserializedValue); - } - - [Fact] - public void Deserialize_ZuluString_DateTimeOffset() - { - // arrange - var dateTimeType = new DateTimeType(); - var dateTime = new DateTimeOffset( - new DateTime(2018, 6, 11, 8, 46, 14), - new TimeSpan(0, 0, 0)); - - // act - var deserializedValue = (DateTimeOffset)dateTimeType - .Deserialize("2018-06-11T08:46:14.000Z"); - - // assert - Assert.Equal(dateTime, deserializedValue); - } - - [Fact] - public void Deserialize_IsoString_DateTime() - { - // arrange - var dateTimeType = new DateTimeType(); - var dateTime = new DateTime( - 2018, - 6, - 11, - 8, - 46, - 14, - DateTimeKind.Unspecified); - - // act - DateTime deserializedValue = ((DateTimeOffset)dateTimeType - .Deserialize("2018-06-11T08:46:14+04:00")).DateTime; - - // assert - Assert.Equal(dateTime, deserializedValue); - Assert.Equal(DateTimeKind.Unspecified, deserializedValue.Kind); - } - - [Fact] - public void Deserialize_ZuluString_DateTime() - { - // arrange - var dateTimeType = new DateTimeType(); - DateTimeOffset dateTime = new DateTime( - 2018, - 6, - 11, - 8, - 46, - 14, - DateTimeKind.Utc); - - // act - DateTimeOffset deserializedValue = ((DateTimeOffset)dateTimeType - .Deserialize("2018-06-11T08:46:14.000Z")); - - // assert - Assert.Equal(dateTime, deserializedValue.UtcDateTime); - } - - [Fact] - public void Deserialize_InvalidString_To_DateTimeOffset() - { - // arrange - var type = new DateTimeType(); - - // act - bool success = type.TryDeserialize("abc", out object deserialized); - - // assert - Assert.False(success); - } - - [Fact] - public void Deserialize_DateTimeOffset_To_DateTimeOffset() - { - // arrange - var type = new DateTimeType(); - var time = new DateTimeOffset( - new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc)); - - // act - bool success = type.TryDeserialize(time, out object deserialized); - - // assert - Assert.True(success); - Assert.Equal(time, deserialized); - } - - [Fact] - public void Deserialize_DateTime_To_DateTimeOffset() - { - // arrange - var type = new DateTimeType(); - var time = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - - // act - bool success = type.TryDeserialize(time, out object deserialized); - - // assert - Assert.True(success); - Assert.Equal(time, - Assert.IsType(deserialized).UtcDateTime); - } - - [Fact] - public void Deserialize_NullableDateTime_To_DateTimeOffset() - { - // arrange - var type = new DateTimeType(); - DateTime? time = - new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - - // act - bool success = type.TryDeserialize(time, out object deserialized); - - // assert - Assert.True(success); - Assert.Equal(time, - Assert.IsType(deserialized).UtcDateTime); - } - - [Fact] - public void Deserialize_NullableDateTime_To_DateTimeOffset_2() - { - // arrange - var type = new DateTimeType(); - DateTime? time = null; - - // act - bool success = type.TryDeserialize(time, out object deserialized); - - // assert - Assert.True(success); - Assert.Null(deserialized); - } - - [Fact] - public void Deserialize_Null_To_Null() - { - // arrange - var type = new DateTimeType(); - - // act - bool success = type.TryDeserialize(null, out object deserialized); - - // assert - Assert.True(success); - Assert.Null(deserialized); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var dateTimeType = new DateTimeType(); - NullValueNode literal = NullValueNode.Default; - - // act - object value = dateTimeType.ParseLiteral(literal); - - // assert - Assert.Null(value); - } - - [Fact] - public void ParseValue_DateTimeOffset() - { - // arrange - var dateTimeType = new DateTimeType(); - var dateTime = new DateTimeOffset( - new DateTime(2018, 6, 11, 8, 46, 14), - new TimeSpan(4, 0, 0)); - string expectedLiteralValue = "2018-06-11T08:46:14.000+04:00"; - - // act - var stringLiteral = - (StringValueNode)dateTimeType.ParseValue(dateTime); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void ParseValue_Utc_DateTimeOffset() - { - // arrange - var dateTimeType = new DateTimeType(); - DateTimeOffset dateTime = - new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - string expectedLiteralValue = "2018-06-11T08:46:14.000Z"; - - // act - var stringLiteral = - (StringValueNode)dateTimeType.ParseValue(dateTime); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var dateTimeType = new DateTimeType(); - - // act - IValueNode literal = dateTimeType.ParseValue(null); - - // assert - Assert.IsType(literal); - } - - [Fact] - public void EnsureDateTimeTypeKindIsCorrect() - { - // arrange - var type = new DateTimeType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [Fact] - public async Task Integration_DefaultDateTime() - { - // arrange - IRequestExecutor executor = await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildRequestExecutorAsync(); - - // act - IExecutionResult res = await executor.ExecuteAsync("{ test }"); - - // assert - res.ToJson().MatchSnapshot(); - } - - public class DefaultDateTime - { - public DateTime Test => default(DateTime); - } + public DateTime Test => default(DateTime); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTypeTests.cs index 37d879e91c4..75e24c4fef8 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DateTypeTests.cs @@ -9,369 +9,368 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DateTypeTests { - public class DateTypeTests + [Fact] + public void Serialize_Date() + { + // arrange + var dateType = new DateType(); + var dateTime = new DateTime( + 2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + var expectedValue = "2018-06-11"; + + // act + var serializedValue = (string)dateType.Serialize(dateTime); + + // assert + Assert.Equal(expectedValue, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var dateType = new DateType(); + + // act + var serializedValue = dateType.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_String_Exception() + { + // arrange + var dateType = new DateType(); + + // act + void Action() => dateType.Serialize("foo"); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Deserialize_IsoString_DateTime() + { + // arrange + var dateType = new DateType(); + var date = new DateTime(2018, 6, 11); + + // act + var result = (DateTime)dateType.Deserialize("2018-06-11")!; + + // assert + Assert.Equal(date, result); + } + + [Fact] + public void Deserialize_InvalidString_To_DateTimeOffset() + { + // arrange + var type = new DateType(); + + // act + var success = type.TryDeserialize("abc", out _); + + // assert + Assert.False(success); + } + + [Fact] + public void Deserialize_DateTimeOffset_To_DateTime() + { + // arrange + var type = new DateType(); + var time = new DateTimeOffset( + new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc)); + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Equal(time.UtcDateTime, + Assert.IsType(deserialized)); + } + + [Fact] + public void Deserialize_DateTime_To_DateTime() + { + // arrange + var type = new DateType(); + var time = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Equal(time, deserialized); + } + + [Fact] + public void Deserialize_NullableDateTime_To_DateTime() + { + // arrange + var type = new DateType(); + DateTime? time = + new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Equal(time, Assert.IsType(deserialized)); + } + + [Fact] + public void Deserialize_NullableDateTime_To_DateTime_2() + { + // arrange + var type = new DateType(); + DateTime? time = null; + + // act + var success = type.TryDeserialize(time, out var deserialized); + + // assert + Assert.True(success); + Assert.Null(deserialized); + } + + [Fact] + public void Deserialize_Null_To_Null() + { + // arrange + var type = new DateType(); + + // act + var success = type.TryDeserialize(null, out var deserialized); + + // assert + Assert.True(success); + Assert.Null(deserialized); + } + + [Fact] + public void ParseLiteral_StringValueNode() + { + // arrange + var dateType = new DateType(); + var literal = new StringValueNode("2018-06-29"); + var expectedDateTime = new DateTime(2018, 6, 29); + + // act + var dateTime = (DateTime)dateType.ParseLiteral(literal)!; + + // assert + Assert.Equal(expectedDateTime, dateTime); + } + + [InlineData("en-US")] + [InlineData("en-AU")] + [InlineData("en-GB")] + [InlineData("de-CH")] + [InlineData("de-de")] + [Theory] + public void ParseLiteral_StringValueNode_DifferentCulture( + string cultureName) + { + // arrange + Thread.CurrentThread.CurrentCulture = + CultureInfo.GetCultureInfo(cultureName); + + var dateType = new DateType(); + var literal = new StringValueNode("2018-06-29"); + var expectedDateTime = new DateTime(2018, 6, 29); + + // act + var dateTime = (DateTime)dateType.ParseLiteral(literal)!; + + // assert + Assert.Equal(expectedDateTime, dateTime); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var dateType = new DateType(); + var literal = NullValueNode.Default; + + // act + var value = dateType.ParseLiteral(literal); + + // assert + Assert.Null(value); + } + + [Fact] + public void ParseValue_DateTime() + { + // arrange + var dateType = new DateType(); + var dateTime = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + var expectedLiteralValue = "2018-06-11"; + + // act + var stringLiteral = + (StringValueNode)dateType.ParseValue(dateTime); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var dateType = new DateType(); + var dateTime = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); + var expectedLiteralValue = "2018-06-11"; + + // act + var stringLiteral = + (StringValueNode)dateType.ParseValue(dateTime); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void EnsureDateTypeKindIsCorrect() + { + // arrange + var type = new DateType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); + } + + [Fact] + public void DateType_Binds_Only_Explicitly() { - [Fact] - public void Serialize_Date() - { - // arrange - var dateType = new DateType(); - var dateTime = new DateTime( - 2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - var expectedValue = "2018-06-11"; - - // act - var serializedValue = (string)dateType.Serialize(dateTime); - - // assert - Assert.Equal(expectedValue, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var dateType = new DateType(); - - // act - var serializedValue = dateType.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_String_Exception() - { - // arrange - var dateType = new DateType(); - - // act - void Action() => dateType.Serialize("foo"); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Deserialize_IsoString_DateTime() - { - // arrange - var dateType = new DateType(); - var date = new DateTime(2018, 6, 11); - - // act - var result = (DateTime)dateType.Deserialize("2018-06-11")!; - - // assert - Assert.Equal(date, result); - } - - [Fact] - public void Deserialize_InvalidString_To_DateTimeOffset() - { - // arrange - var type = new DateType(); - - // act - var success = type.TryDeserialize("abc", out _); - - // assert - Assert.False(success); - } - - [Fact] - public void Deserialize_DateTimeOffset_To_DateTime() - { - // arrange - var type = new DateType(); - var time = new DateTimeOffset( - new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc)); - - // act - var success = type.TryDeserialize(time, out var deserialized); - - // assert - Assert.True(success); - Assert.Equal(time.UtcDateTime, - Assert.IsType(deserialized)); - } - - [Fact] - public void Deserialize_DateTime_To_DateTime() - { - // arrange - var type = new DateType(); - var time = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - - // act - var success = type.TryDeserialize(time, out var deserialized); - - // assert - Assert.True(success); - Assert.Equal(time, deserialized); - } - - [Fact] - public void Deserialize_NullableDateTime_To_DateTime() - { - // arrange - var type = new DateType(); - DateTime? time = - new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - - // act - var success = type.TryDeserialize(time, out var deserialized); - - // assert - Assert.True(success); - Assert.Equal(time, Assert.IsType(deserialized)); - } - - [Fact] - public void Deserialize_NullableDateTime_To_DateTime_2() - { - // arrange - var type = new DateType(); - DateTime? time = null; - - // act - var success = type.TryDeserialize(time, out var deserialized); - - // assert - Assert.True(success); - Assert.Null(deserialized); - } - - [Fact] - public void Deserialize_Null_To_Null() - { - // arrange - var type = new DateType(); - - // act - var success = type.TryDeserialize(null, out var deserialized); - - // assert - Assert.True(success); - Assert.Null(deserialized); - } - - [Fact] - public void ParseLiteral_StringValueNode() - { - // arrange - var dateType = new DateType(); - var literal = new StringValueNode("2018-06-29"); - var expectedDateTime = new DateTime(2018, 6, 29); - - // act - var dateTime = (DateTime)dateType.ParseLiteral(literal)!; - - // assert - Assert.Equal(expectedDateTime, dateTime); - } - - [InlineData("en-US")] - [InlineData("en-AU")] - [InlineData("en-GB")] - [InlineData("de-CH")] - [InlineData("de-de")] - [Theory] - public void ParseLiteral_StringValueNode_DifferentCulture( - string cultureName) - { - // arrange - Thread.CurrentThread.CurrentCulture = - CultureInfo.GetCultureInfo(cultureName); - - var dateType = new DateType(); - var literal = new StringValueNode("2018-06-29"); - var expectedDateTime = new DateTime(2018, 6, 29); - - // act - var dateTime = (DateTime)dateType.ParseLiteral(literal)!; - - // assert - Assert.Equal(expectedDateTime, dateTime); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var dateType = new DateType(); - NullValueNode literal = NullValueNode.Default; - - // act - var value = dateType.ParseLiteral(literal); - - // assert - Assert.Null(value); - } - - [Fact] - public void ParseValue_DateTime() - { - // arrange - var dateType = new DateType(); - var dateTime = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - var expectedLiteralValue = "2018-06-11"; - - // act - var stringLiteral = - (StringValueNode)dateType.ParseValue(dateTime); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var dateType = new DateType(); - var dateTime = new DateTime(2018, 6, 11, 8, 46, 14, DateTimeKind.Utc); - var expectedLiteralValue = "2018-06-11"; - - // act - var stringLiteral = - (StringValueNode)dateType.ParseValue(dateTime); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void EnsureDateTypeKindIsCorrect() - { - // arrange - var type = new DateType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } - - [Fact] - public void DateType_Binds_Only_Explicitly() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new DateType()) - .Create(); - - // assert - IType dateType = schema.QueryType.Fields["dateField"].Type; - IType dateTimeType = schema.QueryType.Fields["dateTimeField"].Type; - - Assert.IsType(dateType); - Assert.IsType(dateTimeType); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new DateType()) + .Create(); + + // assert + IType dateType = schema.QueryType.Fields["dateField"].Type; + IType dateTimeType = schema.QueryType.Fields["dateTimeField"].Type; + + Assert.IsType(dateType); + Assert.IsType(dateTimeType); + } #if NET6_0_OR_GREATER - [Fact] - public async Task DateOnly_And_TimeOnly_As_Argument_Schema() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task DateOnly_And_TimeOnly_As_Argument() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType(() => new TimeSpanType(TimeSpanFormat.DotNet)) - .ExecuteRequestAsync( - @"{ + [Fact] + public async Task DateOnly_And_TimeOnly_As_Argument_Schema() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + [Fact] + public async Task DateOnly_And_TimeOnly_As_Argument() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType(() => new TimeSpanType(TimeSpanFormat.DotNet)) + .ExecuteRequestAsync( + @"{ foo { time(time: ""11:22"") date(date: ""2017-12-30"") } }") - .MatchSnapshotAsync(); - } - - [Fact] - public async Task DateOnly_And_TimeOnly_As_ReturnValue_Schema() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .BuildSchemaAsync() - .MatchSnapshotAsync(); - } - - [Fact] - public async Task DateOnly_And_TimeOnly_As_ReturnValue() - { - Snapshot.FullName(); - - await new ServiceCollection() - .AddGraphQL() - .AddQueryType() - .AddType(() => new TimeSpanType(TimeSpanFormat.DotNet)) - .ExecuteRequestAsync( - @"{ + .MatchSnapshotAsync(); + } + + [Fact] + public async Task DateOnly_And_TimeOnly_As_ReturnValue_Schema() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .BuildSchemaAsync() + .MatchSnapshotAsync(); + } + + [Fact] + public async Task DateOnly_And_TimeOnly_As_ReturnValue() + { + Snapshot.FullName(); + + await new ServiceCollection() + .AddGraphQL() + .AddQueryType() + .AddType(() => new TimeSpanType(TimeSpanFormat.DotNet)) + .ExecuteRequestAsync( + @"{ bar { time date } }") - .MatchSnapshotAsync(); - } + .MatchSnapshotAsync(); + } #endif - public class Query - { - [GraphQLType(typeof(DateType))] - public DateTime? DateField => DateTime.UtcNow; + public class Query + { + [GraphQLType(typeof(DateType))] + public DateTime? DateField => DateTime.UtcNow; - public DateTime? DateTimeField => DateTime.UtcNow; - } + public DateTime? DateTimeField => DateTime.UtcNow; + } #if NET6_0_OR_GREATER - public class QueryDateTime1 - { - public Foo Foo => new(); - } - - public class Foo - { - public TimeSpan GetTime(TimeOnly time) => time.ToTimeSpan(); - - public DateTime GetDate(DateOnly date) - => date.ToDateTime(new TimeOnly(15, 0), DateTimeKind.Utc); - } - - public class QueryDateTime2 - { - public Bar Bar => new(); - } - - public class Bar - { - public TimeOnly GetTime() => TimeOnly.MaxValue; - - public DateOnly GetDate() => DateOnly.MaxValue; - } -#endif + public class QueryDateTime1 + { + public Foo Foo => new(); } + + public class Foo + { + public TimeSpan GetTime(TimeOnly time) => time.ToTimeSpan(); + + public DateTime GetDate(DateOnly date) + => date.ToDateTime(new TimeOnly(15, 0), DateTimeKind.Utc); + } + + public class QueryDateTime2 + { + public Bar Bar => new(); + } + + public class Bar + { + public TimeOnly GetTime() => TimeOnly.MaxValue; + + public DateOnly GetDate() => DateOnly.MaxValue; + } +#endif } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DecimalTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DecimalTypeTests.cs index 7c99dbb5adb..3e7c9e97ac4 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DecimalTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/DecimalTypeTests.cs @@ -3,394 +3,393 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class DecimalTypeTests { - public class DecimalTypeTests + [Fact] + public void IsInstanceOfType_FloatLiteral_True() + { + // arrange + var type = new DecimalType(); + + // act + var result = type.IsInstanceOfType(CreateExponentialLiteral()); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullLiteral_True() + { + // arrange + var type = new DecimalType(); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_IntLiteral_True() + { + // arrange + var type = new DecimalType(); + + // act + var result = type.IsInstanceOfType(new IntValueNode(123)); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringLiteral_False() + { + // arrange + var type = new DecimalType(); + + // act + var result = type.IsInstanceOfType(new StringValueNode("123")); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new DecimalType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new DecimalType(); + var value = 123.456M; + + // act + var serializedValue = type.Serialize(value); + + // assert + Assert.IsType(serializedValue); + Assert.Equal(value, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new DecimalType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new DecimalType(); + var input = "abc"; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void Serialize_MaxValue_Violation() + { + // arrange + var type = new DecimalType(0, 100); + var value = 123.456M; + + // act + // assert + Assert.Throws( + () => type.Serialize(value)); + } + + [Fact] + public void ParseLiteral_FixedPointLiteral() + { + // arrange + var type = new DecimalType(); + var literal = CreateFixedPointLiteral(); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToDecimal(), value); + } + + [Fact] + public void ParseLiteral_ExponentialLiteral() + { + // arrange + var type = new DecimalType(); + var literal = CreateExponentialLiteral(); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToDecimal(), value); + } + + [Fact] + public void ParseLiteral_IntLiteral() + { + // arrange + var type = new DecimalType(); + var literal = new IntValueNode(123); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToDecimal(), value); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new DecimalType(); + + // act + var output = type.ParseLiteral(NullValueNode.Default); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new DecimalType(); + var input = new StringValueNode("abc"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new DecimalType(); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_MaxValue() + { + // arrange + var type = new DecimalType(1, 100); + var input = 100M; + + // act + var literal = (FloatValueNode)type.ParseValue(input); + + // assert + Assert.Equal(100M, literal.ToDecimal()); + } + + [Fact] + public void ParseValue_MaxValue_Violation() + { + // arrange + var type = new DecimalType(1, 100); + var input = 101M; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_MinValue() + { + // arrange + var type = new DecimalType(1, 100); + var input = 1M; + + // act + var literal = (FloatValueNode)type.ParseValue(input); + + // assert + Assert.Equal(1M, literal.ToDecimal()); + } + + [Fact] + public void ParseValue_MinValue_Violation() + { + // arrange + var type = new DecimalType(1, 100); + var input = 0M; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void ParseValue_Wrong_Value_Throws() { - [Fact] - public void IsInstanceOfType_FloatLiteral_True() - { - // arrange - var type = new DecimalType(); - - // act - var result = type.IsInstanceOfType(CreateExponentialLiteral()); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullLiteral_True() - { - // arrange - var type = new DecimalType(); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_IntLiteral_True() - { - // arrange - var type = new DecimalType(); - - // act - var result = type.IsInstanceOfType(new IntValueNode(123)); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringLiteral_False() - { - // arrange - var type = new DecimalType(); - - // act - var result = type.IsInstanceOfType(new StringValueNode("123")); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new DecimalType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new DecimalType(); - decimal value = 123.456M; - - // act - var serializedValue = type.Serialize(value); - - // assert - Assert.IsType(serializedValue); - Assert.Equal(value, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new DecimalType(); - - // act - var serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new DecimalType(); - var input = "abc"; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void Serialize_MaxValue_Violation() - { - // arrange - var type = new DecimalType(0, 100); - decimal value = 123.456M; - - // act - // assert - Assert.Throws( - () => type.Serialize(value)); - } - - [Fact] - public void ParseLiteral_FixedPointLiteral() - { - // arrange - var type = new DecimalType(); - FloatValueNode literal = CreateFixedPointLiteral(); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToDecimal(), value); - } - - [Fact] - public void ParseLiteral_ExponentialLiteral() - { - // arrange - var type = new DecimalType(); - FloatValueNode literal = CreateExponentialLiteral(); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToDecimal(), value); - } - - [Fact] - public void ParseLiteral_IntLiteral() - { - // arrange - var type = new DecimalType(); - var literal = new IntValueNode(123); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToDecimal(), value); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new DecimalType(); - - // act - var output = type.ParseLiteral(NullValueNode.Default); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new DecimalType(); - var input = new StringValueNode("abc"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new DecimalType(); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_MaxValue() - { - // arrange - var type = new DecimalType(1, 100); - decimal input = 100M; - - // act - var literal = (FloatValueNode)type.ParseValue(input); - - // assert - Assert.Equal(100M, literal.ToDecimal()); - } - - [Fact] - public void ParseValue_MaxValue_Violation() - { - // arrange - var type = new DecimalType(1, 100); - decimal input = 101M; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_MinValue() - { - // arrange - var type = new DecimalType(1, 100); - decimal input = 1M; - - // act - var literal = (FloatValueNode)type.ParseValue(input); - - // assert - Assert.Equal(1M, literal.ToDecimal()); - } - - [Fact] - public void ParseValue_MinValue_Violation() - { - // arrange - var type = new DecimalType(1, 100); - decimal input = 0M; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new DecimalType(); - var value = "123"; - - // act - // assert - Assert.Throws( - () => type.ParseValue(value)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new DecimalType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_Nullable() - { - // arrange - var type = new DecimalType(); - decimal? input = 123M; - - // act - FloatValueNode output = (FloatValueNode)type.ParseValue(input); - - // assert - Assert.Equal(123M, output.ToDecimal()); - } - - [Fact] - public void Ensure_TypeKind_is_Scalar() - { - // arrange - var type = new DecimalType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } - - [Fact] - public void ParseValue_HandlesMoreThan6Digits() - { - // arrange - var type = new DecimalType(); - var input = 1234567.1234567m; - var output = "1234567.1234567"; - - // act - var result = type.ParseValue(input); - - // assert - Assert.True(result is FloatValueNode); - Assert.True(result.Value is string); - Assert.Equal(output, (string)result.Value); - } - - [Fact] - public void ParseValue_FormatsToDefaultSignificantDigits() - { - // arrange - var type = new DecimalType(); - var input = 1234567.891123456789m; - var output = "1234567.891123456789"; - - // act - var result = type.ParseValue(input); - - // assert - Assert.True(result is FloatValueNode); - Assert.True(result.Value is string); - Assert.Equal(output, (string)result.Value); - } - - [Fact] - public void ParseValue_Handle12Digits() - { - // arrange - var type = new DecimalType(); - var input = 1234567.890123456789m; - var output = "1234567.890123456789"; - - // act - var result = type.ParseValue(input); - - // assert - Assert.True(result is FloatValueNode); - Assert.True(result.Value is string); - Assert.Equal(output, (string)result.Value); - } - - [Fact] - public void ParseValue_FormatsToSpecifiedNumberOfDecimalDigitsLong() - { - // arrange - var type = new DecimalType(); - var input = 1234567.890123456789m; - var output = "1234567.890123456789"; - - // act - var result = type.ParseValue(input); - - // assert - Assert.True(result is FloatValueNode); - Assert.True(result.Value is string); - Assert.Equal(output, (string)result.Value); - } - - private FloatValueNode CreateExponentialLiteral() => - new FloatValueNode(Encoding.UTF8.GetBytes("1.000000E+000"), FloatFormat.Exponential); - - private FloatValueNode CreateFixedPointLiteral() => - new FloatValueNode(Encoding.UTF8.GetBytes("1.23"), FloatFormat.FixedPoint); + // arrange + var type = new DecimalType(); + var value = "123"; + + // act + // assert + Assert.Throws( + () => type.ParseValue(value)); } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new DecimalType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_Nullable() + { + // arrange + var type = new DecimalType(); + decimal? input = 123M; + + // act + var output = (FloatValueNode)type.ParseValue(input); + + // assert + Assert.Equal(123M, output.ToDecimal()); + } + + [Fact] + public void Ensure_TypeKind_is_Scalar() + { + // arrange + var type = new DecimalType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); + } + + [Fact] + public void ParseValue_HandlesMoreThan6Digits() + { + // arrange + var type = new DecimalType(); + var input = 1234567.1234567m; + var output = "1234567.1234567"; + + // act + var result = type.ParseValue(input); + + // assert + Assert.True(result is FloatValueNode); + Assert.True(result.Value is string); + Assert.Equal(output, (string)result.Value); + } + + [Fact] + public void ParseValue_FormatsToDefaultSignificantDigits() + { + // arrange + var type = new DecimalType(); + var input = 1234567.891123456789m; + var output = "1234567.891123456789"; + + // act + var result = type.ParseValue(input); + + // assert + Assert.True(result is FloatValueNode); + Assert.True(result.Value is string); + Assert.Equal(output, (string)result.Value); + } + + [Fact] + public void ParseValue_Handle12Digits() + { + // arrange + var type = new DecimalType(); + var input = 1234567.890123456789m; + var output = "1234567.890123456789"; + + // act + var result = type.ParseValue(input); + + // assert + Assert.True(result is FloatValueNode); + Assert.True(result.Value is string); + Assert.Equal(output, (string)result.Value); + } + + [Fact] + public void ParseValue_FormatsToSpecifiedNumberOfDecimalDigitsLong() + { + // arrange + var type = new DecimalType(); + var input = 1234567.890123456789m; + var output = "1234567.890123456789"; + + // act + var result = type.ParseValue(input); + + // assert + Assert.True(result is FloatValueNode); + Assert.True(result.Value is string); + Assert.Equal(output, (string)result.Value); + } + + private FloatValueNode CreateExponentialLiteral() => + new FloatValueNode(Encoding.UTF8.GetBytes("1.000000E+000"), FloatFormat.Exponential); + + private FloatValueNode CreateFixedPointLiteral() => + new FloatValueNode(Encoding.UTF8.GetBytes("1.23"), FloatFormat.FixedPoint); } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/FloatTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/FloatTypeTests.cs index 990fa3aee0b..3ff599197e7 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/FloatTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/FloatTypeTests.cs @@ -3,326 +3,325 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class FloatTypeTests { - public class FloatTypeTests + [Fact] + public void IsInstanceOfType_FloatLiteral_True() + { + // arrange + var type = new FloatType(); + + // act + var result = type.IsInstanceOfType(CreateExponentialLiteral()); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullLiteral_True() + { + // arrange + var type = new FloatType(); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_IntLiteral_True() + { + // arrange + var type = new FloatType(); + + // act + var result = type.IsInstanceOfType(new IntValueNode(123)); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringLiteral_False() + { + // arrange + var type = new FloatType(); + + // act + var result = type.IsInstanceOfType(new StringValueNode("123")); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new FloatType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new FloatType(); + var value = 123.456; + + // act + var serializedValue = type.Serialize(value); + + // assert + Assert.IsType(serializedValue); + Assert.Equal(value, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new FloatType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new FloatType(); + var input = "abc"; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void Serialize_MaxValue_Violation() + { + // arrange + var type = new FloatType(0, 100); + var value = 123.456; + + // act + // assert + Assert.Throws( + () => type.Serialize(value)); + } + + [Fact] + public void ParseLiteral_FixedPointLiteral() + { + // arrange + var type = new FloatType(); + var literal = CreateFixedPointLiteral(); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToDouble(), value); + } + + [Fact] + public void ParseLiteral_ExponentialLiteral() + { + // arrange + var type = new FloatType(); + var literal = CreateExponentialLiteral(); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToDouble(), value); + } + + [Fact] + public void ParseLiteral_IntLiteral() + { + // arrange + var type = new FloatType(); + var literal = new IntValueNode(123); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToDouble(), value); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new FloatType(); + + // act + var output = type.ParseLiteral(NullValueNode.Default); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new FloatType(); + var input = new StringValueNode("abc"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() { - [Fact] - public void IsInstanceOfType_FloatLiteral_True() - { - // arrange - var type = new FloatType(); - - // act - var result = type.IsInstanceOfType(CreateExponentialLiteral()); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullLiteral_True() - { - // arrange - var type = new FloatType(); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_IntLiteral_True() - { - // arrange - var type = new FloatType(); - - // act - var result = type.IsInstanceOfType(new IntValueNode(123)); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringLiteral_False() - { - // arrange - var type = new FloatType(); - - // act - var result = type.IsInstanceOfType(new StringValueNode("123")); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new FloatType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new FloatType(); - double value = 123.456; - - // act - var serializedValue = type.Serialize(value); - - // assert - Assert.IsType(serializedValue); - Assert.Equal(value, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new FloatType(); - - // act - var serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new FloatType(); - var input = "abc"; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void Serialize_MaxValue_Violation() - { - // arrange - var type = new FloatType(0, 100); - double value = 123.456; - - // act - // assert - Assert.Throws( - () => type.Serialize(value)); - } - - [Fact] - public void ParseLiteral_FixedPointLiteral() - { - // arrange - var type = new FloatType(); - FloatValueNode literal = CreateFixedPointLiteral(); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToDouble(), value); - } - - [Fact] - public void ParseLiteral_ExponentialLiteral() - { - // arrange - var type = new FloatType(); - FloatValueNode literal = CreateExponentialLiteral(); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToDouble(), value); - } - - [Fact] - public void ParseLiteral_IntLiteral() - { - // arrange - var type = new FloatType(); - var literal = new IntValueNode(123); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToDouble(), value); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new FloatType(); - - // act - var output = type.ParseLiteral(NullValueNode.Default); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new FloatType(); - var input = new StringValueNode("abc"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new FloatType(); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_MaxValue() - { - // arrange - var type = new FloatType(1, 100); - double input = 100; - - // act - var literal = (FloatValueNode)type.ParseValue(input); - - // assert - Assert.Equal(100, literal.ToDouble()); - } - - [Fact] - public void ParseValue_MaxValue_Violation() - { - // arrange - var type = new FloatType(1, 100); - double input = 101; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_MinValue() - { - // arrange - var type = new FloatType(1, 100); - double input = 1; - - // act - var literal = (FloatValueNode)type.ParseValue(input); - - // assert - Assert.Equal(1, literal.ToDouble()); - } - - [Fact] - public void ParseValue_MinValue_Violation() - { - // arrange - var type = new FloatType(1, 100); - double input = 0; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new FloatType(); - var value = "123"; - - // act - // assert - Assert.Throws( - () => type.ParseValue(value)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new FloatType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_Nullable() - { - // arrange - var type = new FloatType(); - double? input = 123; - - // act - FloatValueNode output = (FloatValueNode)type.ParseValue(input); - - // assert - Assert.Equal(123, output.ToDouble()); - } - - [Fact] - public void Ensure_TypeKind_is_Scalar() - { - // arrange - var type = new FloatType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } - - private FloatValueNode CreateExponentialLiteral() => - new FloatValueNode(Encoding.UTF8.GetBytes("1.000000E+000"), FloatFormat.Exponential); - - private FloatValueNode CreateFixedPointLiteral() => - new FloatValueNode(Encoding.UTF8.GetBytes("1.23"), FloatFormat.FixedPoint); + // arrange + var type = new FloatType(); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_MaxValue() + { + // arrange + var type = new FloatType(1, 100); + double input = 100; + + // act + var literal = (FloatValueNode)type.ParseValue(input); + + // assert + Assert.Equal(100, literal.ToDouble()); + } + + [Fact] + public void ParseValue_MaxValue_Violation() + { + // arrange + var type = new FloatType(1, 100); + double input = 101; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_MinValue() + { + // arrange + var type = new FloatType(1, 100); + double input = 1; + + // act + var literal = (FloatValueNode)type.ParseValue(input); + + // assert + Assert.Equal(1, literal.ToDouble()); } + + [Fact] + public void ParseValue_MinValue_Violation() + { + // arrange + var type = new FloatType(1, 100); + double input = 0; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new FloatType(); + var value = "123"; + + // act + // assert + Assert.Throws( + () => type.ParseValue(value)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new FloatType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_Nullable() + { + // arrange + var type = new FloatType(); + double? input = 123; + + // act + var output = (FloatValueNode)type.ParseValue(input); + + // assert + Assert.Equal(123, output.ToDouble()); + } + + [Fact] + public void Ensure_TypeKind_is_Scalar() + { + // arrange + var type = new FloatType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); + } + + private FloatValueNode CreateExponentialLiteral() => + new FloatValueNode(Encoding.UTF8.GetBytes("1.000000E+000"), FloatFormat.Exponential); + + private FloatValueNode CreateFixedPointLiteral() => + new FloatValueNode(Encoding.UTF8.GetBytes("1.23"), FloatFormat.FixedPoint); } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IdTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IdTypeTests.cs index 0b42891f121..aeff3074969 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IdTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IdTypeTests.cs @@ -2,340 +2,339 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class IdTypeTests { - public class IdTypeTests + [Fact] + public void Create_With_Default_Name() + { + // arrange + // act + var type = new IdType(); + + // assert + Assert.Equal(ScalarNames.ID, type.Name); + } + + [Fact] + public void Create_With_Name() + { + // arrange + // act + var type = new IdType("Foo"); + + // assert + Assert.Equal("Foo", type.Name); + } + + [Fact] + public void Create_With_Name_And_Description() + { + // arrange + // act + var type = new IdType("Foo", "Bar"); + + // assert + Assert.Equal("Foo", type.Name); + Assert.Equal("Bar", type.Description); + } + + [Fact] + public void EnsureStringTypeKindIsCorret() + { + // arrange + var type = new IdType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [Fact] + public void IsInstanceOfType_StringValueNode() + { + // arrange + var type = new IdType(); + var input = new StringValueNode("123456"); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + + [Fact] + public void IsInstanceOfType_IntValueNode() + { + // arrange + var type = new IdType(); + var input = new IntValueNode(123456); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullValueNode() + { + // arrange + var type = new IdType(); + var input = NullValueNode.Default; + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_Wrong_ValueNode() + { + // arrange + var type = new IdType(); + var input = new FloatValueNode(123456.0); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new IdType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_String() + { + // arrange + var type = new IdType(); + var input = "123456"; + + // act + var serializedValue = type.Serialize(input); + + // assert + Assert.IsType(serializedValue); + Assert.Equal("123456", serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new IdType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Deserialize_String() { - [Fact] - public void Create_With_Default_Name() - { - // arrange - // act - var type = new IdType(); - - // assert - Assert.Equal(ScalarNames.ID, type.Name); - } - - [Fact] - public void Create_With_Name() - { - // arrange - // act - var type = new IdType("Foo"); - - // assert - Assert.Equal("Foo", type.Name); - } - - [Fact] - public void Create_With_Name_And_Description() - { - // arrange - // act - var type = new IdType("Foo", "Bar"); - - // assert - Assert.Equal("Foo", type.Name); - Assert.Equal("Bar", type.Description); - } - - [Fact] - public void EnsureStringTypeKindIsCorret() - { - // arrange - var type = new IdType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [Fact] - public void IsInstanceOfType_StringValueNode() - { - // arrange - var type = new IdType(); - var input = new StringValueNode("123456"); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - - [Fact] - public void IsInstanceOfType_IntValueNode() - { - // arrange - var type = new IdType(); - var input = new IntValueNode(123456); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullValueNode() - { - // arrange - var type = new IdType(); - NullValueNode input = NullValueNode.Default; - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_Wrong_ValueNode() - { - // arrange - var type = new IdType(); - var input = new FloatValueNode(123456.0); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new IdType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_String() - { - // arrange - var type = new IdType(); - var input = "123456"; - - // act - object serializedValue = type.Serialize(input); - - // assert - Assert.IsType(serializedValue); - Assert.Equal("123456", serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new IdType(); - - // act - object serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Deserialize_String() - { - // arrange - var type = new IdType(); - var serialized = "123456"; - - // act - bool success = type.TryDeserialize(serialized, out object value); - - // assert - Assert.True(success); - Assert.Equal("123456", Assert.IsType(value)); - } - - [Fact] - public void Deserialize_Int() - { - // arrange - IdType type = SchemaBuilder.New() - .AddQueryType(c => c - .Name("QueryRoot") - .Field("abc") - .Type() - .Resolve("abc")) - .Create() - .GetType("ID"); - var serialized = 123456; - - // act - bool success = type.TryDeserialize(serialized, out object value); - - // assert - Assert.True(success); - Assert.Equal("123456", Assert.IsType(value)); - } - - [Fact] - public void Deserialize_Null() - { - // arrange - var type = new IdType(); - object serialized = null; - - // act - bool success = type.TryDeserialize(serialized, out object value); - - // assert - Assert.Null(value); - } - - [Fact] - public void Deserialize_Float() - { - // arrange - var type = new IdType(); - float serialized = 1.1f; - - // act - bool success = type.TryDeserialize(serialized, out object value); - - // assert - Assert.False(success); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new IdType(); - object input = Guid.NewGuid(); - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void ParseLiteral_StringValueNode() - { - // arrange - var type = new IdType(); - var input = new StringValueNode("123456"); - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.IsType(output); - Assert.Equal("123456", output); - } - - [Fact] - public void ParseLiteral_IntValueNode() - { - // arrange - var type = new IdType(); - var input = new IntValueNode(123456); - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.IsType(output); - Assert.Equal("123456", output); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new IdType(); - NullValueNode input = NullValueNode.Default; - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new IdType(); - var input = new FloatValueNode(123456.0); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new IdType(); - - // act - // assert - Assert.Throws(() => - type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new IdType(); - object input = 123.456; - - // act - // assert - Assert.Throws( - () => type.ParseValue(input)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new IdType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_String() - { - // arrange - var type = new IdType(); - object input = "hello"; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } + // arrange + var type = new IdType(); + var serialized = "123456"; + + // act + var success = type.TryDeserialize(serialized, out var value); + + // assert + Assert.True(success); + Assert.Equal("123456", Assert.IsType(value)); + } + + [Fact] + public void Deserialize_Int() + { + // arrange + var type = SchemaBuilder.New() + .AddQueryType(c => c + .Name("QueryRoot") + .Field("abc") + .Type() + .Resolve("abc")) + .Create() + .GetType("ID"); + var serialized = 123456; + + // act + var success = type.TryDeserialize(serialized, out var value); + + // assert + Assert.True(success); + Assert.Equal("123456", Assert.IsType(value)); + } + + [Fact] + public void Deserialize_Null() + { + // arrange + var type = new IdType(); + object serialized = null; + + // act + var success = type.TryDeserialize(serialized, out var value); + + // assert + Assert.Null(value); + } + + [Fact] + public void Deserialize_Float() + { + // arrange + var type = new IdType(); + var serialized = 1.1f; + + // act + var success = type.TryDeserialize(serialized, out var value); + + // assert + Assert.False(success); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new IdType(); + object input = Guid.NewGuid(); + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void ParseLiteral_StringValueNode() + { + // arrange + var type = new IdType(); + var input = new StringValueNode("123456"); + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.IsType(output); + Assert.Equal("123456", output); + } + + [Fact] + public void ParseLiteral_IntValueNode() + { + // arrange + var type = new IdType(); + var input = new IntValueNode(123456); + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.IsType(output); + Assert.Equal("123456", output); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new IdType(); + var input = NullValueNode.Default; + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new IdType(); + var input = new FloatValueNode(123456.0); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new IdType(); + + // act + // assert + Assert.Throws(() => + type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new IdType(); + object input = 123.456; + + // act + // assert + Assert.Throws( + () => type.ParseValue(input)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new IdType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_String() + { + // arrange + var type = new IdType(); + object input = "hello"; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IntTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IntTypeTests.cs index 6d292236ab4..63925153230 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IntTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/IntTypeTests.cs @@ -2,278 +2,277 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class IntTypeTests { - public class IntTypeTests + [Fact] + public void IsInstanceOfType_FloatLiteral_True() + { + // arrange + var type = new IntType(); + var literal = new IntValueNode(1); + + // act + var result = type.IsInstanceOfType(literal); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullLiteral_True() { - [Fact] - public void IsInstanceOfType_FloatLiteral_True() - { - // arrange - var type = new IntType(); - var literal = new IntValueNode(1); - - // act - var result = type.IsInstanceOfType(literal); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullLiteral_True() - { - // arrange - var type = new IntType(); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringLiteral_False() - { - // arrange - var type = new IntType(); - - // act - var result = type.IsInstanceOfType(new FloatValueNode(1M)); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new IntType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new IntType(); - int value = 123; - - // act - var serializedValue = type.Serialize(value); - - // assert - Assert.IsType(serializedValue); - Assert.Equal(value, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new IntType(); - - // act - var serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new IntType(); - var input = "abc"; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void Serialize_MaxValue_Violation() - { - // arrange - var type = new IntType(0, 100); - int value = 200; - - // act - // assert - Assert.Throws( - () => type.Serialize(value)); - } - - [Fact] - public void ParseLiteral_IntLiteral() - { - // arrange - var type = new IntType(); - var literal = new IntValueNode(1); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToInt32(), value); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new IntType(); - - // act - var output = type.ParseLiteral(NullValueNode.Default); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new IntType(); - var input = new StringValueNode("abc"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new IntType(); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_MaxValue() - { - // arrange - var type = new IntType(1, 100); - int input = 100; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(100, literal.ToByte()); - } - - [Fact] - public void ParseValue_MaxValue_Violation() - { - // arrange - var type = new IntType(1, 100); - int input = 101; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_MinValue() - { - // arrange - var type = new IntType(1, 100); - int input = 1; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(1, literal.ToByte()); - } - - [Fact] - public void ParseValue_MinValue_Violation() - { - // arrange - var type = new IntType(1, 100); - int input = 0; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new IntType(); - var value = "123"; - - // act - // assert - Assert.Throws( - () => type.ParseValue(value)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new IntType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_Nullable() - { - // arrange - var type = new IntType(); - int? input = 123; - - // act - IntValueNode output = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(123, output.ToDouble()); - } - - [Fact] - public void Ensure_TypeKind_is_Scalar() - { - // arrange - var type = new IntType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } + // arrange + var type = new IntType(); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringLiteral_False() + { + // arrange + var type = new IntType(); + + // act + var result = type.IsInstanceOfType(new FloatValueNode(1M)); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new IntType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new IntType(); + var value = 123; + + // act + var serializedValue = type.Serialize(value); + + // assert + Assert.IsType(serializedValue); + Assert.Equal(value, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new IntType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new IntType(); + var input = "abc"; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void Serialize_MaxValue_Violation() + { + // arrange + var type = new IntType(0, 100); + var value = 200; + + // act + // assert + Assert.Throws( + () => type.Serialize(value)); + } + + [Fact] + public void ParseLiteral_IntLiteral() + { + // arrange + var type = new IntType(); + var literal = new IntValueNode(1); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToInt32(), value); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new IntType(); + + // act + var output = type.ParseLiteral(NullValueNode.Default); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new IntType(); + var input = new StringValueNode("abc"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new IntType(); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_MaxValue() + { + // arrange + var type = new IntType(1, 100); + var input = 100; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(100, literal.ToByte()); + } + + [Fact] + public void ParseValue_MaxValue_Violation() + { + // arrange + var type = new IntType(1, 100); + var input = 101; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_MinValue() + { + // arrange + var type = new IntType(1, 100); + var input = 1; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(1, literal.ToByte()); + } + + [Fact] + public void ParseValue_MinValue_Violation() + { + // arrange + var type = new IntType(1, 100); + var input = 0; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new IntType(); + var value = "123"; + + // act + // assert + Assert.Throws( + () => type.ParseValue(value)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new IntType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_Nullable() + { + // arrange + var type = new IntType(); + int? input = 123; + + // act + var output = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(123, output.ToDouble()); + } + + [Fact] + public void Ensure_TypeKind_is_Scalar() + { + // arrange + var type = new IntType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/LongTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/LongTypeTests.cs index 3db23171143..c2bff75138f 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/LongTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/LongTypeTests.cs @@ -2,278 +2,277 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class LongTypeTests { - public class LongTypeTests + [Fact] + public void IsInstanceOfType_FloatLiteral_True() + { + // arrange + var type = new LongType(); + var literal = new IntValueNode(1); + + // act + var result = type.IsInstanceOfType(literal); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullLiteral_True() { - [Fact] - public void IsInstanceOfType_FloatLiteral_True() - { - // arrange - var type = new LongType(); - var literal = new IntValueNode(1); - - // act - var result = type.IsInstanceOfType(literal); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullLiteral_True() - { - // arrange - var type = new LongType(); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringLiteral_False() - { - // arrange - var type = new LongType(); - - // act - var result = type.IsInstanceOfType(new FloatValueNode(1M)); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new LongType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new LongType(); - long value = 123; - - // act - var serializedValue = type.Serialize(value); - - // assert - Assert.IsType(serializedValue); - Assert.Equal(value, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new LongType(); - - // act - var serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new LongType(); - var input = "abc"; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void Serialize_MaxValue_Violation() - { - // arrange - var type = new LongType(0, 100); - long value = 200; - - // act - // assert - Assert.Throws( - () => type.Serialize(value)); - } - - [Fact] - public void ParseLiteral_IntLiteral() - { - // arrange - var type = new LongType(); - var literal = new IntValueNode(1); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToInt64(), value); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new LongType(); - - // act - var output = type.ParseLiteral(NullValueNode.Default); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new LongType(); - var input = new StringValueNode("abc"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new LongType(); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_MaxValue() - { - // arrange - var type = new LongType(1, 100); - long input = 100; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(100, literal.ToByte()); - } - - [Fact] - public void ParseValue_MaxValue_Violation() - { - // arrange - var type = new LongType(1, 100); - long input = 101; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_MinValue() - { - // arrange - var type = new LongType(1, 100); - long input = 1; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(1, literal.ToByte()); - } - - [Fact] - public void ParseValue_MinValue_Violation() - { - // arrange - var type = new LongType(1, 100); - long input = 0; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new LongType(); - var value = "123"; - - // act - // assert - Assert.Throws( - () => type.ParseValue(value)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new LongType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_Nullable() - { - // arrange - var type = new LongType(); - long? input = 123; - - // act - IntValueNode output = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(123, output.ToDouble()); - } - - [Fact] - public void Ensure_TypeKind_is_Scalar() - { - // arrange - var type = new LongType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } + // arrange + var type = new LongType(); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringLiteral_False() + { + // arrange + var type = new LongType(); + + // act + var result = type.IsInstanceOfType(new FloatValueNode(1M)); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new LongType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new LongType(); + long value = 123; + + // act + var serializedValue = type.Serialize(value); + + // assert + Assert.IsType(serializedValue); + Assert.Equal(value, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new LongType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new LongType(); + var input = "abc"; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void Serialize_MaxValue_Violation() + { + // arrange + var type = new LongType(0, 100); + long value = 200; + + // act + // assert + Assert.Throws( + () => type.Serialize(value)); + } + + [Fact] + public void ParseLiteral_IntLiteral() + { + // arrange + var type = new LongType(); + var literal = new IntValueNode(1); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToInt64(), value); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new LongType(); + + // act + var output = type.ParseLiteral(NullValueNode.Default); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new LongType(); + var input = new StringValueNode("abc"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new LongType(); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_MaxValue() + { + // arrange + var type = new LongType(1, 100); + long input = 100; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(100, literal.ToByte()); + } + + [Fact] + public void ParseValue_MaxValue_Violation() + { + // arrange + var type = new LongType(1, 100); + long input = 101; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_MinValue() + { + // arrange + var type = new LongType(1, 100); + long input = 1; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(1, literal.ToByte()); + } + + [Fact] + public void ParseValue_MinValue_Violation() + { + // arrange + var type = new LongType(1, 100); + long input = 0; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new LongType(); + var value = "123"; + + // act + // assert + Assert.Throws( + () => type.ParseValue(value)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new LongType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_Nullable() + { + // arrange + var type = new LongType(); + long? input = 123; + + // act + var output = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(123, output.ToDouble()); + } + + [Fact] + public void Ensure_TypeKind_is_Scalar() + { + // arrange + var type = new LongType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/MultiplierPathTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/MultiplierPathTypeTests.cs index 8f3369910ee..d4c7274e364 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/MultiplierPathTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/MultiplierPathTypeTests.cs @@ -13,7 +13,7 @@ public void EnsureStringTypeKindIsCorret() var type = new MultiplierPathType(); // act - TypeKind kind = type.Kind; + var kind = type.Kind; // assert Assert.Equal(TypeKind.Scalar, kind); @@ -38,7 +38,7 @@ public void IsInstanceOfType_NullValueNode() { // arrange var type = new MultiplierPathType(); - NullValueNode input = NullValueNode.Default; + var input = NullValueNode.Default; // act var result = type.IsInstanceOfType(input); @@ -150,7 +150,7 @@ public void ParseLiteral_NullValueNode() { // arrange var type = new MultiplierPathType(); - NullValueNode input = NullValueNode.Default; + var input = NullValueNode.Default; // act var output = type.ParseLiteral(input); diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/NameTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/NameTypeTests.cs index 073996531cb..11b36bbfdb3 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/NameTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/NameTypeTests.cs @@ -2,212 +2,211 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class NameTypeTests { - public class NameTypeTests + [Fact] + public void EnsureStringTypeKindIsCorret() { - [Fact] - public void EnsureStringTypeKindIsCorret() - { - // arrange - var type = new NameType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [Fact] - public void IsInstanceOfType_ValueNode() - { - // arrange - var type = new NameType(); - var input = new StringValueNode("_123456"); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullValueNode() - { - // arrange - var type = new NameType(); - NullValueNode input = NullValueNode.Default; - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_Wrong_ValueNode() - { - // arrange - var type = new NameType(); - var input = new IntValueNode(123456); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.False(result); - } - - [InlineData("1234")] - [InlineData(" ")] - [Theory] - public void IsInstanceOfType_Wrong_StringValue(string s) - { - // arrange - var type = new NameType(); - var input = new StringValueNode(s); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new NameType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new NameType(); - NameString input = "_123456"; - - // act - object serializedValue = type.Serialize(input); - - // assert - Assert.IsType(serializedValue); - Assert.Equal("_123456", serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new NameType(); - - // act - object serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new NameType(); - object input = 123456; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void ParseLiteral_ValueNode() - { - // arrange - var type = new NameType(); - var input = new StringValueNode("__123456"); - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.IsType(output); - Assert.Equal(new NameString("__123456"), output); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new NameType(); - NullValueNode input = NullValueNode.Default; - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new NameType(); - var input = new IntValueNode(123456); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new NameType(); - - // act - // assert - Assert.Throws(() => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new NameType(); - object input = 123456; - - // act - // assert - Assert.Throws( - () => type.ParseValue(input)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new NameType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } + // arrange + var type = new NameType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [Fact] + public void IsInstanceOfType_ValueNode() + { + // arrange + var type = new NameType(); + var input = new StringValueNode("_123456"); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullValueNode() + { + // arrange + var type = new NameType(); + var input = NullValueNode.Default; + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_Wrong_ValueNode() + { + // arrange + var type = new NameType(); + var input = new IntValueNode(123456); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.False(result); + } + + [InlineData("1234")] + [InlineData(" ")] + [Theory] + public void IsInstanceOfType_Wrong_StringValue(string s) + { + // arrange + var type = new NameType(); + var input = new StringValueNode(s); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new NameType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new NameType(); + NameString input = "_123456"; + + // act + var serializedValue = type.Serialize(input); + + // assert + Assert.IsType(serializedValue); + Assert.Equal("_123456", serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new NameType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new NameType(); + object input = 123456; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void ParseLiteral_ValueNode() + { + // arrange + var type = new NameType(); + var input = new StringValueNode("__123456"); + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.IsType(output); + Assert.Equal(new NameString("__123456"), output); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new NameType(); + var input = NullValueNode.Default; + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new NameType(); + var input = new IntValueNode(123456); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new NameType(); + + // act + // assert + Assert.Throws(() => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new NameType(); + object input = 123456; + + // act + // assert + Assert.Throws( + () => type.ParseValue(input)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new NameType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarBindingTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarBindingTests.cs index 1a03a75a1e3..fa79fd26ac1 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarBindingTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarBindingTests.cs @@ -4,110 +4,109 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ScalarBindingTests { - public class ScalarBindingTests + [Fact] + public void Ensure_That_Explicit_Binding_Behavior_Is_Respected_On_Scalars() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void Ensure_That_Implicit_Binding_Behavior_Is_Respected_On_Scalars() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } + + public class QueryA { - [Fact] - public void Ensure_That_Explicit_Binding_Behavior_Is_Respected_On_Scalars() + public Bar? Bar([GraphQLType(typeof(ExplicitBindingScalar))]int id) => new Bar(); + } + + public class QueryB + { + public Bar? Bar([GraphQLType(typeof(ImplicitBindingScalar))]int id) => new Bar(); + } + + public class Bar + { + public Baz? Baz { get; set; } + } + + public class Baz + { + public int Text { get; set; } + } + + public class ImplicitBindingScalar : ScalarType + { + public ImplicitBindingScalar() + : base("FOO", BindingBehavior.Implicit) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); } - [Fact] - public void Ensure_That_Implicit_Binding_Behavior_Is_Respected_On_Scalars() + public override bool IsInstanceOfType(IValueNode literal) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .Create(); - - // assert - schema.ToString().MatchSnapshot(); + throw new System.NotImplementedException(); } - public class QueryA + public override object? ParseLiteral(IValueNode valueSyntax) { - public Bar? Bar([GraphQLType(typeof(ExplicitBindingScalar))]int id) => new Bar(); + throw new System.NotImplementedException(); } - public class QueryB + public override IValueNode ParseValue(object? value) + { + throw new System.NotImplementedException(); + } + + public override IValueNode ParseResult(object? resultValue) + { + throw new System.NotImplementedException(); + } + } + + public class ExplicitBindingScalar : ScalarType + { + public ExplicitBindingScalar() + : base("FOO", BindingBehavior.Explicit) { - public Bar? Bar([GraphQLType(typeof(ImplicitBindingScalar))]int id) => new Bar(); } - public class Bar + public override bool IsInstanceOfType(IValueNode literal) { - public Baz? Baz { get; set; } + throw new System.NotImplementedException(); } - public class Baz + public override object? ParseLiteral(IValueNode valueSyntax) { - public int Text { get; set; } + throw new System.NotImplementedException(); } - public class ImplicitBindingScalar : ScalarType + public override IValueNode ParseValue(object? value) { - public ImplicitBindingScalar() - : base("FOO", BindingBehavior.Implicit) - { - } - - public override bool IsInstanceOfType(IValueNode literal) - { - throw new System.NotImplementedException(); - } - - public override object? ParseLiteral(IValueNode valueSyntax) - { - throw new System.NotImplementedException(); - } - - public override IValueNode ParseValue(object? value) - { - throw new System.NotImplementedException(); - } - - public override IValueNode ParseResult(object? resultValue) - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } - public class ExplicitBindingScalar : ScalarType + public override IValueNode ParseResult(object? resultValue) { - public ExplicitBindingScalar() - : base("FOO", BindingBehavior.Explicit) - { - } - - public override bool IsInstanceOfType(IValueNode literal) - { - throw new System.NotImplementedException(); - } - - public override object? ParseLiteral(IValueNode valueSyntax) - { - throw new System.NotImplementedException(); - } - - public override IValueNode ParseValue(object? value) - { - throw new System.NotImplementedException(); - } - - public override IValueNode ParseResult(object? resultValue) - { - throw new System.NotImplementedException(); - } + throw new System.NotImplementedException(); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarsTests.cs index fee504cb182..1349da64f8e 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ScalarsTests.cs @@ -3,148 +3,147 @@ using System.Reflection; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ScalarsTests { - public class ScalarsTests + [InlineData(Foo.Bar, ValueKind.Enum)] + [InlineData("foo", ValueKind.String)] + [InlineData((short)1, ValueKind.Integer)] + [InlineData((int)1, ValueKind.Integer)] + [InlineData((long)1, ValueKind.Integer)] + [InlineData((ushort)1, ValueKind.Integer)] + [InlineData((uint)1, ValueKind.Integer)] + [InlineData((ulong)1, ValueKind.Integer)] + [InlineData((float)1, ValueKind.Float)] + [InlineData((double)1, ValueKind.Float)] + [InlineData(null, ValueKind.Null)] + [Theory] + public void TryGetKind(object value, ValueKind expectedKind) + { + // arrange + // act + var isScalar = Scalars.TryGetKind(value, out var kind); + + // assert + Assert.True(isScalar); + Assert.Equal(expectedKind, kind); + } + + [InlineData(Foo.Bar, ValueKind.Enum)] + [InlineData((short)1, ValueKind.Integer)] + [InlineData((int)1, ValueKind.Integer)] + [InlineData((long)1, ValueKind.Integer)] + [InlineData((ushort)1, ValueKind.Integer)] + [InlineData((uint)1, ValueKind.Integer)] + [InlineData((ulong)1, ValueKind.Integer)] + [InlineData((float)1, ValueKind.Float)] + [InlineData((double)1, ValueKind.Float)] + [Theory] + public void TryGetKind_From_Nullable( + object value, + ValueKind expectedKind) + { + // arrange + var type = typeof(Nullable<>).MakeGenericType(value.GetType()); + var constructor = + type.GetConstructor(new[] { value.GetType() }); + var nullableValue = constructor!.Invoke(new[] { value }); + + // act + var isScalar = Scalars.TryGetKind( + nullableValue, out var kind); + + // assert + Assert.True(isScalar); + Assert.Equal(expectedKind, kind); + } + + [Fact] + public void Decimal_Is_Float() + { + // arrange + var d = 123.123M; + + // act + var isScalar = Scalars.TryGetKind(d, out var kind); + + // assert + Assert.True(isScalar); + Assert.Equal(ValueKind.Float, kind); + } + + [Fact] + public void NullableDecimal_Is_Float() + { + // arrange + decimal? d = 123.123M; + + // act + var isScalar = Scalars.TryGetKind(d, out var kind); + + // assert + Assert.True(isScalar); + Assert.Equal(ValueKind.Float, kind); + } + + [Fact] + public void Object_Is_Not_A_Serialized_Scalar() + { + // arrange + var o = new object(); + + // act + var isScalar = Scalars.TryGetKind(o, out _); + + // assert + Assert.False(isScalar); + } + + [Fact] + public void List_From_ListOfObject() + { + // arrange + var list = new List(); + + // act + var success = Scalars.TryGetKind(list, out var kind); + + // assert + Assert.True(success); + Assert.Equal(ValueKind.List, kind); + } + + [Fact] + public void List_From_ArrayOfObject() + { + // arrange + var list = new object[0]; + + // act + var success = Scalars.TryGetKind(list, out var kind); + + // assert + Assert.True(success); + Assert.Equal(ValueKind.List, kind); + } + + [Fact] + public void Object_From_Dictionary() + { + // arrange + var list = new Dictionary(); + + // act + var success = Scalars.TryGetKind(list, out var kind); + + // assert + Assert.True(success); + Assert.Equal(ValueKind.Object, kind); + } + + public enum Foo { - [InlineData(Foo.Bar, ValueKind.Enum)] - [InlineData("foo", ValueKind.String)] - [InlineData((short)1, ValueKind.Integer)] - [InlineData((int)1, ValueKind.Integer)] - [InlineData((long)1, ValueKind.Integer)] - [InlineData((ushort)1, ValueKind.Integer)] - [InlineData((uint)1, ValueKind.Integer)] - [InlineData((ulong)1, ValueKind.Integer)] - [InlineData((float)1, ValueKind.Float)] - [InlineData((double)1, ValueKind.Float)] - [InlineData(null, ValueKind.Null)] - [Theory] - public void TryGetKind(object value, ValueKind expectedKind) - { - // arrange - // act - var isScalar = Scalars.TryGetKind(value, out ValueKind kind); - - // assert - Assert.True(isScalar); - Assert.Equal(expectedKind, kind); - } - - [InlineData(Foo.Bar, ValueKind.Enum)] - [InlineData((short)1, ValueKind.Integer)] - [InlineData((int)1, ValueKind.Integer)] - [InlineData((long)1, ValueKind.Integer)] - [InlineData((ushort)1, ValueKind.Integer)] - [InlineData((uint)1, ValueKind.Integer)] - [InlineData((ulong)1, ValueKind.Integer)] - [InlineData((float)1, ValueKind.Float)] - [InlineData((double)1, ValueKind.Float)] - [Theory] - public void TryGetKind_From_Nullable( - object value, - ValueKind expectedKind) - { - // arrange - Type type = typeof(Nullable<>).MakeGenericType(value.GetType()); - ConstructorInfo constructor = - type.GetConstructor(new[] { value.GetType() }); - var nullableValue = constructor!.Invoke(new[] { value }); - - // act - var isScalar = Scalars.TryGetKind( - nullableValue, out ValueKind kind); - - // assert - Assert.True(isScalar); - Assert.Equal(expectedKind, kind); - } - - [Fact] - public void Decimal_Is_Float() - { - // arrange - var d = 123.123M; - - // act - var isScalar = Scalars.TryGetKind(d, out ValueKind kind); - - // assert - Assert.True(isScalar); - Assert.Equal(ValueKind.Float, kind); - } - - [Fact] - public void NullableDecimal_Is_Float() - { - // arrange - decimal? d = 123.123M; - - // act - var isScalar = Scalars.TryGetKind(d, out ValueKind kind); - - // assert - Assert.True(isScalar); - Assert.Equal(ValueKind.Float, kind); - } - - [Fact] - public void Object_Is_Not_A_Serialized_Scalar() - { - // arrange - var o = new object(); - - // act - var isScalar = Scalars.TryGetKind(o, out _); - - // assert - Assert.False(isScalar); - } - - [Fact] - public void List_From_ListOfObject() - { - // arrange - var list = new List(); - - // act - var success = Scalars.TryGetKind(list, out ValueKind kind); - - // assert - Assert.True(success); - Assert.Equal(ValueKind.List, kind); - } - - [Fact] - public void List_From_ArrayOfObject() - { - // arrange - var list = new object[0]; - - // act - var success = Scalars.TryGetKind(list, out ValueKind kind); - - // assert - Assert.True(success); - Assert.Equal(ValueKind.List, kind); - } - - [Fact] - public void Object_From_Dictionary() - { - // arrange - var list = new Dictionary(); - - // act - var success = Scalars.TryGetKind(list, out ValueKind kind); - - // assert - Assert.True(success); - Assert.Equal(ValueKind.Object, kind); - } - - public enum Foo - { - Bar - } + Bar } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ShortTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ShortTypeTests.cs index b1ca9e9bede..c961523ea7a 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ShortTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/ShortTypeTests.cs @@ -2,278 +2,277 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class ShortTypeTests { - public class ShortTypeTests + [Fact] + public void IsInstanceOfType_FloatLiteral_True() + { + // arrange + var type = new ShortType(); + var literal = new IntValueNode(1); + + // act + var result = type.IsInstanceOfType(literal); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullLiteral_True() { - [Fact] - public void IsInstanceOfType_FloatLiteral_True() - { - // arrange - var type = new ShortType(); - var literal = new IntValueNode(1); - - // act - var result = type.IsInstanceOfType(literal); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullLiteral_True() - { - // arrange - var type = new ShortType(); - - // act - var result = type.IsInstanceOfType(NullValueNode.Default); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_StringLiteral_False() - { - // arrange - var type = new ShortType(); - - // act - var result = type.IsInstanceOfType(new FloatValueNode(1M)); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new ShortType(); - - // act - // assert - Assert.Throws( - () => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new ShortType(); - short value = 123; - - // act - var serializedValue = type.Serialize(value); - - // assert - Assert.IsType(serializedValue); - Assert.Equal(value, serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new ShortType(); - - // act - var serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new ShortType(); - var input = "abc"; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void Serialize_MaxValue_Violation() - { - // arrange - var type = new ShortType(0, 100); - short value = 200; - - // act - // assert - Assert.Throws( - () => type.Serialize(value)); - } - - [Fact] - public void ParseLiteral_IntLiteral() - { - // arrange - var type = new ShortType(); - var literal = new IntValueNode(1); - - // act - var value = type.ParseLiteral(literal); - - // assert - Assert.IsType(value); - Assert.Equal(literal.ToInt16(), value); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new ShortType(); - - // act - var output = type.ParseLiteral(NullValueNode.Default); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new ShortType(); - var input = new StringValueNode("abc"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new ShortType(); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_MaxValue() - { - // arrange - var type = new ShortType(1, 100); - short input = 100; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(100, literal.ToByte()); - } - - [Fact] - public void ParseValue_MaxValue_Violation() - { - // arrange - var type = new ShortType(1, 100); - short input = 101; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - [Fact] - public void ParseValue_MinValue() - { - // arrange - var type = new ShortType(1, 100); - short input = 1; - - // act - var literal = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(1, literal.ToByte()); - } - - [Fact] - public void ParseValue_MinValue_Violation() - { - // arrange - var type = new ShortType(1, 100); - short input = 0; - - // act - Action action = () => type.ParseValue(input); - - // assert - Assert.Throws(action); - } - - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new ShortType(); - var value = "123"; - - // act - // assert - Assert.Throws( - () => type.ParseValue(value)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new ShortType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } - - [Fact] - public void ParseValue_Nullable() - { - // arrange - var type = new ShortType(); - short? input = 123; - - // act - IntValueNode output = (IntValueNode)type.ParseValue(input); - - // assert - Assert.Equal(123, output.ToDouble()); - } - - [Fact] - public void Ensure_TypeKind_is_Scalar() - { - // arrange - var type = new ShortType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, kind); - } + // arrange + var type = new ShortType(); + + // act + var result = type.IsInstanceOfType(NullValueNode.Default); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_StringLiteral_False() + { + // arrange + var type = new ShortType(); + + // act + var result = type.IsInstanceOfType(new FloatValueNode(1M)); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new ShortType(); + + // act + // assert + Assert.Throws( + () => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new ShortType(); + short value = 123; + + // act + var serializedValue = type.Serialize(value); + + // assert + Assert.IsType(serializedValue); + Assert.Equal(value, serializedValue); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var type = new ShortType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new ShortType(); + var input = "abc"; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void Serialize_MaxValue_Violation() + { + // arrange + var type = new ShortType(0, 100); + short value = 200; + + // act + // assert + Assert.Throws( + () => type.Serialize(value)); + } + + [Fact] + public void ParseLiteral_IntLiteral() + { + // arrange + var type = new ShortType(); + var literal = new IntValueNode(1); + + // act + var value = type.ParseLiteral(literal); + + // assert + Assert.IsType(value); + Assert.Equal(literal.ToInt16(), value); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new ShortType(); + + // act + var output = type.ParseLiteral(NullValueNode.Default); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new ShortType(); + var input = new StringValueNode("abc"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new ShortType(); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_MaxValue() + { + // arrange + var type = new ShortType(1, 100); + short input = 100; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(100, literal.ToByte()); + } + + [Fact] + public void ParseValue_MaxValue_Violation() + { + // arrange + var type = new ShortType(1, 100); + short input = 101; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + [Fact] + public void ParseValue_MinValue() + { + // arrange + var type = new ShortType(1, 100); + short input = 1; + + // act + var literal = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(1, literal.ToByte()); + } + + [Fact] + public void ParseValue_MinValue_Violation() + { + // arrange + var type = new ShortType(1, 100); + short input = 0; + + // act + Action action = () => type.ParseValue(input); + + // assert + Assert.Throws(action); + } + + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new ShortType(); + var value = "123"; + + // act + // assert + Assert.Throws( + () => type.ParseValue(value)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new ShortType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); + } + + [Fact] + public void ParseValue_Nullable() + { + // arrange + var type = new ShortType(); + short? input = 123; + + // act + var output = (IntValueNode)type.ParseValue(input); + + // assert + Assert.Equal(123, output.ToDouble()); + } + + [Fact] + public void Ensure_TypeKind_is_Scalar() + { + // arrange + var type = new ShortType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, kind); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/StringTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/StringTypeTests.cs index 9316eed9356..e9e590aef50 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/StringTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/StringTypeTests.cs @@ -2,195 +2,194 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class StringTypeTests { - public class StringTypeTests + [Fact] + public void EnsureStringTypeKindIsCorret() + { + // arrange + var type = new StringType(); + + // act + var kind = type.Kind; + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [Fact] + public void IsInstanceOfType_ValueNode() + { + // arrange + var type = new StringType(); + var input = new StringValueNode("123456"); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_NullValueNode() + { + // arrange + var type = new StringType(); + var input = NullValueNode.Default; + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.True(result); + } + + [Fact] + public void IsInstanceOfType_Wrong_ValueNode() + { + // arrange + var type = new StringType(); + var input = new IntValueNode(123456); + + // act + var result = type.IsInstanceOfType(input); + + // assert + Assert.False(result); + } + + [Fact] + public void IsInstanceOfType_Null_Throws() + { + // arrange + var type = new StringType(); + + // act + // assert + Assert.Throws(() => type.IsInstanceOfType(null)); + } + + [Fact] + public void Serialize_Type() + { + // arrange + var type = new StringType(); + var input = "123456"; + + // act + var serializedValue = type.Serialize(input); + + // assert + Assert.IsType(serializedValue); + Assert.Equal("123456", serializedValue); + } + + [Fact] + public void Serialize_Null() { - [Fact] - public void EnsureStringTypeKindIsCorret() - { - // arrange - var type = new StringType(); - - // act - TypeKind kind = type.Kind; - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [Fact] - public void IsInstanceOfType_ValueNode() - { - // arrange - var type = new StringType(); - var input = new StringValueNode("123456"); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_NullValueNode() - { - // arrange - var type = new StringType(); - NullValueNode input = NullValueNode.Default; - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.True(result); - } - - [Fact] - public void IsInstanceOfType_Wrong_ValueNode() - { - // arrange - var type = new StringType(); - var input = new IntValueNode(123456); - - // act - bool result = type.IsInstanceOfType(input); - - // assert - Assert.False(result); - } - - [Fact] - public void IsInstanceOfType_Null_Throws() - { - // arrange - var type = new StringType(); - - // act - // assert - Assert.Throws(() => type.IsInstanceOfType(null)); - } - - [Fact] - public void Serialize_Type() - { - // arrange - var type = new StringType(); - string input = "123456"; - - // act - object serializedValue = type.Serialize(input); - - // assert - Assert.IsType(serializedValue); - Assert.Equal("123456", serializedValue); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var type = new StringType(); - - // act - object serializedValue = type.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Wrong_Type_Throws() - { - // arrange - var type = new StringType(); - object input = 123456; - - // act - // assert - Assert.Throws( - () => type.Serialize(input)); - } - - [Fact] - public void ParseLiteral_ValueNode() - { - // arrange - var type = new StringType(); - var input = new StringValueNode("123456"); - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.IsType(output); - Assert.Equal("123456", output); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var type = new StringType(); - NullValueNode input = NullValueNode.Default; - - // act - object output = type.ParseLiteral(input); - - // assert - Assert.Null(output); - } - - [Fact] - public void ParseLiteral_Wrong_ValueNode_Throws() - { - // arrange - var type = new StringType(); - var input = new IntValueNode(123456); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseLiteral_Null_Throws() - { - // arrange - var type = new StringType(); - - // act - // assert - Assert.Throws(() => type.ParseLiteral(null)); - } - - [Fact] - public void ParseValue_Wrong_Value_Throws() - { - // arrange - var type = new StringType(); - object input = 123456; - - // act - // assert - Assert.Throws( - () => type.ParseValue(input)); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var type = new StringType(); - object input = null; - - // act - object output = type.ParseValue(input); - - // assert - Assert.IsType(output); - } + // arrange + var type = new StringType(); + + // act + var serializedValue = type.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Wrong_Type_Throws() + { + // arrange + var type = new StringType(); + object input = 123456; + + // act + // assert + Assert.Throws( + () => type.Serialize(input)); + } + + [Fact] + public void ParseLiteral_ValueNode() + { + // arrange + var type = new StringType(); + var input = new StringValueNode("123456"); + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.IsType(output); + Assert.Equal("123456", output); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var type = new StringType(); + var input = NullValueNode.Default; + + // act + var output = type.ParseLiteral(input); + + // assert + Assert.Null(output); + } + + [Fact] + public void ParseLiteral_Wrong_ValueNode_Throws() + { + // arrange + var type = new StringType(); + var input = new IntValueNode(123456); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseLiteral_Null_Throws() + { + // arrange + var type = new StringType(); + + // act + // assert + Assert.Throws(() => type.ParseLiteral(null)); + } + + [Fact] + public void ParseValue_Wrong_Value_Throws() + { + // arrange + var type = new StringType(); + object input = 123456; + + // act + // assert + Assert.Throws( + () => type.ParseValue(input)); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var type = new StringType(); + object input = null; + + // act + object output = type.ParseValue(input); + + // assert + Assert.IsType(output); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/TimeSpanTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/TimeSpanTypeTests.cs index 5154985ae59..b733b07b725 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/TimeSpanTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/TimeSpanTypeTests.cs @@ -7,321 +7,320 @@ using HotChocolate.Types.Descriptors; using System.Reflection; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class TimeSpanTypeTests { - public class TimeSpanTypeTests + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "PT5M")] + [InlineData(TimeSpanFormat.DotNet, "00:05:00")] + public void Serialize_TimeSpan(TimeSpanFormat format, string expectedValue) { - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "PT5M")] - [InlineData(TimeSpanFormat.DotNet, "00:05:00")] - public void Serialize_TimeSpan(TimeSpanFormat format, string expectedValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - var timeSpan = TimeSpan.FromMinutes(5); + // arrange + var timeSpanType = new TimeSpanType(format); + var timeSpan = TimeSpan.FromMinutes(5); - // act - string serializedValue = (string)timeSpanType.Serialize(timeSpan); + // act + var serializedValue = (string)timeSpanType.Serialize(timeSpan); - // assert - Assert.Equal(expectedValue, serializedValue); - } + // assert + Assert.Equal(expectedValue, serializedValue); + } - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "P10675199DT2H48M5.4775807S")] - [InlineData(TimeSpanFormat.DotNet, "10675199.02:48:05.4775807")] - public void Serialize_TimeSpan_Max(TimeSpanFormat format, string expectedValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - TimeSpan timeSpan = TimeSpan.MaxValue; + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "P10675199DT2H48M5.4775807S")] + [InlineData(TimeSpanFormat.DotNet, "10675199.02:48:05.4775807")] + public void Serialize_TimeSpan_Max(TimeSpanFormat format, string expectedValue) + { + // arrange + var timeSpanType = new TimeSpanType(format); + var timeSpan = TimeSpan.MaxValue; - // act - string serializedValue = (string)timeSpanType.Serialize(timeSpan); + // act + var serializedValue = (string)timeSpanType.Serialize(timeSpan); - // assert - Assert.Equal(expectedValue, serializedValue); - } + // assert + Assert.Equal(expectedValue, serializedValue); + } - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "-P10675199DT2H48M5.4775808S")] - [InlineData(TimeSpanFormat.DotNet, "-10675199.02:48:05.4775808")] - public void Serialize_TimeSpan_Min(TimeSpanFormat format, string expectedValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - TimeSpan timeSpan = TimeSpan.MinValue; + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "-P10675199DT2H48M5.4775808S")] + [InlineData(TimeSpanFormat.DotNet, "-10675199.02:48:05.4775808")] + public void Serialize_TimeSpan_Min(TimeSpanFormat format, string expectedValue) + { + // arrange + var timeSpanType = new TimeSpanType(format); + var timeSpan = TimeSpan.MinValue; - // act - string serializedValue = (string)timeSpanType.Serialize(timeSpan); + // act + var serializedValue = (string)timeSpanType.Serialize(timeSpan); - // assert - Assert.Equal(expectedValue, serializedValue); - } + // assert + Assert.Equal(expectedValue, serializedValue); + } - [Fact] - public void Serialize_TimeSpan_DefaultFormat() - { - // arrange - var timeSpanType = new TimeSpanType(); - var timeSpan = TimeSpan.FromMinutes(5); - string expectedValue = "PT5M"; + [Fact] + public void Serialize_TimeSpan_DefaultFormat() + { + // arrange + var timeSpanType = new TimeSpanType(); + var timeSpan = TimeSpan.FromMinutes(5); + var expectedValue = "PT5M"; - // act - string serializedValue = (string)timeSpanType.Serialize(timeSpan); + // act + var serializedValue = (string)timeSpanType.Serialize(timeSpan); - // assert - Assert.Equal(expectedValue, serializedValue); - } + // assert + Assert.Equal(expectedValue, serializedValue); + } - [Fact] - public void Serialize_Null() - { - // arrange - var timeSpanType = new TimeSpanType(); + [Fact] + public void Serialize_Null() + { + // arrange + var timeSpanType = new TimeSpanType(); - // act - object serializedValue = timeSpanType.Serialize(null); + // act + var serializedValue = timeSpanType.Serialize(null); - // assert - Assert.Null(serializedValue); - } + // assert + Assert.Null(serializedValue); + } - [Fact] - public void Serialize_String_Exception() - { - // arrange - var timeSpanType = new TimeSpanType(); + [Fact] + public void Serialize_String_Exception() + { + // arrange + var timeSpanType = new TimeSpanType(); - // act - Action a = () => timeSpanType.Serialize("bad"); + // act + Action a = () => timeSpanType.Serialize("bad"); - // assert - Assert.Throws(a); - } + // assert + Assert.Throws(a); + } - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "PT5M")] - [InlineData(TimeSpanFormat.DotNet, "00:05:00")] - public void ParseLiteral_StringValueNode(TimeSpanFormat format, string literalValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - var literal = new StringValueNode(literalValue); - var expectedTimeSpan = TimeSpan.FromMinutes(5); + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "PT5M")] + [InlineData(TimeSpanFormat.DotNet, "00:05:00")] + public void ParseLiteral_StringValueNode(TimeSpanFormat format, string literalValue) + { + // arrange + var timeSpanType = new TimeSpanType(format); + var literal = new StringValueNode(literalValue); + var expectedTimeSpan = TimeSpan.FromMinutes(5); - // act - var timeSpan = (TimeSpan)timeSpanType - .ParseLiteral(literal); + // act + var timeSpan = (TimeSpan)timeSpanType + .ParseLiteral(literal); - // assert - Assert.Equal(expectedTimeSpan, timeSpan); - } + // assert + Assert.Equal(expectedTimeSpan, timeSpan); + } - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "PT5M")] - [InlineData(TimeSpanFormat.DotNet, "00:05:00")] - public void Deserialize_TimeSpan(TimeSpanFormat format, string actualValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - var timeSpan = TimeSpan.FromMinutes(5); + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "PT5M")] + [InlineData(TimeSpanFormat.DotNet, "00:05:00")] + public void Deserialize_TimeSpan(TimeSpanFormat format, string actualValue) + { + // arrange + var timeSpanType = new TimeSpanType(format); + var timeSpan = TimeSpan.FromMinutes(5); - // act - var deserializedValue = (TimeSpan)timeSpanType - .Deserialize(actualValue); + // act + var deserializedValue = (TimeSpan)timeSpanType + .Deserialize(actualValue); - // assert - Assert.Equal(timeSpan, deserializedValue); - } + // assert + Assert.Equal(timeSpan, deserializedValue); + } - [Fact] - public void Deserialize_TimeSpan_Weeks() - { - // arrange - var timeSpanType = new TimeSpanType(); - var timeSpan = TimeSpan.FromDays(79); + [Fact] + public void Deserialize_TimeSpan_Weeks() + { + // arrange + var timeSpanType = new TimeSpanType(); + var timeSpan = TimeSpan.FromDays(79); - // act - var deserializedValue = (TimeSpan)timeSpanType - .Deserialize("P2M2W5D"); + // act + var deserializedValue = (TimeSpan)timeSpanType + .Deserialize("P2M2W5D"); - // assert - Assert.Equal(timeSpan, deserializedValue); - } + // assert + Assert.Equal(timeSpan, deserializedValue); + } - [Fact] - public void Deserialize_TimeSpan_CannotEndWithDigits() - { - // arrange - var timeSpanType = new TimeSpanType(); + [Fact] + public void Deserialize_TimeSpan_CannotEndWithDigits() + { + // arrange + var timeSpanType = new TimeSpanType(); - // act - bool success = timeSpanType - .TryDeserialize("PT5", out var deserialized); + // act + var success = timeSpanType + .TryDeserialize("PT5", out var deserialized); - // assert - Assert.False(success); - } + // assert + Assert.False(success); + } - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "P10675199DT2H48M5.4775807S")] - [InlineData(TimeSpanFormat.DotNet, "10675199.02:48:05.4775807")] - public void Deserialize_TimeSpan_Max(TimeSpanFormat format, string actualValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - TimeSpan timeSpan = TimeSpan.MaxValue; + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "P10675199DT2H48M5.4775807S")] + [InlineData(TimeSpanFormat.DotNet, "10675199.02:48:05.4775807")] + public void Deserialize_TimeSpan_Max(TimeSpanFormat format, string actualValue) + { + // arrange + var timeSpanType = new TimeSpanType(format); + var timeSpan = TimeSpan.MaxValue; - // act - var deserializedValue = (TimeSpan)timeSpanType - .Deserialize(actualValue); + // act + var deserializedValue = (TimeSpan)timeSpanType + .Deserialize(actualValue); - // assert - Assert.Equal(timeSpan, deserializedValue); - } + // assert + Assert.Equal(timeSpan, deserializedValue); + } - [Theory] - [InlineData(TimeSpanFormat.Iso8601, "-P10675199DT2H48M5.4775808S")] - [InlineData(TimeSpanFormat.DotNet, "-10675199.02:48:05.4775808")] - public void Deserialize_TimeSpan_Min(TimeSpanFormat format, string actualValue) - { - // arrange - var timeSpanType = new TimeSpanType(format); - TimeSpan timeSpan = TimeSpan.MinValue; + [Theory] + [InlineData(TimeSpanFormat.Iso8601, "-P10675199DT2H48M5.4775808S")] + [InlineData(TimeSpanFormat.DotNet, "-10675199.02:48:05.4775808")] + public void Deserialize_TimeSpan_Min(TimeSpanFormat format, string actualValue) + { + // arrange + var timeSpanType = new TimeSpanType(format); + var timeSpan = TimeSpan.MinValue; - // act - var deserializedValue = (TimeSpan)timeSpanType - .Deserialize(actualValue); + // act + var deserializedValue = (TimeSpan)timeSpanType + .Deserialize(actualValue); - // assert - Assert.Equal(timeSpan, deserializedValue); - } + // assert + Assert.Equal(timeSpan, deserializedValue); + } - [Fact] - public void Deserialize_InvalidString() - { - // arrange - var timeSpanType = new TimeSpanType(); + [Fact] + public void Deserialize_InvalidString() + { + // arrange + var timeSpanType = new TimeSpanType(); - // act - bool success = timeSpanType - .TryDeserialize("bad", out object deserialized); + // act + var success = timeSpanType + .TryDeserialize("bad", out var deserialized); - // assert - Assert.False(success); - } + // assert + Assert.False(success); + } - [Fact] - public void Deserialize_Null_To_Null() - { - // arrange - var timeSpanType = new TimeSpanType(); + [Fact] + public void Deserialize_Null_To_Null() + { + // arrange + var timeSpanType = new TimeSpanType(); - // act - bool success = timeSpanType - .TryDeserialize(null, out object deserialized); + // act + var success = timeSpanType + .TryDeserialize(null, out var deserialized); - // assert - Assert.True(success); - Assert.Null(deserialized); - } + // assert + Assert.True(success); + Assert.Null(deserialized); + } - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var timeSpanType = new TimeSpanType(); - NullValueNode literal = NullValueNode.Default; + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var timeSpanType = new TimeSpanType(); + var literal = NullValueNode.Default; - // act - object value = timeSpanType.ParseLiteral(literal); + // act + var value = timeSpanType.ParseLiteral(literal); - // assert - Assert.Null(value); - } + // assert + Assert.Null(value); + } - [Fact] - public void ParseValue_Null() - { - // arrange - var timeSpanType = new TimeSpanType(); + [Fact] + public void ParseValue_Null() + { + // arrange + var timeSpanType = new TimeSpanType(); - // act - IValueNode literal = timeSpanType.ParseValue(null); + // act + var literal = timeSpanType.ParseValue(null); - // assert - Assert.IsType(literal); - } + // assert + Assert.IsType(literal); + } - [Fact] - public void PureCodeFirst_AutomaticallyBinds_TimeSpan() - { - SchemaBuilder.New() - .AddQueryType() - .Create() - .ToString() - .MatchSnapshot(); - } + [Fact] + public void PureCodeFirst_AutomaticallyBinds_TimeSpan() + { + SchemaBuilder.New() + .AddQueryType() + .Create() + .ToString() + .MatchSnapshot(); + } - [InlineData(TimeSpanFormat.Iso8601)] - [InlineData(TimeSpanFormat.DotNet)] - [Theory] - public void PureCodeFirst_AutomaticallyBinds_TimeSpan_With_Format( - TimeSpanFormat format) - { - SchemaBuilder.New() - .AddQueryType() - .AddType(new TimeSpanType(format: format)) - .Create() - .MakeExecutable() - .Execute("{ duration }") - .ToJson() - .MatchSnapshot(new SnapshotNameExtension(format)); - } + [InlineData(TimeSpanFormat.Iso8601)] + [InlineData(TimeSpanFormat.DotNet)] + [Theory] + public void PureCodeFirst_AutomaticallyBinds_TimeSpan_With_Format( + TimeSpanFormat format) + { + SchemaBuilder.New() + .AddQueryType() + .AddType(new TimeSpanType(format: format)) + .Create() + .MakeExecutable() + .Execute("{ duration }") + .ToJson() + .MatchSnapshot(new SnapshotNameExtension(format)); + } - [Fact] - public void PureCodeFirst_Different_TimeSpan_Formats_In_Same_Type() - { - SchemaBuilder.New() - .AddQueryType() - .AddType(new TimeSpanType(format: TimeSpanFormat.DotNet)) - .AddType(new TimeSpanType( - "IsoTimeSpan", - format: TimeSpanFormat.Iso8601, - bind: BindingBehavior.Explicit)) - .Create() - .MakeExecutable() - .Execute("{ duration1 duration2 }") - .ToJson() - .MatchSnapshot(); - } + [Fact] + public void PureCodeFirst_Different_TimeSpan_Formats_In_Same_Type() + { + SchemaBuilder.New() + .AddQueryType() + .AddType(new TimeSpanType(format: TimeSpanFormat.DotNet)) + .AddType(new TimeSpanType( + "IsoTimeSpan", + format: TimeSpanFormat.Iso8601, + bind: BindingBehavior.Explicit)) + .Create() + .MakeExecutable() + .Execute("{ duration1 duration2 }") + .ToJson() + .MatchSnapshot(); + } - public class Query - { - public TimeSpan Duration() => TimeSpan.FromDays(1); - } + public class Query + { + public TimeSpan Duration() => TimeSpan.FromDays(1); + } - public class QueryWithTwoDurations - { - public TimeSpan Duration1() => TimeSpan.FromDays(1); + public class QueryWithTwoDurations + { + public TimeSpan Duration1() => TimeSpan.FromDays(1); - [IsoTimeSpan] - public TimeSpan Duration2() => TimeSpan.FromDays(1); - } + [IsoTimeSpan] + public TimeSpan Duration2() => TimeSpan.FromDays(1); + } - private sealed class IsoTimeSpanAttribute : ObjectFieldDescriptorAttribute + private sealed class IsoTimeSpanAttribute : ObjectFieldDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IObjectFieldDescriptor descriptor, + MemberInfo member) { - public override void OnConfigure( - IDescriptorContext context, - IObjectFieldDescriptor descriptor, - MemberInfo member) - { - descriptor.Extend().OnBeforeCreate( - d => d.Type = new SyntaxTypeReference( - new NamedTypeNode("IsoTimeSpan"), - TypeContext.Output)); - } + descriptor.Extend().OnBeforeCreate( + d => d.Type = new SyntaxTypeReference( + new NamedTypeNode("IsoTimeSpan"), + TypeContext.Output)); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UrlTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UrlTypeTests.cs index 0e33d0de657..0f5469ec4b0 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UrlTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UrlTypeTests.cs @@ -2,218 +2,217 @@ using HotChocolate.Language; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class UrlTypeTests { - public class UrlTypeTests + [Fact] + public void EnsureUrlTypeKindIsCorrect() + { + // arrange + var type = new UrlType(); + + // act + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [Fact] + public void ParseLiteral_StringValueNode() + { + // arrange + var urlType = new UrlType(); + var expected = new Uri("http://domain.test/url"); + var literal = new StringValueNode(expected.AbsoluteUri); + + // act + var actual = (Uri)urlType.ParseLiteral(literal); + + // assert + Assert.Equal(expected, actual); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var urlType = new UrlType(); + var literal = NullValueNode.Default; + + // act + var value = urlType.ParseLiteral(literal); + + // assert + Assert.Null(value); + } + + [Fact] + public void ParseLiteral_RelativeUrl() + { + // arrange + var urlType = new UrlType(); + var expected = new Uri("/relative/path", UriKind.Relative); + var literal = new StringValueNode($"{expected}"); + + // act + var actual = (Uri)urlType.ParseLiteral(literal); + + // Assert + Assert.Equal(expected, actual); + } + + [Fact] + public void ParseLiteral_Invalid_Url_Throws() + { + // arrange + var type = new UrlType(); + var input = new StringValueNode("$*^domain.test"); + + // act + // assert + Assert.Throws( + () => type.ParseLiteral(input)); + } + + [Fact] + public void ParseValue_Url() + { + // arrange + var urlType = new UrlType(); + var uri = new Uri("http://domain.test/url"); + var expectedLiteralValue = uri.AbsoluteUri; + + // act + var stringLiteral = + (StringValueNode)urlType.ParseValue(uri); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void ParseValue_Encoded() + { + // arrange + var urlType = new UrlType(); + var uri = new Uri("http://domain.test/ä+😄?q=a/α"); + var expectedLiteralValue = uri.AbsoluteUri; + + // act + var stringLiteral = + (StringValueNode)urlType.ParseValue(uri); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void Serialize_Null() + { + // arrange + var dateType = new UrlType(); + + // act + var serializedValue = dateType.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Url() + { + // arrange + var urlType = new UrlType(); + var uri = new Uri("http://domain.test/url"); + + // act + var serializedValue = urlType.Serialize(uri); + + // assert + Assert.Equal(uri.AbsoluteUri, Assert.IsType(serializedValue)); + } + + [Fact] + public void Serialize_RelativeUrl() + { + // arrange + var urlType = new UrlType(); + var uri = new Uri("/relative/path", UriKind.Relative); + + // act + var serializedValue = urlType.Serialize(uri); + + // assert + Assert.Equal(uri.ToString(), Assert.IsType(serializedValue)); + } + + [Fact] + public void IsInstanceOfType_GivenUriAsStringValueNode_ReturnsTrue() { - [Fact] - public void EnsureUrlTypeKindIsCorrect() - { - // arrange - var type = new UrlType(); - - // act - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [Fact] - public void ParseLiteral_StringValueNode() - { - // arrange - var urlType = new UrlType(); - var expected = new Uri("http://domain.test/url"); - var literal = new StringValueNode(expected.AbsoluteUri); - - // act - var actual = (Uri)urlType.ParseLiteral(literal); - - // assert - Assert.Equal(expected, actual); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var urlType = new UrlType(); - NullValueNode literal = NullValueNode.Default; - - // act - object value = urlType.ParseLiteral(literal); - - // assert - Assert.Null(value); - } - - [Fact] - public void ParseLiteral_RelativeUrl() - { - // arrange - var urlType = new UrlType(); - var expected = new Uri("/relative/path", UriKind.Relative); - var literal = new StringValueNode($"{expected}"); - - // act - var actual = (Uri)urlType.ParseLiteral(literal); - - // Assert - Assert.Equal(expected, actual); - } - - [Fact] - public void ParseLiteral_Invalid_Url_Throws() - { - // arrange - var type = new UrlType(); - var input = new StringValueNode("$*^domain.test"); - - // act - // assert - Assert.Throws( - () => type.ParseLiteral(input)); - } - - [Fact] - public void ParseValue_Url() - { - // arrange - var urlType = new UrlType(); - var uri = new Uri("http://domain.test/url"); - string expectedLiteralValue = uri.AbsoluteUri; - - // act - var stringLiteral = - (StringValueNode)urlType.ParseValue(uri); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void ParseValue_Encoded() - { - // arrange - var urlType = new UrlType(); - var uri = new Uri("http://domain.test/ä+😄?q=a/α"); - string expectedLiteralValue = uri.AbsoluteUri; - - // act - var stringLiteral = - (StringValueNode)urlType.ParseValue(uri); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var dateType = new UrlType(); - - // act - object serializedValue = dateType.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Url() - { - // arrange - var urlType = new UrlType(); - var uri = new Uri("http://domain.test/url"); - - // act - object serializedValue = urlType.Serialize(uri); - - // assert - Assert.Equal(uri.AbsoluteUri, Assert.IsType(serializedValue)); - } - - [Fact] - public void Serialize_RelativeUrl() - { - // arrange - var urlType = new UrlType(); - var uri = new Uri("/relative/path", UriKind.Relative); - - // act - object serializedValue = urlType.Serialize(uri); - - // assert - Assert.Equal(uri.ToString(), Assert.IsType(serializedValue)); - } - - [Fact] - public void IsInstanceOfType_GivenUriAsStringValueNode_ReturnsTrue() - { - // Arrange - var urlType = new UrlType(); - var uri = new Uri("http://domain.test/url"); - - // Act - var isUrlType = urlType.IsInstanceOfType(new StringValueNode(uri.AbsoluteUri)); - - // Assert - Assert.True(isUrlType); - } - - [Fact] - public void IsInstanceOfType_GivenNullValueNode_ReturnsTrue() - { - // arrange - var urlType = new UrlType(); - - // act - var isUrlType = urlType.IsInstanceOfType(new NullValueNode(null)); - - // assert - Assert.True(isUrlType); - } - - [Fact] - public void IsInstanceOfType_GivenInvalidUriAsStringLiteral_False() - { - // arrange - var urlType = new UrlType(); - - // act - var isUrlType = urlType.IsInstanceOfType( - new StringValueNode("$*^domain.test")); - - // assert - Assert.False(isUrlType); - } - - [Fact] - public void IsInstanceOfType_GivenNull_ThrowsArgumentException() - { - // arrange - var urlType = new UrlType(); - - // act - Action action = () => urlType.IsInstanceOfType(null); - - // assert - Assert.Throws(action); - } - - [Fact] - public void IsInstanceOfType_GivenNonUrlValueNode_ReturnsFalse() - { - // arrange - var urlType = new UrlType(); - var intValue = new IntValueNode(1); - - // act - var isUrlType = urlType.IsInstanceOfType(intValue); - - // assert - Assert.False(isUrlType); - } + // Arrange + var urlType = new UrlType(); + var uri = new Uri("http://domain.test/url"); + + // Act + var isUrlType = urlType.IsInstanceOfType(new StringValueNode(uri.AbsoluteUri)); + // Assert + Assert.True(isUrlType); } + + [Fact] + public void IsInstanceOfType_GivenNullValueNode_ReturnsTrue() + { + // arrange + var urlType = new UrlType(); + + // act + var isUrlType = urlType.IsInstanceOfType(new NullValueNode(null)); + + // assert + Assert.True(isUrlType); + } + + [Fact] + public void IsInstanceOfType_GivenInvalidUriAsStringLiteral_False() + { + // arrange + var urlType = new UrlType(); + + // act + var isUrlType = urlType.IsInstanceOfType( + new StringValueNode("$*^domain.test")); + + // assert + Assert.False(isUrlType); + } + + [Fact] + public void IsInstanceOfType_GivenNull_ThrowsArgumentException() + { + // arrange + var urlType = new UrlType(); + + // act + Action action = () => urlType.IsInstanceOfType(null); + + // assert + Assert.Throws(action); + } + + [Fact] + public void IsInstanceOfType_GivenNonUrlValueNode_ReturnsFalse() + { + // arrange + var urlType = new UrlType(); + var intValue = new IntValueNode(1); + + // act + var isUrlType = urlType.IsInstanceOfType(intValue); + + // assert + Assert.False(isUrlType); + } + } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UuidTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UuidTypeTests.cs index 411725d3766..210ff484d29 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UuidTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/Scalars/UuidTypeTests.cs @@ -5,476 +5,475 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class UuidTypeTests { - public class UuidTypeTests + [Fact] + public void IsInstanceOfType_StringLiteral() + { + // arrange + var uuidType = new UuidType(); + var guid = Guid.NewGuid(); + + // act + var isOfType = uuidType.IsInstanceOfType(guid); + + // assert + Assert.True(isOfType); + } + + [Fact] + public void IsInstanceOfType_NullLiteral() + { + // arrange + var uuidType = new UuidType(); + var literal = new NullValueNode(null); + + // act + var isOfType = uuidType.IsInstanceOfType(literal); + + // assert + Assert.True(isOfType); + } + + [Fact] + public void IsInstanceOfType_IntLiteral() + { + // arrange + var uuidType = new UuidType(); + var literal = new IntValueNode(123); + + // act + var isOfType = uuidType.IsInstanceOfType(literal); + + // assert + Assert.False(isOfType); + } + + [Fact] + public void IsInstanceOfType_Null() + { + // arrange + var uuidType = new UuidType(); + + // act + void Action() => uuidType.IsInstanceOfType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Serialize_Guid() + { + // arrange + var uuidType = new UuidType(); + var guid = Guid.NewGuid(); + + // act + var serializedValue = uuidType.Serialize(guid); + + // assert + Assert.Equal(guid.ToString("D"), Assert.IsType(serializedValue)); + } + + [Fact] + public void Serialize_Null() { - [Fact] - public void IsInstanceOfType_StringLiteral() - { - // arrange - var uuidType = new UuidType(); - var guid = Guid.NewGuid(); - - // act - var isOfType = uuidType.IsInstanceOfType(guid); - - // assert - Assert.True(isOfType); - } - - [Fact] - public void IsInstanceOfType_NullLiteral() - { - // arrange - var uuidType = new UuidType(); - var literal = new NullValueNode(null); - - // act - var isOfType = uuidType.IsInstanceOfType(literal); - - // assert - Assert.True(isOfType); - } - - [Fact] - public void IsInstanceOfType_IntLiteral() - { - // arrange - var uuidType = new UuidType(); - var literal = new IntValueNode(123); - - // act - var isOfType = uuidType.IsInstanceOfType(literal); - - // assert - Assert.False(isOfType); - } - - [Fact] - public void IsInstanceOfType_Null() - { - // arrange - var uuidType = new UuidType(); - - // act - void Action() => uuidType.IsInstanceOfType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Serialize_Guid() - { - // arrange - var uuidType = new UuidType(); - var guid = Guid.NewGuid(); - - // act - var serializedValue = uuidType.Serialize(guid); - - // assert - Assert.Equal(guid.ToString("D"), Assert.IsType(serializedValue)); - } - - [Fact] - public void Serialize_Null() - { - // arrange - var uuidType = new UuidType(); - - // act - var serializedValue = uuidType.Serialize(null); - - // assert - Assert.Null(serializedValue); - } - - [Fact] - public void Serialize_Int() - { - // arrange - var uuidType = new UuidType(); - var value = 123; - - // act - void Action() => uuidType.Serialize(value); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void Deserialize_Null() - { - // arrange - var uuidType = new UuidType(); - - // act - var success = uuidType.TryDeserialize(null, out var o); - - // assert - Assert.True(success); - Assert.Null(o); - } - - [Fact] - public void Deserialize_String() - { - // arrange - var uuidType = new UuidType(); - var guid = Guid.NewGuid(); - - // act - var success = uuidType.TryDeserialize(guid.ToString("N"), out var o); - - // assert - Assert.True(success); - Assert.Equal(guid, o); - } - - [Fact] - public void Deserialize_Guid() - { - // arrange - var uuidType = new UuidType(); - var guid = Guid.NewGuid(); - - // act - var success = uuidType.TryDeserialize(guid, out var o); - - // assert - Assert.True(success); - Assert.Equal(guid, o); - } - - [Fact] - public void Deserialize_Int() - { - // arrange - var uuidType = new UuidType(); - var value = 123; - - // act - var success = uuidType.TryDeserialize(value, out _); - - // assert - Assert.False(success); - } - - [Fact] - public void ParseLiteral_StringValueNode() - { - // arrange - var uuidType = new UuidType(); - var expected = Guid.NewGuid(); - var literalA = new StringValueNode(expected.ToString("N")); - var literalB = new StringValueNode(expected.ToString("P")); - - // act - var runtimeValueA = (Guid)uuidType.ParseLiteral(literalA)!; - var runtimeValueB = (Guid)uuidType.ParseLiteral(literalB)!; - - // assert - Assert.Equal(expected, runtimeValueA); - Assert.Equal(expected, runtimeValueB); - } - - [Fact] - public void ParseLiteral_StringValueNode_Enforce_Format() - { - // arrange - var uuidType = new UuidType(defaultFormat: 'P', enforceFormat: true); - var expected = Guid.NewGuid(); - var literal = new StringValueNode(expected.ToString("N")); - - // act - void Action() => uuidType.ParseLiteral(literal); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void ParseLiteral_IntValueNode() - { - // arrange - var uuidType = new UuidType(); - var literal = new IntValueNode(123); - - // act - void Action() => uuidType.ParseLiteral(literal); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void ParseLiteral_NullValueNode() - { - // arrange - var uuidType = new UuidType(); - NullValueNode literal = NullValueNode.Default; - - // act - var value = uuidType.ParseLiteral(literal); - - // assert - Assert.Null(value); - } - - [Fact] - public void ParseLiteral_Null() - { - // arrange - var uuidType = new UuidType(); - - // act - void Action() => uuidType.ParseLiteral(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void ParseValue_Guid() - { - // arrange - var uuidType = new UuidType(); - var expected = Guid.NewGuid(); - var expectedLiteralValue = expected.ToString("D"); - - // act - var stringLiteral = (StringValueNode)uuidType.ParseValue(expected); - - // assert - Assert.Equal(expectedLiteralValue, stringLiteral.Value); - } - - [Fact] - public void ParseValue_Null() - { - // arrange - var uuidType = new UuidType(); - Guid? guid = null; - - // act - IValueNode stringLiteral = uuidType.ParseValue(guid); - - // assert - Assert.True(stringLiteral is NullValueNode); - Assert.Null(((NullValueNode)stringLiteral).Value); - } - - [Fact] - public void ParseValue_Int() - { - // arrange - var uuidType = new UuidType(); - var value = 123; - - // act - void Action() => uuidType.ParseValue(value); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void EnsureDateTypeKindIsCorrect() - { - // arrange - var type = new UuidType(); - - // assert - Assert.Equal(TypeKind.Scalar, type.Kind); - } - - [InlineData('N')] - [InlineData('D')] - [InlineData('B')] - [InlineData('P')] - [Theory] - public void Serialize_With_Format(char format) - { - // arrange - var uuidType = new UuidType(defaultFormat: format); - Guid guid = Guid.Empty; - - // act - string s = (string)uuidType.Serialize(guid)!; - - // assert - Assert.Equal(guid.ToString(format.ToString()), s); - } - - [InlineData('N')] - [InlineData('D')] - [InlineData('B')] - [InlineData('P')] - [Theory] - public void Deserialize_With_Format(char format) - { - // arrange - var uuidType = new UuidType(defaultFormat: format); - Guid guid = Guid.Empty; - string serialized = guid.ToString(format.ToString()); - - // act - var deserialized = (Guid)uuidType.Deserialize(serialized)!; - - // assert - Assert.Equal(guid, deserialized); - } - - [InlineData('N')] - [InlineData('D')] - [InlineData('B')] - [InlineData('P')] - [Theory] - public void ParseValue_With_Format(char format) - { - // arrange - var uuidType = new UuidType(defaultFormat: format); - Guid guid = Guid.Empty; - - // act - var s = (StringValueNode)uuidType.ParseValue(guid); - - // assert - Assert.Equal(guid.ToString(format.ToString()), s.Value); - } - - [InlineData('N')] - [InlineData('D')] - [InlineData('B')] - [InlineData('P')] - [Theory] - public void ParseLiteral_With_Format(char format) - { - // arrange - var uuidType = new UuidType(defaultFormat: format); - Guid guid = Guid.Empty; - var literal = new StringValueNode(guid.ToString(format.ToString())); - - // act - var deserialized = (Guid)uuidType.ParseLiteral(literal)!; - - // assert - Assert.Equal(guid, deserialized); - } - - [Fact] - public void Specify_Invalid_Format() - { - // arrange - // act - void Action() => new UuidType(defaultFormat: 'z'); - - // assert + // arrange + var uuidType = new UuidType(); + + // act + var serializedValue = uuidType.Serialize(null); + + // assert + Assert.Null(serializedValue); + } + + [Fact] + public void Serialize_Int() + { + // arrange + var uuidType = new UuidType(); + var value = 123; + + // act + void Action() => uuidType.Serialize(value); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void Deserialize_Null() + { + // arrange + var uuidType = new UuidType(); + + // act + var success = uuidType.TryDeserialize(null, out var o); + + // assert + Assert.True(success); + Assert.Null(o); + } + + [Fact] + public void Deserialize_String() + { + // arrange + var uuidType = new UuidType(); + var guid = Guid.NewGuid(); + + // act + var success = uuidType.TryDeserialize(guid.ToString("N"), out var o); + + // assert + Assert.True(success); + Assert.Equal(guid, o); + } + + [Fact] + public void Deserialize_Guid() + { + // arrange + var uuidType = new UuidType(); + var guid = Guid.NewGuid(); + + // act + var success = uuidType.TryDeserialize(guid, out var o); + + // assert + Assert.True(success); + Assert.Equal(guid, o); + } + + [Fact] + public void Deserialize_Int() + { + // arrange + var uuidType = new UuidType(); + var value = 123; + + // act + var success = uuidType.TryDeserialize(value, out _); + + // assert + Assert.False(success); + } + + [Fact] + public void ParseLiteral_StringValueNode() + { + // arrange + var uuidType = new UuidType(); + var expected = Guid.NewGuid(); + var literalA = new StringValueNode(expected.ToString("N")); + var literalB = new StringValueNode(expected.ToString("P")); + + // act + var runtimeValueA = (Guid)uuidType.ParseLiteral(literalA)!; + var runtimeValueB = (Guid)uuidType.ParseLiteral(literalB)!; + + // assert + Assert.Equal(expected, runtimeValueA); + Assert.Equal(expected, runtimeValueB); + } + + [Fact] + public void ParseLiteral_StringValueNode_Enforce_Format() + { + // arrange + var uuidType = new UuidType(defaultFormat: 'P', enforceFormat: true); + var expected = Guid.NewGuid(); + var literal = new StringValueNode(expected.ToString("N")); + + // act + void Action() => uuidType.ParseLiteral(literal); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void ParseLiteral_IntValueNode() + { + // arrange + var uuidType = new UuidType(); + var literal = new IntValueNode(123); + + // act + void Action() => uuidType.ParseLiteral(literal); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void ParseLiteral_NullValueNode() + { + // arrange + var uuidType = new UuidType(); + var literal = NullValueNode.Default; + + // act + var value = uuidType.ParseLiteral(literal); + + // assert + Assert.Null(value); + } + + [Fact] + public void ParseLiteral_Null() + { + // arrange + var uuidType = new UuidType(); + + // act + void Action() => uuidType.ParseLiteral(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void ParseValue_Guid() + { + // arrange + var uuidType = new UuidType(); + var expected = Guid.NewGuid(); + var expectedLiteralValue = expected.ToString("D"); + + // act + var stringLiteral = (StringValueNode)uuidType.ParseValue(expected); + + // assert + Assert.Equal(expectedLiteralValue, stringLiteral.Value); + } + + [Fact] + public void ParseValue_Null() + { + // arrange + var uuidType = new UuidType(); + Guid? guid = null; + + // act + var stringLiteral = uuidType.ParseValue(guid); + + // assert + Assert.True(stringLiteral is NullValueNode); + Assert.Null(((NullValueNode)stringLiteral).Value); + } + + [Fact] + public void ParseValue_Int() + { + // arrange + var uuidType = new UuidType(); + var value = 123; + + // act + void Action() => uuidType.ParseValue(value); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void EnsureDateTypeKindIsCorrect() + { + // arrange + var type = new UuidType(); + + // assert + Assert.Equal(TypeKind.Scalar, type.Kind); + } + + [InlineData('N')] + [InlineData('D')] + [InlineData('B')] + [InlineData('P')] + [Theory] + public void Serialize_With_Format(char format) + { + // arrange + var uuidType = new UuidType(defaultFormat: format); + var guid = Guid.Empty; + + // act + var s = (string)uuidType.Serialize(guid)!; + + // assert + Assert.Equal(guid.ToString(format.ToString()), s); + } + + [InlineData('N')] + [InlineData('D')] + [InlineData('B')] + [InlineData('P')] + [Theory] + public void Deserialize_With_Format(char format) + { + // arrange + var uuidType = new UuidType(defaultFormat: format); + var guid = Guid.Empty; + var serialized = guid.ToString(format.ToString()); + + // act + var deserialized = (Guid)uuidType.Deserialize(serialized)!; + + // assert + Assert.Equal(guid, deserialized); + } + + [InlineData('N')] + [InlineData('D')] + [InlineData('B')] + [InlineData('P')] + [Theory] + public void ParseValue_With_Format(char format) + { + // arrange + var uuidType = new UuidType(defaultFormat: format); + var guid = Guid.Empty; + + // act + var s = (StringValueNode)uuidType.ParseValue(guid); + + // assert + Assert.Equal(guid.ToString(format.ToString()), s.Value); + } + + [InlineData('N')] + [InlineData('D')] + [InlineData('B')] + [InlineData('P')] + [Theory] + public void ParseLiteral_With_Format(char format) + { + // arrange + var uuidType = new UuidType(defaultFormat: format); + var guid = Guid.Empty; + var literal = new StringValueNode(guid.ToString(format.ToString())); + + // act + var deserialized = (Guid)uuidType.ParseLiteral(literal)!; + + // assert + Assert.Equal(guid, deserialized); + } + + [Fact] + public void Specify_Invalid_Format() + { + // arrange + // act + void Action() => new UuidType(defaultFormat: 'z'); + + // assert #if NETCOREAPP2_1 Assert.Throws(Action).Message .MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1")); #else - Assert.Throws(Action).Message.MatchSnapshot(); + Assert.Throws(Action).Message.MatchSnapshot(); #endif - } - - [InlineData(false)] - [InlineData(true)] - [Theory] - public void Parse_Guid_String_With_Appended_String(bool enforceFormat) - { - // arrange - var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f-foobar"); - var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); - - // act - void Fail() => uuidType.ParseLiteral(input); - - // assert - Assert.Throws(Fail); - } - - [InlineData(false)] - [InlineData(true)] - [Theory] - public void Parse_Guid_Valid_Input(bool enforceFormat) - { - // arrange - var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f"); - var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); - - // act - var guid = (Guid)uuidType.ParseLiteral(input)!; - - // assert - Assert.Equal(input.Value, guid.ToString("D")); - } - - [InlineData(false)] - [InlineData(true)] - [Theory] - public void Deserialize_Guid_String_With_Appended_String(bool enforceFormat) - { - // arrange - var input = "fbdef721-93c5-4267-8f92-ca27b60aa51f-foobar"; - var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); - - // act - void Fail() => uuidType.Deserialize(input); - - // assert - Assert.Throws(Fail); - } - - [InlineData(false)] - [InlineData(true)] - [Theory] - public void Deserialize_Guid_Valid_Format(bool enforceFormat) - { - // arrange - var input = "fbdef721-93c5-4267-8f92-ca27b60aa51f"; - var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); - - // act - var guid = (Guid)uuidType.Deserialize(input)!; - - // assert - Assert.Equal(input, guid.ToString("D")); - } - - [InlineData(false)] - [InlineData(true)] - [Theory] - public void IsInstanceOf_Guid_String_With_Appended_String(bool enforceFormat) - { - // arrange - var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f-foobar"); - var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); - - // act - var result = uuidType.IsInstanceOfType(input); - - // assert - Assert.False(result); - } - - [InlineData(false)] - [InlineData(true)] - [Theory] - public void IsInstanceOf_Guid_Valid_Format(bool enforceFormat) - { - // arrange - var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f"); - var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); - - // act - var result = uuidType.IsInstanceOfType(input); - - // assert - Assert.True(result); - } + } + + [InlineData(false)] + [InlineData(true)] + [Theory] + public void Parse_Guid_String_With_Appended_String(bool enforceFormat) + { + // arrange + var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f-foobar"); + var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); + + // act + void Fail() => uuidType.ParseLiteral(input); + + // assert + Assert.Throws(Fail); + } + + [InlineData(false)] + [InlineData(true)] + [Theory] + public void Parse_Guid_Valid_Input(bool enforceFormat) + { + // arrange + var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f"); + var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); + + // act + var guid = (Guid)uuidType.ParseLiteral(input)!; + + // assert + Assert.Equal(input.Value, guid.ToString("D")); + } + + [InlineData(false)] + [InlineData(true)] + [Theory] + public void Deserialize_Guid_String_With_Appended_String(bool enforceFormat) + { + // arrange + var input = "fbdef721-93c5-4267-8f92-ca27b60aa51f-foobar"; + var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); + + // act + void Fail() => uuidType.Deserialize(input); + + // assert + Assert.Throws(Fail); + } + + [InlineData(false)] + [InlineData(true)] + [Theory] + public void Deserialize_Guid_Valid_Format(bool enforceFormat) + { + // arrange + var input = "fbdef721-93c5-4267-8f92-ca27b60aa51f"; + var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); + + // act + var guid = (Guid)uuidType.Deserialize(input)!; + + // assert + Assert.Equal(input, guid.ToString("D")); + } + + [InlineData(false)] + [InlineData(true)] + [Theory] + public void IsInstanceOf_Guid_String_With_Appended_String(bool enforceFormat) + { + // arrange + var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f-foobar"); + var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); + + // act + var result = uuidType.IsInstanceOfType(input); + + // assert + Assert.False(result); + } + + [InlineData(false)] + [InlineData(true)] + [Theory] + public void IsInstanceOf_Guid_Valid_Format(bool enforceFormat) + { + // arrange + var input = new StringValueNode("fbdef721-93c5-4267-8f92-ca27b60aa51f"); + var uuidType = new UuidType(defaultFormat: 'D', enforceFormat: enforceFormat); + + // act + var result = uuidType.IsInstanceOfType(input); + + // assert + Assert.True(result); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/SubscriptionTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/SubscriptionTypeTests.cs index f0a1b90e40c..a0398317421 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/SubscriptionTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/SubscriptionTypeTests.cs @@ -14,1059 +14,1057 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class SubscriptionTypeTests : TypeTestBase { - public class SubscriptionTypeTests : TypeTestBase + [Fact] + public async Task Subscribe_With_Enumerable() { - [Fact] - public async Task Subscribe_With_Enumerable() + Snapshot.FullName(); + + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType(t => t + .Field("test") + .Type() + .Resolve(ctx => ctx.GetEventMessage()) + .Subscribe(_ => new List { "a", "b", "c" })) + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { test }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType(t => t - .Field("test") - .Type() - .Resolve(ctx => ctx.GetEventMessage()) - .Subscribe(_ => new List { "a", "b", "c" })) - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { test }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(queryResult.ToJson()); - } + results.AppendLine(queryResult.ToJson()); + } - results.ToString().MatchSnapshot(); - }); - } + results.ToString().MatchSnapshot(); + }); + } - [Fact] - public async Task Subscribe_With_Enumerable_Async() + [Fact] + public async Task Subscribe_With_Enumerable_Async() + { + Snapshot.FullName(); + + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType(t => t + .Field("test") + .Type() + .Resolve(ctx => ctx.GetEventMessage()) + .Subscribe(_ => Task.FromResult>( + new List { "a", "b", "c" }))) + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { test }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType(t => t - .Field("test") - .Type() - .Resolve(ctx => ctx.GetEventMessage()) - .Subscribe(_ => Task.FromResult>( - new List { "a", "b", "c" }))) - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { test }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + results.AppendLine(result.ToJson()); + } - results.ToString().MatchSnapshot(); - }); - } + results.ToString().MatchSnapshot(); + }); + } - [Fact] - public async Task Subscribe_With_Observable() - { - Snapshot.FullName(); + [Fact] + public async Task Subscribe_With_Observable() + { + Snapshot.FullName(); - await TryTest(async ct => - { - // arrange - var observable = new TestObservable(); - - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType(t => t - .Field("test") - .Type() - .Resolve(ctx => ctx.GetEventMessage()) - .Subscribe(_ => observable)) - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { test }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - } + await TryTest(async ct => + { + // arrange + var observable = new TestObservable(); - Assert.True(observable.DisposeRaised); - results.ToString().MatchSnapshot(); - }); - } + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType(t => t + .Field("test") + .Type() + .Resolve(ctx => ctx.GetEventMessage()) + .Subscribe(_ => observable)) + .ModifyOptions(t => t.StrictValidation = false) + .Create(); - [Fact] - public async Task Subscribe_With_Observable_Async() - { - Snapshot.FullName(); + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { test }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - var observable = new TestObservable(); - - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType(t => t - .Field("test") - .Type() - .Resolve(ctx => ctx.GetEventMessage()) - .Subscribe(_ => Task.FromResult>(observable))) - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { test }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + var result = queryResult; + results.AppendLine(result.ToJson()); + } - Assert.True(observable.DisposeRaised); - results.ToString().MatchSnapshot(); - }); - } + Assert.True(observable.DisposeRaised); + results.ToString().MatchSnapshot(); + }); + } - [Fact] - public async Task Subscribe_With_AsyncEnumerable() - { - Snapshot.FullName(); + [Fact] + public async Task Subscribe_With_Observable_Async() + { + Snapshot.FullName(); - await TryTest(async ct => - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType(t => t - .Field("test") - .Type() - .Resolve(ctx => ctx.GetEventMessage()) - .Subscribe(_ => new TestAsyncEnumerable())) - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { test }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + await TryTest(async ct => + { + // arrange + var observable = new TestObservable(); - results.ToString().MatchSnapshot(); - }); - } + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType(t => t + .Field("test") + .Type() + .Resolve(ctx => ctx.GetEventMessage()) + .Subscribe(_ => Task.FromResult>(observable))) + .ModifyOptions(t => t.StrictValidation = false) + .Create(); - [Fact] - public async Task Subscribe_With_AsyncEnumerable_Async() - { - Snapshot.FullName(); + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { test }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType(t => t - .Field("test") - .Type() - .Resolve(ctx => ctx.GetEventMessage()) - .Subscribe(_ => Task.FromResult>( - new TestAsyncEnumerable()))) - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { test }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + results.AppendLine(result.ToJson()); + } - results.ToString().MatchSnapshot(); - }); - } + Assert.True(observable.DisposeRaised); + results.ToString().MatchSnapshot(); + }); + } + + [Fact] + public async Task Subscribe_With_AsyncEnumerable() + { + Snapshot.FullName(); - [InlineData("onSomething")] - [InlineData("onSomethingTask")] - [InlineData("onSomethingValueTask")] - [InlineData("onSomethingObj")] - [InlineData("onSomethingObjTask")] - [InlineData("onSomethingObjValueTask")] - [Theory] - public async Task SubscribeAndResolve_Attribute_AsyncEnumerable(string field) + await TryTest(async ct => { - SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType(t => t + .Field("test") + .Type() + .Resolve(ctx => ctx.GetEventMessage()) + .Subscribe(_ => new TestAsyncEnumerable())) + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { test }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType() - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { " + field + " }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + results.AppendLine(result.ToJson()); + } - results.ToString().MatchSnapshot(snapshotFullName); - }); - } + results.ToString().MatchSnapshot(); + }); + } + + [Fact] + public async Task Subscribe_With_AsyncEnumerable_Async() + { + Snapshot.FullName(); - [InlineData("onSomething")] - [Theory] - public async Task SubscribeAndResolve_Attribute_ISourceStream(string field) + await TryTest(async ct => { - SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType(t => t + .Field("test") + .Type() + .Resolve(ctx => ctx.GetEventMessage()) + .Subscribe(_ => Task.FromResult>( + new TestAsyncEnumerable()))) + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { test }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - IRequestExecutor executor = await CreateExecutorAsync(r => r - .AddInMemorySubscriptions() - .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddMutationType() - .AddSubscriptionType()); - - // act - var subscriptionResult = (IResponseStream)await executor.ExecuteAsync( - "subscription { " + field + " (userId: \"1\") }", ct); - - IExecutionResult mutationResult = await executor.ExecuteAsync( - "mutation { writeBoolean(userId: \"1\" message: true) }", - ct); - Assert.Null(mutationResult.ExpectQueryResult().Errors); - - // assert - var results = new StringBuilder(); - await foreach (IQueryResult result in - subscriptionResult.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - break; - } + results.AppendLine(result.ToJson()); + } - results.ToString().MatchSnapshot(snapshotFullName); - }); - } + results.ToString().MatchSnapshot(); + }); + } + + [InlineData("onSomething")] + [InlineData("onSomethingTask")] + [InlineData("onSomethingValueTask")] + [InlineData("onSomethingObj")] + [InlineData("onSomethingObjTask")] + [InlineData("onSomethingObjValueTask")] + [Theory] + public async Task SubscribeAndResolve_Attribute_AsyncEnumerable(string field) + { + var snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); - [InlineData("onSomething")] - [InlineData("onSomethingTask")] - [InlineData("onSomethingValueTask")] - [InlineData("onSomethingObj")] - [InlineData("onSomethingObjTask")] - [InlineData("onSomethingObjValueTask")] - [Theory] - public async Task SubscribeAndResolve_Attribute_Enumerable(string field) + await TryTest(async ct => { - SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType() + .ModifyOptions(t => t.StrictValidation = false) + .Create(); - await TryTest(async ct => + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { " + field + " }", ct); + + var results = new StringBuilder(); + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType() - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { " + field + " }", ct); - - var results = new StringBuilder(); - - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + results.AppendLine(result.ToJson()); + } - results.ToString().MatchSnapshot(snapshotFullName); - }); - } + results.ToString().MatchSnapshot(snapshotFullName); + }); + } - [InlineData("onSomething")] - [InlineData("onSomethingTask")] - [InlineData("onSomethingValueTask")] - [InlineData("onSomethingObj")] - [InlineData("onSomethingObjTask")] - [InlineData("onSomethingObjValueTask")] - [Theory] - public async Task SubscribeAndResolve_Attribute_Queryable(string field) - { - SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); + [InlineData("onSomething")] + [Theory] + public async Task SubscribeAndResolve_Attribute_ISourceStream(string field) + { + var snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); - await TryTest(async ct => - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType() - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { " + field + " }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult result in - stream.ReadResultsAsync().WithCancellation(ct)) - { - results.AppendLine(result.ToJson()); - } + await TryTest(async ct => + { + // arrange + // act + var executor = await CreateExecutorAsync(r => r + .AddInMemorySubscriptions() + .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) + .AddMutationType() + .AddSubscriptionType()); - results.ToString().MatchSnapshot(snapshotFullName); - }); - } + // act + var subscriptionResult = (IResponseStream)await executor.ExecuteAsync( + "subscription { " + field + " (userId: \"1\") }", ct); - [InlineData("onSomething")] - [InlineData("onSomethingTask")] - [InlineData("onSomethingValueTask")] - [InlineData("onSomethingObj")] - [InlineData("onSomethingObjTask")] - [InlineData("onSomethingObjValueTask")] - [Theory] - public async Task SubscribeAndResolve_Attribute_Observable(string field) - { - SnapshotFullName snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); + var mutationResult = await executor.ExecuteAsync( + "mutation { writeBoolean(userId: \"1\" message: true) }", + ct); + Assert.Null(mutationResult.ExpectQueryResult().Errors); - await TryTest(async ct => + // assert + var results = new StringBuilder(); + await foreach (var result in + subscriptionResult.ReadResultsAsync().WithCancellation(ct)) { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddSubscriptionType() - .ModifyOptions(t => t.StrictValidation = false) - .Create(); - - // assert - IRequestExecutor executor = schema.MakeExecutable(); - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { " + field + " }", ct); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - } + results.AppendLine(result.ToJson()); + break; + } - results.ToString().MatchSnapshot(snapshotFullName); - }); - } + results.ToString().MatchSnapshot(snapshotFullName); + }); + } - [Fact] - public async Task Subscribe_Attribute_With_Argument_Topic() + [InlineData("onSomething")] + [InlineData("onSomethingTask")] + [InlineData("onSomethingValueTask")] + [InlineData("onSomethingObj")] + [InlineData("onSomethingObjTask")] + [InlineData("onSomethingObjValueTask")] + [Theory] + public async Task SubscribeAndResolve_Attribute_Enumerable(string field) + { + var snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); + + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType() + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { " + field + " }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(r => r - .AddInMemorySubscriptions() - .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddMutationType() - .AddSubscriptionType()); - - // act - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { onMessage(userId: \"abc\") }", - ct); - - // assert - IExecutionResult mutationResult = await executor.ExecuteAsync( - "mutation { writeMessage(userId: \"abc\" message: \"def\") }", - ct); - Assert.Null(mutationResult.ExpectQueryResult().Errors); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - break; - } + results.AppendLine(result.ToJson()); + } - await stream.DisposeAsync(); + results.ToString().MatchSnapshot(snapshotFullName); + }); + } - results.ToString().MatchSnapshot(); - }); - } + [InlineData("onSomething")] + [InlineData("onSomethingTask")] + [InlineData("onSomethingValueTask")] + [InlineData("onSomethingObj")] + [InlineData("onSomethingObjTask")] + [InlineData("onSomethingObjValueTask")] + [Theory] + public async Task SubscribeAndResolve_Attribute_Queryable(string field) + { + var snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); - [Fact] - public async Task Subscribe_Attribute_With_Static_Topic_Defined_On_Attribute() + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType() + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { " + field + " }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var result in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(r => r - .AddInMemorySubscriptions() - .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddMutationType() - .AddSubscriptionType()); - - // act - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { onFixedMessage }", - ct); - - // assert - IExecutionResult mutationResult = await executor.ExecuteAsync( - "mutation { writeFixedMessage(message: \"def\") }", - ct); - Assert.Null(mutationResult.ExpectQueryResult().Errors); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - break; - } + results.AppendLine(result.ToJson()); + } - await stream.DisposeAsync(); + results.ToString().MatchSnapshot(snapshotFullName); + }); + } - results.ToString().MatchSnapshot(); - }); - } + [InlineData("onSomething")] + [InlineData("onSomethingTask")] + [InlineData("onSomethingValueTask")] + [InlineData("onSomethingObj")] + [InlineData("onSomethingObjTask")] + [InlineData("onSomethingObjValueTask")] + [Theory] + public async Task SubscribeAndResolve_Attribute_Observable(string field) + { + var snapshotFullName = Snapshot.FullName(new SnapshotNameExtension(field)); - [Fact] - public async Task Subscribe_Attribute_With_Static_Topic() + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + // act + var schema = SchemaBuilder.New() + .AddSubscriptionType() + .ModifyOptions(t => t.StrictValidation = false) + .Create(); + + // assert + var executor = schema.MakeExecutable(); + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { " + field + " }", ct); - await TryTest(async ct => + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(r => r - .AddInMemorySubscriptions() - .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddMutationType() - .AddSubscriptionType()); - - // act - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { onSysMessage }", - ct); - - // assert - IExecutionResult mutationResult = await executor.ExecuteAsync( - "mutation { writeSysMessage(message: \"def\") }", - ct); - Assert.Null(mutationResult.ExpectQueryResult().Errors); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - break; - } + var result = queryResult; + results.AppendLine(result.ToJson()); + } - await stream.DisposeAsync(); + results.ToString().MatchSnapshot(snapshotFullName); + }); + } - results.ToString().MatchSnapshot(); - }); - } + [Fact] + public async Task Subscribe_Attribute_With_Argument_Topic() + { + Snapshot.FullName(); - [Fact] - public async Task Subscribe_Attribute_With_Static_Topic_Infer_Topic() + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + var executor = await CreateExecutorAsync(r => r + .AddInMemorySubscriptions() + .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) + .AddMutationType() + .AddSubscriptionType()); - await TryTest(async ct => + // act + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { onMessage(userId: \"abc\") }", + ct); + + // assert + var mutationResult = await executor.ExecuteAsync( + "mutation { writeMessage(userId: \"abc\" message: \"def\") }", + ct); + Assert.Null(mutationResult.ExpectQueryResult().Errors); + + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(r => r - .AddInMemorySubscriptions() - .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddMutationType() - .AddSubscriptionType()); - - // act - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { onInferTopic }", - ct); - - // assert - IExecutionResult mutationResult = await executor.ExecuteAsync( - "mutation { writeOnInferTopic(message: \"def\") }", - ct); - Assert.Null(mutationResult.ExpectQueryResult().Errors); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - break; - } + var result = queryResult; + results.AppendLine(result.ToJson()); + break; + } - await stream.DisposeAsync(); + await stream.DisposeAsync(); - results.ToString().MatchSnapshot(); - }); - } + results.ToString().MatchSnapshot(); + }); + } - [Fact] - public async Task Subscribe_Attribute_With_Explicitly_Defined_Subscribe() + [Fact] + public async Task Subscribe_Attribute_With_Static_Topic_Defined_On_Attribute() + { + Snapshot.FullName(); + + await TryTest(async ct => { - Snapshot.FullName(); + // arrange + var executor = await CreateExecutorAsync(r => r + .AddInMemorySubscriptions() + .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) + .AddMutationType() + .AddSubscriptionType()); + + // act + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { onFixedMessage }", + ct); - await TryTest(async ct => + // assert + var mutationResult = await executor.ExecuteAsync( + "mutation { writeFixedMessage(message: \"def\") }", + ct); + Assert.Null(mutationResult.ExpectQueryResult().Errors); + + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) { - // arrange - IRequestExecutor executor = await CreateExecutorAsync(r => r - .AddInMemorySubscriptions() - .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddMutationType() - .AddSubscriptionType()); - - // act - var stream = (IResponseStream)await executor.ExecuteAsync( - "subscription { onExplicit }", - ct); - - // assert - IExecutionResult mutationResult = await executor.ExecuteAsync( - "mutation { writeOnExplicit(message: \"def\") }", - ct); - Assert.Null(mutationResult.ExpectQueryResult().Errors); - - var results = new StringBuilder(); - await foreach (IQueryResult queryResult in - stream.ReadResultsAsync().WithCancellation(ct)) - { - IQueryResult result = queryResult; - results.AppendLine(result.ToJson()); - break; - } + var result = queryResult; + results.AppendLine(result.ToJson()); + break; + } - await stream.DisposeAsync(); + await stream.DisposeAsync(); - results.ToString().MatchSnapshot(); - }); - } + results.ToString().MatchSnapshot(); + }); + } + + [Fact] + public async Task Subscribe_Attribute_With_Static_Topic() + { + Snapshot.FullName(); - [Fact] - public async Task Subscribe_Attribute_Schema_Is_Generated_Correctly() + await TryTest(async ct => { // arrange - // act - IRequestExecutor executor = await CreateExecutorAsync(r => r + var executor = await CreateExecutorAsync(r => r .AddInMemorySubscriptions() .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) .AddMutationType() .AddSubscriptionType()); + // act + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { onSysMessage }", + ct); + // assert - executor.Schema.ToString().MatchSnapshot(); - } + var mutationResult = await executor.ExecuteAsync( + "mutation { writeSysMessage(message: \"def\") }", + ct); + Assert.Null(mutationResult.ExpectQueryResult().Errors); + + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) + { + var result = queryResult; + results.AppendLine(result.ToJson()); + break; + } + + await stream.DisposeAsync(); + + results.ToString().MatchSnapshot(); + }); + } + + [Fact] + public async Task Subscribe_Attribute_With_Static_Topic_Infer_Topic() + { + Snapshot.FullName(); - [Fact] - public async Task Subscribe_Attribute_Schema_Is_Generated_Correctly_2() + await TryTest(async ct => { // arrange - // act - IRequestExecutor executor = await CreateExecutorAsync(r => r + var executor = await CreateExecutorAsync(r => r .AddInMemorySubscriptions() .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddSubscriptionType(d => d.Name("Subscription")) - .AddTypeExtension()); + .AddMutationType() + .AddSubscriptionType()); + + // act + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { onInferTopic }", + ct); // assert - executor.Schema.ToString().MatchSnapshot(); - } + var mutationResult = await executor.ExecuteAsync( + "mutation { writeOnInferTopic(message: \"def\") }", + ct); + Assert.Null(mutationResult.ExpectQueryResult().Errors); + + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) + { + var result = queryResult; + results.AppendLine(result.ToJson()); + break; + } + + await stream.DisposeAsync(); - [Fact] - public async Task Subscribe_Attribute_With_Two_Topic_Attributes_Error() + results.ToString().MatchSnapshot(); + }); + } + + [Fact] + public async Task Subscribe_Attribute_With_Explicitly_Defined_Subscribe() + { + Snapshot.FullName(); + + await TryTest(async ct => { // arrange - // act - async Task Error() => await CreateExecutorAsync(r => r.AddInMemorySubscriptions() + var executor = await CreateExecutorAsync(r => r + .AddInMemorySubscriptions() .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) - .AddSubscriptionType()); + .AddMutationType() + .AddSubscriptionType()); + + // act + var stream = (IResponseStream)await executor.ExecuteAsync( + "subscription { onExplicit }", + ct); // assert - (await Assert.ThrowsAsync(Error)).Message.MatchSnapshot(); - } + var mutationResult = await executor.ExecuteAsync( + "mutation { writeOnExplicit(message: \"def\") }", + ct); + Assert.Null(mutationResult.ExpectQueryResult().Errors); + + var results = new StringBuilder(); + await foreach (var queryResult in + stream.ReadResultsAsync().WithCancellation(ct)) + { + var result = queryResult; + results.AppendLine(result.ToJson()); + break; + } - public class TestObservable - : IObservable + await stream.DisposeAsync(); + + results.ToString().MatchSnapshot(); + }); + } + + [Fact] + public async Task Subscribe_Attribute_Schema_Is_Generated_Correctly() + { + // arrange + // act + var executor = await CreateExecutorAsync(r => r + .AddInMemorySubscriptions() + .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) + .AddMutationType() + .AddSubscriptionType()); + + // assert + executor.Schema.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Subscribe_Attribute_Schema_Is_Generated_Correctly_2() + { + // arrange + // act + var executor = await CreateExecutorAsync(r => r + .AddInMemorySubscriptions() + .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) + .AddSubscriptionType(d => d.Name("Subscription")) + .AddTypeExtension()); + + // assert + executor.Schema.ToString().MatchSnapshot(); + } + + [Fact] + public async Task Subscribe_Attribute_With_Two_Topic_Attributes_Error() + { + // arrange + // act + async Task Error() => await CreateExecutorAsync(r => r.AddInMemorySubscriptions() + .AddQueryType(c => c.Name("Query").Field("a").Resolve("b")) + .AddSubscriptionType()); + + // assert + (await Assert.ThrowsAsync(Error)).Message.MatchSnapshot(); + } + + public class TestObservable + : IObservable , IDisposable - { - public bool DisposeRaised { get; private set; } + { + public bool DisposeRaised { get; private set; } - public IDisposable Subscribe(IObserver observer) + public IDisposable Subscribe(IObserver observer) + { + Task.Run(async () => { - Task.Run(async () => - { - await Task.Delay(250); + await Task.Delay(250); - foreach (var s in new[] { "a", "b", "c" }) - { - observer.OnNext(s); - } + foreach (var s in new[] { "a", "b", "c" }) + { + observer.OnNext(s); + } - observer.OnCompleted(); - }); + observer.OnCompleted(); + }); - return this; - } + return this; + } - public void Dispose() - { - DisposeRaised = true; - } + public void Dispose() + { + DisposeRaised = true; } + } - public class TestAsyncEnumerable - : IAsyncEnumerable + public class TestAsyncEnumerable + : IAsyncEnumerable + { + public async IAsyncEnumerator GetAsyncEnumerator( + CancellationToken cancellationToken = default) { - public async IAsyncEnumerator GetAsyncEnumerator( - CancellationToken cancellationToken = default) - { - await Task.Delay(50, cancellationToken); - yield return "a"; - yield return "b"; - yield return "c"; - } + await Task.Delay(50, cancellationToken); + yield return "a"; + yield return "b"; + yield return "c"; } + } - public class PureCodeFirstAsyncEnumerable + public class PureCodeFirstAsyncEnumerable + { + [SubscribeAndResolve] + public async IAsyncEnumerable OnSomething() { - [SubscribeAndResolve] - public async IAsyncEnumerable OnSomething() - { - await Task.Delay(50); - yield return "a"; - yield return "b"; - yield return "c"; - } + await Task.Delay(50); + yield return "a"; + yield return "b"; + yield return "c"; + } - [SubscribeAndResolve] - public Task> OnSomethingTask() - { - return Task.FromResult(OnSomething()); - } + [SubscribeAndResolve] + public Task> OnSomethingTask() + { + return Task.FromResult(OnSomething()); + } - [SubscribeAndResolve] - public ValueTask> OnSomethingValueTask() - { - return new(OnSomething()); - } + [SubscribeAndResolve] + public ValueTask> OnSomethingValueTask() + { + return new(OnSomething()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public async IAsyncEnumerable OnSomethingObj() - { - await Task.Delay(50); - yield return "a"; - yield return "b"; - yield return "c"; - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public async IAsyncEnumerable OnSomethingObj() + { + await Task.Delay(50); + yield return "a"; + yield return "b"; + yield return "c"; + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public Task> OnSomethingObjTask() - { - return Task.FromResult(OnSomethingObj()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public Task> OnSomethingObjTask() + { + return Task.FromResult(OnSomethingObj()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public ValueTask> OnSomethingObjValueTask() - { - return new(OnSomethingObj()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public ValueTask> OnSomethingObjValueTask() + { + return new(OnSomethingObj()); } + } - public class PureCodeFirstSourceStream + public class PureCodeFirstSourceStream + { + [SubscribeAndResolve] + public ValueTask> OnSomething( + string userId, + [Service] ITopicEventReceiver receiver) { - [SubscribeAndResolve] - public ValueTask> OnSomething( - string userId, - [Service] ITopicEventReceiver receiver) - { - return receiver.SubscribeAsync(userId); - } + return receiver.SubscribeAsync(userId); } + } - public class PureCodeFirstEnumerable + public class PureCodeFirstEnumerable + { + [SubscribeAndResolve] + public IEnumerable OnSomething() { - [SubscribeAndResolve] - public IEnumerable OnSomething() - { - yield return "a"; - yield return "b"; - yield return "c"; - } + yield return "a"; + yield return "b"; + yield return "c"; + } - [SubscribeAndResolve] - public Task> OnSomethingTask() - { - return Task.FromResult(OnSomething()); - } + [SubscribeAndResolve] + public Task> OnSomethingTask() + { + return Task.FromResult(OnSomething()); + } - [SubscribeAndResolve] - public ValueTask> OnSomethingValueTask() - { - return new(OnSomething()); - } + [SubscribeAndResolve] + public ValueTask> OnSomethingValueTask() + { + return new(OnSomething()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public IEnumerable OnSomethingObj() - { - yield return "a"; - yield return "b"; - yield return "c"; - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public IEnumerable OnSomethingObj() + { + yield return "a"; + yield return "b"; + yield return "c"; + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public Task> OnSomethingObjTask() - { - return Task.FromResult(OnSomethingObj()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public Task> OnSomethingObjTask() + { + return Task.FromResult(OnSomethingObj()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public ValueTask> OnSomethingObjValueTask() - { - return new(OnSomethingObj()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public ValueTask> OnSomethingObjValueTask() + { + return new(OnSomethingObj()); } + } - public class PureCodeFirstQueryable + public class PureCodeFirstQueryable + { + private readonly List _strings = new() { - private readonly List _strings = new() - { - "a", - "b", - "c" - }; + "a", + "b", + "c" + }; - [SubscribeAndResolve] - public IQueryable OnSomething() => _strings.AsQueryable(); + [SubscribeAndResolve] + public IQueryable OnSomething() => _strings.AsQueryable(); - [SubscribeAndResolve] - public Task> OnSomethingTask() - { - return Task.FromResult(OnSomething()); - } + [SubscribeAndResolve] + public Task> OnSomethingTask() + { + return Task.FromResult(OnSomething()); + } - [SubscribeAndResolve] - public ValueTask> OnSomethingValueTask() - { - return new(OnSomething()); - } + [SubscribeAndResolve] + public ValueTask> OnSomethingValueTask() + { + return new(OnSomething()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public IQueryable OnSomethingObj() => _strings.Cast().AsQueryable(); + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public IQueryable OnSomethingObj() => _strings.Cast().AsQueryable(); - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public Task> OnSomethingObjTask() - { - return Task.FromResult(OnSomethingObj()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public Task> OnSomethingObjTask() + { + return Task.FromResult(OnSomethingObj()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public ValueTask> OnSomethingObjValueTask() - { - return new(OnSomethingObj()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public ValueTask> OnSomethingObjValueTask() + { + return new(OnSomethingObj()); } + } - public class PureCodeFirstObservable + public class PureCodeFirstObservable + { + [SubscribeAndResolve] + public IObservable OnSomething() => new StringObservable(); + + [SubscribeAndResolve] + public Task> OnSomethingTask() { - [SubscribeAndResolve] - public IObservable OnSomething() => new StringObservable(); + return Task.FromResult(OnSomething()); + } - [SubscribeAndResolve] - public Task> OnSomethingTask() - { - return Task.FromResult(OnSomething()); - } + [SubscribeAndResolve] + public ValueTask> OnSomethingValueTask() + { + return new(OnSomething()); + } - [SubscribeAndResolve] - public ValueTask> OnSomethingValueTask() - { - return new(OnSomething()); - } + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public IObservable OnSomethingObj() => new StringObservable(); + + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public Task> OnSomethingObjTask() + { + return Task.FromResult(OnSomethingObj()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public IObservable OnSomethingObj() => new StringObservable(); + [GraphQLType(typeof(StringType))] + [SubscribeAndResolve] + public ValueTask> OnSomethingObjValueTask() + { + return new(OnSomethingObj()); + } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public Task> OnSomethingObjTask() + private sealed class StringObservable + : IObservable + , IObservable + { + public IDisposable Subscribe(IObserver observer) { - return Task.FromResult(OnSomethingObj()); + return new Subscription(observer); } - [GraphQLType(typeof(StringType))] - [SubscribeAndResolve] - public ValueTask> OnSomethingObjValueTask() + public IDisposable Subscribe(IObserver observer) { - return new(OnSomethingObj()); + return new Subscription(observer); } - private sealed class StringObservable - : IObservable - , IObservable + private sealed class Subscription : IDisposable { - public IDisposable Subscribe(IObserver observer) + public Subscription(IObserver observer) { - return new Subscription(observer); + new Thread(() => + { + observer.OnNext("a"); + observer.OnNext("b"); + observer.OnNext("c"); + observer.OnCompleted(); + }).Start(); } - public IDisposable Subscribe(IObserver observer) + public Subscription(IObserver observer) { - return new Subscription(observer); + new Thread(() => + { + observer.OnNext("a"); + observer.OnNext("b"); + observer.OnNext("c"); + observer.OnCompleted(); + }).Start(); } - private sealed class Subscription : IDisposable + public void Dispose() { - public Subscription(IObserver observer) - { - new Thread(() => - { - observer.OnNext("a"); - observer.OnNext("b"); - observer.OnNext("c"); - observer.OnCompleted(); - }).Start(); - } - - public Subscription(IObserver observer) - { - new Thread(() => - { - observer.OnNext("a"); - observer.OnNext("b"); - observer.OnNext("c"); - observer.OnCompleted(); - }).Start(); - } - - public void Dispose() - { - } } } } + } - public class MyMutation + public class MyMutation + { + public bool WriteBoolean( + string userId, + bool message, + [Service] ITopicEventSender eventSender) { - public bool WriteBoolean( - string userId, - bool message, - [Service] ITopicEventSender eventSender) - { - eventSender.SendAsync(userId, message); - return message; - } - - public string WriteMessage( - string userId, - string message, - [Service] ITopicEventSender eventSender) - { - eventSender.SendAsync(userId, message); - return message; - } - - public string WriteSysMessage( - string message, - [Service] ITopicEventSender eventSender) - { - eventSender.SendAsync("OnSysMessage", message); - return message; - } - - public string WriteFixedMessage( - string message, - [Service] ITopicEventSender eventSender) - { - eventSender.SendAsync("Fixed", message); - return message; - } + eventSender.SendAsync(userId, message); + return message; + } - public string WriteOnInferTopic( - string message, - [Service] ITopicEventSender eventSender) - { - eventSender.SendAsync("OnInferTopic", message); - return message; - } + public string WriteMessage( + string userId, + string message, + [Service] ITopicEventSender eventSender) + { + eventSender.SendAsync(userId, message); + return message; + } - public string WriteOnExplicit( - string message, - [Service] ITopicEventSender eventSender) - { - eventSender.SendAsync("explicit", message); - return message; - } + public string WriteSysMessage( + string message, + [Service] ITopicEventSender eventSender) + { + eventSender.SendAsync("OnSysMessage", message); + return message; } - public class MySubscription + public string WriteFixedMessage( + string message, + [Service] ITopicEventSender eventSender) { - [Subscribe] - public string OnMessage( - [Topic] string userId, - [EventMessage] string message) => - message; - - [Subscribe] - [Topic] - public string OnSysMessage( - [EventMessage] string message) => - message; - - [Subscribe] - [Topic("Fixed")] - public string OnFixedMessage( - [EventMessage] string message) => - message; - - [Subscribe] - public string OnInferTopic( - [EventMessage] string message) => - message; - - public ValueTask> SubscribeToOnExplicit( - [Service] ITopicEventReceiver eventReceiver) => - eventReceiver.SubscribeAsync("explicit"); - - [Subscribe(With = nameof(SubscribeToOnExplicit))] - public string OnExplicit( - [EventMessage] string message) => - message; - - public ValueTask SubscribeToOnExplicitNonGeneric( - [Service] ITopicEventReceiver eventReceiver) => - default; - - [Subscribe(With = nameof(SubscribeToOnExplicitNonGeneric))] - public string OnExplicitNonGeneric( - [EventMessage] string message) => - message; - - public ISourceStream SubscribeToOnExplicitNonGenericSync( - [Service] ITopicEventReceiver eventReceiver) => - default!; - - [Subscribe(With = nameof(SubscribeToOnExplicitNonGenericSync))] - public string OnExplicitNonGenericSync( - [EventMessage] string message) => - message; - - public ISourceStream SubscribeToOnExplicitSync( - [Service] ITopicEventReceiver eventReceiver) => - default!; - - [Subscribe(With = nameof(SubscribeToOnExplicitSync))] - public string OnExplicitSync( - [EventMessage] string message) => - message; + eventSender.SendAsync("Fixed", message); + return message; } - public class InvalidSubscription_TwoTopicAttributes + public string WriteOnInferTopic( + string message, + [Service] ITopicEventSender eventSender) { - [Subscribe] - [Topic] - public string OnMessage( - [Topic] string userId, - [EventMessage] string message) => - message; + eventSender.SendAsync("OnInferTopic", message); + return message; } - [ExtendObjectType("Subscription")] - public class MySubscriptionExtension + public string WriteOnExplicit( + string message, + [Service] ITopicEventSender eventSender) { - public async ValueTask> SubscribeToOnExplicit( - [Service] ITopicEventReceiver eventReceiver) => - await eventReceiver.SubscribeAsync("explicit"); - - [Subscribe(With = nameof(SubscribeToOnExplicit))] - public string OnExplicit( - [EventMessage] string message) => - message; + eventSender.SendAsync("explicit", message); + return message; } } -} + public class MySubscription + { + [Subscribe] + public string OnMessage( + [Topic] string userId, + [EventMessage] string message) => + message; + + [Subscribe] + [Topic] + public string OnSysMessage( + [EventMessage] string message) => + message; + + [Subscribe] + [Topic("Fixed")] + public string OnFixedMessage( + [EventMessage] string message) => + message; + + [Subscribe] + public string OnInferTopic( + [EventMessage] string message) => + message; + + public ValueTask> SubscribeToOnExplicit( + [Service] ITopicEventReceiver eventReceiver) => + eventReceiver.SubscribeAsync("explicit"); + + [Subscribe(With = nameof(SubscribeToOnExplicit))] + public string OnExplicit( + [EventMessage] string message) => + message; + + public ValueTask SubscribeToOnExplicitNonGeneric( + [Service] ITopicEventReceiver eventReceiver) => + default; + + [Subscribe(With = nameof(SubscribeToOnExplicitNonGeneric))] + public string OnExplicitNonGeneric( + [EventMessage] string message) => + message; + + public ISourceStream SubscribeToOnExplicitNonGenericSync( + [Service] ITopicEventReceiver eventReceiver) => + default!; + + [Subscribe(With = nameof(SubscribeToOnExplicitNonGenericSync))] + public string OnExplicitNonGenericSync( + [EventMessage] string message) => + message; + + public ISourceStream SubscribeToOnExplicitSync( + [Service] ITopicEventReceiver eventReceiver) => + default!; + + [Subscribe(With = nameof(SubscribeToOnExplicitSync))] + public string OnExplicitSync( + [EventMessage] string message) => + message; + } + + public class InvalidSubscription_TwoTopicAttributes + { + [Subscribe] + [Topic] + public string OnMessage( + [Topic] string userId, + [EventMessage] string message) => + message; + } + + [ExtendObjectType("Subscription")] + public class MySubscriptionExtension + { + public async ValueTask> SubscribeToOnExplicit( + [Service] ITopicEventReceiver eventReceiver) => + await eventReceiver.SubscribeAsync("explicit"); + + [Subscribe(With = nameof(SubscribeToOnExplicit))] + public string OnExplicit( + [EventMessage] string message) => + message; + } +} diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/TypeExtensionsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/TypeExtensionsTests.cs index 37c5b66ca08..c975a2928eb 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/TypeExtensionsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/TypeExtensionsTests.cs @@ -3,896 +3,895 @@ using Moq; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class TypeExtensionsTests { - public class TypeExtensionsTests - { - [Fact] - public void IsEquals_TwoStringNonNullTypes_True() - { - // arrange - var x = new NonNullType(new StringType()); - var y = new NonNullType(new StringType()); - - // act - var result = x.IsEqualTo(y); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEquals_TwoStringListTypes_True() - { - // arrange - var x = new ListType(new StringType()); - var y = new ListType(new StringType()); - - // act - var result = x.IsEqualTo(y); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEquals_TwoStringNonNullListTypes_True() - { - // arrange - var x = new NonNullType(new ListType(new StringType())); - var y = new NonNullType(new ListType(new StringType())); - - // act - var result = x.IsEqualTo(y); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEquals_NonNullStringListToStringList_False() - { - // arrange - var x = new NonNullType(new ListType(new StringType())); - var y = new ListType(new StringType()); - - // act - var result = x.IsEqualTo(y); - - // assert - Assert.False(result); - } - - [Fact] - public void IsEquals_StringToSelf_True() - { - // arrange - var x = new StringType(); - - // act - var result = x.IsEqualTo(x); - - // assert - Assert.True(result); - } - - [Fact] - public void IsEquals_StringListToIntList_False() - { - // arrange - var x = new ListType(new StringType()); - var y = new ListType(new IntType()); - - // act - var result = x.IsEqualTo(y); - - // assert - Assert.False(result); - } - - [Fact] - public static void NamedType() - { - // arrange - var type = new NonNullType( + [Fact] + public void IsEquals_TwoStringNonNullTypes_True() + { + // arrange + var x = new NonNullType(new StringType()); + var y = new NonNullType(new StringType()); + + // act + var result = x.IsEqualTo(y); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEquals_TwoStringListTypes_True() + { + // arrange + var x = new ListType(new StringType()); + var y = new ListType(new StringType()); + + // act + var result = x.IsEqualTo(y); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEquals_TwoStringNonNullListTypes_True() + { + // arrange + var x = new NonNullType(new ListType(new StringType())); + var y = new NonNullType(new ListType(new StringType())); + + // act + var result = x.IsEqualTo(y); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEquals_NonNullStringListToStringList_False() + { + // arrange + var x = new NonNullType(new ListType(new StringType())); + var y = new ListType(new StringType()); + + // act + var result = x.IsEqualTo(y); + + // assert + Assert.False(result); + } + + [Fact] + public void IsEquals_StringToSelf_True() + { + // arrange + var x = new StringType(); + + // act + var result = x.IsEqualTo(x); + + // assert + Assert.True(result); + } + + [Fact] + public void IsEquals_StringListToIntList_False() + { + // arrange + var x = new ListType(new StringType()); + var y = new ListType(new IntType()); + + // act + var result = x.IsEqualTo(y); + + // assert + Assert.False(result); + } + + [Fact] + public static void NamedType() + { + // arrange + var type = new NonNullType( + new ListType( + new NonNullType( + new StringType()))); + + // act + var stringType = type.NamedType() as StringType; + + // assert + Assert.NotNull(stringType); + } + + [Fact] + public static void NamedType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.NamedType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsNonNullType_True() + { + // arrange + var type = new NonNullType(new StringType()); + + // act + var result = type.IsNonNullType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsNonNullType_False() + { + // arrange + var type = new StringType(); + + // act + var result = type.IsNonNullType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsNonNullType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsNonNullType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsCompositeType_ObjectType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsCompositeType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsCompositeType_InterfaceType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsCompositeType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsCompositeType_UnionType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsCompositeType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsCompositeType_False() + { + // arrange + var type = new StringType(); + + // act + var result = type.IsCompositeType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsCompositeType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsCompositeType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsComplexType_ObjectType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsComplexType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsComplexType_InterfaceType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsComplexType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsComplexType_UnionType_False() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.Union); + + // act + var result = type.Object.IsComplexType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsComplexType_False() + { + // arrange + var type = new StringType(); + + // act + var result = type.IsComplexType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsComplexType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsComplexType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsLeafType_ScalarType_True() + { + // arrange + var type = new StringType(); + + // act + var result = type.IsLeafType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsLeafType_EnumType_True() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.Enum); + + // act + var result = type.Object.IsLeafType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsLeafType_UnionType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsLeafType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsLeafType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsLeafType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsListType_StringListType_True() + { + // arrange + IType type = new ListType(new StringType()); + + // act + var result = type.IsListType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsListType_UnionType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsListType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsListType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsListType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsScalarType_StringType_True() + { + // arrange + IType type = new StringType(); + + // act + var result = type.IsScalarType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsScalarType_UnionType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsScalarType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsScalarType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsScalarType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsObjectType_True() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.Object); + + // act + var result = type.Object.IsObjectType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsObjectType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsObjectType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsObjectType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsObjectType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsInterfaceType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsInterfaceType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsScalarType_False() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.Union); + + // act + var result = type.Object.IsScalarType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsInterfaceType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsInterfaceType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsEnumType_True() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.Enum); + + // act + var result = type.Object.IsEnumType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsEnumType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsEnumType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsEnumType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsEnumType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsUnionType_True() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.Union); + + // act + var result = type.Object.IsUnionType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsUnionType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsUnionType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsUnionType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsUnionType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsInputObjectType_True() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.InputObject); + + // act + var result = type.Object.IsInputObjectType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsInputObjectType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsInputObjectType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsInputObjectType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsInputObjectType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsInputType_True() + { + // arrange + IType type = new StringType(); + + // act + var result = type.IsInputType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsInputType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsInputType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsInputType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsInputType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsOutputType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsOutputType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsOutputType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsOutputType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsOutputType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsOutputType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsAbstractType_InterfaceType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsAbstractType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsAbstractType_UnionType_True() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsAbstractType(); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsAbstractType_False() + { + // arrange + var type = new Mock(); + type.SetupGet(t => t.Kind).Returns(TypeKind.InputObject); + + // act + var result = type.Object.IsAbstractType(); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsAbstractType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsAbstractType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public static void IsType_StringType_True() + { + // arrange + IType type = new StringType(); + + // act + var result = type.IsType(TypeKind.Scalar); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsType_NonNullStringType_True() + { + // arrange + IType type = new NonNullType(new StringType()); + + // act + var result = type.IsType(TypeKind.Scalar); + + // assert + Assert.True(result); + } + + [Fact] + public static void IsType_InputObjectType_False() + { + // arrange + IType type = Mock.Of(); + + // act + var result = type.IsType(TypeKind.Scalar); + + // assert + Assert.False(result); + } + + [Fact] + public static void IsType_Type_Is_Null() + { + // act + void Action() => TypeExtensions.IsAbstractType(null!); + + // assert + Assert.Throws(Action); + } + + [Fact] + public void RewriteType_NonNull_To_Nullable() + { + // arrange + var type = new NonNullType(new StringType()); + var nullability = new OptionalModifierNode(null, null); + + // act + var rewritten = type.RewriteNullability(nullability); + + // assert + Assert.IsType(rewritten); + } + + [Fact] + public void RewriteType_NonNull_To_NonNull() + { + // arrange + var type = new NonNullType(new StringType()); + var nullability = new RequiredModifierNode(null, null); + + // act + var rewritten = type.RewriteNullability(nullability); + + // assert + Assert.IsType(Assert.IsType(rewritten).Type); + } + + [Fact] + public void RewriteType_Nullable_To_NonNull() + { + // arrange + var type = new StringType(); + var nullability = new RequiredModifierNode(null, null); + + // act + var rewritten = type.RewriteNullability(nullability); + + // assert + Assert.IsType(Assert.IsType(rewritten).Type); + } + + [Fact] + public void RewriteType_Nullable_To_Nullable() + { + // arrange + var type = new StringType(); + var nullability = new OptionalModifierNode(null, null); + + // act + var rewritten = type.RewriteNullability(nullability); + + // assert + Assert.IsType(rewritten); + } + + [Fact] + public void RewriteType_ListNonNull_To_ListNullable() + { + // arrange + var type = new ListType(new NonNullType(new StringType())); + var nullability = new ListNullabilityNode(null, new OptionalModifierNode(null, null)); + + // act + var rewritten = type.RewriteNullability(nullability); + + // assert + Assert.IsType( + Assert.IsType(rewritten).ElementType); + } + + [Fact] + public void RewriteType_NonNullListNonNull_To_NonNullListNullable() + { + // arrange + var type = new NonNullType(new ListType(new NonNullType(new StringType()))); + var nullability = new ListNullabilityNode(null, new OptionalModifierNode(null, null)); + + // act + var rewritten = type.RewriteNullability(nullability); + + // assert + Assert.IsType( + Assert.IsType( + Assert.IsType(rewritten).Type).ElementType); + } + + [Fact] + public void RewriteType_DoNothing() + { + // arrange + var type = new NonNullType( + new ListType( new ListType( new NonNullType( - new StringType()))); - - // act - var stringType = type.NamedType() as StringType; - - // assert - Assert.NotNull(stringType); - } - - [Fact] - public static void NamedType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.NamedType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsNonNullType_True() - { - // arrange - var type = new NonNullType(new StringType()); - - // act - var result = type.IsNonNullType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsNonNullType_False() - { - // arrange - var type = new StringType(); - - // act - var result = type.IsNonNullType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsNonNullType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsNonNullType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsCompositeType_ObjectType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsCompositeType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsCompositeType_InterfaceType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsCompositeType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsCompositeType_UnionType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsCompositeType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsCompositeType_False() - { - // arrange - var type = new StringType(); - - // act - var result = type.IsCompositeType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsCompositeType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsCompositeType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsComplexType_ObjectType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsComplexType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsComplexType_InterfaceType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsComplexType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsComplexType_UnionType_False() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.Union); - - // act - var result = type.Object.IsComplexType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsComplexType_False() - { - // arrange - var type = new StringType(); - - // act - var result = type.IsComplexType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsComplexType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsComplexType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsLeafType_ScalarType_True() - { - // arrange - var type = new StringType(); - - // act - var result = type.IsLeafType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsLeafType_EnumType_True() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.Enum); - - // act - var result = type.Object.IsLeafType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsLeafType_UnionType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsLeafType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsLeafType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsLeafType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsListType_StringListType_True() - { - // arrange - IType type = new ListType(new StringType()); - - // act - var result = type.IsListType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsListType_UnionType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsListType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsListType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsListType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsScalarType_StringType_True() - { - // arrange - IType type = new StringType(); - - // act - var result = type.IsScalarType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsScalarType_UnionType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsScalarType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsScalarType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsScalarType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsObjectType_True() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.Object); - - // act - var result = type.Object.IsObjectType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsObjectType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsObjectType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsObjectType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsObjectType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsInterfaceType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsInterfaceType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsScalarType_False() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.Union); - - // act - var result = type.Object.IsScalarType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsInterfaceType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsInterfaceType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsEnumType_True() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.Enum); - - // act - var result = type.Object.IsEnumType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsEnumType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsEnumType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsEnumType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsEnumType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsUnionType_True() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.Union); - - // act - var result = type.Object.IsUnionType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsUnionType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsUnionType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsUnionType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsUnionType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsInputObjectType_True() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.InputObject); - - // act - var result = type.Object.IsInputObjectType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsInputObjectType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsInputObjectType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsInputObjectType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsInputObjectType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsInputType_True() - { - // arrange - IType type = new StringType(); - - // act - var result = type.IsInputType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsInputType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsInputType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsInputType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsInputType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsOutputType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsOutputType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsOutputType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsOutputType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsOutputType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsOutputType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsAbstractType_InterfaceType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsAbstractType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsAbstractType_UnionType_True() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsAbstractType(); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsAbstractType_False() - { - // arrange - var type = new Mock(); - type.SetupGet(t => t.Kind).Returns(TypeKind.InputObject); - - // act - var result = type.Object.IsAbstractType(); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsAbstractType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsAbstractType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public static void IsType_StringType_True() - { - // arrange - IType type = new StringType(); - - // act - var result = type.IsType(TypeKind.Scalar); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsType_NonNullStringType_True() - { - // arrange - IType type = new NonNullType(new StringType()); - - // act - var result = type.IsType(TypeKind.Scalar); - - // assert - Assert.True(result); - } - - [Fact] - public static void IsType_InputObjectType_False() - { - // arrange - IType type = Mock.Of(); - - // act - var result = type.IsType(TypeKind.Scalar); - - // assert - Assert.False(result); - } - - [Fact] - public static void IsType_Type_Is_Null() - { - // act - void Action() => TypeExtensions.IsAbstractType(null!); - - // assert - Assert.Throws(Action); - } - - [Fact] - public void RewriteType_NonNull_To_Nullable() - { - // arrange - var type = new NonNullType(new StringType()); - var nullability = new OptionalModifierNode(null, null); - - // act - IType rewritten = type.RewriteNullability(nullability); - - // assert - Assert.IsType(rewritten); - } - - [Fact] - public void RewriteType_NonNull_To_NonNull() - { - // arrange - var type = new NonNullType(new StringType()); - var nullability = new RequiredModifierNode(null, null); - - // act - IType rewritten = type.RewriteNullability(nullability); - - // assert - Assert.IsType(Assert.IsType(rewritten).Type); - } - - [Fact] - public void RewriteType_Nullable_To_NonNull() - { - // arrange - var type = new StringType(); - var nullability = new RequiredModifierNode(null, null); - - // act - IType rewritten = type.RewriteNullability(nullability); - - // assert - Assert.IsType(Assert.IsType(rewritten).Type); - } - - [Fact] - public void RewriteType_Nullable_To_Nullable() - { - // arrange - var type = new StringType(); - var nullability = new OptionalModifierNode(null, null); - - // act - IType rewritten = type.RewriteNullability(nullability); - - // assert - Assert.IsType(rewritten); - } - - [Fact] - public void RewriteType_ListNonNull_To_ListNullable() - { - // arrange - var type = new ListType(new NonNullType(new StringType())); - var nullability = new ListNullabilityNode(null, new OptionalModifierNode(null, null)); - - // act - IType rewritten = type.RewriteNullability(nullability); - - // assert - Assert.IsType( - Assert.IsType(rewritten).ElementType); - } - - [Fact] - public void RewriteType_NonNullListNonNull_To_NonNullListNullable() - { - // arrange - var type = new NonNullType(new ListType(new NonNullType(new StringType()))); - var nullability = new ListNullabilityNode(null, new OptionalModifierNode(null, null)); - - // act - IType rewritten = type.RewriteNullability(nullability); - - // assert - Assert.IsType( - Assert.IsType( - Assert.IsType(rewritten).Type).ElementType); - } - - [Fact] - public void RewriteType_DoNothing() - { - // arrange - var type = new NonNullType( - new ListType( - new ListType( - new NonNullType( - new StringType())))); + new StringType())))); - var nullability = new ListNullabilityNode(null, new ListNullabilityNode(null, null)); + var nullability = new ListNullabilityNode(null, new ListNullabilityNode(null, null)); - // act - IType rewritten = type.RewriteNullability(nullability); + // act + var rewritten = type.RewriteNullability(nullability); - // assert - Assert.IsType( - Assert.IsType( + // assert + Assert.IsType( + Assert.IsType( Assert.IsType( - Assert.IsType( - Assert.IsType(rewritten).Type) + Assert.IsType( + Assert.IsType(rewritten).Type) .ElementType) - .ElementType) - .Type); - } - - [Fact] - public void RewriteType_Modifier_Structure_Does_Not_Match_Type_Structure() - { - // arrange - var type = new StringType(); - var nullability = new ListNullabilityNode(null, null); - - // act - void Fail() => type.RewriteNullability(nullability); - - // assert - Assert.Throws(Fail); - } - - [Fact] - public void RewriteType_No_Nullable_Modifier() - { - // arrange - var type = new StringType(); - - // act - IType rewritten = type.RewriteNullability(null); - - // assert - Assert.IsType(rewritten); - } + .ElementType) + .Type); + } + + [Fact] + public void RewriteType_Modifier_Structure_Does_Not_Match_Type_Structure() + { + // arrange + var type = new StringType(); + var nullability = new ListNullabilityNode(null, null); + + // act + void Fail() => type.RewriteNullability(nullability); + + // assert + Assert.Throws(Fail); + } + + [Fact] + public void RewriteType_No_Nullable_Modifier() + { + // arrange + var type = new StringType(); + + // act + var rewritten = type.RewriteNullability(null); + + // assert + Assert.IsType(rewritten); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/TypeFactoryTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/TypeFactoryTests.cs index 24d5cda763c..f3f9ba689ee 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/TypeFactoryTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/TypeFactoryTests.cs @@ -2,61 +2,61 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class TypeFactoryTests : TypeTestBase { - public class TypeFactoryTests : TypeTestBase + [Fact] + public void CreateObjectType() { - [Fact] - public void CreateObjectType() - { - // arrange - var source = @" + // arrange + var source = @" type Simple { a: String b: [String] } schema { query: Simple }"; - var resolvers = new - { - Simple = new { A = "hello", B = new[] { "hello" } } - }; + var resolvers = new + { + Simple = new { A = "hello", B = new[] { "hello" } } + }; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddRootResolver(resolvers) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddRootResolver(resolvers) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void ObjectFieldDeprecationReason() - { - // arrange - var source = @" + [Fact] + public void ObjectFieldDeprecationReason() + { + // arrange + var source = @" type Simple { a: String @deprecated(reason: ""reason123"") } schema { query: Simple }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .Use(_ => _) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .Use(_ => _) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void CreateObjectTypeDescriptions() - { - // arrange - var source = @" + [Fact] + public void CreateObjectTypeDescriptions() + { + // arrange + var source = @" ""SimpleDesc"" type Simple { ""ADesc"" @@ -64,290 +64,289 @@ type Simple { } schema { query: Simple }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .Use(_ => _) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .Use(_ => _) + .Create(); - // assert - schema.ToString().MatchSnapshot(); - } + // assert + schema.ToString().MatchSnapshot(); + } - [Fact] - public void CreateInterfaceType() - { - // arrange - var source = "interface Simple { a: String b: [String] }"; - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - InterfaceType type = schema.GetType("Simple"); - - Assert.Equal("Simple", type.Name); - Assert.Equal(2, type.Fields.Count); - - Assert.True(type.Fields.ContainsField("a")); - Assert.False(type.Fields["a"].Type.IsNonNullType()); - Assert.False(type.Fields["a"].Type.IsListType()); - Assert.True(type.Fields["a"].Type.IsScalarType()); - Assert.Equal("String", type.Fields["a"].Type.TypeName()); - - Assert.True(type.Fields.ContainsField("b")); - Assert.False(type.Fields["b"].Type.IsNonNullType()); - Assert.True(type.Fields["b"].Type.IsListType()); - Assert.False(type.Fields["b"].Type.IsScalarType()); - Assert.Equal("String", type.Fields["b"].Type.TypeName()); - - schema.ToString().MatchSnapshot(); - } - - [Fact] - public void InterfaceFieldDeprecationReason() - { - // arrange - var source = @" + [Fact] + public void CreateInterfaceType() + { + // arrange + var source = "interface Simple { a: String b: [String] }"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Simple"); + + Assert.Equal("Simple", type.Name); + Assert.Equal(2, type.Fields.Count); + + Assert.True(type.Fields.ContainsField("a")); + Assert.False(type.Fields["a"].Type.IsNonNullType()); + Assert.False(type.Fields["a"].Type.IsListType()); + Assert.True(type.Fields["a"].Type.IsScalarType()); + Assert.Equal("String", type.Fields["a"].Type.TypeName()); + + Assert.True(type.Fields.ContainsField("b")); + Assert.False(type.Fields["b"].Type.IsNonNullType()); + Assert.True(type.Fields["b"].Type.IsListType()); + Assert.False(type.Fields["b"].Type.IsScalarType()); + Assert.Equal("String", type.Fields["b"].Type.TypeName()); + + schema.ToString().MatchSnapshot(); + } + + [Fact] + public void InterfaceFieldDeprecationReason() + { + // arrange + var source = @" interface Simple { a: String @deprecated(reason: ""reason123"") }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - InterfaceType type = schema.GetType("Simple"); + // assert + var type = schema.GetType("Simple"); - Assert.True(type.Fields["a"].IsDeprecated); - Assert.Equal("reason123", type.Fields["a"].DeprecationReason); + Assert.True(type.Fields["a"].IsDeprecated); + Assert.Equal("reason123", type.Fields["a"].DeprecationReason); - schema.ToString().MatchSnapshot(); - } + schema.ToString().MatchSnapshot(); + } - [Fact] - public void InterfaceFieldDeprecationWithoutReason() - { - // arrange - var source = @" + [Fact] + public void InterfaceFieldDeprecationWithoutReason() + { + // arrange + var source = @" interface Simple { a: String @deprecated }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + var type = schema.GetType("Simple"); - // assert - InterfaceType type = schema.GetType("Simple"); + Assert.True(type.Fields["a"].IsDeprecated); + Assert.Equal( + WellKnownDirectives.DeprecationDefaultReason, + type.Fields["a"].DeprecationReason); - Assert.True(type.Fields["a"].IsDeprecated); - Assert.Equal( - WellKnownDirectives.DeprecationDefaultReason, - type.Fields["a"].DeprecationReason); + schema.ToString().MatchSnapshot(); + } - schema.ToString().MatchSnapshot(); - } + [Fact] + public void CreateUnion() + { + // arrange + var objectTypeA = new ObjectType(d => d + .Name("A") + .Field("a") + .Type() + .Resolve("a")); + + var objectTypeB = new ObjectType(d => d + .Name("B") + .Field("a") + .Type() + .Resolve("b")); + + var source = "union X = A | B"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .AddType(objectTypeA) + .AddType(objectTypeB) + .Create(); + + // assert + var type = schema.GetType("X"); + + Assert.Equal("X", type.Name); + Assert.Equal(2, type.Types.Count); + Assert.Equal("A", type.Types.First().Key); + Assert.Equal("B", type.Types.Last().Key); + } - [Fact] - public void CreateUnion() - { - // arrange - var objectTypeA = new ObjectType(d => d - .Name("A") - .Field("a") - .Type() - .Resolve("a")); - - var objectTypeB = new ObjectType(d => d - .Name("B") - .Field("a") - .Type() - .Resolve("b")); - - var source = "union X = A | B"; - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .AddType(objectTypeA) - .AddType(objectTypeB) - .Create(); - - // assert - UnionType type = schema.GetType("X"); - - Assert.Equal("X", type.Name); - Assert.Equal(2, type.Types.Count); - Assert.Equal("A", type.Types.First().Key); - Assert.Equal("B", type.Types.Last().Key); - } - - [Fact] - public void CreateEnum() - { - // arrange - var source = "enum Abc { A B C }"; - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .Create(); - - // assert - EnumType type = schema.GetType("Abc"); - - Assert.Equal("Abc", type.Name); - Assert.Collection(type.Values, - t => Assert.Equal("A", t.Name), - t => Assert.Equal("B", t.Name), - t => Assert.Equal("C", t.Name)); - } - - [Fact] - public void EnumValueDeprecationReason() - { - // arrange - var source = @" + [Fact] + public void CreateEnum() + { + // arrange + var source = "enum Abc { A B C }"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .Create(); + + // assert + var type = schema.GetType("Abc"); + + Assert.Equal("Abc", type.Name); + Assert.Collection(type.Values, + t => Assert.Equal("A", t.Name), + t => Assert.Equal("B", t.Name), + t => Assert.Equal("C", t.Name)); + } + + [Fact] + public void EnumValueDeprecationReason() + { + // arrange + var source = @" enum Abc { A B @deprecated(reason: ""reason123"") C }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .Create(); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .Create(); - // assert - EnumType type = schema.GetType("Abc"); + // assert + var type = schema.GetType("Abc"); - IEnumValue value = type.Values.FirstOrDefault(t => t.Name == "B"); - Assert.NotNull(value); - Assert.True(value.IsDeprecated); - Assert.Equal("reason123", value.DeprecationReason); - } + var value = type.Values.FirstOrDefault(t => t.Name == "B"); + Assert.NotNull(value); + Assert.True(value.IsDeprecated); + Assert.Equal("reason123", value.DeprecationReason); + } - [Fact] - public void CreateInputObjectType() - { - // arrange - var source = @" + [Fact] + public void CreateInputObjectType() + { + // arrange + var source = @" input Simple { a: String @bind(to: ""Name"") b: [String] @bind(to: ""Friends"") }"; - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .BindRuntimeType("Simple") - .Create(); - - // assert - InputObjectType type = schema.GetType("Simple"); - - Assert.Equal("Simple", type.Name); - Assert.Equal(2, type.Fields.Count); - - Assert.True(type.Fields.ContainsField("a")); - Assert.False(type.Fields["a"].Type.IsNonNullType()); - Assert.False(type.Fields["a"].Type.IsListType()); - Assert.True(type.Fields["a"].Type.IsScalarType()); - Assert.Equal("String", type.Fields["a"].Type.TypeName()); - - Assert.True(type.Fields.ContainsField("b")); - Assert.False(type.Fields["b"].Type.IsNonNullType()); - Assert.True(type.Fields["b"].Type.IsListType()); - Assert.False(type.Fields["b"].Type.IsScalarType()); - Assert.Equal("String", type.Fields["b"].Type.TypeName()); - } - - [Fact] - public void CreateDirectiveType() - { - // arrange - var source = "directive @foo(a:String) on QUERY"; - - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .Create(); - - // assert - DirectiveType type = schema.GetDirectiveType("foo"); - - Assert.Equal("foo", type.Name); - Assert.False(type.IsRepeatable); - - Assert.Collection( - type.Locations, - t => Assert.Equal(DirectiveLocation.Query, t)); - - Assert.Collection( - type.Arguments, - t => - { - Assert.Equal("a", t.Name); - Assert.IsType(t.Type); - }); - } - - [Fact] - public void CreateRepeatableDirectiveType() - { - // arrange - var source = "directive @foo(a:String) repeatable on QUERY"; + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .BindRuntimeType("Simple") + .Create(); + + // assert + var type = schema.GetType("Simple"); + + Assert.Equal("Simple", type.Name); + Assert.Equal(2, type.Fields.Count); + + Assert.True(type.Fields.ContainsField("a")); + Assert.False(type.Fields["a"].Type.IsNonNullType()); + Assert.False(type.Fields["a"].Type.IsListType()); + Assert.True(type.Fields["a"].Type.IsScalarType()); + Assert.Equal("String", type.Fields["a"].Type.TypeName()); + + Assert.True(type.Fields.ContainsField("b")); + Assert.False(type.Fields["b"].Type.IsNonNullType()); + Assert.True(type.Fields["b"].Type.IsListType()); + Assert.False(type.Fields["b"].Type.IsScalarType()); + Assert.Equal("String", type.Fields["b"].Type.TypeName()); + } - // act - ISchema schema = SchemaBuilder.New() - .AddDocumentFromString(source) - .AddQueryType() - .Create(); + [Fact] + public void CreateDirectiveType() + { + // arrange + var source = "directive @foo(a:String) on QUERY"; - // assert - DirectiveType type = schema.GetDirectiveType("foo"); + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .Create(); - Assert.Equal("foo", type.Name); - Assert.True(type.IsRepeatable); + // assert + var type = schema.GetDirectiveType("foo"); - Assert.Collection(type.Locations, - t => Assert.Equal(DirectiveLocation.Query, t)); + Assert.Equal("foo", type.Name); + Assert.False(type.IsRepeatable); - Assert.Collection(type.Arguments, - t => - { - Assert.Equal("a", t.Name); - Assert.IsType(t.Type); - }); - } + Assert.Collection( + type.Locations, + t => Assert.Equal(DirectiveLocation.Query, t)); - public class SimpleInputObject - { - public string Name { get; set; } - public string[] Friends { get; set; } - } + Assert.Collection( + type.Arguments, + t => + { + Assert.Equal("a", t.Name); + Assert.IsType(t.Type); + }); + } - public class DummyQuery - { - public string Bar { get; set; } - } + [Fact] + public void CreateRepeatableDirectiveType() + { + // arrange + var source = "directive @foo(a:String) repeatable on QUERY"; + + // act + var schema = SchemaBuilder.New() + .AddDocumentFromString(source) + .AddQueryType() + .Create(); + + // assert + var type = schema.GetDirectiveType("foo"); + + Assert.Equal("foo", type.Name); + Assert.True(type.IsRepeatable); + + Assert.Collection(type.Locations, + t => Assert.Equal(DirectiveLocation.Query, t)); + + Assert.Collection(type.Arguments, + t => + { + Assert.Equal("a", t.Name); + Assert.IsType(t.Type); + }); + } + + public class SimpleInputObject + { + public string Name { get; set; } + public string[] Friends { get; set; } + } + + public class DummyQuery + { + public string Bar { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/TypeTestBase.cs b/src/HotChocolate/Core/test/Types.Tests/Types/TypeTestBase.cs index 58131ced635..03d5fec401c 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/TypeTestBase.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/TypeTestBase.cs @@ -1,75 +1,74 @@ using System; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class TypeTestBase { - public class TypeTestBase + protected T CreateDirective(T directiveType) + where T : DirectiveType { - protected T CreateDirective(T directiveType) - where T : DirectiveType - { - return CreateDirective(directiveType, b => { }); - } + return CreateDirective(directiveType, b => { }); + } - protected T CreateDirective(T directiveType, - Action configure) - where T : DirectiveType - { - ISchemaBuilder builder = SchemaBuilder.New() - .AddQueryType(c => - c.Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddDirectiveType(directiveType); + protected T CreateDirective(T directiveType, + Action configure) + where T : DirectiveType + { + var builder = SchemaBuilder.New() + .AddQueryType(c => + c.Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddDirectiveType(directiveType); - configure(builder); + configure(builder); - builder.Create(); + builder.Create(); - return directiveType; - } + return directiveType; + } - protected static T CreateType(T type) - where T : INamedType - { - return CreateType(type, b => { }); - } + protected static T CreateType(T type) + where T : INamedType + { + return CreateType(type, b => { }); + } - protected static T CreateType(T type, - Action configure) - where T : INamedType - { - ISchemaBuilder builder = SchemaBuilder.New() - .AddQueryType(c => - c.Name("Query") - .Field("foo") - .Type() - .Resolve("bar")) - .AddType(type); + protected static T CreateType(T type, + Action configure) + where T : INamedType + { + var builder = SchemaBuilder.New() + .AddQueryType(c => + c.Name("Query") + .Field("foo") + .Type() + .Resolve("bar")) + .AddType(type); - configure(builder); + configure(builder); - builder.Create(); + builder.Create(); - return type; - } + return type; + } - public static ISchema CreateSchema(T type) - where T : INamedType => - CreateSchema(builder => builder.AddType(type)); + public static ISchema CreateSchema(T type) + where T : INamedType => + CreateSchema(builder => builder.AddType(type)); - public static ISchema CreateSchema(Action configure) - { - ISchemaBuilder builder = SchemaBuilder.New() - .AddQueryType(c => - c.Name("Query") - .Field("foo") - .Type() - .Resolve("bar")); + public static ISchema CreateSchema(Action configure) + { + var builder = SchemaBuilder.New() + .AddQueryType(c => + c.Name("Query") + .Field("foo") + .Type() + .Resolve("bar")); - configure(builder); + configure(builder); - return builder.Create(); - } + return builder.Create(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeAttributeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeAttributeTests.cs index 90420b5853f..0ef7b0476fb 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeAttributeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeAttributeTests.cs @@ -5,58 +5,57 @@ #nullable enable -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class UnionTypeAttributeTests { - public class UnionTypeAttributeTests + [Fact] + public void SetName_Union_Interface() { - [Fact] - public void SetName_Union_Interface() - { - // act - ISchema schema = SchemaBuilder.New() - .AddUnionType() - .AddType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - Assert.NotNull(schema.GetType("Abc")); - } + // act + var schema = SchemaBuilder.New() + .AddUnionType() + .AddType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + Assert.NotNull(schema.GetType("Abc")); + } - [Fact] - public void UnionTypeAttribute_Infer_Union() - { - // act - ISchema schema = SchemaBuilder.New() - .AddType() - .AddType() - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - schema.ToString().MatchSnapshot(); - } + [Fact] + public void UnionTypeAttribute_Infer_Union() + { + // act + var schema = SchemaBuilder.New() + .AddType() + .AddType() + .ModifyOptions(o => o.StrictValidation = false) + .Create(); + + // assert + schema.ToString().MatchSnapshot(); + } - [SetName] - public interface IUnion1 { } + [SetName] + public interface IUnion1 { } - public class Foo : IUnion1 { } + public class Foo : IUnion1 { } - public class SetNameAttribute : UnionTypeDescriptorAttribute + public class SetNameAttribute : UnionTypeDescriptorAttribute + { + public override void OnConfigure( + IDescriptorContext context, + IUnionTypeDescriptor descriptor, + Type type) { - public override void OnConfigure( - IDescriptorContext context, - IUnionTypeDescriptor descriptor, - Type type) - { - descriptor.Name("Abc"); - } + descriptor.Name("Abc"); } + } - [UnionType(Name = "Union")] - public interface IUnion2 { } + [UnionType(Name = "Union")] + public interface IUnion2 { } - [ObjectType(Name = "Type")] - public class Union2Type1 : IUnion2 { } - } + [ObjectType(Name = "Type")] + public class Union2Type1 : IUnion2 { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeExtensionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeExtensionTests.cs index 62514abf425..64ccf88bd43 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeExtensionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeExtensionTests.cs @@ -2,232 +2,231 @@ using HotChocolate.Language; using System.Linq; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class UnionTypeExtensionTests { - public class UnionTypeExtensionTests + [Fact] + public void UnionTypeExtension_AddType() { - [Fact] - public void UnionTypeExtension_AddType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType() - .Create(); - - // assert - FooType type = schema.GetType("Foo"); - Assert.Collection(type.Types.Values, - t => Assert.IsType(t), - t => Assert.IsType(t)); - } + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Types.Values, + t => Assert.IsType(t), + t => Assert.IsType(t)); + } - [Fact] - public void UnionTypeExtension_SetTypeContextData() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new UnionTypeExtension(d => d - .Name("Foo") - .Extend() - .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) - .Create(); - - // assert - UnionType type = schema.GetType("Foo"); - Assert.True(type.ContextData.ContainsKey("foo")); - } + [Fact] + public void UnionTypeExtension_SetTypeContextData() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new UnionTypeExtension(d => d + .Name("Foo") + .Extend() + .OnBeforeCreate(c => c.ContextData["foo"] = "bar"))) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.ContextData.ContainsKey("foo")); + } - [Fact] - public void UnionTypeExtension_SetDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new UnionTypeExtension(d => d - .Name("Foo") - .Directive("dummy"))) - .AddDirectiveType() - .Create(); - - // assert - UnionType type = schema.GetType("Foo"); - Assert.True(type.Directives.Contains("dummy")); - } + [Fact] + public void UnionTypeExtension_SetDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new UnionTypeExtension(d => d + .Name("Foo") + .Directive("dummy"))) + .AddDirectiveType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.True(type.Directives.Contains("dummy")); + } - [Fact] - public void UnionTypeExtension_ReplaceDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new UnionType(t => t - .Name("Foo") - .Type() - .Directive("dummy_arg", new ArgumentNode("a", "a")))) - .AddType(new UnionTypeExtension(d => d - .Name("Foo") - .Directive("dummy_arg", new ArgumentNode("a", "b")))) - .AddDirectiveType() - .Create(); - - // assert - UnionType type = schema.GetType("Foo"); - string value = type.Directives["dummy_arg"] - .First().GetArgument("a"); - Assert.Equal("b", value); - } + [Fact] + public void UnionTypeExtension_ReplaceDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new UnionType(t => t + .Name("Foo") + .Type() + .Directive("dummy_arg", new ArgumentNode("a", "a")))) + .AddType(new UnionTypeExtension(d => d + .Name("Foo") + .Directive("dummy_arg", new ArgumentNode("a", "b")))) + .AddDirectiveType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + var value = type.Directives["dummy_arg"] + .First().GetArgument("a"); + Assert.Equal("b", value); + } - [Fact] - public void UnionTypeExtension_CopyDependencies_ToType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType() - .AddType(new UnionTypeExtension(d => d - .Name("Foo") - .Type())) - .Create(); - - // assert - FooType type = schema.GetType("Foo"); - Assert.Collection(type.Types.Values, - t => Assert.IsType(t), - t => Assert.IsType(t)); - } + [Fact] + public void UnionTypeExtension_CopyDependencies_ToType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType() + .AddType(new UnionTypeExtension(d => d + .Name("Foo") + .Type())) + .Create(); + + // assert + var type = schema.GetType("Foo"); + Assert.Collection(type.Types.Values, + t => Assert.IsType(t), + t => Assert.IsType(t)); + } - [Fact] - public void UnionTypeExtension_RepeatableDirectiveOnType() - { - // arrange - // act - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType(new UnionType(t => t - .Name("Foo") - .Type() - .Directive("dummy_rep"))) - .AddType(new UnionTypeExtension(d => d - .Name("Foo") - .Directive("dummy_rep"))) - .AddDirectiveType() - .Create(); - - // assert - UnionType type = schema.GetType("Foo"); - int count = type.Directives["dummy_rep"].Count(); - Assert.Equal(2, count); - } + [Fact] + public void UnionTypeExtension_RepeatableDirectiveOnType() + { + // arrange + // act + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType(new UnionType(t => t + .Name("Foo") + .Type() + .Directive("dummy_rep"))) + .AddType(new UnionTypeExtension(d => d + .Name("Foo") + .Directive("dummy_rep"))) + .AddDirectiveType() + .Create(); + + // assert + var type = schema.GetType("Foo"); + var count = type.Directives["dummy_rep"].Count(); + Assert.Equal(2, count); + } - public class QueryType - : ObjectType + public class QueryType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("Query"); - descriptor.Field("description").Resolve("bar"); - } + descriptor.Name("Query"); + descriptor.Field("description").Resolve("bar"); } + } - public class AType - : ObjectType + public class AType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("A"); - descriptor.Field("description").Resolve("bar"); - } + descriptor.Name("A"); + descriptor.Field("description").Resolve("bar"); } + } - public class BType - : ObjectType + public class BType + : ObjectType + { + protected override void Configure( + IObjectTypeDescriptor descriptor) { - protected override void Configure( - IObjectTypeDescriptor descriptor) - { - descriptor.Name("B"); - descriptor.Field("description").Resolve("bar"); - } + descriptor.Name("B"); + descriptor.Field("description").Resolve("bar"); } + } - public class FooType - : UnionType + public class FooType + : UnionType + { + protected override void Configure( + IUnionTypeDescriptor descriptor) { - protected override void Configure( - IUnionTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Type(); - } + descriptor.Name("Foo"); + descriptor.Type(); } + } - public class FooTypeExtension - : UnionTypeExtension + public class FooTypeExtension + : UnionTypeExtension + { + protected override void Configure( + IUnionTypeDescriptor descriptor) { - protected override void Configure( - IUnionTypeDescriptor descriptor) - { - descriptor.Name("Foo"); - descriptor.Type(); - } + descriptor.Name("Foo"); + descriptor.Type(); } + } - public class Foo - { - public string Description { get; } = "hello"; + public class Foo + { + public string Description { get; } = "hello"; - public string GetName(string a) - { - return null; - } + public string GetName(string a) + { + return null; } + } - public class DummyDirective - : DirectiveType + public class DummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy"); - descriptor.Location(DirectiveLocation.Union); - } + descriptor.Name("dummy"); + descriptor.Location(DirectiveLocation.Union); } + } - public class DummyWithArgDirective - : DirectiveType + public class DummyWithArgDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_arg"); - descriptor.Argument("a").Type(); - descriptor.Location(DirectiveLocation.Union); - } + descriptor.Name("dummy_arg"); + descriptor.Argument("a").Type(); + descriptor.Location(DirectiveLocation.Union); } + } - public class RepeatableDummyDirective - : DirectiveType + public class RepeatableDummyDirective + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("dummy_rep"); - descriptor.Repeatable(); - descriptor.Location(DirectiveLocation.Union); - } + descriptor.Name("dummy_rep"); + descriptor.Repeatable(); + descriptor.Location(DirectiveLocation.Union); } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeTests.cs b/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeTests.cs index 0dae7d011cf..1f998b1cc64 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Types/UnionTypeTests.cs @@ -3,271 +3,270 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Types +namespace HotChocolate.Types; + +public class UnionTypeTests + : TypeTestBase { - public class UnionTypeTests - : TypeTestBase + [Fact] + public void UnionType_DynamicName() { - [Fact] - public void UnionType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddUnionType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn() - .Type() - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - UnionType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + // act + var schema = SchemaBuilder.New() + .AddUnionType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn() + .Type() + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public void UnionType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddUnionType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType)) - .Type() - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - UnionType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void GenericUnionType_DynamicName() - { - // act - ISchema schema = SchemaBuilder.New() - .AddUnionType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn() - .Type() - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - UnionType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + [Fact] + public void UnionType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddUnionType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType)) + .Type() + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public void GenericUnionType_DynamicName_NonGeneric() - { - // act - ISchema schema = SchemaBuilder.New() - .AddUnionType(d => d - .Name(dep => dep.Name + "Foo") - .DependsOn(typeof(StringType)) - .Type() - .Type()) - .ModifyOptions(o => o.StrictValidation = false) - .Create(); - - // assert - UnionType type = schema.GetType("StringFoo"); - Assert.NotNull(type); - } + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void DeclareUnion_ByProvidingExplicitTypeSet() - { - // arrange - // act - UnionType fooBarType = CreateType(new UnionType(d => d - .Name("FooOrBar") + [Fact] + public void GenericUnionType_DynamicName() + { + // act + var schema = SchemaBuilder.New() + .AddUnionType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn() .Type() - .Type())); + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - // assert - Assert.Collection(fooBarType.Types.Values, - t => Assert.Equal("Foo", t.Name), - t => Assert.Equal("Bar", t.Name)); - } + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void DeclareUnion_InferTypeSetFromMarkerInterface() - { - // arrange - // act - UnionType fooBarType = CreateType( - new UnionType(), - b => b.AddTypes(new FooType(), new BarType())); - - // assert - Assert.Collection(fooBarType.Types.Values, - t => Assert.Equal("Foo", t.Name), - t => Assert.Equal("Bar", t.Name)); - } + [Fact] + public void GenericUnionType_DynamicName_NonGeneric() + { + // act + var schema = SchemaBuilder.New() + .AddUnionType(d => d + .Name(dep => dep.Name + "Foo") + .DependsOn(typeof(StringType)) + .Type() + .Type()) + .ModifyOptions(o => o.StrictValidation = false) + .Create(); - [Fact] - public void DeclareUnion_MarkerInterfaceAndTypeSet() - { - // arrange - // act - UnionType fooBarType = CreateType( - new UnionType(c => c.Type()), - b => b.AddTypes(new FooType(), new BarType())); - - // assert - Assert.Collection(fooBarType.Types.Values, - t => Assert.Equal("Baz", t.Name), - t => Assert.Equal("Foo", t.Name), - t => Assert.Equal("Bar", t.Name)); - } + // assert + var type = schema.GetType("StringFoo"); + Assert.NotNull(type); + } - [Fact] - public void UnionType_AddDirectives_NameArgs() - { - // arrange - // act - UnionType fooBarType = CreateType(new UnionType(d => d + [Fact] + public void DeclareUnion_ByProvidingExplicitTypeSet() + { + // arrange + // act + var fooBarType = CreateType(new UnionType(d => d + .Name("FooOrBar") + .Type() + .Type())); + + // assert + Assert.Collection(fooBarType.Types.Values, + t => Assert.Equal("Foo", t.Name), + t => Assert.Equal("Bar", t.Name)); + } + + [Fact] + public void DeclareUnion_InferTypeSetFromMarkerInterface() + { + // arrange + // act + var fooBarType = CreateType( + new UnionType(), + b => b.AddTypes(new FooType(), new BarType())); + + // assert + Assert.Collection(fooBarType.Types.Values, + t => Assert.Equal("Foo", t.Name), + t => Assert.Equal("Bar", t.Name)); + } + + [Fact] + public void DeclareUnion_MarkerInterfaceAndTypeSet() + { + // arrange + // act + var fooBarType = CreateType( + new UnionType(c => c.Type()), + b => b.AddTypes(new FooType(), new BarType())); + + // assert + Assert.Collection(fooBarType.Types.Values, + t => Assert.Equal("Baz", t.Name), + t => Assert.Equal("Foo", t.Name), + t => Assert.Equal("Bar", t.Name)); + } + + [Fact] + public void UnionType_AddDirectives_NameArgs() + { + // arrange + // act + var fooBarType = CreateType(new UnionType(d => d .Name("BarUnion") .Directive("foo") .Type() .Type()), - b => b.AddDirectiveType()); + b => b.AddDirectiveType()); - // assert - Assert.NotEmpty(fooBarType.Directives["foo"]); - } + // assert + Assert.NotEmpty(fooBarType.Directives["foo"]); + } - [Fact] - public void UnionType_AddDirectives_NameArgs2() - { - // arrange - // act - UnionType fooBarType = CreateType(new UnionType(d => d + [Fact] + public void UnionType_AddDirectives_NameArgs2() + { + // arrange + // act + var fooBarType = CreateType(new UnionType(d => d .Name("BarUnion") .Directive(new NameString("foo")) .Type() .Type()), - b => b.AddDirectiveType()); + b => b.AddDirectiveType()); - // assert - Assert.NotEmpty(fooBarType.Directives["foo"]); - } + // assert + Assert.NotEmpty(fooBarType.Directives["foo"]); + } - [Fact] - public void UnionType_AddDirectives_DirectiveNode() - { - // arrange - // act - UnionType fooBarType = CreateType(new UnionType(d => d + [Fact] + public void UnionType_AddDirectives_DirectiveNode() + { + // arrange + // act + var fooBarType = CreateType(new UnionType(d => d .Name("BarUnion") .Directive(new DirectiveNode("foo")) .Type() .Type()), - b => b.AddDirectiveType()); + b => b.AddDirectiveType()); - // assert - Assert.NotEmpty(fooBarType.Directives["foo"]); - } + // assert + Assert.NotEmpty(fooBarType.Directives["foo"]); + } - [Fact] - public void UnionType_AddDirectives_DirectiveClassInstance() - { - // arrange - // act - UnionType fooBarType = CreateType(new UnionType(d => d + [Fact] + public void UnionType_AddDirectives_DirectiveClassInstance() + { + // arrange + // act + var fooBarType = CreateType(new UnionType(d => d .Name("BarUnion") .Directive(new FooDirective()) .Type() .Type()), - b => b.AddDirectiveType()); + b => b.AddDirectiveType()); - // assert - Assert.NotEmpty(fooBarType.Directives["foo"]); - } + // assert + Assert.NotEmpty(fooBarType.Directives["foo"]); + } - [Fact] - public void UnionType_AddDirectives_DirectiveType() - { - // arrange - // act - UnionType fooBarType = CreateType(new UnionType(d => d + [Fact] + public void UnionType_AddDirectives_DirectiveType() + { + // arrange + // act + var fooBarType = CreateType(new UnionType(d => d .Name("BarUnion") .Directive() .Type() .Type()), - b => b.AddDirectiveType()); + b => b.AddDirectiveType()); - // assert - Assert.NotEmpty(fooBarType.Directives["foo"]); - } + // assert + Assert.NotEmpty(fooBarType.Directives["foo"]); + } - [Fact] - public void UnionType_InUnionType_ThrowsSchemaException() - { - // arrange - // act - Exception ex = Record.Exception( - () => SchemaBuilder - .New() - .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) - .AddType>>() - .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) - .Create()); - - // assert - Assert.IsType(ex); - ex.Message.MatchSnapshot(); - } + [Fact] + public void UnionType_InUnionType_ThrowsSchemaException() + { + // arrange + // act + var ex = Record.Exception( + () => SchemaBuilder + .New() + .AddQueryType(x => x.Name("Query").Field("Foo").Resolve("bar")) + .AddType>>() + .ModifyOptions(o => o.StrictRuntimeTypeValidation = true) + .Create()); + + // assert + Assert.IsType(ex); + ex.Message.MatchSnapshot(); + } - public class FooType : ObjectType - { - } + public class FooType : ObjectType + { + } - public class BarType : ObjectType - { - } + public class BarType : ObjectType + { + } - public class BazType : ObjectType - { - } + public class BazType : ObjectType + { + } - public class Foo : IFooOrBar - { - public string FooField { get; set; } - } + public class Foo : IFooOrBar + { + public string FooField { get; set; } + } - public class Bar : IFooOrBar - { - public string BarField { get; set; } - } + public class Bar : IFooOrBar + { + public string BarField { get; set; } + } - public class Baz : IFooOrBar - { - public string BazField { get; set; } - } + public class Baz : IFooOrBar + { + public string BazField { get; set; } + } - public interface IFooOrBar - { - } + public interface IFooOrBar + { + } - public class FooDirectiveType - : DirectiveType + public class FooDirectiveType + : DirectiveType + { + protected override void Configure( + IDirectiveTypeDescriptor descriptor) { - protected override void Configure( - IDirectiveTypeDescriptor descriptor) - { - descriptor.Name("foo"); - descriptor.Location(DirectiveLocation.Union) - .Location(DirectiveLocation.FieldDefinition); - } + descriptor.Name("foo"); + descriptor.Location(DirectiveLocation.Union) + .Location(DirectiveLocation.FieldDefinition); } - - public class FooDirective { } } + + public class FooDirective { } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/BaseTypesTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/BaseTypesTests.cs index 9bd80619cf4..b789a331782 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/BaseTypesTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/BaseTypesTests.cs @@ -3,68 +3,67 @@ using HotChocolate.Types; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class BaseTypesTests { - public class BaseTypesTests + [InlineData(typeof(StringType), true)] + [InlineData(typeof(ScalarType), false)] + [InlineData(typeof(ListType), true)] + [InlineData(typeof(NonNullType), true)] + [InlineData(typeof(InputObjectType), false)] + [InlineData(typeof(InputObjectType), true)] + [InlineData(typeof(ObjectType), false)] + [InlineData(typeof(ObjectType), true)] + [InlineData(typeof(EnumType), false)] + [InlineData(typeof(EnumType), true)] + [InlineData(typeof(InterfaceType), false)] + [InlineData(typeof(InterfaceType), true)] + [InlineData(typeof(UnionType), false)] + [InlineData(typeof(UnionType), true)] + [InlineData(typeof(Foo), false)] + [InlineData(typeof(FooEnum), false)] + [Theory] + public void IsSchemaType(Type type, bool expectedResult) { - [InlineData(typeof(StringType), true)] - [InlineData(typeof(ScalarType), false)] - [InlineData(typeof(ListType), true)] - [InlineData(typeof(NonNullType), true)] - [InlineData(typeof(InputObjectType), false)] - [InlineData(typeof(InputObjectType), true)] - [InlineData(typeof(ObjectType), false)] - [InlineData(typeof(ObjectType), true)] - [InlineData(typeof(EnumType), false)] - [InlineData(typeof(EnumType), true)] - [InlineData(typeof(InterfaceType), false)] - [InlineData(typeof(InterfaceType), true)] - [InlineData(typeof(UnionType), false)] - [InlineData(typeof(UnionType), true)] - [InlineData(typeof(Foo), false)] - [InlineData(typeof(FooEnum), false)] - [Theory] - public void IsSchemaType(Type type, bool expectedResult) - { - // act - var result = ExtendedType.Tools.IsSchemaType(type); + // act + var result = ExtendedType.Tools.IsSchemaType(type); - // assert - Assert.Equal(expectedResult, result); - } + // assert + Assert.Equal(expectedResult, result); + } - [InlineData(typeof(StringType), false)] - [InlineData(typeof(ScalarType), true)] - [InlineData(typeof(ListType), false)] - [InlineData(typeof(NonNullType), false)] - [InlineData(typeof(InputObjectType), true)] - [InlineData(typeof(InputObjectType), false)] - [InlineData(typeof(ObjectType), true)] - [InlineData(typeof(ObjectType), false)] - [InlineData(typeof(EnumType), true)] - [InlineData(typeof(EnumType), false)] - [InlineData(typeof(InterfaceType), true)] - [InlineData(typeof(UnionType), true)] - [InlineData(typeof(Foo), false)] - [InlineData(typeof(FooEnum), false)] - [Theory] - public void IsNonGenericBaseType(Type type, bool expectedResult) - { - // act - var result = ExtendedType.Tools.IsNonGenericBaseType(type); + [InlineData(typeof(StringType), false)] + [InlineData(typeof(ScalarType), true)] + [InlineData(typeof(ListType), false)] + [InlineData(typeof(NonNullType), false)] + [InlineData(typeof(InputObjectType), true)] + [InlineData(typeof(InputObjectType), false)] + [InlineData(typeof(ObjectType), true)] + [InlineData(typeof(ObjectType), false)] + [InlineData(typeof(EnumType), true)] + [InlineData(typeof(EnumType), false)] + [InlineData(typeof(InterfaceType), true)] + [InlineData(typeof(UnionType), true)] + [InlineData(typeof(Foo), false)] + [InlineData(typeof(FooEnum), false)] + [Theory] + public void IsNonGenericBaseType(Type type, bool expectedResult) + { + // act + var result = ExtendedType.Tools.IsNonGenericBaseType(type); - // assert - Assert.Equal(expectedResult, result); - } + // assert + Assert.Equal(expectedResult, result); + } - public class Foo - { - public string Bar { get; set; } - } + public class Foo + { + public string Bar { get; set; } + } - public enum FooEnum - { - Bar - } + public enum FooEnum + { + Bar } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/DictionaryToObjectConverterTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/DictionaryToObjectConverterTests.cs index f3b3a8094da..fb0fe433445 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/DictionaryToObjectConverterTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/DictionaryToObjectConverterTests.cs @@ -2,120 +2,119 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class DictionaryToObjectConverterTests { - public class DictionaryToObjectConverterTests + [Fact] + public void Convert_Dictionary_FooObject() + { + // arrange + var baz = new Dictionary(); + baz["Number"] = "1.5"; + + var bar = new Dictionary(); + bar["State"] = "On"; + bar["Bazs"] = new List { baz }; + + var foo = new Dictionary(); + foo["text"] = "abc"; + foo["BAR"] = bar; + + // assert + var converter = new DictionaryToObjectConverter( + DefaultTypeConverter.Default); + var converted = converter.Convert(foo, typeof(Foo)); + + // assert + converted.MatchSnapshot(); + } + + [Fact] + public void Convert_Dictionary_BarObjectWithArray() + { + // arrange + var baz = new Dictionary(); + baz["Number"] = "1.5"; + + var bar = new Dictionary(); + bar["State"] = "On"; + bar["Bazs"] = new List { baz }; + bar["BazArray"] = new List { baz }; + bar["StringArray"] = new List { "a", 1, true }; + + // assert + var converter = new DictionaryToObjectConverter( + DefaultTypeConverter.Default); + var converted = converter.Convert(bar, typeof(Bar)); + + // assert + converted.MatchSnapshot(); + } + + [Fact] + public void Convert_List_ListOfBar() + { + // arrange + var baz = new Dictionary(); + baz["Number"] = "1.5"; + + var bar = new Dictionary(); + bar["State"] = "On"; + bar["Bazs"] = new List { baz }; + bar["BazArray"] = new List { baz }; + bar["StringArray"] = new List { "a", 1, true }; + + var list = new List { bar }; + + // assert + var converter = new DictionaryToObjectConverter( + DefaultTypeConverter.Default); + var converted = converter.Convert( + list, typeof(ICollection)); + + // assert + converted.MatchSnapshot(); + } + + [Fact] + public void Convert_String_Int() + { + // arrange + var input = "1"; + + // assert + var converter = new DictionaryToObjectConverter( + DefaultTypeConverter.Default); + var converted = converter.Convert( + input, typeof(int)); + + // assert + converted.MatchSnapshot(); + } + + public class Foo + { + public string Text { get; set; } + public Bar Bar { get; set; } + } + + public class Bar + { + public State State { get; set; } + public IReadOnlyCollection Bazs { get; set; } + public Baz[] BazArray { get; set; } + public string[] StringArray { get; set; } + } + + public class Baz + { + public decimal Number { get; set; } + } + + public enum State { - [Fact] - public void Convert_Dictionary_FooObject() - { - // arrange - var baz = new Dictionary(); - baz["Number"] = "1.5"; - - var bar = new Dictionary(); - bar["State"] = "On"; - bar["Bazs"] = new List { baz }; - - var foo = new Dictionary(); - foo["text"] = "abc"; - foo["BAR"] = bar; - - // assert - var converter = new DictionaryToObjectConverter( - DefaultTypeConverter.Default); - object converted = converter.Convert(foo, typeof(Foo)); - - // assert - converted.MatchSnapshot(); - } - - [Fact] - public void Convert_Dictionary_BarObjectWithArray() - { - // arrange - var baz = new Dictionary(); - baz["Number"] = "1.5"; - - var bar = new Dictionary(); - bar["State"] = "On"; - bar["Bazs"] = new List { baz }; - bar["BazArray"] = new List { baz }; - bar["StringArray"] = new List { "a", 1, true }; - - // assert - var converter = new DictionaryToObjectConverter( - DefaultTypeConverter.Default); - object converted = converter.Convert(bar, typeof(Bar)); - - // assert - converted.MatchSnapshot(); - } - - [Fact] - public void Convert_List_ListOfBar() - { - // arrange - var baz = new Dictionary(); - baz["Number"] = "1.5"; - - var bar = new Dictionary(); - bar["State"] = "On"; - bar["Bazs"] = new List { baz }; - bar["BazArray"] = new List { baz }; - bar["StringArray"] = new List { "a", 1, true }; - - var list = new List { bar }; - - // assert - var converter = new DictionaryToObjectConverter( - DefaultTypeConverter.Default); - object converted = converter.Convert( - list, typeof(ICollection)); - - // assert - converted.MatchSnapshot(); - } - - [Fact] - public void Convert_String_Int() - { - // arrange - var input = "1"; - - // assert - var converter = new DictionaryToObjectConverter( - DefaultTypeConverter.Default); - object converted = converter.Convert( - input, typeof(int)); - - // assert - converted.MatchSnapshot(); - } - - public class Foo - { - public string Text { get; set; } - public Bar Bar { get; set; } - } - - public class Bar - { - public State State { get; set; } - public IReadOnlyCollection Bazs { get; set; } - public Baz[] BazArray { get; set; } - public string[] StringArray { get; set; } - } - - public class Baz - { - public decimal Number { get; set; } - } - - public enum State - { - On, - Off - } + On, + Off } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/ExpressionUtilsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/ExpressionUtilsTests.cs index 095159a0d01..485f4630eb4 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/ExpressionUtilsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/ExpressionUtilsTests.cs @@ -3,65 +3,64 @@ using System.Reflection; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class ExpressionUtilsTests { - public class ExpressionUtilsTests + [Fact] + public void PublicFieldExpression_ShouldThrow() { - [Fact] - public void PublicFieldExpression_ShouldThrow() - { - // act - Action a = () => GetMember(t => t.Field); - - // assert - Assert.Throws(a); - } + // act + Action a = () => GetMember(t => t.Field); - [Fact] - public void PublicPropertyExpression_ShouldReturnProperty() - { - // act - MemberInfo member = GetMember(t => t.Property); + // assert + Assert.Throws(a); + } - // assert - Assert.NotNull(member); - Assert.Equal("Property", member.Name); - } + [Fact] + public void PublicPropertyExpression_ShouldReturnProperty() + { + // act + var member = GetMember(t => t.Property); - [Fact] - public void PublicMethodExpression_ShouldReturnMethod() - { - // act - MemberInfo member = GetMember(t => t.Method()); + // assert + Assert.NotNull(member); + Assert.Equal("Property", member.Name); + } - // assert - Assert.NotNull(member); - Assert.Equal("Method", member.Name); - } + [Fact] + public void PublicMethodExpression_ShouldReturnMethod() + { + // act + var member = GetMember(t => t.Method()); - [Fact] - public void IndexerExpression_ShouldThrow() - { - // act - void Action() => GetMember(t => t[default]); + // assert + Assert.NotNull(member); + Assert.Equal("Method", member.Name); + } - // assert - Assert.Throws(Action); - } + [Fact] + public void IndexerExpression_ShouldThrow() + { + // act + void Action() => GetMember(t => t[default]); - public static MemberInfo GetMember(Expression> expr) - { - return expr.ExtractMember(); - } + // assert + Assert.Throws(Action); } - public class ExpressionUtilsTestDummy + public static MemberInfo GetMember(Expression> expr) { - public string Field; - public string this[int index] { get => null; } - public string Property { get; private set; } - internal string InternalProperty { get; private set; } - public string Method() => Property; - internal string InternalMethod() => InternalProperty; + return expr.ExtractMember(); } } + +public class ExpressionUtilsTestDummy +{ + public string Field; + public string this[int index] { get => null; } + public string Property { get; private set; } + internal string InternalProperty { get; private set; } + public string Method() => Property; + internal string InternalMethod() => InternalProperty; +} diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/InputObjectToDictionaryConverterTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/InputObjectToDictionaryConverterTests.cs index 10419bcfa7d..4abcfac93ff 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/InputObjectToDictionaryConverterTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/InputObjectToDictionaryConverterTests.cs @@ -3,118 +3,117 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class InputObjectToDictionaryConverterTests { - public class InputObjectToDictionaryConverterTests + [Fact] + public void Convert_InputObject_Dictionary() { - [Fact] - public void Convert_InputObject_Dictionary() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType>() - .Create(); - - InputObjectType type = schema.GetType("FooInput"); - - var bar1 = new Bar { Number = 1, Baz = Baz.Bar }; - var bar2 = new Bar { Number = 2, Baz = Baz.Bar }; - var bar3 = new Bar { Number = 3, Baz = Baz.Foo }; - var foo = new Foo - { - Bar = bar1, - Bars = new List { bar2, bar3 } - }; - - // act - var converter = new InputObjectToDictionaryConverter( - DefaultTypeConverter.Default); - Dictionary dict = converter.Convert(type, foo); - - // assert - dict.MatchSnapshot(); - } - - [Fact] - public void Convert_InputObjectWithNullField_Dictionary() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType>() - .Create(); - - InputObjectType type = schema.GetType("FooInput"); - - var bar2 = new Bar { Number = 2, Baz = Baz.Bar }; - var bar3 = new Bar { Number = 3, Baz = Baz.Foo }; - var foo = new Foo - { - Bar = null, - Bars = new List { bar2, bar3 } - }; - - // act - var converter = new InputObjectToDictionaryConverter( - DefaultTypeConverter.Default); - Dictionary dict = converter.Convert(type, foo); - - // assert - dict.MatchSnapshot(); - } - - [Fact] - public void Convert_InputObjectWithNullElement_Dictionary() - { - // arrange - ISchema schema = SchemaBuilder.New() - .AddQueryType() - .AddType>() - .Create(); - - InputObjectType type = schema.GetType("FooInput"); - - var bar1 = new Bar { Number = 1, Baz = Baz.Bar }; - var bar2 = new Bar { Number = 2, Baz = Baz.Bar }; - var foo = new Foo - { - Bar = bar1, - Bars = new List { bar2, null } - }; - - // act - var converter = new InputObjectToDictionaryConverter( - DefaultTypeConverter.Default); - Dictionary dict = converter.Convert(type, foo); - - // assert - dict.MatchSnapshot(); - } - - public class Foo + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType>() + .Create(); + + var type = schema.GetType("FooInput"); + + var bar1 = new Bar { Number = 1, Baz = Baz.Bar }; + var bar2 = new Bar { Number = 2, Baz = Baz.Bar }; + var bar3 = new Bar { Number = 3, Baz = Baz.Foo }; + var foo = new Foo { - public List Bars { get; set; } + Bar = bar1, + Bars = new List { bar2, bar3 } + }; - public Bar Bar { get; set; } - } + // act + var converter = new InputObjectToDictionaryConverter( + DefaultTypeConverter.Default); + var dict = converter.Convert(type, foo); - public class Bar - { - public int Number { get; set; } + // assert + dict.MatchSnapshot(); + } + + [Fact] + public void Convert_InputObjectWithNullField_Dictionary() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType>() + .Create(); - public Baz Baz { get; set; } - } + var type = schema.GetType("FooInput"); - public enum Baz + var bar2 = new Bar { Number = 2, Baz = Baz.Bar }; + var bar3 = new Bar { Number = 3, Baz = Baz.Foo }; + var foo = new Foo { - Foo, - Bar - } + Bar = null, + Bars = new List { bar2, bar3 } + }; - public class DummyQuery + // act + var converter = new InputObjectToDictionaryConverter( + DefaultTypeConverter.Default); + var dict = converter.Convert(type, foo); + + // assert + dict.MatchSnapshot(); + } + + [Fact] + public void Convert_InputObjectWithNullElement_Dictionary() + { + // arrange + var schema = SchemaBuilder.New() + .AddQueryType() + .AddType>() + .Create(); + + var type = schema.GetType("FooInput"); + + var bar1 = new Bar { Number = 1, Baz = Baz.Bar }; + var bar2 = new Bar { Number = 2, Baz = Baz.Bar }; + var foo = new Foo { - public string Foo { get; set; } - } + Bar = bar1, + Bars = new List { bar2, null } + }; + + // act + var converter = new InputObjectToDictionaryConverter( + DefaultTypeConverter.Default); + var dict = converter.Convert(type, foo); + + // assert + dict.MatchSnapshot(); + } + + public class Foo + { + public List Bars { get; set; } + + public Bar Bar { get; set; } + } + + public class Bar + { + public int Number { get; set; } + + public Baz Baz { get; set; } + } + + public enum Baz + { + Foo, + Bar + } + + public class DummyQuery + { + public string Foo { get; set; } } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/ObjectValueToDictionaryConverterTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/ObjectValueToDictionaryConverterTests.cs index 8f5a809dd9c..f3acb953e4c 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/ObjectValueToDictionaryConverterTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/ObjectValueToDictionaryConverterTests.cs @@ -3,79 +3,78 @@ using Snapshooter.Xunit; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class ObjectValueToDictionaryConverterTests { - public class ObjectValueToDictionaryConverterTests + [Fact] + public void Convert_ObjectGraphWithScalars_DictionaryWithClrRepres() { - [Fact] - public void Convert_ObjectGraphWithScalars_DictionaryWithClrRepres() - { - // arrange - var obj = new ObjectValueNode( - new ObjectFieldNode("a", new StringValueNode("abc")), - new ObjectFieldNode("b", new IntValueNode(123)), - new ObjectFieldNode("c", new FloatValueNode(1.5d)), - new ObjectFieldNode("d", new BooleanValueNode(true)), - new ObjectFieldNode("e", new EnumValueNode("DEF")), - new ObjectFieldNode("f", NullValueNode.Default)); + // arrange + var obj = new ObjectValueNode( + new ObjectFieldNode("a", new StringValueNode("abc")), + new ObjectFieldNode("b", new IntValueNode(123)), + new ObjectFieldNode("c", new FloatValueNode(1.5d)), + new ObjectFieldNode("d", new BooleanValueNode(true)), + new ObjectFieldNode("e", new EnumValueNode("DEF")), + new ObjectFieldNode("f", NullValueNode.Default)); - // act - var converter = new ObjectValueToDictionaryConverter(); - Dictionary dict = converter.Convert(obj); + // act + var converter = new ObjectValueToDictionaryConverter(); + var dict = converter.Convert(obj); - // assert - dict.MatchSnapshot(); - } + // assert + dict.MatchSnapshot(); + } - [Fact] - public void Convert_ObjectGraphOfObjects_DictionaryWithClrRepres() - { - // arrange - var child = new ObjectValueNode( - new ObjectFieldNode("a", new StringValueNode("abc")), - new ObjectFieldNode("b", new IntValueNode(123)), - new ObjectFieldNode("c", new FloatValueNode(1.5d)), - new ObjectFieldNode("d", new BooleanValueNode(true)), - new ObjectFieldNode("e", new EnumValueNode("DEF")), - new ObjectFieldNode("f", NullValueNode.Default)); + [Fact] + public void Convert_ObjectGraphOfObjects_DictionaryWithClrRepres() + { + // arrange + var child = new ObjectValueNode( + new ObjectFieldNode("a", new StringValueNode("abc")), + new ObjectFieldNode("b", new IntValueNode(123)), + new ObjectFieldNode("c", new FloatValueNode(1.5d)), + new ObjectFieldNode("d", new BooleanValueNode(true)), + new ObjectFieldNode("e", new EnumValueNode("DEF")), + new ObjectFieldNode("f", NullValueNode.Default)); - var obj = new ObjectValueNode( - new ObjectFieldNode("a", child)); + var obj = new ObjectValueNode( + new ObjectFieldNode("a", child)); - // act - var converter = new ObjectValueToDictionaryConverter(); - Dictionary dict = converter.Convert(obj); + // act + var converter = new ObjectValueToDictionaryConverter(); + var dict = converter.Convert(obj); - // assert - dict.MatchSnapshot(); - } + // assert + dict.MatchSnapshot(); + } - [Fact] - public void Convert_ObjectGraphWithList_DictionaryWithClrRepres() - { - // arrange - var child = new ObjectValueNode( - new ObjectFieldNode("a", new StringValueNode("abc")), - new ObjectFieldNode("b", new IntValueNode(123)), - new ObjectFieldNode("c", new FloatValueNode(1.5d)), - new ObjectFieldNode("d", new BooleanValueNode(true)), - new ObjectFieldNode("e", new EnumValueNode("DEF")), - new ObjectFieldNode("f", NullValueNode.Default)); + [Fact] + public void Convert_ObjectGraphWithList_DictionaryWithClrRepres() + { + // arrange + var child = new ObjectValueNode( + new ObjectFieldNode("a", new StringValueNode("abc")), + new ObjectFieldNode("b", new IntValueNode(123)), + new ObjectFieldNode("c", new FloatValueNode(1.5d)), + new ObjectFieldNode("d", new BooleanValueNode(true)), + new ObjectFieldNode("e", new EnumValueNode("DEF")), + new ObjectFieldNode("f", NullValueNode.Default)); - var obj = new ObjectValueNode( - new ObjectFieldNode("a", - new ListValueNode(new IValueNode[] { child, child })), - new ObjectFieldNode("b", - new ListValueNode(new IValueNode[] { - new StringValueNode("a"), - new StringValueNode("b") }))); + var obj = new ObjectValueNode( + new ObjectFieldNode("a", + new ListValueNode(new IValueNode[] { child, child })), + new ObjectFieldNode("b", + new ListValueNode(new IValueNode[] { + new StringValueNode("a"), + new StringValueNode("b") }))); - // act - var converter = new ObjectValueToDictionaryConverter(); - Dictionary dict = converter.Convert(obj); + // act + var converter = new ObjectValueToDictionaryConverter(); + var dict = converter.Convert(obj); - // assert - dict.MatchSnapshot(); - } + // assert + dict.MatchSnapshot(); } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/ReflectionUtilsTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/ReflectionUtilsTests.cs index f53582500ae..58c6d4490d2 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/ReflectionUtilsTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/ReflectionUtilsTests.cs @@ -1,84 +1,83 @@ using System; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class ReflectionUtilsTests { - public class ReflectionUtilsTests + [Fact] + public void GetTypeNameFromGenericType() + { + // arrange + var type = typeof(GenericNonNestedFoo); + + // act + var typeName = type.GetTypeName(); + + // assert + Assert.Equal( + "HotChocolate.Utilities.GenericNonNestedFoo", + typeName); + } + + [Fact] + public void GetTypeNameFromType() + { + // arrange + var type = typeof(ReflectionUtilsTests); + + // act + var typeName = type.GetTypeName(); + + // assert + Assert.Equal( + "HotChocolate.Utilities.ReflectionUtilsTests", + typeName); + } + + [Fact] + public void GetTypeNameFromGenericNestedType() + { + // arrange + var type = typeof(GenericNestedFoo); + + // act + var typeName = type.GetTypeName(); + + // assert + Assert.Equal( + "HotChocolate.Utilities.ReflectionUtilsTests" + + ".GenericNestedFoo", + typeName); + } + + [Fact] + public void GetTypeNameFromNestedType() { - [Fact] - public void GetTypeNameFromGenericType() - { - // arrange - Type type = typeof(GenericNonNestedFoo); - - // act - string typeName = type.GetTypeName(); - - // assert - Assert.Equal( - "HotChocolate.Utilities.GenericNonNestedFoo", - typeName); - } - - [Fact] - public void GetTypeNameFromType() - { - // arrange - Type type = typeof(ReflectionUtilsTests); - - // act - string typeName = type.GetTypeName(); - - // assert - Assert.Equal( - "HotChocolate.Utilities.ReflectionUtilsTests", - typeName); - } - - [Fact] - public void GetTypeNameFromGenericNestedType() - { - // arrange - Type type = typeof(GenericNestedFoo); - - // act - string typeName = type.GetTypeName(); - - // assert - Assert.Equal( - "HotChocolate.Utilities.ReflectionUtilsTests" + - ".GenericNestedFoo", - typeName); - } - - [Fact] - public void GetTypeNameFromNestedType() - { - // arrange - Type type = typeof(Foo); - - // act - string typeName = type.GetTypeName(); - - // assert - Assert.Equal( - "HotChocolate.Utilities.ReflectionUtilsTests.Foo", - typeName); - } - - public class GenericNestedFoo - { - public T Value { get; } - } - - public class Foo - { - public string Value { get; } - } + // arrange + var type = typeof(Foo); + + // act + var typeName = type.GetTypeName(); + + // assert + Assert.Equal( + "HotChocolate.Utilities.ReflectionUtilsTests.Foo", + typeName); } - public class GenericNonNestedFoo + public class GenericNestedFoo { public T Value { get; } } + + public class Foo + { + public string Value { get; } + } +} + +public class GenericNonNestedFoo +{ + public T Value { get; } } diff --git a/src/HotChocolate/Core/test/Types.Tests/Utilities/TypeConversionTests.cs b/src/HotChocolate/Core/test/Types.Tests/Utilities/TypeConversionTests.cs index 21de07ceb5b..894090fae53 100644 --- a/src/HotChocolate/Core/test/Types.Tests/Utilities/TypeConversionTests.cs +++ b/src/HotChocolate/Core/test/Types.Tests/Utilities/TypeConversionTests.cs @@ -3,480 +3,479 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; -namespace HotChocolate.Utilities +namespace HotChocolate.Utilities; + +public class TypeConverterTests { - public class TypeConverterTests + [InlineData((ushort)1, (short)1, typeof(ushort), typeof(short))] + [InlineData((ushort)1, (int)1, typeof(ushort), typeof(int))] + [InlineData((ushort)1, (long)1, typeof(ushort), typeof(long))] + [InlineData((ushort)1, (uint)1, typeof(ushort), typeof(uint))] + [InlineData((ushort)1, (ulong)1, typeof(ushort), typeof(ulong))] + [InlineData((ushort)1, (float)1, typeof(ushort), typeof(float))] + [InlineData((ushort)1, (double)1, typeof(ushort), typeof(double))] + [InlineData((ushort)1, "1", typeof(ushort), typeof(string))] + + [InlineData((uint)1, (short)1, typeof(uint), typeof(short))] + [InlineData((uint)1, (int)1, typeof(uint), typeof(int))] + [InlineData((uint)1, (long)1, typeof(uint), typeof(long))] + [InlineData((uint)1, (ushort)1, typeof(uint), typeof(ushort))] + [InlineData((uint)1, (ulong)1, typeof(uint), typeof(ulong))] + [InlineData((uint)1, (float)1, typeof(uint), typeof(float))] + [InlineData((uint)1, (double)1, typeof(uint), typeof(double))] + [InlineData((uint)1, "1", typeof(uint), typeof(string))] + + [InlineData((ulong)1, (short)1, typeof(ulong), typeof(short))] + [InlineData((ulong)1, (int)1, typeof(ulong), typeof(int))] + [InlineData((ulong)1, (long)1, typeof(ulong), typeof(long))] + [InlineData((ulong)1, (ushort)1, typeof(ulong), typeof(ushort))] + [InlineData((ulong)1, (uint)1, typeof(ulong), typeof(uint))] + [InlineData((ulong)1, (float)1, typeof(ulong), typeof(float))] + [InlineData((ulong)1, (double)1, typeof(ulong), typeof(double))] + [InlineData((ulong)1, "1", typeof(ulong), typeof(string))] + + [InlineData((short)1, (int)1, typeof(short), typeof(int))] + [InlineData((short)1, (long)1, typeof(short), typeof(long))] + [InlineData((short)1, (ushort)1, typeof(short), typeof(ushort))] + [InlineData((short)1, (uint)1, typeof(short), typeof(uint))] + [InlineData((short)1, (ulong)1, typeof(short), typeof(ulong))] + [InlineData((short)1, (float)1, typeof(short), typeof(float))] + [InlineData((short)1, (double)1, typeof(short), typeof(double))] + [InlineData((short)1, "1", typeof(short), typeof(string))] + + [InlineData((int)1, (short)1, typeof(int), typeof(short))] + [InlineData((int)1, (long)1, typeof(int), typeof(long))] + [InlineData((int)1, (ushort)1, typeof(int), typeof(ushort))] + [InlineData((int)1, (uint)1, typeof(int), typeof(uint))] + [InlineData((int)1, (ulong)1, typeof(int), typeof(ulong))] + [InlineData((int)1, (float)1, typeof(int), typeof(float))] + [InlineData((int)1, (double)1, typeof(int), typeof(double))] + [InlineData((int)1, "1", typeof(int), typeof(string))] + + [InlineData((long)1, (short)1, typeof(long), typeof(short))] + [InlineData((long)1, (int)1, typeof(long), typeof(int))] + [InlineData((long)1, (ushort)1, typeof(long), typeof(ushort))] + [InlineData((long)1, (uint)1, typeof(long), typeof(uint))] + [InlineData((long)1, (ulong)1, typeof(long), typeof(ulong))] + [InlineData((long)1, (float)1, typeof(long), typeof(float))] + [InlineData((long)1, (double)1, typeof(long), typeof(double))] + [InlineData((long)1, "1", typeof(long), typeof(string))] + + [InlineData((float)1.1, (short)1, typeof(float), typeof(short))] + [InlineData((float)1.1, (int)1, typeof(float), typeof(int))] + [InlineData((float)1.1, (long)1, typeof(float), typeof(long))] + [InlineData((float)1.1, (ushort)1, typeof(float), typeof(ushort))] + [InlineData((float)1.1, (uint)1, typeof(float), typeof(uint))] + [InlineData((float)1.1, (ulong)1, typeof(float), typeof(ulong))] + [InlineData((float)1, 1d, typeof(float), typeof(double))] + [InlineData((float)1.1, "1.1", typeof(float), typeof(string))] + + [InlineData((double)1.1, (short)1, typeof(double), typeof(short))] + [InlineData((double)1.1, (int)1, typeof(double), typeof(int))] + [InlineData((double)1.1, (long)1, typeof(double), typeof(long))] + [InlineData((double)1.1, (ushort)1, typeof(double), typeof(ushort))] + [InlineData((double)1.1, (uint)1, typeof(double), typeof(uint))] + [InlineData((double)1.1, (ulong)1, typeof(double), typeof(ulong))] + [InlineData((double)1.1, (float)1.1, typeof(double), typeof(float))] + [InlineData((double)1.1, "1.1", typeof(double), typeof(string))] + + [Theory] + public void ConvertNumber(object input, object expectedOutput, + Type from, Type to) + { + // arrange + // act + var success = DefaultTypeConverter.Default.TryConvert( + from, to, input, out var output); + + // assert + Assert.True(success); + Assert.Equal(to, output.GetType()); + Assert.Equal(expectedOutput, output); + } + + [Fact] + public void Convert_Int_NullableLong() + { + // arrange + var source = 55; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(int), typeof(long?), + source, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(55L, output); + } + + [Fact] + public void Convert_NullableInt_NullableLong() + { + // arrange + int? source = 55; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(int?), typeof(long?), + source, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(55L, output); + } + + [Fact] + public void Convert_NullString_NullableLong() + { + // arrange + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string), typeof(long?), + null, out var output); + + // assert + Assert.True(success); + Assert.Null(output); + } + + + [Fact] + public void Convert_NullableLong_Int() + { + // arrange + long? source = 55; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(long?), typeof(int), + source, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(55, output); + } + + + [InlineData("{2d84dcd6-3439-4ebe-8427-f4b1e1730c47}")] + [InlineData("2d84dcd6-3439-4ebe-8427-f4b1e1730c47")] + [InlineData("2d84dcd634394ebe8427f4b1e1730c47")] + [Theory] + public void Convert_String_Guid(string input) + { + // arrange + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string), typeof(Guid), + input, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(Guid.Parse(input), output); + } + + [Fact] + public void Convert_Guid_String() + { + // arrange + const string expectedOutput = "2d84dcd634394ebe8427f4b1e1730c47"; + var input = Guid.Parse(expectedOutput); + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(Guid), typeof(string), + input, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(expectedOutput, output); + } + + [Fact] + public void Convert_String_Uri() + { + // arrange + const string expectedOutput = "http://foo/"; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string), typeof(Uri), + expectedOutput, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(expectedOutput, output.ToString()); + } + + [Fact] + public void Convert_Uri_String() + { + // arrange + const string expectedOutput = "http://foo/"; + var input = new Uri(expectedOutput); + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(Uri), typeof(string), + input, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(expectedOutput, output); + } + + [Fact] + public void Convert_String_String() + { + // arrange + const string expectedOutput = "2d84dcd634394ebe8427f4b1e1730c47"; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string), typeof(string), + expectedOutput, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal(expectedOutput, output); + } + + [InlineData(1, "1")] + [InlineData(null, null)] + [InlineData("foo", "foo")] + [InlineData(true, "True")] + [Theory] + public void Convert_Object_String(object input, object expectedOutput) + { + // arrange + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(object), typeof(string), + input, out var output); + + // assert + Assert.True(success); + Assert.Equal(expectedOutput, output); + } + + [Fact] + public void Convert_ArrayOfString_ListOfString() + { + // arrange + string[] list = { "a", "b", "c" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(List), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType>(output); + Assert.Collection((List)output, + t => Assert.Equal("a", t), + t => Assert.Equal("b", t), + t => Assert.Equal("c", t)); + } + + [Fact] + public void Convert_ArrayOfString_ListOfInt() + { + // arrange + string[] list = { "1", "2", "3" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(List), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType>(output); + Assert.Collection((List)output, + t => Assert.Equal(1, t), + t => Assert.Equal(2, t), + t => Assert.Equal(3, t)); + } + + [Fact] + public void Convert_ArrayOfString_ArrayOfInt() + { + // arrange + string[] list = { "1", "2", "3" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(int[]), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Collection((int[])output, + t => Assert.Equal(1, t), + t => Assert.Equal(2, t), + t => Assert.Equal(3, t)); + } + + [Fact] + public void Convert_ArrayOfString_IListOfInt() + { + // arrange + string[] list = { "1", "2", "3" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(IList), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType>(output); + Assert.Collection((List)output, + t => Assert.Equal(1, t), + t => Assert.Equal(2, t), + t => Assert.Equal(3, t)); + } + + [Fact] + public void Convert_ArrayOfString_ICollectionOfInt() + { + // arrange + string[] list = { "1", "2", "3" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(ICollection), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType>(output); + Assert.Collection((List)output, + t => Assert.Equal(1, t), + t => Assert.Equal(2, t), + t => Assert.Equal(3, t)); + } + + [Fact] + public void Convert_ArrayOfString_String() + { + // arrange + var list = new[] { "1", "2", "3" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(string), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType(output); + Assert.Equal("1,2,3", output); + } + + [Fact] + public void Convert_ArrayOfString_NullableListOfFooOrBar() + { + // arrange + var list = new[] { "Foo", "Bar" }; + + // act + var success = DefaultTypeConverter.Default.TryConvert( + typeof(string[]), typeof(List), + list, out var output); + + // assert + Assert.True(success); + Assert.IsType>(output); + Assert.Collection((List)output, + t => Assert.Equal(FooOrBar.Foo, t), + t => Assert.Equal(FooOrBar.Bar, t)); + } + + [Fact] + public void GenericTryConvert_ArrayOfString_NullableListOfFooOrBar() + { + // arrange + var list = new[] { "Foo", "Bar" }; + + // act + var success = + TypeConverterExtensions.TryConvert>( + DefaultTypeConverter.Default, + list, out var output); + + // assert + Assert.True(success); + Assert.IsType>(output); + Assert.Collection((List)output, + t => Assert.Equal(FooOrBar.Foo, t), + t => Assert.Equal(FooOrBar.Bar, t)); + } + + [Fact] + public void GenericTryConvert_TypeconverterIsNull_ArgumentNullExc() + { + // arrange + var list = new[] { "Foo", "Bar" }; + + // act + Action action = () => + TypeConverterExtensions.TryConvert>( + null, + list, out var output); + + // assert + Assert.Throws(action); + } + + [Fact] + public void GenericConvert_TypeconverterIsNull_ArgumentNullExc() + { + // arrange + var list = new[] { "Foo", "Bar" }; + + // act + Action action = () => + TypeConverterExtensions.Convert>( + null, list); + + // assert + Assert.Throws(action); + } + + [Fact] + public void Convert_WithDependencyInjection() + { + // arrange + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddTypeConverter(input => "Bar"); + + IServiceProvider serviceProvider = services.BuildServiceProvider(); + + // act + var converter = + serviceProvider.GetService(); + var converted = converter.Convert(true); + + // assert + Assert.Equal("Bar", converted); + } + + public enum FooOrBar { - [InlineData((ushort)1, (short)1, typeof(ushort), typeof(short))] - [InlineData((ushort)1, (int)1, typeof(ushort), typeof(int))] - [InlineData((ushort)1, (long)1, typeof(ushort), typeof(long))] - [InlineData((ushort)1, (uint)1, typeof(ushort), typeof(uint))] - [InlineData((ushort)1, (ulong)1, typeof(ushort), typeof(ulong))] - [InlineData((ushort)1, (float)1, typeof(ushort), typeof(float))] - [InlineData((ushort)1, (double)1, typeof(ushort), typeof(double))] - [InlineData((ushort)1, "1", typeof(ushort), typeof(string))] - - [InlineData((uint)1, (short)1, typeof(uint), typeof(short))] - [InlineData((uint)1, (int)1, typeof(uint), typeof(int))] - [InlineData((uint)1, (long)1, typeof(uint), typeof(long))] - [InlineData((uint)1, (ushort)1, typeof(uint), typeof(ushort))] - [InlineData((uint)1, (ulong)1, typeof(uint), typeof(ulong))] - [InlineData((uint)1, (float)1, typeof(uint), typeof(float))] - [InlineData((uint)1, (double)1, typeof(uint), typeof(double))] - [InlineData((uint)1, "1", typeof(uint), typeof(string))] - - [InlineData((ulong)1, (short)1, typeof(ulong), typeof(short))] - [InlineData((ulong)1, (int)1, typeof(ulong), typeof(int))] - [InlineData((ulong)1, (long)1, typeof(ulong), typeof(long))] - [InlineData((ulong)1, (ushort)1, typeof(ulong), typeof(ushort))] - [InlineData((ulong)1, (uint)1, typeof(ulong), typeof(uint))] - [InlineData((ulong)1, (float)1, typeof(ulong), typeof(float))] - [InlineData((ulong)1, (double)1, typeof(ulong), typeof(double))] - [InlineData((ulong)1, "1", typeof(ulong), typeof(string))] - - [InlineData((short)1, (int)1, typeof(short), typeof(int))] - [InlineData((short)1, (long)1, typeof(short), typeof(long))] - [InlineData((short)1, (ushort)1, typeof(short), typeof(ushort))] - [InlineData((short)1, (uint)1, typeof(short), typeof(uint))] - [InlineData((short)1, (ulong)1, typeof(short), typeof(ulong))] - [InlineData((short)1, (float)1, typeof(short), typeof(float))] - [InlineData((short)1, (double)1, typeof(short), typeof(double))] - [InlineData((short)1, "1", typeof(short), typeof(string))] - - [InlineData((int)1, (short)1, typeof(int), typeof(short))] - [InlineData((int)1, (long)1, typeof(int), typeof(long))] - [InlineData((int)1, (ushort)1, typeof(int), typeof(ushort))] - [InlineData((int)1, (uint)1, typeof(int), typeof(uint))] - [InlineData((int)1, (ulong)1, typeof(int), typeof(ulong))] - [InlineData((int)1, (float)1, typeof(int), typeof(float))] - [InlineData((int)1, (double)1, typeof(int), typeof(double))] - [InlineData((int)1, "1", typeof(int), typeof(string))] - - [InlineData((long)1, (short)1, typeof(long), typeof(short))] - [InlineData((long)1, (int)1, typeof(long), typeof(int))] - [InlineData((long)1, (ushort)1, typeof(long), typeof(ushort))] - [InlineData((long)1, (uint)1, typeof(long), typeof(uint))] - [InlineData((long)1, (ulong)1, typeof(long), typeof(ulong))] - [InlineData((long)1, (float)1, typeof(long), typeof(float))] - [InlineData((long)1, (double)1, typeof(long), typeof(double))] - [InlineData((long)1, "1", typeof(long), typeof(string))] - - [InlineData((float)1.1, (short)1, typeof(float), typeof(short))] - [InlineData((float)1.1, (int)1, typeof(float), typeof(int))] - [InlineData((float)1.1, (long)1, typeof(float), typeof(long))] - [InlineData((float)1.1, (ushort)1, typeof(float), typeof(ushort))] - [InlineData((float)1.1, (uint)1, typeof(float), typeof(uint))] - [InlineData((float)1.1, (ulong)1, typeof(float), typeof(ulong))] - [InlineData((float)1, 1d, typeof(float), typeof(double))] - [InlineData((float)1.1, "1.1", typeof(float), typeof(string))] - - [InlineData((double)1.1, (short)1, typeof(double), typeof(short))] - [InlineData((double)1.1, (int)1, typeof(double), typeof(int))] - [InlineData((double)1.1, (long)1, typeof(double), typeof(long))] - [InlineData((double)1.1, (ushort)1, typeof(double), typeof(ushort))] - [InlineData((double)1.1, (uint)1, typeof(double), typeof(uint))] - [InlineData((double)1.1, (ulong)1, typeof(double), typeof(ulong))] - [InlineData((double)1.1, (float)1.1, typeof(double), typeof(float))] - [InlineData((double)1.1, "1.1", typeof(double), typeof(string))] - - [Theory] - public void ConvertNumber(object input, object expectedOutput, - Type from, Type to) - { - // arrange - // act - var success = DefaultTypeConverter.Default.TryConvert( - from, to, input, out object output); - - // assert - Assert.True(success); - Assert.Equal(to, output.GetType()); - Assert.Equal(expectedOutput, output); - } - - [Fact] - public void Convert_Int_NullableLong() - { - // arrange - var source = 55; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(int), typeof(long?), - source, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(55L, output); - } - - [Fact] - public void Convert_NullableInt_NullableLong() - { - // arrange - int? source = 55; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(int?), typeof(long?), - source, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(55L, output); - } - - [Fact] - public void Convert_NullString_NullableLong() - { - // arrange - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string), typeof(long?), - null, out object output); - - // assert - Assert.True(success); - Assert.Null(output); - } - - - [Fact] - public void Convert_NullableLong_Int() - { - // arrange - long? source = 55; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(long?), typeof(int), - source, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(55, output); - } - - - [InlineData("{2d84dcd6-3439-4ebe-8427-f4b1e1730c47}")] - [InlineData("2d84dcd6-3439-4ebe-8427-f4b1e1730c47")] - [InlineData("2d84dcd634394ebe8427f4b1e1730c47")] - [Theory] - public void Convert_String_Guid(string input) - { - // arrange - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string), typeof(Guid), - input, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(Guid.Parse(input), output); - } - - [Fact] - public void Convert_Guid_String() - { - // arrange - const string expectedOutput = "2d84dcd634394ebe8427f4b1e1730c47"; - var input = Guid.Parse(expectedOutput); - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(Guid), typeof(string), - input, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(expectedOutput, output); - } - - [Fact] - public void Convert_String_Uri() - { - // arrange - const string expectedOutput = "http://foo/"; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string), typeof(Uri), - expectedOutput, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(expectedOutput, output.ToString()); - } - - [Fact] - public void Convert_Uri_String() - { - // arrange - const string expectedOutput = "http://foo/"; - var input = new Uri(expectedOutput); - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(Uri), typeof(string), - input, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(expectedOutput, output); - } - - [Fact] - public void Convert_String_String() - { - // arrange - const string expectedOutput = "2d84dcd634394ebe8427f4b1e1730c47"; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string), typeof(string), - expectedOutput, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal(expectedOutput, output); - } - - [InlineData(1, "1")] - [InlineData(null, null)] - [InlineData("foo", "foo")] - [InlineData(true, "True")] - [Theory] - public void Convert_Object_String(object input, object expectedOutput) - { - // arrange - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(object), typeof(string), - input, out object output); - - // assert - Assert.True(success); - Assert.Equal(expectedOutput, output); - } - - [Fact] - public void Convert_ArrayOfString_ListOfString() - { - // arrange - string[] list = { "a", "b", "c" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(List), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType>(output); - Assert.Collection((List)output, - t => Assert.Equal("a", t), - t => Assert.Equal("b", t), - t => Assert.Equal("c", t)); - } - - [Fact] - public void Convert_ArrayOfString_ListOfInt() - { - // arrange - string[] list = { "1", "2", "3" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(List), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType>(output); - Assert.Collection((List)output, - t => Assert.Equal(1, t), - t => Assert.Equal(2, t), - t => Assert.Equal(3, t)); - } - - [Fact] - public void Convert_ArrayOfString_ArrayOfInt() - { - // arrange - string[] list = { "1", "2", "3" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(int[]), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Collection((int[])output, - t => Assert.Equal(1, t), - t => Assert.Equal(2, t), - t => Assert.Equal(3, t)); - } - - [Fact] - public void Convert_ArrayOfString_IListOfInt() - { - // arrange - string[] list = { "1", "2", "3" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(IList), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType>(output); - Assert.Collection((List)output, - t => Assert.Equal(1, t), - t => Assert.Equal(2, t), - t => Assert.Equal(3, t)); - } - - [Fact] - public void Convert_ArrayOfString_ICollectionOfInt() - { - // arrange - string[] list = { "1", "2", "3" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(ICollection), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType>(output); - Assert.Collection((List)output, - t => Assert.Equal(1, t), - t => Assert.Equal(2, t), - t => Assert.Equal(3, t)); - } - - [Fact] - public void Convert_ArrayOfString_String() - { - // arrange - string[] list = new[] { "1", "2", "3" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(string), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType(output); - Assert.Equal("1,2,3", output); - } - - [Fact] - public void Convert_ArrayOfString_NullableListOfFooOrBar() - { - // arrange - string[] list = new[] { "Foo", "Bar" }; - - // act - var success = DefaultTypeConverter.Default.TryConvert( - typeof(string[]), typeof(List), - list, out object output); - - // assert - Assert.True(success); - Assert.IsType>(output); - Assert.Collection((List)output, - t => Assert.Equal(FooOrBar.Foo, t), - t => Assert.Equal(FooOrBar.Bar, t)); - } - - [Fact] - public void GenericTryConvert_ArrayOfString_NullableListOfFooOrBar() - { - // arrange - string[] list = new[] { "Foo", "Bar" }; - - // act - var success = - TypeConverterExtensions.TryConvert>( - DefaultTypeConverter.Default, - list, out var output); - - // assert - Assert.True(success); - Assert.IsType>(output); - Assert.Collection((List)output, - t => Assert.Equal(FooOrBar.Foo, t), - t => Assert.Equal(FooOrBar.Bar, t)); - } - - [Fact] - public void GenericTryConvert_TypeconverterIsNull_ArgumentNullExc() - { - // arrange - string[] list = new[] { "Foo", "Bar" }; - - // act - Action action = () => - TypeConverterExtensions.TryConvert>( - null, - list, out var output); - - // assert - Assert.Throws(action); - } - - [Fact] - public void GenericConvert_TypeconverterIsNull_ArgumentNullExc() - { - // arrange - string[] list = new[] { "Foo", "Bar" }; - - // act - Action action = () => - TypeConverterExtensions.Convert>( - null, list); - - // assert - Assert.Throws(action); - } - - [Fact] - public void Convert_WithDependencyInjection() - { - // arrange - var services = new ServiceCollection(); - services.AddSingleton(); - services.AddTypeConverter(input => "Bar"); - - IServiceProvider serviceProvider = services.BuildServiceProvider(); - - // act - ITypeConverter converter = - serviceProvider.GetService(); - var converted = converter.Convert(true); - - // assert - Assert.Equal("Bar", converted); - } - - public enum FooOrBar - { - Foo, - Bar - } + Foo, + Bar } } From 7c1396684b488fc549b4602477ffbb6d03152e43 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Thu, 23 Jun 2022 12:19:16 +0200 Subject: [PATCH 04/11] Complete Resolvers --- .../Execution/Processing/OperationCompiler.cs | 30 ++++++++++++++----- .../test/Execution.Tests/CodeFirstTests.cs | 3 +- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs index 03d9a1ac864..7899e181c88 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs @@ -22,6 +22,7 @@ public sealed partial class OperationCompiler private readonly Dictionary _contextData = new(); private readonly List _operationOptimizers = new(); private readonly List _selectionSetOptimizers = new(); + private readonly List _selections = new(); private IncludeCondition[] _includeConditions = Array.Empty(); private CompilerContext? _deferContext; private int _nextSelectionId; @@ -97,6 +98,7 @@ public IOperation Compile( _contextData.Clear(); _operationOptimizers.Clear(); _selectionSetOptimizers.Clear(); + _selections.Clear(); _includeConditions = Array.Empty(); _deferContext = null; @@ -114,6 +116,8 @@ private Operation CreateOperation( if (_operationOptimizers.Count == 0) { + CompleteResolvers(schema); + // if we do not have any optimizers we will copy // the variants and seal them in one go. foreach (var item in _selectionVariants) @@ -144,6 +148,8 @@ private Operation CreateOperation( _operationOptimizers[i].OptimizeOperation(context); } + CompleteResolvers(schema); + for (var i = 0; i < variants.Length; i++) { variants[i].Seal(); @@ -160,6 +166,21 @@ private Operation CreateOperation( new Dictionary(_contextData)); } + private void CompleteResolvers(ISchema schema) + { + foreach (var selection in _selections) + { + if (selection.ResolverPipeline is null && selection.PureResolver is null) + { + var field = selection.Field; + var syntaxNode = selection.SyntaxNode; + var resolver = CreateFieldMiddleware(schema, field, syntaxNode); + var pureResolver = TryCreatePureField(field, syntaxNode); + selection.SetResolvers(resolver, pureResolver); + } + } + } + private void CompileSelectionSet(CompilerContext context) { // We first collect the fields that we find in the selection set ... @@ -188,7 +209,6 @@ private void CompleteSelectionSet(CompilerContext context) // if the field of the selection returns a composite type we will traverse // the child selection-sets as well. var fieldType = selection.Type.NamedType(); - var selectionSetId = -1; if (selection.IsConditional) { @@ -204,7 +224,7 @@ private void CompleteSelectionSet(CompilerContext context) throw QueryCompiler_CompositeTypeSelectionSet(selection.SyntaxNode); } - selectionSetId = GetOrCreateSelectionSetId(selection.SelectionSet); + var selectionSetId = GetOrCreateSelectionSetId(selection.SelectionSet); var selectionVariants = GetOrCreateSelectionVariants(selectionSetId); var possibleTypes = context.Schema.GetPossibleTypes(fieldType); @@ -222,9 +242,8 @@ private void CompleteSelectionSet(CompilerContext context) } } - // we now seal the selection to make it immutable. - selection.Seal(selectionSetId); selections[selectionIndex++] = selection; + _selections.Add(selection); } if (context.Fragments.Count > 0) @@ -341,9 +360,6 @@ selection.SelectionSet is not null selection.SelectionSet.Selections)) : selection, responseName: responseName, - // FIX: selection must be bound later - resolverPipeline: CreateFieldMiddleware(context.Schema, field, selection), - pureResolver: TryCreatePureField(field, selection), strategy: field.IsParallelExecutable ? SelectionExecutionStrategy.Default : SelectionExecutionStrategy.Serial, diff --git a/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs index ef7cc6ff941..fdf2b885d44 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/CodeFirstTests.cs @@ -25,8 +25,7 @@ public async Task ExecuteOneFieldQueryWithProperty() .Create(); // act - var result = - await schema.MakeExecutable().ExecuteAsync("{ test }"); + var result = await schema.MakeExecutable().ExecuteAsync("{ test }"); // assert Assert.Null(Assert.IsType(result).Errors); From ecc34eb094fc4d8dcd9fb5aa5f11edf37518e814 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Thu, 23 Jun 2022 17:51:07 +0300 Subject: [PATCH 05/11] Fixed some of the issues with the new scheduler --- .../src/Execution/Processing/Operation.cs | 5 ++-- .../Execution/Processing/OperationCompiler.cs | 4 ++- .../src/Execution/Processing/Selection.cs | 13 +++++++-- .../src/Execution/Processing/SelectionSet.cs | 6 ++-- .../Execution/Processing/SelectionVariants.cs | 28 +++++++++++-------- .../Processing/Tasks/ResolverTask.Execute.cs | 16 +++++++++++ .../Processing/Tasks/ResolverTask.cs | 5 ---- .../Processing/WorkScheduler.Execute.cs | 15 +++------- .../Properties/Resources.Designer.cs | 18 ++++++++++++ .../src/Execution/Properties/Resources.resx | 9 ++++++ .../Core/src/Execution/ThrowHelper.cs | 13 +++++++-- 11 files changed, 95 insertions(+), 37 deletions(-) diff --git a/src/HotChocolate/Core/src/Execution/Processing/Operation.cs b/src/HotChocolate/Core/src/Execution/Processing/Operation.cs index 19c6695ede2..6c227ee1e7d 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Operation.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Operation.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using HotChocolate.Language; using HotChocolate.Types; +using static HotChocolate.Execution.ThrowHelper; namespace HotChocolate.Execution.Processing; @@ -73,9 +74,9 @@ public ISelectionSet GetSelectionSet(ISelection selection, IObjectType typeConte var selectionSetId = ((Selection)selection).SelectionSetId; - if (selectionSetId == -1) + if (selectionSetId is -1) { - throw new ArgumentException("The specified selection does not have a selection set."); + throw Operation_NoSelectionSet(); } return _selectionVariants[selectionSetId].GetSelectionSet(typeContext); diff --git a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs index 7899e181c88..6ad7d559e2e 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/OperationCompiler.cs @@ -209,6 +209,7 @@ private void CompleteSelectionSet(CompilerContext context) // if the field of the selection returns a composite type we will traverse // the child selection-sets as well. var fieldType = selection.Type.NamedType(); + var selectionSetId = -1; if (selection.IsConditional) { @@ -224,7 +225,7 @@ private void CompleteSelectionSet(CompilerContext context) throw QueryCompiler_CompositeTypeSelectionSet(selection.SyntaxNode); } - var selectionSetId = GetOrCreateSelectionSetId(selection.SelectionSet); + selectionSetId = GetOrCreateSelectionSetId(selection.SelectionSet); var selectionVariants = GetOrCreateSelectionVariants(selectionSetId); var possibleTypes = context.Schema.GetPossibleTypes(fieldType); @@ -242,6 +243,7 @@ private void CompleteSelectionSet(CompilerContext context) } } + selection.SetSelectionSetId(selectionSetId); selections[selectionIndex++] = selection; _selections.Add(selection); } diff --git a/src/HotChocolate/Core/src/Execution/Processing/Selection.cs b/src/HotChocolate/Core/src/Execution/Processing/Selection.cs index 29562ee7fc0..3ea95221e48 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Selection.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Selection.cs @@ -253,11 +253,20 @@ internal void SetResolvers( PureResolver = pureResolver; } - internal void Seal(int selectionSetId) + internal void SetSelectionSetId(int selectionSetId) + { + if ((_flags & Flags.Sealed) == Flags.Sealed) + { + throw new NotSupportedException(Resources.PreparedSelection_ReadOnly); + } + + SelectionSetId = selectionSetId; + } + + internal void Seal() { if ((_flags & Flags.Sealed) != Flags.Sealed) { - SelectionSetId = selectionSetId; _flags |= Flags.Sealed; } } diff --git a/src/HotChocolate/Core/src/Execution/Processing/SelectionSet.cs b/src/HotChocolate/Core/src/Execution/Processing/SelectionSet.cs index f4d8b3f1027..b43192ebe76 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/SelectionSet.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/SelectionSet.cs @@ -57,7 +57,7 @@ public SelectionSet( } /// - public bool IsConditional => (_flags & Flags.Conditional) != Flags.Conditional; + public bool IsConditional => (_flags & Flags.Conditional) == Flags.Conditional; /// public IReadOnlyList Selections => _selections; @@ -70,13 +70,13 @@ public SelectionSet( /// public static SelectionSet Empty { get; } = new(Array.Empty(), false); - internal void Seal(int selectionSetId) + internal void Seal() { if ((_flags & Flags.Sealed) != Flags.Sealed) { for (var i = 0; i < _selections.Count; i++) { - _selections[i].Seal(selectionSetId); + _selections[i].Seal(); } _flags |= Flags.Sealed; diff --git a/src/HotChocolate/Core/src/Execution/Processing/SelectionVariants.cs b/src/HotChocolate/Core/src/Execution/Processing/SelectionVariants.cs index 409c1d2864b..3c99ad7c645 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/SelectionVariants.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/SelectionVariants.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; -using HotChocolate.Execution.Properties; using HotChocolate.Types; +using static HotChocolate.Execution.Properties.Resources; +using static HotChocolate.Execution.ThrowHelper; namespace HotChocolate.Execution.Processing; @@ -40,7 +41,7 @@ public ISelectionSet GetSelectionSet(IObjectType typeContext) { return _map.TryGetValue(typeContext, out var selections) ? selections - : SelectionSet.Empty; + : throw SelectionSet_TypeContextInvalid(typeContext); } if (ReferenceEquals(_firstType, typeContext)) @@ -53,7 +54,7 @@ public ISelectionSet GetSelectionSet(IObjectType typeContext) return _secondSelections!; } - return SelectionSet.Empty; + throw SelectionSet_TypeContextInvalid(typeContext); } internal bool ContainsSelectionSet(IObjectType typeContext) @@ -84,7 +85,7 @@ internal void AddSelectionSet( { if (_readOnly) { - throw new NotSupportedException(Resources.SelectionVariants_ReadOnly); + throw new NotSupportedException(SelectionVariants_ReadOnly); } var selectionSet = new SelectionSet(selections, fragments, isConditional); @@ -104,8 +105,7 @@ internal void AddSelectionSet( { if (typeContext == _firstType) { - throw new InvalidOperationException( - $"The type {typeContext.Name} was already added."); + throw SelectionSet_TypeAlreadyAdded(typeContext); } _secondType = typeContext; @@ -130,14 +130,20 @@ internal void AddSelectionSet( internal void Seal() { - _readOnly = true; - - if (_map is not null) + if (!_readOnly) { - foreach (var selectionSet in _map.Values) + _firstSelections?.Seal(); + _secondSelections?.Seal(); + + if (_map is not null) { - selectionSet.Seal(Id); + foreach (var selectionSet in _map.Values) + { + selectionSet.Seal(); + } } + + _readOnly = true; } } } diff --git a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs index 0f8dc7b1c96..6495ceaf700 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs @@ -16,6 +16,22 @@ private async Task ExecuteAsync(CancellationToken cancellationToken) { var success = await TryExecuteAsync(cancellationToken).ConfigureAwait(false); CompleteValue(success, cancellationToken); + + switch (_taskBuffer.Count) + { + case 0: + break; + + case 1: + _operationContext.Scheduler.Register(_taskBuffer[0]); + _taskBuffer.Clear(); + break; + + default: + _operationContext.Scheduler.Register(_taskBuffer); + _taskBuffer.Clear(); + break; + } } Status = _completionStatus; diff --git a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs index 3240b363584..9832cd3b6cd 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.cs @@ -70,11 +70,6 @@ public ResolverTask(ObjectPool objectPool) /// public bool IsRegistered { get; set; } - /// - /// Tasks that were created through the field completion. - /// - public List ChildTasks => _taskBuffer; - /// public void BeginExecute(CancellationToken cancellationToken) { diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs index d360ed8f161..e734fbf5d34 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs @@ -11,7 +11,7 @@ internal sealed partial class WorkScheduler public async Task ExecuteAsync() { AssertNotPooled(); - + try { await ExecuteInternalAsync(_buffer); @@ -24,7 +24,7 @@ public async Task ExecuteAsync() private async Task ExecuteInternalAsync(IExecutionTask?[] buffer) { - RESTART: +RESTART: _diagnosticEvents.StartProcessing(_requestContext); try @@ -78,8 +78,6 @@ private async Task ExecuteInternalAsync(IExecutionTask?[] buffer) } } - _ct.ThrowIfCancellationRequested(); - if (!_isCompleted) { lock (_sync) @@ -108,17 +106,12 @@ private async Task ExecuteInternalAsync(IExecutionTask?[] buffer) await _pause; goto RESTART; } - } - + _ct.ThrowIfCancellationRequested(); + } private int TryTake(IExecutionTask?[] buffer) { - if (_isCompleted || _ct.IsCancellationRequested) - { - return default; - } - var size = 0; lock (_sync) diff --git a/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs b/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs index 80a7e0023da..102dbab7782 100644 --- a/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs +++ b/src/HotChocolate/Core/src/Execution/Properties/Resources.Designer.cs @@ -392,5 +392,23 @@ internal static string OperationCompiler_ToManyIncludeConditions { return ResourceManager.GetString("OperationCompiler_ToManyIncludeConditions", resourceCulture); } } + + internal static string SelectionVariants_TypeContextInvalid { + get { + return ResourceManager.GetString("SelectionVariants_TypeContextInvalid", resourceCulture); + } + } + + internal static string ThrowHelper_SelectionSet_TypeAlreadyAdded { + get { + return ResourceManager.GetString("ThrowHelper_SelectionSet_TypeAlreadyAdded", resourceCulture); + } + } + + internal static string ThrowHelper_OneOfFieldMustBeNonNull { + get { + return ResourceManager.GetString("ThrowHelper_OneOfFieldMustBeNonNull", resourceCulture); + } + } } } diff --git a/src/HotChocolate/Core/src/Execution/Properties/Resources.resx b/src/HotChocolate/Core/src/Execution/Properties/Resources.resx index 4bdf20c3189..08a12a3a683 100644 --- a/src/HotChocolate/Core/src/Execution/Properties/Resources.resx +++ b/src/HotChocolate/Core/src/Execution/Properties/Resources.resx @@ -291,4 +291,13 @@ The operation compiler only allows for 64 unique include conditions. + + The specified type `{0}` is not a possible type to this selection set. + + + The type {0} was already added. + + + Value for oneof field {0} must be non-null. + diff --git a/src/HotChocolate/Core/src/Execution/ThrowHelper.cs b/src/HotChocolate/Core/src/Execution/ThrowHelper.cs index f4be84f2494..61b1d5d8d42 100644 --- a/src/HotChocolate/Core/src/Execution/ThrowHelper.cs +++ b/src/HotChocolate/Core/src/Execution/ThrowHelper.cs @@ -18,7 +18,7 @@ public static GraphQLException VariableIsNotAnInputType( variableDefinition.Variable.Name.Value) .SetCode(ErrorCodes.Execution.MustBeInputType) .SetExtension("variable", variableDefinition.Variable.Name.Value) - .SetExtension("type", variableDefinition.Type.ToString()!) + .SetExtension("type", variableDefinition.Type.ToString()) .AddLocation(variableDefinition) .Build()); } @@ -312,8 +312,17 @@ public static GraphQLException ResolverContext_CannotCastParent( public static GraphQLException OneOfFieldMustBeNonNull( FieldCoordinate field) => new(ErrorBuilder.New() - .SetMessage($"Value for oneof field {field.FieldName} must be non-null.") + .SetMessage(string.Format(ThrowHelper_OneOfFieldMustBeNonNull, field.FieldName)) .SetCode(ErrorCodes.Execution.OneOfFieldMustBeNonNull) .SetExtension(nameof(field), field.ToString()) .Build()); + + public static ArgumentException SelectionSet_TypeContextInvalid(IObjectType typeContext) + => new(string.Format(SelectionVariants_TypeContextInvalid, typeContext.Name)); + + public static InvalidOperationException SelectionSet_TypeAlreadyAdded(IObjectType typeContext) + => new(string.Format(ThrowHelper_SelectionSet_TypeAlreadyAdded, typeContext.Name)); + + public static ArgumentException Operation_NoSelectionSet() + => new("The specified selection does not have a selection set."); } From 2b6e313d24d7e6e0f290f8f9d0a2b1fad324bbc3 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Fri, 24 Jun 2022 17:28:41 +0300 Subject: [PATCH 06/11] fixed deadlocks --- .vscode/extensions.json | 6 ++ .vscode/launch.json | 11 +++ .vscode/settings.json | 8 ++ .vscode/tasks.json | 86 ++++++++++++++++--- .../Processing/Internal/WorkQueue.cs | 10 ++- .../Processing/Tasks/ResolverTask.Execute.cs | 12 +-- .../Processing/WorkScheduler.Execute.cs | 65 ++++++++------ .../Processing/WorkScheduler.Pause.cs | 6 +- .../src/Execution/Processing/WorkScheduler.cs | 15 +--- .../Integration/DataLoader/DataLoaderTests.cs | 19 ++-- .../Integration/DataLoader/Query.cs | 6 +- .../StarWarsCodeFirstTests.cs | 22 ++--- 12 files changed, 188 insertions(+), 78 deletions(-) create mode 100644 .vscode/extensions.json create mode 100644 .vscode/launch.json create mode 100644 .vscode/settings.json diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000000..de991f40a7b --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "ms-azuretools.vscode-azurefunctions", + "ms-dotnettools.csharp" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000000..894cbe6aab7 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Attach to .NET Functions", + "type": "coreclr", + "request": "attach", + "processId": "${command:azureFunctions.pickProcess}" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000000..7239878b198 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "azureFunctions.deploySubpath": "templates/v12/function/bin/Release/net6.0/publish", + "azureFunctions.projectLanguage": "C#", + "azureFunctions.projectRuntime": "~4", + "debug.internalConsoleOptions": "neverOpen", + "azureFunctions.projectSubpath": "templates/v12/function", + "azureFunctions.preDeployTask": "publish (functions)" +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index bd0e69b381a..364e79a252e 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -10,9 +10,7 @@ "args": [ "build", "src/All.sln", - // Ask dotnet build to generate full paths for file names. "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel "/consoleloggerparameters:NoSummary" ], "group": "build", @@ -28,9 +26,7 @@ "args": [ "build", "src/HotChocolate/Core", - // Ask dotnet build to generate full paths for file names. "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel "/consoleloggerparameters:NoSummary" ], "group": "build", @@ -46,9 +42,7 @@ "args": [ "build", "src/HotChocolate/Core/test/Types.Analyzers.Tests", - // Ask dotnet build to generate full paths for file names. "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel "/consoleloggerparameters:NoSummary" ], "group": "build", @@ -64,9 +58,7 @@ "args": [ "build", "src/StrawberryShake/CodeGeneration", - // Ask dotnet build to generate full paths for file names. "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel "/consoleloggerparameters:NoSummary" ], "group": "build", @@ -82,9 +74,7 @@ "args": [ "build", "src/StrawberryShake/SourceGenerator", - // Ask dotnet build to generate full paths for file names. "/property:GenerateFullPaths=true", - // Do not generate summary otherwise it leads to duplicate errors in Problems panel "/consoleloggerparameters:NoSummary" ], "group": "build", @@ -92,6 +82,82 @@ "reveal": "silent" }, "problemMatcher": "$msCompile" + }, + { + "label": "clean (functions)", + "command": "dotnet", + "args": [ + "clean", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/templates/v12/function" + } + }, + { + "label": "build (functions)", + "command": "dotnet", + "args": [ + "build", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "dependsOn": "clean (functions)", + "group": { + "kind": "build", + "isDefault": true + }, + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/templates/v12/function" + } + }, + { + "label": "clean release (functions)", + "command": "dotnet", + "args": [ + "clean", + "--configuration", + "Release", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/templates/v12/function" + } + }, + { + "label": "publish (functions)", + "command": "dotnet", + "args": [ + "publish", + "--configuration", + "Release", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "type": "process", + "dependsOn": "clean release (functions)", + "problemMatcher": "$msCompile", + "options": { + "cwd": "${workspaceFolder}/templates/v12/function" + } + }, + { + "type": "func", + "dependsOn": "build (functions)", + "options": { + "cwd": "${workspaceFolder}/templates/v12/function/bin/Debug/net6.0" + }, + "command": "host start", + "isBackground": true, + "problemMatcher": "$func-dotnet-watch" } ] } \ No newline at end of file diff --git a/src/HotChocolate/Core/src/Execution/Processing/Internal/WorkQueue.cs b/src/HotChocolate/Core/src/Execution/Processing/Internal/WorkQueue.cs index 5450081cacf..fc5cb4345b0 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Internal/WorkQueue.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Internal/WorkQueue.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Threading; namespace HotChocolate.Execution.Processing.Internal; @@ -18,8 +18,10 @@ internal sealed class WorkQueue public void Complete() { - Debug.Assert(_running > 0, "There are no running tasks."); - _running--; + if (Interlocked.Decrement(ref _running) < 0) + { + throw new InvalidOperationException(); + } } public bool TryTake([MaybeNullWhen(false)] out IExecutionTask executionTask) @@ -36,7 +38,7 @@ public bool TryTake([MaybeNullWhen(false)] out IExecutionTask executionTask) #else if (_stack.TryPop(out executionTask)) { - _running++; + Interlocked.Increment(ref _running); return true; } #endif diff --git a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs index 6495ceaf700..2ed9691fde0 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs @@ -8,6 +8,8 @@ namespace HotChocolate.Execution.Processing.Tasks; internal sealed partial class ResolverTask { + private readonly string s = Guid.NewGuid().ToString("N"); + private async Task ExecuteAsync(CancellationToken cancellationToken) { try @@ -24,12 +26,10 @@ private async Task ExecuteAsync(CancellationToken cancellationToken) case 1: _operationContext.Scheduler.Register(_taskBuffer[0]); - _taskBuffer.Clear(); break; default: _operationContext.Scheduler.Register(_taskBuffer); - _taskBuffer.Clear(); break; } } @@ -50,9 +50,11 @@ private async Task ExecuteAsync(CancellationToken cancellationToken) Status = ExecutionTaskStatus.Faulted; _resolverContext.Result = null; } - - _operationContext.Scheduler.Complete(this); - _objectPool.Return(this); + finally + { + _operationContext.Scheduler.Complete(this); + _objectPool.Return(this); + } } private async ValueTask TryExecuteAsync(CancellationToken cancellationToken) diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs index e734fbf5d34..3ee7c0738d2 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Execute.cs @@ -78,32 +78,10 @@ private async Task ExecuteInternalAsync(IExecutionTask?[] buffer) } } - if (!_isCompleted) - { - lock (_sync) - { - if (!_isCompleted) - { - var isWaitingForTaskCompletion = _work.HasRunningTasks && _work.IsEmpty; - var hasWork = !_work.IsEmpty || !_serial.IsEmpty; - - if (isWaitingForTaskCompletion && _hasBatches) - { - _hasBatches = false; - _pause.Reset(); - _batchDispatcher.BeginDispatch(_ct); - } - else if (!isWaitingForTaskCompletion && !_hasBatches && !hasWork) - { - _isCompleted = true; - } - } - } - } + TryDispatchOrComplete(); - if (!_isCompleted) + if (await TryPauseAsync().ConfigureAwait(false)) { - await _pause; goto RESTART; } @@ -183,4 +161,43 @@ private void HandleError(Exception exception) _result.AddError(error); } } + + private void TryDispatchOrComplete() + { + if (!_isCompleted) + { + lock (_sync) + { + if (!_isCompleted) + { + var isWaitingForTaskCompletion = _work.HasRunningTasks && _work.IsEmpty; + var hasWork = !_work.IsEmpty || !_serial.IsEmpty; + + if (isWaitingForTaskCompletion && _hasBatches) + { + _hasBatches = false; + _pause.Reset(); + _batchDispatcher.BeginDispatch(_ct); + } + else if (!isWaitingForTaskCompletion && !_hasBatches && !hasWork) + { + _isCompleted = true; + } + } + } + } + } + + private async ValueTask TryPauseAsync() + { + if (!_isCompleted) + { + if (_pause.IsPaused) + { + await _pause; + } + return true; + } + return false; + } } diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs index cbb3817f108..b2be3193f94 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.Pause.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Runtime.CompilerServices; +using System.Threading; namespace HotChocolate.Execution.Processing; @@ -56,7 +57,10 @@ public void TryContinue() _continuation = null; } - continuation?.Invoke(); + if (continuation is not null) + { + ThreadPool.QueueUserWorkItem(_ => continuation()); + } } public void Reset() diff --git a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs index a24a6a8a184..c7bb24b0dab 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/WorkScheduler.cs @@ -65,23 +65,14 @@ public void Register(IReadOnlyList tasks) public void Complete(IExecutionTask task) { AssertNotPooled(); - - var hasWork = true; if (task.IsRegistered) { + // complete is thread-safe var work = task.IsSerial ? _serial : _work; - - lock (task) - { - work.Complete(); - hasWork = (!_work.IsEmpty && !_serial.IsEmpty) || _work.HasRunningTasks; - } + work.Complete(); } - if (!hasWork) - { - _pause.TryContinue(); - } + _pause.TryContinue(); } } diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs index fa0145e6e8b..a096456f3bb 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/DataLoaderTests.cs @@ -363,7 +363,7 @@ await executor.ExecuteAsync( [Fact] public async Task NestedDataLoader() { - using var cts = new CancellationTokenSource(500); + using var cts = new CancellationTokenSource(500000000); Snapshot.FullName(); @@ -453,11 +453,16 @@ public FooObject(string field) } public string id { get; } + public string field => id; - public static async Task Get(IResolverContext context, string id, - CancellationToken ct) => - new((await context.DataLoader().LoadAsync(id, ct)).Field); + public static async Task Get( + IResolverContext context, + string id, + CancellationToken ct) + { + return new((await context.DataLoader().LoadAsync(id, ct)).Field); + } } public class FooDataLoader : BatchDataLoader @@ -476,8 +481,10 @@ public FooDataLoader( protected override async Task> LoadBatchAsync( IReadOnlyList keys, CancellationToken cancellationToken) - => (await _nestedDataLoader.LoadAsync(keys, cancellationToken)) + { + return (await _nestedDataLoader.LoadAsync(keys, cancellationToken)) .ToImmutableDictionary(x => x.Field); + } } public class FooNestedDataLoader : BatchDataLoader @@ -544,4 +551,4 @@ protected override Task> LoadBatchAsync( return Task.FromResult>(dict); } } -} \ No newline at end of file +} diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs index 05a35e50099..26bd7976ee9 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/DataLoader/Query.cs @@ -17,13 +17,13 @@ public Task GetWithDataLoader( public Bar Bar => new Bar(); - public Task GetWithDataLoader2( + public async Task GetWithDataLoader2( string key, FieldNode fieldSelection, [DataLoader("fooBar")] TestDataLoader testDataLoader, CancellationToken cancellationToken) { - return testDataLoader.LoadAsync(key, cancellationToken); + return await testDataLoader.LoadAsync(key, cancellationToken); } public Task GetDataLoaderWithInterface( @@ -64,4 +64,4 @@ public Task GetWithDataLoader( { return testDataLoader.LoadAsync(key, cancellationToken); } -} \ No newline at end of file +} diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs index 9d056c9f08f..a3db0ef6de2 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs @@ -941,36 +941,32 @@ await ExpectValid(@" public async Task Ensure_Benchmark_Query_GetHeroQuery() { Snapshot.FullName(); - await ExpectValid( - FileResource.Open("GetHeroQuery.graphql")) - .MatchSnapshotAsync(); + var query = FileResource.Open("GetHeroQuery.graphql"); + await ExpectValid(query).MatchSnapshotAsync(); } [Fact] public async Task Ensure_Benchmark_Query_GetHeroWithFriendsQuery() { Snapshot.FullName(); - await ExpectValid( - FileResource.Open("GetHeroWithFriendsQuery.graphql")) - .MatchSnapshotAsync(); + var query = FileResource.Open("GetHeroWithFriendsQuery.graphql"); + await ExpectValid(query).MatchSnapshotAsync(); } [Fact] public async Task Ensure_Benchmark_Query_GetTwoHerosWithFriendsQuery() { Snapshot.FullName(); - await ExpectValid( - FileResource.Open("GetTwoHerosWithFriendsQuery.graphql")) - .MatchSnapshotAsync(); + var query = FileResource.Open("GetTwoHerosWithFriendsQuery.graphql"); + await ExpectValid(query).MatchSnapshotAsync(); } [Fact] public async Task Ensure_Benchmark_Query_LargeQuery() { Snapshot.FullName(); - await ExpectValid( - FileResource.Open("LargeQuery.graphql")) - .MatchSnapshotAsync(); + var query = FileResource.Open("LargeQuery.graphql"); + await ExpectValid(query).MatchSnapshotAsync(); } [Fact] @@ -1024,4 +1020,4 @@ fragment Human3 on Human { request: r => r.SetVariableValue("if", true)) .MatchSnapshotAsync(); } -} \ No newline at end of file +} From ec1525ea2c274a4a4cc9352f82584607a1f2a08b Mon Sep 17 00:00:00 2001 From: Pascal Senn Date: Sat, 25 Jun 2022 21:48:03 +0200 Subject: [PATCH 07/11] Migrate data to selections --- .../AutoMapperQueryableExtensions.cs | 2 ++ .../Projections/Context/ISelectedField.cs | 3 +- .../Data/Projections/Context/SelectedField.cs | 4 +-- .../Convention/IProjectionConvention.cs | 2 +- .../Convention/IProjectionProvider.cs | 2 +- .../Convention/ProjectionConvention.cs | 2 +- .../Convention/ProjectionProvider.cs | 2 +- .../QueryableFilterProjectionOptimizer.cs | 13 +++---- .../QueryablePagingProjectionOptimizer.cs | 35 +++++++++--------- .../QueryableSortProjectionOptimizer.cs | 10 +++--- .../IsProjectedProjectionOptimizer.cs | 17 ++++----- .../Data/Projections/ProjectionOptimizer.cs | 36 ++++++------------- .../Visitor/IProjectionOptimizer.cs | 2 +- .../ProjectionConventionExtensionsTests.cs | 5 ++- .../QueryableFilterMiddleware.cs | 2 +- 15 files changed, 66 insertions(+), 71 deletions(-) diff --git a/src/HotChocolate/Data/src/AutoMapper/AutoMapperQueryableExtensions.cs b/src/HotChocolate/Data/src/AutoMapper/AutoMapperQueryableExtensions.cs index 9a48720b582..6ec6948af2e 100644 --- a/src/HotChocolate/Data/src/AutoMapper/AutoMapperQueryableExtensions.cs +++ b/src/HotChocolate/Data/src/AutoMapper/AutoMapperQueryableExtensions.cs @@ -38,7 +38,9 @@ public static IQueryable ProjectTo( QueryableProjectionVisitor.Default.Visit(visitorContext); +#pragma warning disable CS8631 Expression> projection = visitorContext.Project(); +#pragma warning restore CS8631 return queryable.ProjectTo(mapper.ConfigurationProvider, projection); } diff --git a/src/HotChocolate/Data/src/Data/Projections/Context/ISelectedField.cs b/src/HotChocolate/Data/src/Data/Projections/Context/ISelectedField.cs index 1b8d74292fd..294d4abe739 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Context/ISelectedField.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Context/ISelectedField.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using HotChocolate.Execution.Processing; using HotChocolate.Resolvers; using HotChocolate.Types; @@ -38,7 +39,7 @@ public interface ISelectedField /// Gets the field selection for which a field resolver is /// being executed. /// - IFieldSelection Selection { get; } + ISelection Selection { get; } /// /// Gets the field on which the field resolver is being executed. diff --git a/src/HotChocolate/Data/src/Data/Projections/Context/SelectedField.cs b/src/HotChocolate/Data/src/Data/Projections/Context/SelectedField.cs index cf494393e46..53dad0fd8bc 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Context/SelectedField.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Context/SelectedField.cs @@ -27,7 +27,7 @@ internal SelectedField(IResolverContext resolverContext, ISelection selection) } /// - public IFieldSelection Selection => _selection; + public ISelection Selection => _selection; /// public IObjectField Field => Selection.Field; @@ -87,7 +87,7 @@ public bool IsSelected( return false; } - private IReadOnlyList? GetFieldSelections( + private IReadOnlyList? GetFieldSelections( ObjectType? type = null, bool allowInternals = false) { diff --git a/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionConvention.cs b/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionConvention.cs index 3aee02a2483..2bd6ffb78e0 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionConvention.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionConvention.cs @@ -28,5 +28,5 @@ public interface IProjectionConvention : IConvention /// /// Returns the selection optimizer for this projection convention. /// - ISelectionOptimizer CreateOptimizer(); + ISelectionSetOptimizer CreateOptimizer(); } diff --git a/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionProvider.cs b/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionProvider.cs index 0f785e784e3..62dd88ea385 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionProvider.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Convention/IProjectionProvider.cs @@ -31,6 +31,6 @@ public interface IProjectionProvider : IConvention /// Either a new rewritten selection or the same one if no rewriting was performed /// Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection); } diff --git a/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionConvention.cs b/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionConvention.cs index edbb3bf8e09..986a8ad682a 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionConvention.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionConvention.cs @@ -85,7 +85,7 @@ protected internal override void Complete(IConventionContext context) public FieldMiddleware CreateExecutor() => _provider.CreateExecutor(); - public ISelectionOptimizer CreateOptimizer() => + public ISelectionSetOptimizer CreateOptimizer() => new ProjectionOptimizer(_provider); private static IReadOnlyList CollectExtensions( diff --git a/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionProvider.cs b/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionProvider.cs index 5e68a73fa1c..dd4612301f1 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionProvider.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Convention/ProjectionProvider.cs @@ -156,7 +156,7 @@ protected internal override void Complete(IConventionContext context) } public Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection) { for (var i = 0; i < _optimizer.Count; i++) diff --git a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs index 01ab8693800..e0b732296fb 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs @@ -12,7 +12,7 @@ field.Field.Member is { } && field.Field.ContextData.ContainsKey(ContextArgumentNameKey); public Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection) { var resolverPipeline = @@ -32,17 +32,18 @@ static FieldDelegate WrappedPipeline(FieldDelegate next) => resolverPipeline = WrappedPipeline(resolverPipeline); var compiledSelection = new Selection( - context.GetNextId(), + selection.Id, context.Type, selection.Field, selection.Field.Type, selection.SyntaxNode, selection.ResponseName, - resolverPipeline, - arguments: selection.Arguments, - isInternal: false); + SelectionExecutionStrategy.Default, + selection.Arguments, + // TODO I think i need to have access to the include conditions here + resolverPipeline:resolverPipeline); - context.Fields[compiledSelection.ResponseName] = compiledSelection; + context.ReplaceSelection(compiledSelection.ResponseName, compiledSelection); return compiledSelection; } } diff --git a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryablePagingProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryablePagingProjectionOptimizer.cs index c70c9a2454a..e042b62aa66 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryablePagingProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryablePagingProjectionOptimizer.cs @@ -17,7 +17,7 @@ field.DeclaringType is IPageType && field.Field.Name.Value is "edges" or "items" or "nodes"; public Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection) { if (context.Type.NamedType() is not IPageType pageType) @@ -30,18 +30,21 @@ public Selection RewriteSelection( var selections = CollectSelection(context); - context.Fields[CombinedEdgeField] = - CreateCombinedSelection(context, + var combinedSelection = + CreateCombinedSelection( + context, selection, selection.DeclaringType, pageType, selections); + context.AddSelection(CombinedEdgeField, combinedSelection); + return selection; } private Selection CreateCombinedSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, ISelection selection, IObjectType declaringType, IPageType pageType, @@ -63,13 +66,13 @@ private Selection CreateCombinedSelection( context.CompileResolverPipeline(nodesField, combinedField); return new Selection( - context.GetNextId(), + context.GetNextSelectionId(), declaringType, nodesField, nodesField.Type, combinedField, CombinedEdgeField, - nodesPipeline, + resolverPipeline: nodesPipeline, arguments: selection.Arguments, isInternal: true); } @@ -90,7 +93,7 @@ private static (string filedName, IObjectField field) TryGetObjectField(IPageTyp ErrorHelper.ProjectionVisitor_NodeFieldWasNotFound(type)); } - private IReadOnlyList CollectSelection(SelectionOptimizerContext context) + private IReadOnlyList CollectSelection(SelectionSetOptimizerContext context) { var selections = new List(); @@ -102,11 +105,11 @@ private IReadOnlyList CollectSelection(SelectionOptimizerContext } private static void CollectSelectionOfEdges( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, List selections) { - if (context.Fields.Values - .FirstOrDefault(x => x.Field.Name == "edges") is { } edgeSelection) + if (context.Selections.Values + .FirstOrDefault(x => x.Field.Name == "edges") is { } edgeSelection) { foreach (var edgeSubField in edgeSelection.SelectionSet!.Selections) { @@ -124,11 +127,11 @@ edgeSubFieldNode.Name.Value is "node" && } private static void CollectSelectionOfItems( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, List selections) { - if (context.Fields.Values - .FirstOrDefault(x => x.Field.Name == "items") is { } itemSelection) + if (context.Selections.Values + .FirstOrDefault(x => x.Field.Name == "items") is { } itemSelection) { foreach (var nodeField in itemSelection.SelectionSet!.Selections) { @@ -138,11 +141,11 @@ private static void CollectSelectionOfItems( } private static void CollectSelectionOfNodes( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, List selections) { - if (context.Fields.Values - .FirstOrDefault(x => x.Field.Name == "nodes") is { } nodeSelection) + if (context.Selections.Values + .FirstOrDefault(x => x.Field.Name == "nodes") is { } nodeSelection) { foreach (var nodeField in nodeSelection.SelectionSet!.Selections) { diff --git a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs index af72bc4a55e..474d042e56c 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs @@ -12,7 +12,7 @@ field.Field.Member is { } && field.Field.ContextData.ContainsKey(ContextArgumentNameKey); public Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection) { var resolverPipeline = @@ -28,18 +28,20 @@ static FieldDelegate WrappedPipeline(FieldDelegate next) => resolverPipeline = WrappedPipeline(resolverPipeline); + // TODO include condition? var compiledSelection = new Selection( - context.GetNextId(), + context.GetNextSelectionId(), context.Type, selection.Field, selection.Field.Type, selection.SyntaxNode, selection.ResponseName, - resolverPipeline, + resolverPipeline: resolverPipeline, arguments: selection.Arguments, isInternal: false); - context.Fields[compiledSelection.ResponseName] = compiledSelection; + context.ReplaceSelection(compiledSelection.ResponseName, compiledSelection); + return compiledSelection; } } diff --git a/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs index ec232dee0e1..b5a53f5a9f0 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs @@ -14,12 +14,12 @@ field.DeclaringType is ObjectType objectType && objectType.ContextData.ContainsKey(AlwaysProjectedFieldsKey); public Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection) { if (!(context.Type is ObjectType type && - type.ContextData.TryGetValue(AlwaysProjectedFieldsKey, out var fieldsObj) && - fieldsObj is string[] fields)) + type.ContextData.TryGetValue(AlwaysProjectedFieldsKey, out var fieldsObj) && + fieldsObj is string[] fields)) { return selection; } @@ -29,14 +29,14 @@ public Selection RewriteSelection( var alias = "__projection_alias_" + i; // if the field is already in the selection set we do not need to project it - if (context.Fields.TryGetValue(fields[i], out var field) && + if (context.Selections.TryGetValue(fields[i], out var field) && field.Field.Name == fields[i]) { continue; } // if the field is already added as an alias we do not need to add it - if (context.Fields.TryGetValue(alias, out field) && + if (context.Selections.TryGetValue(alias, out field) && field.Field.Name == fields[i]) { continue; @@ -54,18 +54,19 @@ public Selection RewriteSelection( var nodesPipeline = context.CompileResolverPipeline(nodesField, nodesFieldNode); + // TODO include condition? var compiledSelection = new Selection( - context.GetNextId(), + context.GetNextSelectionId(), context.Type, nodesField, nodesField.Type, nodesFieldNode, alias, - nodesPipeline, + resolverPipeline: nodesPipeline, arguments: selection.Arguments, isInternal: true); - context.Fields[alias] = compiledSelection; + context.ReplaceSelection(alias, compiledSelection); } return selection; diff --git a/src/HotChocolate/Data/src/Data/Projections/ProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/ProjectionOptimizer.cs index 2cc9cdb6f65..8a95bcc06de 100644 --- a/src/HotChocolate/Data/src/Data/Projections/ProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/ProjectionOptimizer.cs @@ -4,7 +4,7 @@ namespace HotChocolate.Data.Projections; -public class ProjectionOptimizer : ISelectionOptimizer +public class ProjectionOptimizer : ISelectionSetOptimizer { private readonly IProjectionProvider _provider; @@ -13,34 +13,20 @@ public ProjectionOptimizer(IProjectionProvider provider) _provider = provider; } - public void OptimizeSelectionSet(SelectionOptimizerContext context) + public void OptimizeSelectionSet(SelectionSetOptimizerContext context) { - var processedFields = new HashSet(); - while (!processedFields.SetEquals(context.Fields.Keys)) + var processedSelections = new HashSet(); + while (!processedSelections.SetEquals(context.Selections.Keys)) { - var fieldsToProcess = new HashSet(context.Fields.Keys); - fieldsToProcess.ExceptWith(processedFields); - foreach (var field in fieldsToProcess) + var selectionToProcess = new HashSet(context.Selections.Keys); + selectionToProcess.ExceptWith(processedSelections); + foreach (var responseName in selectionToProcess) { - context.Fields[field] = - _provider.RewriteSelection(context, context.Fields[field]); - processedFields.Add(field); + var rewrittenSelection = + _provider.RewriteSelection(context, context.Selections[responseName]); + context.ReplaceSelection(responseName, rewrittenSelection); + processedSelections.Add(responseName); } } } - - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - InlineFragmentNode fragment) - { - return false; - } - - public bool AllowFragmentDeferral( - SelectionOptimizerContext context, - FragmentSpreadNode fragmentSpread, - FragmentDefinitionNode fragmentDefinition) - { - return false; - } } diff --git a/src/HotChocolate/Data/src/Data/Projections/Visitor/IProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Visitor/IProjectionOptimizer.cs index 886a813889b..4222ab7f8e2 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Visitor/IProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Visitor/IProjectionOptimizer.cs @@ -23,6 +23,6 @@ public interface IProjectionOptimizer /// Returns either the original or a rewritten version of it /// Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection); } diff --git a/src/HotChocolate/Data/test/Data.Projections.Tests/ProjectionConventionExtensionsTests.cs b/src/HotChocolate/Data/test/Data.Projections.Tests/ProjectionConventionExtensionsTests.cs index 95e4a5d89b9..cb478afcc0c 100644 --- a/src/HotChocolate/Data/test/Data.Projections.Tests/ProjectionConventionExtensionsTests.cs +++ b/src/HotChocolate/Data/test/Data.Projections.Tests/ProjectionConventionExtensionsTests.cs @@ -124,7 +124,7 @@ public FieldMiddleware CreateExecutor() } public Selection RewriteSelection( - SelectionOptimizerContext context, + SelectionSetOptimizerContext context, Selection selection) { throw new NotImplementedException(); @@ -133,8 +133,7 @@ public Selection RewriteSelection( private sealed class MockProjectionConvention : ProjectionConvention { - public MockProjectionConvention( - Action configure) + public MockProjectionConvention(Action configure) : base(configure) { } diff --git a/src/HotChocolate/Filters/src/Types.Filters/QueryableFilterMiddleware.cs b/src/HotChocolate/Filters/src/Types.Filters/QueryableFilterMiddleware.cs index 5e93e1c92f6..b1f9bb5be2f 100644 --- a/src/HotChocolate/Filters/src/Types.Filters/QueryableFilterMiddleware.cs +++ b/src/HotChocolate/Filters/src/Types.Filters/QueryableFilterMiddleware.cs @@ -49,7 +49,7 @@ public async Task InvokeAsync(IMiddlewareContext context) } if (source is not null && - context.Field.Arguments[_contextData.ArgumentName].Type is InputObjectType iot && + context.Selection.Arguments[_contextData.ArgumentName].Type is InputObjectType iot && iot is IFilterInputType fit) { var visitorContext = new QueryableFilterVisitorContext( From 5d2fd203f9270af6742a9d278a71e1edea025ac1 Mon Sep 17 00:00:00 2001 From: Pascal Senn Date: Mon, 27 Jun 2022 21:44:25 +0200 Subject: [PATCH 08/11] Optimize handling of selections --- .../QueryableFilterProjectionOptimizer.cs | 17 +++-------------- .../QueryableSortProjectionOptimizer.cs | 16 ++-------------- .../Expressions/QueryableProjectionVisitor.cs | 2 -- .../IsProjectedProjectionOptimizer.cs | 2 +- 4 files changed, 6 insertions(+), 31 deletions(-) diff --git a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs index e0b732296fb..06eb770f8fb 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableFilterProjectionOptimizer.cs @@ -31,19 +31,8 @@ static FieldDelegate WrappedPipeline(FieldDelegate next) => resolverPipeline = WrappedPipeline(resolverPipeline); - var compiledSelection = new Selection( - selection.Id, - context.Type, - selection.Field, - selection.Field.Type, - selection.SyntaxNode, - selection.ResponseName, - SelectionExecutionStrategy.Default, - selection.Arguments, - // TODO I think i need to have access to the include conditions here - resolverPipeline:resolverPipeline); - - context.ReplaceSelection(compiledSelection.ResponseName, compiledSelection); - return compiledSelection; + context.SetResolver(selection, resolverPipeline); + + return selection; } } diff --git a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs index 474d042e56c..d64c5def7a0 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Expressions/Optimizers/QueryableSortProjectionOptimizer.cs @@ -28,20 +28,8 @@ static FieldDelegate WrappedPipeline(FieldDelegate next) => resolverPipeline = WrappedPipeline(resolverPipeline); - // TODO include condition? - var compiledSelection = new Selection( - context.GetNextSelectionId(), - context.Type, - selection.Field, - selection.Field.Type, - selection.SyntaxNode, - selection.ResponseName, - resolverPipeline: resolverPipeline, - arguments: selection.Arguments, - isInternal: false); + context.SetResolver(selection, resolverPipeline); - context.ReplaceSelection(compiledSelection.ResponseName, compiledSelection); - - return compiledSelection; + return selection; } } diff --git a/src/HotChocolate/Data/src/Data/Projections/Expressions/QueryableProjectionVisitor.cs b/src/HotChocolate/Data/src/Data/Projections/Expressions/QueryableProjectionVisitor.cs index 2ecb1ef12ce..ca0e6b93646 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Expressions/QueryableProjectionVisitor.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Expressions/QueryableProjectionVisitor.cs @@ -2,8 +2,6 @@ using System.Linq.Expressions; using HotChocolate.Data.Projections.Expressions.Handlers; using HotChocolate.Execution.Processing; -using HotChocolate.Language; -using HotChocolate.Resolvers; using HotChocolate.Types; namespace HotChocolate.Data.Projections.Expressions; diff --git a/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs index b5a53f5a9f0..006da4ec033 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs @@ -66,7 +66,7 @@ public Selection RewriteSelection( arguments: selection.Arguments, isInternal: true); - context.ReplaceSelection(alias, compiledSelection); + context.AddSelection(alias, compiledSelection); } return selection; From ac45a018c49a1a4dd65991f5439cbf9f87e06e0b Mon Sep 17 00:00:00 2001 From: Pascal Senn Date: Mon, 27 Jun 2022 21:47:49 +0200 Subject: [PATCH 09/11] Fix format --- .../Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs b/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs index 3ddbe040156..3dc5610d834 100644 --- a/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs +++ b/src/HotChocolate/Core/test/Execution.Tests/Integration/StarWarsCodeFirst/StarWarsCodeFirstTests.cs @@ -580,7 +580,6 @@ public async Task SubscribeToReview_WithInlineFragment() // arrange var executor = await CreateExecutorAsync(); - // act var subscriptionResult = (IResponseStream)await executor.ExecuteAsync( From 946810ca8f60af59c145ff46a1722138c9b95293 Mon Sep 17 00:00:00 2001 From: Pascal Senn Date: Mon, 27 Jun 2022 21:49:00 +0200 Subject: [PATCH 10/11] Fix format --- .../Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs index 2ed9691fde0..1c280073c39 100644 --- a/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs +++ b/src/HotChocolate/Core/src/Execution/Processing/Tasks/ResolverTask.Execute.cs @@ -8,8 +8,6 @@ namespace HotChocolate.Execution.Processing.Tasks; internal sealed partial class ResolverTask { - private readonly string s = Guid.NewGuid().ToString("N"); - private async Task ExecuteAsync(CancellationToken cancellationToken) { try From 68794c544c199b278e70832ab3de9f3799a67020 Mon Sep 17 00:00:00 2001 From: Pascal Senn Date: Mon, 27 Jun 2022 21:50:06 +0200 Subject: [PATCH 11/11] Fix format --- .../Projections/Optimizers/IsProjectedProjectionOptimizer.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs b/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs index 006da4ec033..b783734a3e7 100644 --- a/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs +++ b/src/HotChocolate/Data/src/Data/Projections/Optimizers/IsProjectedProjectionOptimizer.cs @@ -54,7 +54,6 @@ public Selection RewriteSelection( var nodesPipeline = context.CompileResolverPipeline(nodesField, nodesFieldNode); - // TODO include condition? var compiledSelection = new Selection( context.GetNextSelectionId(), context.Type,