コード例 #1
0
 public async Task EnumValueIsCoercedToListValue()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             heroes(episodes: EMPIRE) {
                 name
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #2
0
 public async Task GetHeroName()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             hero {
                 name
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #3
0
 public async Task NonNullEnumsSerializeCorrectlyFromVariables()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query getHero($episode: Episode!) {
             hero(episode: $episode) {
                 name
             }
         }",
                       request : r => r.SetVariableValue("episode", "NEW_HOPE"))
     .MatchSnapshotAsync();
 }
コード例 #4
0
 public async Task GraphQLOrgFieldArgumentExample2()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             human(id: ""1000"") {
                 name
                 height(unit: FOOT)
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #5
0
 public async Task Skip_With_Literal(string ifValue)
 {
     Snapshot.FullName(new SnapshotNameExtension(ifValue));
     await ExpectValid($@"
         {{
             human(id: ""1000"") {{
                 name @skip(if: {ifValue})
                 height
             }}
         }}")
     .MatchSnapshotAsync();
 }
コード例 #6
0
        public async Task DirectiveIntrospection_SomeDirectives_Internal()
        {
            Snapshot.FullName();

            await new ServiceCollection()
            .AddGraphQL()
            .AddDocumentFromString(
                @"
                        type Query {
                            foo: String
                                @foo
                                @bar(baz: ""ABC"")
                                @bar(baz: null)
                                @bar(quox: { a: ""ABC"" })
                                @bar(quox: { })
                                @bar
                        }

                        input SomeInput {
                            a: String!
                        }

                        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(
                @"
                        {
                            __schema {
                                types {
                                    fields {
                                        appliedDirectives {
                                            name
                                            args {
                                                name
                                                value
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    ")
            .MatchSnapshotAsync();
        }
コード例 #7
0
 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)
                 height
             }
         }",
                       request : r => r.SetVariableValue("if", ifValue))
     .MatchSnapshotAsync();
 }
コード例 #8
0
        public async Task SkipAllSecondLevelFields()
        {
            Snapshot.FullName();

            await ExpectValid(@"
                query ($if: Boolean!) {
                    human(id: ""1000"")  {
                        name @skip(if: $if)
                    }
                }",
                              request : r => r.SetVariableValue("if", true))
            .MatchSnapshotAsync();
        }
コード例 #9
0
        public async Task SkipAll_Default_True()
        {
            Snapshot.FullName();

            await ExpectValid(@"
                query ($if: Boolean! = true) {
                    human(id: ""1000"") @skip(if: $if) {
                        name
                        height
                    }
                }")
            .MatchSnapshotAsync();
        }
コード例 #10
0
 public async Task ConditionalInlineFragment()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             heroes(episodes: [EMPIRE]) {
                 name
                 ... @include(if: true) {
                     height
                 }
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #11
0
 public async Task Ensure_Type_Introspection_Returns_Null_If_Type_Not_Found()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query {
             a: __type(name: ""Foo"") {
                 name
             }
             b: __type(name: ""Query"") {
                 name
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #12
0
 public async Task GraphQLOrgAliasExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             empireHero: hero(episode: EMPIRE) {
                 name
             }
             jediHero: hero(episode: JEDI) {
                 name
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #13
0
 public async Task NonNullListVariableValues()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query op($ep: [Episode!]!)
         {
             heroes(episodes: $ep) {
                 name
             }
         }",
                       request : r => r
                       .SetVariableValue("ep", new ListValueNode(new EnumValueNode("EMPIRE"))))
     .MatchSnapshotAsync();
 }
コード例 #14
0
        public async Task NestedFragmentsWithNestedObjectFieldsAndSkip()
        {
            Snapshot.FullName();

            await ExpectValid(@"
                query ($if: Boolean!) {
                    human(id: ""1000"") {
                        ... Human1 @include(if: $if)
                        ... Human2 @skip(if: $if)
                    }
                }
                fragment Human1 on Human {
                    friends {
                        edges {
                            ... FriendEdge1
                        }
                    }
                }
                fragment FriendEdge1 on FriendsEdge {
                    node {
                        __typename
                        friends {
                            nodes {
                                __typename
                                ... Human3
                            }
                        }
                    }
                }
                fragment Human2 on Human {
                    friends {
                        edges {
                            node {
                                __typename
                                ... Human3
                            }
                        }
                    }
                }
                fragment Human3 on Human {
                    name
                    otherHuman {
                      __typename
                      name
                    }
                }
                ",
                              request : r => r.SetVariableValue("if", true))
            .MatchSnapshotAsync();
        }
コード例 #15
0
 public async Task Execute_ListWithNullValues_ResultContainsNullElement()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query {
             human(id: ""1001"") {
                 id
                 name
                 otherHuman {
                     name
                 }
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #16
0
 public async Task ExecutionDepthShouldNotLeadToEmptyObjects()
 {
     Snapshot.FullName();
     await ExpectError(@"
         query ExecutionDepthShouldNotLeadToEmptyObjects {
             hero(episode: NEW_HOPE) {
                 __typename
                 id
                 name
                 ... on Human {
                     __typename
                     homePlanet
                 }
                 ... on Droid {
                     __typename
                     primaryFunction
                 }
                 friends {
                     nodes {
                         __typename
                         ... on Human {
                             __typename
                             homePlanet
                             friends {
                                 nodes {
                                     __typename
                                 }
                             }
                         }
                         ... on Droid {
                             __typename
                             primaryFunction
                             friends {
                                 nodes {
                                     __typename
                                 }
                             }
                         }
                     }
                 }
             }
         }",
                       configure : c =>
     {
         AddDefaultConfiguration(c);
         c.AddMaxExecutionDepthRule(3);
     });
 }
コード例 #17
0
 public async Task GraphQLOrgOperationNameExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query HeroNameAndFriends {
             hero {
                 name
                 friends {
                     nodes {
                         name
                     }
                 }
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #18
0
        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();
        }
コード例 #19
0
 public async Task GraphQLOrgVariableWithDefaultValueExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query HeroNameAndFriends($episode: Episode = JEDI) {
             hero(episode: $episode) {
                 name
                 friends {
                     nodes {
                         name
                     }
                 }
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #20
0
 public async Task GraphQLOrgVariableExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query HeroNameAndFriends($episode: Episode) {
             hero(episode: $episode) {
                 name
                 friends {
                     nodes {
                         name
                     }
                 }
             }
         }",
                       request : c => c.SetVariableValue("episode", new EnumValueNode("JEDI")))
     .MatchSnapshotAsync();
 }
コード例 #21
0
 public async Task GraphQLOrgFieldExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             hero {
                 name
                 # Queries can have comments!
                 friends {
                     nodes {
                         name
                     }
                 }
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #22
0
 public async Task GraphQLOrgInlineFragmentExample2()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query HeroForEpisode($ep: Episode!) {
             hero(episode: $ep) {
                 name
                 ... on Droid {
                     primaryFunction
                 }
                 ... on Human {
                     height
                 }
             }
         }",
                       request : r => r.SetVariableValue("ep", new EnumValueNode("EMPIRE")))
     .MatchSnapshotAsync();
 }
コード例 #23
0
 public async Task GraphQLOrgDirectiveSkipExample2()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query Hero($episode: Episode, $withFriends: Boolean!) {
             hero(episode: $episode) {
                 name
                 friends @skip(if: $withFriends) {
                     nodes {
                         name
                     }
                 }
             }
         }",
                       request : r => r
                       .SetVariableValue("episode", new EnumValueNode("JEDI"))
                       .SetVariableValue("withFriends", new BooleanValueNode(true)))
     .MatchSnapshotAsync();
 }
コード例 #24
0
 public async Task GraphQLOrgDirectiveSkipExample1WithPlainClrVarTypes()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         query Hero($episode: Episode, $withFriends: Boolean!) {
             hero(episode: $episode) {
                 name
                 friends @skip(if: $withFriends) {
                     nodes {
                         name
                     }
                 }
             }
         }",
                       request : r => r
                       .SetVariableValue("episode", "JEDI")
                       .SetVariableValue("withFriends", false))
     .MatchSnapshotAsync();
 }
コード例 #25
0
 public async Task GraphQLOrgMutationExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         mutation CreateReviewForEpisode(
             $ep: Episode!, $review: ReviewInput!) {
             createReview(episode: $ep, review: $review) {
                 stars
                 commentary
             }
         }",
                       request : r => r
                       .SetVariableValue("ep", new EnumValueNode("JEDI"))
                       .SetVariableValue("review", new ObjectValueNode(
                                             new ObjectFieldNode("stars", new IntValueNode(5)),
                                             new ObjectFieldNode("commentary",
                                                                 new StringValueNode("This is a great movie!")))))
     .MatchSnapshotAsync();
 }
コード例 #26
0
 public async Task GraphQLOrgMutationExample_With_ValueVariables()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         mutation CreateReviewForEpisode(
             $ep: Episode!
             $stars: Int!
             $commentary: String!) {
             createReview(
                 episode: $ep
                 review: { stars: $stars commentary: $commentary }) {
                 stars
                 commentary
             }
         }",
                       request : r => r
                       .SetVariableValue("ep", new EnumValueNode("JEDI"))
                       .SetVariableValue("stars", new IntValueNode(5))
                       .SetVariableValue("commentary", new StringValueNode("This is a great movie!")))
     .MatchSnapshotAsync();
 }
コード例 #27
0
 public async Task GraphQLOrgMetaFieldAndUnionExample()
 {
     Snapshot.FullName();
     await ExpectValid(@"
         {
             search(text: ""an"") {
                 __typename
                 ... on Human {
                     name
                     height
                 }
                 ... on Droid {
                     name
                     primaryFunction
                 }
                 ... on Starship {
                     name
                     length
                 }
             }
         }")
     .MatchSnapshotAsync();
 }
コード例 #28
0
        public static AssertSettings CreateIntegrationTest(
            Descriptors.Operations.RequestStrategy requestStrategy =
            Descriptors.Operations.RequestStrategy.Default,
            TransportProfile[]?profiles = null,
            bool noStore = false,
            [CallerMemberName] string?testName = null)
        {
            SnapshotFullName snapshotFullName = Snapshot.FullName();
            string           testFile         = System.IO.Path.Combine(
                snapshotFullName.FolderPath,
                testName + "Test.cs");
            string ns = "StrawberryShake.CodeGeneration.CSharp.Integration." + testName;

            if (!File.Exists(testFile))
            {
                File.WriteAllText(
                    testFile,
                    FileResource.Open("TestTemplate.txt")
                    .Replace("{TestName}", testName)
                    .Replace("{Namespace}", ns));
            }

            return(new AssertSettings
            {
                ClientName = testName !+"Client",
                Namespace = ns,
                StrictValidation = true,
                SnapshotFile = System.IO.Path.Combine(
                    snapshotFullName.FolderPath,
                    testName + "Test.Client.cs"),
                RequestStrategy = requestStrategy,
                NoStore = noStore,
                Profiles = (profiles ?? new[]
                {
                    TransportProfile.Default
                }).ToList()
            });
コード例 #29
0
        public async Task GraphQLOrgFragmentExample()
        {
            Snapshot.FullName();
            await ExpectValid(@"
                {
                    leftComparison: hero(episode: EMPIRE) {
                        ...comparisonFields
                    }
                    rightComparison: hero(episode: JEDI) {
                        ...comparisonFields
                    }
                }

                fragment comparisonFields on Character {
                    name
                    appearsIn
                    friends {
                        nodes {
                            name
                        }
                    }
                }")
            .MatchSnapshotAsync();
        }
コード例 #30
0
        public static void AssertResult(
            AssertSettings settings,
            bool skipWarnings,
            params string[] sourceTexts)
        {
            ClientModel clientModel =
                CreateClientModel(sourceTexts, settings.StrictValidation, settings.NoStore);

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

            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();

            if (settings.Profiles.Count == 0)
            {
                settings.Profiles.Add(TransportProfile.Default);
            }

            CSharpGeneratorResult result = Generate(
                clientModel,
                new CSharpGeneratorSettings
            {
                Namespace              = settings.Namespace ?? "Foo.Bar",
                ClientName             = settings.ClientName ?? "FooClient",
                StrictSchemaValidation = settings.StrictValidation,
                RequestStrategy        = settings.RequestStrategy,
                TransportProfiles      = settings.Profiles,
                NoStore       = settings.NoStore,
                InputRecords  = settings.InputRecords,
                EntityRecords = settings.EntityRecords
            });

            Assert.False(
                result.Errors.Any(),
                "It is expected that the result has no generator errors!");

            foreach (var document in result.Documents)
            {
                if (!documentNames.Add(document.Name))
                {
                    Assert.True(false, $"Document name duplicated {document.Name}");
                }

                if (document.Kind == SourceDocumentKind.CSharp)
                {
                    documents.AppendLine("// " + document.Name);
                    documents.AppendLine();
                    documents.AppendLine(document.SourceText);
                    documents.AppendLine();
                }
                else if (document.Kind == SourceDocumentKind.GraphQL)
                {
                    documents.AppendLine("// " + document.Name);
                    documents.AppendLine("// " + document.Hash);
                    documents.AppendLine();

                    using var reader = new StringReader(document.SourceText);
                    string?line;

                    do
                    {
                        line = reader.ReadLine();
                        if (line is not null)
                        {
                            documents.AppendLine("// " + line);
                        }
                    } while (line is not null);

                    documents.AppendLine();
                }
            }

            if (settings.SnapshotFile is not null)
            {
                documents.ToString()
                .MatchSnapshot(
                    new SnapshotFullName(
                        settings.SnapshotFile,
                        Snapshot.FullName().FolderPath));
            }
            else
            {
                documents.ToString().MatchSnapshot();
            }

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

            if (skipWarnings)
            {
                diagnostics = diagnostics
                              .Where(x => x.Severity == DiagnosticSeverity.Error)
                              .ToList();
            }

            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));
            }
        }