Example #1
0
        public void Operation_With_MultipleOperations()
        {
            // arrange
            ClientModel clientModel = new DocumentAnalyzer()
                                      .SetSchema(
                SchemaHelper.Load(
                    ("",
                     Utf8GraphQLParser.Parse(@"
                            schema {
                                query: Query
                            }

                            type Query {
                                foo(single: Bar!, list: [Bar!]!, nestedList: [[Bar]]): String
                            }

                            input Bar {
                                str: String
                                strNonNullable: String!
                                nested: Bar
                                nestedList: [Bar!]!
                                nestedMatrix: [[Bar]]
                            }"))
                    ))
                                      .AddDocument(
                Utf8GraphQLParser.Parse(
                    @"
                        query TestOperation($single: Bar!, $list: [Bar!]!, $nestedList: [[Bar!]]) {
                          foo(single: $single, list: $list, nestedList:$nestedList)
                        }
                    "))
                                      .AddDocument(
                Utf8GraphQLParser.Parse(
                    @"
                        query TestOperation2($single: Bar!, $list: [Bar!]!, $nestedList: [[Bar!]]) {
                          foo(single: $single, list: $list, nestedList:$nestedList)
                        }
                    "))
                                      .AddDocument(
                Utf8GraphQLParser.Parse(
                    @"
                        query TestOperation3($single: Bar!, $list: [Bar!]!, $nestedList: [[Bar!]]) {
                          foo(single: $single, list: $list, nestedList:$nestedList)
                        }
                    "))
                                      .AddDocument(Utf8GraphQLParser.Parse("extend schema @key(fields: \"id\")"))
                                      .Analyze();

            // act
            var documents = new StringBuilder();
            var generator = new CSharpGeneratorExecutor();

            // assert
            AssertResult(clientModel, generator, documents);
        }
Example #2
0
        public static void AssertResult(params string[] sourceTexts)
        {
            ClientModel clientModel = CreateClientModel(sourceTexts);

            var documents     = new StringBuilder();
            var documentNames = new HashSet <string>();
            var generator     = new CSharpGeneratorExecutor();

            documents.AppendLine("// ReSharper disable BuiltInTypeReferenceStyle");
            documents.AppendLine("// ReSharper disable RedundantNameQualifier");
            documents.AppendLine("// ReSharper disable ArrangeObjectCreationWhenTypeEvident");
            documents.AppendLine("// ReSharper disable UnusedType.Global");
            documents.AppendLine("// ReSharper disable PartialTypeWithSinglePart");
            documents.AppendLine("// ReSharper disable UnusedMethodReturnValue.Local");
            documents.AppendLine("// ReSharper disable ConvertToAutoProperty");
            documents.AppendLine("// ReSharper disable UnusedMember.Global");
            documents.AppendLine("// ReSharper disable SuggestVarOrType_SimpleTypes");
            documents.AppendLine("// ReSharper disable InconsistentNaming");
            documents.AppendLine();

            foreach (CSharpDocument document in generator.Generate(clientModel, "Foo", "FooClient"))
            {
                if (!documentNames.Add(document.Name))
                {
                    Assert.True(false, $"Document name duplicated {document.Name}");
                }

                documents.AppendLine("// " + document.Name);
                documents.AppendLine();
                documents.AppendLine(document.SourceText);
                documents.AppendLine();
            }

            documents.ToString().MatchSnapshot();

            IReadOnlyList <Diagnostic> diagnostics =
                CSharpCompiler.GetDiagnosticErrors(documents.ToString());

            if (diagnostics.Any())
            {
                Assert.True(false,
                            "Diagnostic Errors: \n" +
                            diagnostics
                            .Select(x =>
                                    $"{x.GetMessage()}" +
                                    $" (Line: {x.Location.GetLineSpan().StartLinePosition.Line})")
                            .Aggregate((acc, val) => acc + "\n" + val));
            }
        }
Example #3
0
        public async Task Interface_With_Default_Names()
        {
            // arrange
            ClientModel clientModel =
                await TestHelper.CreateClientModelAsync(
                    @"query GetHero {
                        hero(episode: NEW_HOPE) {
                            name
                            appearsIn
                        }
                    }",
                    "extend schema @key(fields: \"id\")");

            // act
            var documents = new StringBuilder();
            var generator = new CSharpGeneratorExecutor();

            // assert
            AssertResult(clientModel, generator, documents);
        }
Example #4
0
        public async Task Subscription_With_Default_Names()
        {
            // arrange
            ClientModel clientModel =
                await TestHelper.CreateClientModelAsync(
                    @"subscription OnReviewSub {
                        onReview(episode: NEW_HOPE) {
                            stars
                            commentary
                        }
                    }",
                    "extend schema @key(fields: \"id\")");

            // act
            var documents = new StringBuilder();
            var generator = new CSharpGeneratorExecutor();

            // assert
            AssertResult(clientModel, generator, documents);
        }
Example #5
0
        public async Task Operation_With_Type_Argument()
        {
            // arrange
            ClientModel clientModel =
                await TestHelper.CreateClientModelAsync(
                    @"
                    mutation createReviewMut($episode: Episode!, $review: ReviewInput!) {
                      createReview(episode: $episode, review: $review) {
                        stars
                        commentary
                      }
                    }
                    ",
                    "extend schema @key(fields: \"id\")");

            // act
            var documents = new StringBuilder();
            var generator = new CSharpGeneratorExecutor();

            // assert
            AssertResult(clientModel, generator, documents);
        }
Example #6
0
        public async Task Operation_With_Leaf_Argument()
        {
            // arrange
            ClientModel clientModel =
                await TestHelper.CreateClientModelAsync(
                    @"
                    query GetHero($episode: Episode) {
                        hero(episode: $episode) {
                            name
                            appearsIn
                        }
                    }
                    ",
                    "extend schema @key(fields: \"id\")");

            // act
            var documents = new StringBuilder();
            var generator = new CSharpGeneratorExecutor();

            // assert
            AssertResult(clientModel, generator, documents);
        }
Example #7
0
        public async Task Interface_With_Fragment_Definition_Two_Models()
        {
            // arrange
            ClientModel clientModel =
                await TestHelper.CreateClientModelAsync(
                    @"query GetHero {
                        hero(episode: NEW_HOPE) {
                            ... Hero
                        }
                    }

                    fragment Hero on Character {
                        name
                        ... Human
                        ... Droid
                        friends {
                            nodes {
                                name
                            }
                        }
                    }

                    fragment Human on Human {
                        homePlanet
                    }

                    fragment Droid on Droid {
                        primaryFunction
                    }",
                    "extend schema @key(fields: \"id\")");

            // act
            var documents = new StringBuilder();
            var generator = new CSharpGeneratorExecutor();

            // assert
            AssertResult(clientModel, generator, documents);
        }
Example #8
0
        private static void AssertResult(
            ClientModel clientModel,
            CSharpGeneratorExecutor generator,
            StringBuilder documents)
        {
            var documentName = new HashSet <string>();

            foreach (CSharpDocument document in generator.Generate(clientModel, "Foo", "FooClient"))
            {
                if (!documentName.Add(document.Name))
                {
                    Assert.True(false, $"Document name duplicated {document.Name}");
                }

                documents.AppendLine("// " + document.Name);
                documents.AppendLine();
                documents.AppendLine(document.SourceText);
                documents.AppendLine();
            }

            documents.ToString().MatchSnapshot();

            IReadOnlyList <Diagnostic> diagnostics =
                CSharpCompiler.GetDiagnosticErrors(documents.ToString());

            if (diagnostics.Any())
            {
                Assert.True(false,
                            "Diagnostic Errors: \n" +
                            diagnostics
                            .Select(x =>
                                    $"{x.GetMessage()}" +
                                    $" (Line: {x.Location.GetLineSpan().StartLinePosition.Line})")
                            .Aggregate((acc, val) => acc + "\n" + val));
            }
        }
Example #9
0
        public CSharpGeneratorResult Generate(
            IEnumerable <string> graphQLFiles,
            string clientName = "GraphQL",
            string @namespace = "StrawberryShake.GraphQL")
        {
            if (graphQLFiles is null)
            {
                throw new ArgumentNullException(nameof(graphQLFiles));
            }

            var errors    = new List <IError>();
            var documents = new List <(string file, DocumentNode document)>();

            foreach (var file in graphQLFiles)
            {
                try
                {
                    documents.Add((file, Utf8GraphQLParser.Parse(File.ReadAllBytes(file))));
                }
                catch (SyntaxException syntaxException)
                {
                    errors.Add(
                        Generator_SyntaxException(
                            syntaxException,
                            file));
                }
            }

            if (errors.Count > 0)
            {
                return(new CSharpGeneratorResult(
                           new List <CSharpDocument>(),
                           errors));
            }

            var typeSystemDocs = documents.GetTypeSystemDocuments();
            var executableDocs = documents.GetExecutableDocuments();

            if (typeSystemDocs.Count == 0)
            {
                errors.AddRange(Generator_NoTypeDocumentsFound());
            }

            if (executableDocs.Count == 0)
            {
                errors.AddRange(Generator_NoExecutableDocumentsFound());
            }

            if (errors.Any())
            {
                return(new CSharpGeneratorResult(
                           new List <CSharpDocument>(),
                           errors));
            }

            ISchema            schema    = SchemaHelper.Load(typeSystemDocs);
            IDocumentValidator validator = new ServiceCollection()
                                           .AddValidation()
                                           .Services
                                           .BuildServiceProvider()
                                           .GetRequiredService <IDocumentValidatorFactory>()
                                           .CreateValidator();

            // TODO: MST we need to rework this to reflect back on the correct file
            var merged = new DocumentNode(
                executableDocs.SelectMany(t => t.document.Definitions).ToList());
            var validationResult = validator.Validate(
                schema,
                merged);

            if (validationResult.HasErrors)
            {
                errors.AddRange(
                    validationResult.Errors.Select(
                        error => error
                        .WithCode(CodeGenerationErrorCodes.SchemaValidationError)
                        .WithExtensions(new Dictionary <string, object?>
                {
                    { TitleExtensionKey, "Schema validation error" }
                })));
            }

            /*
             * foreach ((string file, DocumentNode document) executableDoc in executableDocs)
             * {
             *  var validationResult = validator.Validate(
             *      schema,
             *      executableDoc.document);
             *  if (validationResult.HasErrors)
             *  {
             *      errors.AddRange(
             *          validationResult.Errors
             *              .Select(
             *                  error => error
             *                      .WithCode(CodeGenerationErrorCodes.SchemaValidationError)
             *                      .WithExtensions(new Dictionary<string, object?>
             *                      {
             *                          { FileExtensionKey, executableDoc.file },
             *                          { TitleExtensionKey, "Schema validation error" }
             *                      })));
             *  }
             * }
             */

            if (errors.Any())
            {
                return(new CSharpGeneratorResult(
                           new List <CSharpDocument>(),
                           errors));
            }

            var analyzer = new DocumentAnalyzer();

            analyzer.SetSchema(schema);

            foreach ((string file, DocumentNode document)executableDocument in executableDocs)
            {
                analyzer.AddDocument(executableDocument.document);
            }

            ClientModel clientModel = analyzer.Analyze();

            var executor = new CSharpGeneratorExecutor();

            return(new CSharpGeneratorResult(
                       executor.Generate(
                           clientModel,
                           @namespace,
                           clientName).ToList(),
                       errors));
        }