repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/document_from_schema_definition_spec.rb
spec/graphql/language/document_from_schema_definition_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::DocumentFromSchemaDefinition do let(:subject) { GraphQL::Language::DocumentFromSchemaDefinition } describe "#document" do let(:schema_idl) { <<-GRAPHQL type QueryType { foo: Foo u: Union } type Foo implements Bar { one: Type two(argument: InputType!): Site three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } type MutationType { a(input: InputType): String } # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | QueryType schema { query: QueryType mutation: MutationType } GRAPHQL } let(:schema) { GraphQL::Schema.from_definition(schema_idl) } let(:expected_document) { GraphQL.parse(expected_idl) } describe "when schemas have enums and directives" do let(:schema_idl) { <<-GRAPHQL directive @locale(lang: LangEnum!) on FIELD directive @secret(top: Boolean = false) on FIELD_DEFINITION enum LangEnum { en ru } type Query { i: Int @secret ssn: String @secret(top: true) } GRAPHQL } class DirectiveSchema < GraphQL::Schema class Secret < GraphQL::Schema::Directive argument :top, Boolean, required: false, default_value: false locations FIELD_DEFINITION end class Query < GraphQL::Schema::Object field :i, Int do directive Secret end field :ssn, String do directive Secret, top: true end end class Locale < GraphQL::Schema::Directive class LangEnum < GraphQL::Schema::Enum value "en" value "ru" end locations GraphQL::Schema::Directive::FIELD argument :lang, LangEnum end query(Query) directive(Locale) end it "dumps them into the string" do assert_equal schema_idl, DirectiveSchema.to_definition end end describe "when it has an enum_value with an adjacent custom directive" do let(:schema_idl) { <<-GRAPHQL directive @customEnumValueDirective(fakeArgument: String!) on ENUM_VALUE enum FakeEnum { VALUE1 VALUE2 @customEnumValueDirective(fakeArgument: "Value1 is better...") } type Query { fakeQueryField: FakeEnum! } GRAPHQL } class EnumValueDirectiveSchema < GraphQL::Schema class CustomEnumValueDirective < GraphQL::Schema::Directive locations GraphQL::Schema::Directive::ENUM_VALUE argument :fake_argument, String end class FakeEnum < GraphQL::Schema::Enum value "VALUE1" value "VALUE2" do directive CustomEnumValueDirective, fake_argument: "Value1 is better..." end end class Query < GraphQL::Schema::Object field :fake_query_field, FakeEnum, null: false end query(Query) end it "dumps the custom directive definition to the IDL" do assert_equal schema_idl, EnumValueDirectiveSchema.to_definition end end describe "when printing and schema respects root name conventions" do let(:schema_idl) { <<-GRAPHQL type Query { foo: Foo u: Union } type Foo implements Bar { one: Type two(argument: InputType!): Site three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } type Mutation { a(input: InputType): String } # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | Query schema { query: Query mutation: Mutation } GRAPHQL } let(:expected_idl) { <<-GRAPHQL type QueryType { foo: Foo u: Union } type Foo implements Bar { one: Type two(argument: InputType!): Site three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } type MutationType { a(input: InputType): String } # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | QueryType GRAPHQL } let(:document) { subject.new( schema ).document } it "returns the IDL without introspection, built ins and schema root" do assert equivalent_node?(expected_document, document) end end describe "with defaults" do let(:expected_idl) { <<-GRAPHQL type QueryType { foo: Foo u: Union } type Foo implements Bar { one: Type two(argument: InputType!): Site three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } type MutationType { a(input: InputType): String } # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | QueryType schema { query: QueryType mutation: MutationType } GRAPHQL } let(:document) { subject.new( schema ).document } it "returns the IDL without introspection, built ins and schema if it doesnt respect name conventions" do assert equivalent_node?(expected_document, document) end end describe "with a visibility check" do let(:expected_idl) { <<-GRAPHQL type QueryType { foo: Foo u: Union } type Foo implements Bar { three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): Site } interface Bar { one: Type four(argument: String = "string"): String } input InputType { key: String! answer: Int = 42 } type MutationType { a(input: InputType): String } # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } schema { query: QueryType mutation: MutationType } GRAPHQL } let(:schema) { Class.new(GraphQL::Schema.from_definition(schema_idl)) do def self.visible?(m, ctx) m.graphql_name != "Type" end end } let(:document) { doc_schema = Class.new(schema) do use GraphQL::Schema::Visibility def self.visible?(m, _ctx) m.respond_to?(:graphql_name) && m.graphql_name != "Type" end end subject.new(doc_schema).document } it "returns the IDL minus the filtered members" do assert equivalent_node?(expected_document, document) end end describe "with an only filter" do let(:expected_idl) { <<-GRAPHQL type QueryType { foo: Foo u: Union } type Foo implements Bar { three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): Site } interface Bar { one: Type four(argument: String = "string"): String } input InputType { key: String! answer: Int = 42 } type MutationType { a(input: InputType): String } enum Site { DESKTOP MOBILE } schema { query: QueryType mutation: MutationType } GRAPHQL } let(:schema) { Class.new(GraphQL::Schema.from_definition(schema_idl)) do def self.visible?(m, ctx) !(m.respond_to?(:kind) && m.kind.scalar? && m.name == "CustomScalar") end end } let(:document) { doc_schema = Class.new(schema) do def self.visible?(m, _ctx) !(m.respond_to?(:kind) && m.kind.scalar? && m.name == "CustomScalar") end end subject.new(doc_schema).document } it "returns the IDL minus the filtered members" do assert equivalent_node?(expected_document, document) end end describe "when excluding built ins and introspection types" do let(:expected_idl) { <<-GRAPHQL type QueryType { foo: Foo u: Union } type Foo implements Bar { one: Type two(argument: InputType!): Site three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } type MutationType { a(input: InputType): String } # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | QueryType schema { query: QueryType mutation: MutationType } GRAPHQL } let(:document) { subject.new( schema, always_include_schema: true ).document } it "returns the schema idl besides introspection types and built ins" do assert equivalent_node?(expected_document, document) end end describe "when printing excluding only introspection types" do let(:expected_idl) { <<-GRAPHQL # Represents `true` or `false` values. scalar Boolean # Represents textual data as UTF-8 character sequences. This type is most often # used by GraphQL to represent free-form human-readable text. scalar String type QueryType { foo: Foo } type Foo implements Bar { one: Type two(argument: InputType!): Type three(argument: InputType, other: String): CustomScalar four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } # Represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. scalar Int type MutationType { a(input: InputType): String } # Represents signed double-precision fractional values as specified by [IEEE # 754](https://en.wikipedia.org/wiki/IEEE_floating_point). scalar Float # Represents a unique identifier that is Base64 obfuscated. It is often used to # refetch an object or as key for a cache. The ID type appears in a JSON response # as a String; however, it is not intended to be human-readable. When expected as # an input type, any string (such as `"VXNlci0xMA=="`) or integer (such as `4`) # input value will be accepted as an ID. scalar ID # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | QueryType directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT # Marks an element of a GraphQL schema as no longer supported. directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ENUM_VALUE schema { query: QueryType mutation: MutationType } GRAPHQL } let(:document) { subject.new( schema, include_built_in_scalars: true, include_built_in_directives: true, ).document } it "returns the schema IDL including only the built ins and not introspection types" do assert equivalent_node?(expected_document, document) end end describe "when printing the full schema" do let(:expected_idl) { <<-GRAPHQL # Represents `true` or `false` values. scalar Boolean # Represents textual data as UTF-8 character sequences. This type is most often # used by GraphQL to represent free-form human-readable text. scalar String # The fundamental unit of any GraphQL Schema is the type. There are many kinds of # types in GraphQL as represented by the `__TypeKind` enum. # # Depending on the kind of a type, certain fields describe information about that # type. Scalar types provide no information beyond a name and description, while # Enum types provide their values. Object and Interface types provide the fields # they describe. Abstract types, Union and Interface, provide the Object types # possible at runtime. List and NonNull types compose other types. type __Type { kind: __TypeKind! name: String description: String fields(includeDeprecated: Boolean = false): [__Field!] interfaces: [__Type!] possibleTypes: [__Type!] enumValues(includeDeprecated: Boolean = false): [__EnumValue!] inputFields: [__InputValue!] ofType: __Type } # An enum describing what kind of type a given `__Type` is. enum __TypeKind { # Indicates this type is a scalar. SCALAR # Indicates this type is an object. `fields` and `interfaces` are valid fields. OBJECT # Indicates this type is an interface. `fields` and `possibleTypes` are valid fields. INTERFACE # Indicates this type is a union. `possibleTypes` is a valid field. UNION # Indicates this type is an enum. `enumValues` is a valid field. ENUM # Indicates this type is an input object. `inputFields` is a valid field. INPUT_OBJECT # Indicates this type is a list. `ofType` is a valid field. LIST # Indicates this type is a non-null. `ofType` is a valid field. NON_NULL } # Object and Interface types are described by a list of Fields, each of which has # a name, potentially a list of arguments, and a return type. type __Field { name: String! description: String args: [__InputValue!]! type: __Type! isDeprecated: Boolean! deprecationReason: String } # Arguments provided to Fields or Directives and the input fields of an # InputObject are represented as Input Values which describe their type and # optionally a default value. type __InputValue { name: String! description: String type: __Type! # A GraphQL-formatted string representing the default value for this input value. defaultValue: String } # One possible value for a given Enum. Enum values are unique values, not a # placeholder for a string or numeric value. However an Enum value is returned in # a JSON response as a string. type __EnumValue { name: String! description: String isDeprecated: Boolean! deprecationReason: String } type QueryType { foo: Foo } type Foo implements Bar { one: Type two(argument: InputType!): Type three(argument: InputType, other: String): Int four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: String): Type } interface Bar { one: Type four(argument: String = "string"): String } type Type { a: String } input InputType { key: String! answer: Int = 42 } # Represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. scalar Int type MutationType { a(input: InputType): String } # A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all # available types and directives on the server, as well as the entry points for # query, mutation, and subscription operations. type __Schema { # A list of all types supported by this server. types: [__Type!]! # The type that query operations will be rooted at. queryType: __Type! # If this server supports mutation, the type that mutation operations will be rooted at. mutationType: __Type # If this server support subscription, the type that subscription operations will be rooted at. subscriptionType: __Type # A list of all directives supported by this server. directives: [__Directive!]! } # A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document. # # In some cases, you need to provide options to alter GraphQL's execution behavior # in ways field arguments will not suffice, such as conditionally including or # skipping a field. Directives provide this by describing additional information # to the executor. type __Directive { name: String! description: String locations: [__DirectiveLocation!]! args: [__InputValue!]! onOperation: Boolean! onFragment: Boolean! onField: Boolean! } # A Directive can be adjacent to many parts of the GraphQL language, a # __DirectiveLocation describes one such possible adjacencies. enum __DirectiveLocation { # Location adjacent to a query operation. QUERY # Location adjacent to a mutation operation. MUTATION # Location adjacent to a subscription operation. SUBSCRIPTION # Location adjacent to a field. FIELD # Location adjacent to a fragment definition. FRAGMENT_DEFINITION # Location adjacent to a fragment spread. FRAGMENT_SPREAD # Location adjacent to an inline fragment. INLINE_FRAGMENT # Location adjacent to a schema definition. SCHEMA # Location adjacent to a scalar definition. SCALAR # Location adjacent to an object type definition. OBJECT # Location adjacent to a field definition. FIELD_DEFINITION # Location adjacent to an argument definition. ARGUMENT_DEFINITION # Location adjacent to an interface definition. INTERFACE # Location adjacent to a union definition. UNION # Location adjacent to an enum definition. ENUM # Location adjacent to an enum value definition. ENUM_VALUE # Location adjacent to an input object type definition. INPUT_OBJECT # Location adjacent to an input object field definition. INPUT_FIELD_DEFINITION } # Represents signed double-precision fractional values as specified by [IEEE # 754](https://en.wikipedia.org/wiki/IEEE_floating_point). scalar Float # Represents a unique identifier that is Base64 obfuscated. It is often used to # refetch an object or as key for a cache. The ID type appears in a JSON response # as a String; however, it is not intended to be human-readable. When expected as # an input type, any string (such as `"VXNlci0xMA=="`) or integer (such as `4`) # input value will be accepted as an ID. scalar ID # Scalar description scalar CustomScalar enum Site { DESKTOP MOBILE } union Union = Type | QueryType directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT # Marks an element of a GraphQL schema as no longer supported. directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ENUM_VALUE schema { query: QueryType mutation: MutationType } GRAPHQL } let(:document) { subject.new( schema, include_introspection_types: true, include_built_in_directives: true, include_built_in_scalars: true, always_include_schema: true, ).document } it "returns the full document AST from the given schema including built ins and introspection" do assert equivalent_node?(expected_document, document) end end end private def equivalent_node?(expected, node) return false unless expected.is_a?(node.class) if expected.respond_to?(:children) && expected.respond_to?(:scalars) children_equal = expected.children.all? do |expected_child| node.children.find { |child| equivalent_node?(expected_child, child) } end scalars_equal = expected.children.all? do |expected_child| node.children.find { |child| equivalent_node?(expected_child, child) } end children_equal && scalars_equal else expected == node end end describe "custom SDL directives" do class CustomSDLDirectiveSchema < GraphQL::Schema class CustomThing < GraphQL::Schema::Directive locations(FIELD_DEFINITION) argument :stuff, String end directive CustomThing class Query < GraphQL::Schema::Object field :f, Int, directives: { CustomThing => { stuff: "ok" } } end query(Query) end it "prints them out" do expected_str = <<~GRAPHQL directive @customThing(stuff: String!) on FIELD_DEFINITION type Query { f: Int @customThing(stuff: "ok") } GRAPHQL assert_equal expected_str, CustomSDLDirectiveSchema.to_definition end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/sanitized_printer_spec.rb
spec/graphql/language/sanitized_printer_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::SanitizedPrinter do module SanitizeTest class Color < GraphQL::Schema::Enum value "RED" value "BLUE" end class Url < GraphQL::Schema::Scalar end class SimpleInput < GraphQL::Schema::InputObject argument :string, String end class ExampleInput < GraphQL::Schema::InputObject argument :string, String argument :id, ID argument :int, Int argument :float, Float argument :enum, Color argument :input_object, ExampleInput, required: false argument :url, Url end class Query < GraphQL::Schema::Object field :inputs, String, null: false do argument :string, String argument :id, ID argument :int, Int argument :float, Float argument :enum, Color argument :input_object, ExampleInput argument :url, Url end field :nested_array_inputs, String, null: false do argument :inputs, [SimpleInput] end field :colors, String, null: false do argument :colors, [Color] end field :strings, String, null: false do argument :strings, [String] end field :custom_scalar, String, null: false do argument :scalar, GraphQL::Types::JSON end end class Schema < GraphQL::Schema query(Query) end class CustomSanitizedPrinter < GraphQL::Language::SanitizedPrinter def redact_argument_value?(argument, value) true end def redacted_argument_value(argument) "<#{argument.graphql_name}-redacted>" end end class CustomSanitizedPrinterSchema < GraphQL::Schema query(Query) sanitized_printer(CustomSanitizedPrinter) end end def sanitize_string(query_string, inline_variables: true, **options) query = GraphQL::Query.new( SanitizeTest::Schema, query_string, **options ) query.sanitized_query_string(inline_variables: inline_variables) end it "replaces strings with redacted" do query_str = ' { inputs( string: "string", id: "id", int: 1, float: 2.0, url: "http://graphqliscool.com", enum: RED inputObject: { string: "string" id: "id" int: 1 float: 2.0 url: "http://graphqliscool.com" enum: RED } ) } ' expected_query_string = 'query { inputs(string: "<REDACTED>", id: "id", int: 1, float: 2.0, url: "<REDACTED>", enum: RED, inputObject: {string: "<REDACTED>", id: "id", int: 1, float: 2.0, url: "<REDACTED>", enum: RED}) }' assert_equal expected_query_string, sanitize_string(query_str) end it "inlines variables AND redacts their values" do query_str = ' query($string1: String!, $string2: String = "str2", $inputObject: ExampleInput!) { inputs( string: $string1, id: "id1", int: 1, float: 1.0, url: "http://graphqliscool.com", enum: RED inputObject: { string: $string2 id: "id2" int: 2 float: 2.0 url: "http://graphqliscool.com" enum: RED inputObject: $inputObject } ) } ' variables = { "string1" => "str1", "inputObject" => { "string" => "str3", "id" => "id3", "int" => 3, "float" => 3.3, "url" => "three.com", "enum" => "BLUE" } } expected_query_string = 'query { inputs(' + 'string: "<REDACTED>", id: "id1", int: 1, float: 1.0, url: "<REDACTED>", enum: RED, inputObject: {' + 'string: "<REDACTED>", id: "id2", int: 2, float: 2.0, url: "<REDACTED>", enum: RED, inputObject: {' + 'string: "<REDACTED>", id: "id3", int: 3, float: 3.3, url: "<REDACTED>", enum: BLUE}}) }' assert_equal expected_query_string, sanitize_string(query_str, variables: variables) end it "doesn't inline variables when inline_variables is false" do query_str = ' query($string1: String!, $string2: String = "str2", $inputObject: ExampleInput!, $strings: [String!]!) { inputs( string: $string1, id: "id1", int: 1, float: 1.0, url: "http://graphqliscool.com", enum: RED inputObject: { string: $string2 id: "id2" int: 2 float: 2.0 url: "http://graphqliscool.com" enum: RED inputObject: $inputObject } ) strings(strings: $strings) } ' variables = { "string1" => "str1", "strings" => ["str1", "str2"], "inputObject" => { "string" => "str3", "id" => "id3", "int" => 3, "float" => 3.3, "url" => "three.com", "enum" => "BLUE" } } expected_query_string = 'query($string1: String!, $string2: String = "str2", $inputObject: ExampleInput!, $strings: [String!]!) { inputs(' + 'string: $string1, id: "id1", int: 1, float: 1.0, url: "<REDACTED>", enum: RED, inputObject: {' + 'string: $string2, id: "id2", int: 2, float: 2.0, url: "<REDACTED>", enum: RED, inputObject: $inputObject}) strings(strings: $strings) }' assert_equal expected_query_string, sanitize_string(query_str, variables: variables, inline_variables: false) end it "redacts from lists" do query_str_1 = '{ strings(strings: ["s1", "s2"]) }' query_str_2 = 'query($strings: [String!]!) { strings(strings: $strings) }' query_str_3 = 'query($string1: String!, $string2: String!) { strings(strings: [$string1, $string2]) }' expected_query_string = 'query { strings(strings: ["<REDACTED>", "<REDACTED>"]) }' assert_equal expected_query_string, sanitize_string(query_str_1) assert_equal expected_query_string, sanitize_string(query_str_2, variables: { "strings" => ["s1", "s2"] }) assert_equal expected_query_string, sanitize_string(query_str_3, variables: { "string1" => "s1", "string2" => "s2" }) end it "redacts from coerced lists" do query_str = ' query { strings(strings: "s1") nestedArrayInputs(inputs: {string: "s2"}) } ' expected_query_string = 'query { strings(strings: ["<REDACTED>"]) nestedArrayInputs(inputs: [{string: "<REDACTED>"}]) }' assert_equal expected_query_string, sanitize_string(query_str) end it "doesn't redact enums" do query_str_1 = '{ colors(colors: [RED, BLUE]) }' query_str_2 = 'query($colors: [Color!]!) { colors(colors: $colors) }' expected_query_string = 'query { colors(colors: [RED, BLUE]) }' assert_equal expected_query_string, sanitize_string(query_str_1) assert_equal expected_query_string, sanitize_string(query_str_2, variables: { "colors" => ["RED", "BLUE"] }) end it "redacts strings from custom scalars" do query_str_1 = ' query { s1: customScalar(scalar: "s1") s2: customScalar(scalar: 1) s3: customScalar(scalar: {string: "s2"}) s4: customScalar(scalar: [{string: "s3"}]) } ' query_str_2 = ' query($jsonString: JSON!, $jsonInt: JSON!, $jsonObject: JSON!, $jsonArray: JSON!) { s1: customScalar(scalar: $jsonString) s2: customScalar(scalar: $jsonInt) s3: customScalar(scalar: $jsonObject) s4: customScalar(scalar: $jsonArray) } ' expected_query_string = 'query { s1: customScalar(scalar: "<REDACTED>") s2: customScalar(scalar: 1) s3: customScalar(scalar: {string: "<REDACTED>"}) s4: customScalar(scalar: [{string: "<REDACTED>"}]) }' assert_equal expected_query_string, sanitize_string(query_str_1) variables = { "jsonString" => "s1", "jsonInt" => 1, "jsonObject" => { "string" => "s2" }, "jsonArray" => [{ "string" => "s3" }] } assert_equal expected_query_string, sanitize_string(query_str_2, variables: variables) end it "returns nil on invalid queries" do assert_nil sanitize_string "{ __typename " end it "provides hooks to override the redaction behavior" do query_str = ' { inputs( string: "string", id: "id", int: 1, float: 2.0, url: "http://graphqliscool.com", enum: RED inputObject: { string: "string" id: "id" int: 1 float: 2.0 url: "http://graphqliscool.com" enum: RED } ) } ' expected_query_string = 'query { inputs(' + 'string: <string-redacted>, id: <id-redacted>, int: <int-redacted>, float: <float-redacted>, url: <url-redacted>, enum: RED, inputObject: {' + 'string: <string-redacted>, id: <id-redacted>, int: <int-redacted>, float: <float-redacted>, url: <url-redacted>, enum: RED}) }' query = GraphQL::Query.new(SanitizeTest::Schema, query_str) sanitized_query = SanitizeTest::CustomSanitizedPrinter.new(query).sanitized_query_string assert_equal expected_query_string, sanitized_query end it 'configure a custom printer from the schema' do query_str = ' { inputs( string: "string", id: "id", int: 1, float: 2.0, url: "http://graphqliscool.com", enum: RED inputObject: { string: "string" id: "id" int: 1 float: 2.0 url: "http://graphqliscool.com" enum: RED } ) } ' expected_query_string = 'query { inputs(' + 'string: <string-redacted>, id: <id-redacted>, int: <int-redacted>, float: <float-redacted>, url: <url-redacted>, enum: RED, inputObject: {' + 'string: <string-redacted>, id: <id-redacted>, int: <int-redacted>, float: <float-redacted>, url: <url-redacted>, enum: RED}) }' query = GraphQL::Query.new(SanitizeTest::CustomSanitizedPrinterSchema, query_str) assert_equal expected_query_string, query.sanitized_query_string end it "properly prints enum variable default values" do class EnumSchema < GraphQL::Schema class Grouping < GraphQL::Schema::Enum value "DAY" end class Query < GraphQL::Schema::Object field :things, [String] do argument :group, Grouping end def things(group:) [group] end end query(Query) end query_string = <<~EOS query( $group: Grouping = DAY ) { things(group: $group) } EOS query = ::GraphQL::Query.new(EnumSchema, query_string) assert_equal ["DAY"], query.result["data"]["things"] expected_query_string = "query {\n things(group: DAY)\n}" assert_equal expected_query_string, query.sanitized_query_string end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/nodes_spec.rb
spec/graphql/language/nodes_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::Nodes::AbstractNode do describe ".visit_method" do # `.visit_method` is really helpful for generating methods in # custom visitor classes -- make sure this API keeps working. it "names a method on the visitor class" do node_classes = GraphQL::Language::Nodes.constants .map { |c| GraphQL::Language::Nodes.const_get(c) } .select { |obj| obj.is_a?(Class) && obj < GraphQL::Language::Nodes::AbstractNode } node_classes -= [GraphQL::Language::Nodes::WrapperType, GraphQL::Language::Nodes::NameOnlyNode] expected_classes = 35 assert_equal 35, node_classes.size tested_classes = 0 node_classes.each do |node_class| expected_method_name = "on_#{GraphQL::Schema::Member::BuildType.underscore(node_class.name.split("::").last)}" assert_equal node_class.visit_method.to_s, expected_method_name, "#{node_class} has #{expected_method_name} for visit_method" assert GraphQL::Language::Visitor.method_defined?(expected_method_name), "Visitor has ##{expected_method_name}" assert GraphQL::Language::StaticVisitor.method_defined?(expected_method_name), "Visitor has ##{expected_method_name}" tested_classes += 1 end assert_equal expected_classes, tested_classes, "All classes were tested" end end describe "Marshal" do it "marshals and unmarshals parsed ASTs" do str = "query($var: [Int!] = [100001]) { f1(arg: {input: $var, nullInput: null}) @stuff { ...F2 } } fragment F2 on SomeType { ... { someField(arg1: true, arg2: THING, arg3: 5.01234) { a @someDirective @anotherDirective @yetAnother b c } } }" doc = GraphQL.parse(str) data = Marshal.dump(doc) new_doc = Marshal.load(data) assert_equal doc, new_doc assert_equal str, doc.to_query_string assert_equal str, new_doc.to_query_string # also test schema definition nodes: str2 = Dummy::Schema.to_definition.strip doc2 = GraphQL.parse(str2) data2 = Marshal.dump(doc2) new_doc2 = Marshal.load(data2) assert_equal doc, new_doc assert_equal str2, doc2.to_query_string assert_equal str2, new_doc2.to_query_string end end describe "#filename" do it "is set after .parse_file" do filename = "spec/support/parser/filename_example.graphql" doc = GraphQL.parse_file(filename) op = doc.definitions.first field = op.selections.first arg = field.arguments.first assert_equal filename, doc.filename assert_equal filename, op.filename assert_equal filename, field.filename assert_equal filename, arg.filename end it "is null when parse from string" do doc = GraphQL.parse("{ thing }") assert_nil doc.filename end end describe "#to_query_tring" do let(:document) { GraphQL.parse('type Query { a: String! }') } let(:custom_printer_class) { Class.new(GraphQL::Language::Printer) { def print_field_definition(print_field_definition) print_string("<Field Hidden>") end } } it "accepts a custom printer" do expected = <<-SCHEMA type Query { <Field Hidden> } SCHEMA assert_equal expected.chomp, document.to_query_string(printer: custom_printer_class.new) end end describe "#dup" do it "works with adding selections" do f = GraphQL::Language::Nodes::Field.new(name: "f") # Calling `.children` may populate an internal cache assert_equal "f", f.to_query_string, "the original is unchanged" assert_equal 0, f.children.size assert_equal 0, f.selections.size f2 = f.merge(selections: [GraphQL::Language::Nodes::Field.new(name: "__typename")]) assert_equal "f", f.to_query_string, "the original is unchanged" assert_equal 0, f.children.size assert_equal 0, f.selections.size assert_equal "f {\n __typename\n}", f2.to_query_string, "the duplicate is updated" assert_equal 1, f2.children.size assert_equal 1, f2.selections.size end end describe "merge_methods" do it "generates merge methods" do classes_to_test = { GraphQL::Language::Nodes::Argument => [], GraphQL::Language::Nodes::Directive => [:merge_argument], GraphQL::Language::Nodes::DirectiveDefinition => [:merge_argument, :merge_location], GraphQL::Language::Nodes::DirectiveLocation => [], GraphQL::Language::Nodes::Document => [], GraphQL::Language::Nodes::Enum => [], GraphQL::Language::Nodes::EnumTypeDefinition => [:merge_directive, :merge_value], GraphQL::Language::Nodes::EnumTypeExtension => [:merge_directive, :merge_value], GraphQL::Language::Nodes::EnumValueDefinition => [:merge_directive], GraphQL::Language::Nodes::Field => [:merge_argument, :merge_directive, :merge_selection], GraphQL::Language::Nodes::FieldDefinition => [:merge_argument, :merge_directive], GraphQL::Language::Nodes::FragmentDefinition => [:merge_directive, :merge_selection], GraphQL::Language::Nodes::FragmentSpread => [:merge_directive], GraphQL::Language::Nodes::InlineFragment => [:merge_directive, :merge_selection], GraphQL::Language::Nodes::InputObject => [:merge_argument], GraphQL::Language::Nodes::InputObjectTypeDefinition => [:merge_directive, :merge_field], GraphQL::Language::Nodes::InputObjectTypeExtension => [:merge_directive, :merge_field], GraphQL::Language::Nodes::InputValueDefinition => [:merge_directive], GraphQL::Language::Nodes::InterfaceTypeDefinition => [:merge_directive, :merge_field, :merge_interface], GraphQL::Language::Nodes::InterfaceTypeExtension => [:merge_directive, :merge_field, :merge_interface], GraphQL::Language::Nodes::ListType => [], GraphQL::Language::Nodes::NonNullType => [], GraphQL::Language::Nodes::NullValue => [], GraphQL::Language::Nodes::ObjectTypeDefinition => [:merge_directive, :merge_field], GraphQL::Language::Nodes::ObjectTypeExtension => [:merge_directive, :merge_field], GraphQL::Language::Nodes::OperationDefinition => [:merge_directive, :merge_selection, :merge_variable], GraphQL::Language::Nodes::ScalarTypeDefinition => [:merge_directive], GraphQL::Language::Nodes::ScalarTypeExtension => [:merge_directive], GraphQL::Language::Nodes::SchemaDefinition => [:merge_directive], GraphQL::Language::Nodes::SchemaExtension => [:merge_directive], GraphQL::Language::Nodes::TypeName => [], GraphQL::Language::Nodes::UnionTypeDefinition => [:merge_directive], GraphQL::Language::Nodes::UnionTypeExtension => [:merge_directive], GraphQL::Language::Nodes::VariableDefinition => [:merge_directive], GraphQL::Language::Nodes::VariableIdentifier => [] } classes_to_test.each do |cls, expected_methods| assert cls.instance_methods.include?(:merge), "#{cls} has a merge method" assert cls.instance_methods.include?(:merge!), "#{cls} has a merge! method" assert_equal expected_methods, cls.instance_methods.select { |m| m.start_with?("merge_")}.sort, "#{cls} has the expected merge children methods" end end it "makes copies with merged children" do node_1 = GraphQL::Language::Nodes::Field.new( name: "f1", field_alias: "myField" ) node_2 = node_1 .merge_argument(name: "arg1", value: 5) .merge_directive(name: "topSecret") .merge_argument(name: "arg2", value: GraphQL::Language::Nodes::Enum.new(name: "HELLO")) .merge_selection(name: "f2", field_alias: "myOtherField") assert_equal "myField: f1", node_1.to_query_string assert_equal "myField: f1(arg1: 5, arg2: HELLO) @topSecret {\n myOtherField: f2\n}", node_2.to_query_string end end describe "manually-created AST nodes" do it "works with line and column" do node = GraphQL::Language::Nodes::Document.new( definitions: [ GraphQL::Language::Nodes::OperationDefinition.new( operation_type: "query", selections: [ GraphQL::Language::Nodes::Field.new(name: "f1"), GraphQL::Language::Nodes::FragmentSpread.new(name: "DoesntExist") ] ) ] ) assert_equal "query {\n f1\n ...DoesntExist\n}", node.to_query_string schema = GraphQL::Schema.from_definition <<-GRAPHQL type Query { f1: String } GRAPHQL result = GraphQL::StaticValidation::Validator.new(schema: schema).validate(GraphQL::Query.new(schema, nil, document: node)) expected_errs = [ { "message"=>"Fragment DoesntExist was used, but not defined", "locations"=>[{"line"=>nil, "column"=>nil}], "path"=>["query", "... DoesntExist"], "extensions"=> { "code"=>"useAndDefineFragment", "fragmentName"=>"DoesntExist" } } ] assert_equal expected_errs, result[:errors].map(&:to_h) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/generation_spec.rb
spec/graphql/language/generation_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::Generation do describe "#to_query_tring" do let(:document) { GraphQL.parse('type Query { a: String! }') } let(:custom_printer_class) { Class.new(GraphQL::Language::Printer) { def print_field_definition(print_field_definition) print_string("<Field Hidden>") end } } it "accepts a custom printer" do expected = <<-SCHEMA type Query { a: String! } SCHEMA assert_equal expected.chomp, GraphQL::Language::Generation.generate(document) end it "accepts a custom printer" do expected = <<-SCHEMA type Query { <Field Hidden> } SCHEMA assert_equal expected.chomp, GraphQL::Language::Generation.generate(document, printer: custom_printer_class.new) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/printer_spec.rb
spec/graphql/language/printer_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::Printer do let(:document) { GraphQL.parse(query_string) } let(:query_string) {%| query getStuff($someVar: Int = 1, $anotherVar: [String!] @special(very: true), $skipNested: Boolean! = false) @skip(if: false) { myField: someField(someArg: $someVar, ok: 1.4) @skip(if: $anotherVar) @thing(or: "Whatever") anotherField(someArg: [1, 2, 3]) { nestedField ...moreNestedFields @skip(if: $skipNested) } ... on OtherType @include(unless: false) { field(arg: [{key: "value", anotherKey: 0.9, anotherAnotherKey: WHATEVER}]) anotherField } ... { id } } fragment moreNestedFields on NestedType @or(something: "ok") { anotherNestedField } |} let(:printer) { GraphQL::Language::Printer.new } describe "#print" do it "prints the query string" do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end it "prints a truncated query string" do expected = query_string.gsub(/^ /, "").strip[0, 50 - GraphQL::Language::Printer::OMISSION.size] expected = "#{expected}#{GraphQL::Language::Printer::OMISSION}" assert_equal( expected, printer.print(document, truncate_size: 50), ) end describe "inputs" do let(:query_string) {%| query { field(null_value: null, null_in_array: [1, null, 3], int: 3, float: 4.7e-24, bool: false, string: "☀︎🏆\\n escaped \\" unicode ¶ /", enum: ENUM_NAME, array: [7, 8, 9], object: {a: [1, 2, 3], b: {c: "4"}}, unicode_bom: "\xef\xbb\xbfquery") } |} it "prints the query string" do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end end describe "schema" do describe "schema with convention names for root types" do let(:query_string) {<<-schema schema { query: Query mutation: Mutation subscription: Subscription } schema } it 'omits schema definition' do refute printer.print(document) =~ /schema/ end end describe "schema with custom query root name" do let(:query_string) {<<-schema schema { query: MyQuery mutation: Mutation subscription: Subscription } schema } it 'includes schema definition' do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end end describe "schema with custom mutation root name" do let(:query_string) {<<-schema schema { query: Query mutation: MyMutation subscription: Subscription } schema } it 'includes schema definition' do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end end describe "schema with custom subscription root name" do let(:query_string) {<<-schema schema { query: Query mutation: Mutation subscription: MySubscription } schema } it 'includes schema definition' do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end end describe "full featured schema" do # Based on: https://github.com/graphql/graphql-js/blob/bc96406ab44453a120da25a0bd6e2b0237119ddf/src/language/__tests__/schema-kitchen-sink.graphql let(:query_string) {<<-schema schema { query: QueryType mutation: MutationType } """ Union description """ union AnnotatedUnion @onUnion = A | B type Foo implements Bar & AnnotatedInterface { one: Type two(argument: InputType!): Type three(argument: InputType, other: String): Int four(argument: String = "string"): String five(argument: [String] = ["string", "string"]): String six(argument: InputType = {key: "value"}): Type seven(argument: String = null): Type } """ Scalar description """ scalar CustomScalar type AnnotatedObject implements Bar @onObject(arg: "value") { annotatedField(arg: Type = "default" @onArg): Type @onField } interface Bar { one: Type four(argument: String = "string"): String } """ Enum description """ enum Site { """ Enum value description """ DESKTOP MOBILE } interface AnnotatedInterface @onInterface { annotatedField(arg: Type @onArg): Type @onField } union Feed = Story | Article | Advert """ Input description """ input InputType { key: String! answer: Int = 42 } union AnnotatedUnion @onUnion = A | B scalar CustomScalar """ Directive description """ directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT scalar AnnotatedScalar @onScalar enum Site { DESKTOP MOBILE } enum AnnotatedEnum @onEnum { ANNOTATED_VALUE @onEnumValue OTHER_VALUE } input InputType { key: String! answer: Int = 42 } input AnnotatedInput @onInputObjectType { annotatedField: Type @onField } directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT schema } it "generate" do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end it "doesn't mutate the document" do assert_equal printer.print(document), printer.print(document) end end describe "schema extension" do let(:query_string) do <<-SCHEMA extend schema @onSchema { query: QueryType mutation: MutationType } extend union AnnotatedUnion @onUnion = A | B extend type Foo implements Bar @onType { one: Type two(argument: InputType!): Type } extend scalar CustomScalar @onScalar extend interface Bar @onInterface { one: Type } extend enum Site @onEnum { DESKTOP MOBILE } extend input InputType @onInputType { key: String! answer: Int = 42 } SCHEMA end it "generates correctly" do assert_equal query_string.gsub(/^ /, "").strip, printer.print(document) end end end end it "handles comments" do module MyInterface include GraphQL::Schema::Interface comment "Interface comment" end scalar = Class.new(GraphQL::Schema::Scalar) do graphql_name "DateTime" comment "Scalar comment" end query_type = Class.new(GraphQL::Schema::Object) do implements MyInterface graphql_name "Query" field :issue, Integer, comment: "Field comment" do argument :number, Integer, comment: "Argument comment" argument :date_time, scalar end def issue(number:) number end end enum_type = Class.new(GraphQL::Schema::Enum) do graphql_name "UserRole" comment "Enum comment" value "ADMIN" value "VIEWER", comment: "Enum value comment" end input_object = Class.new(GraphQL::Schema::InputObject) do graphql_name "CreateUserInput" comment "Input object comment" argument :first_name, String, comment: "Argument comment" argument :role, enum_type do comment "Argument comment" end end union = Class.new(GraphQL::Schema::Union) do graphql_name "CreateUserResponse" comment "Union comment" possible_types( Class.new(GraphQL::Schema::Object) do graphql_name "CreateUserSuccess" field :user, (Class.new(GraphQL::Schema::Object) do graphql_name "User" field :first_name, String, comment: "Field comment" end) end, Class.new(GraphQL::Schema::Object) do graphql_name "CreateUserError" comment "Object type comment" field :message, String, null: false do comment "Field comment" end end ) end mutation = Class.new(GraphQL::Schema::Mutation) do graphql_name "CreateUser" comment "Mutation comment" argument :input, input_object, comment: "Input argument comment" field :payload, union, null: false end mutation_type = Class.new(GraphQL::Schema::Object) do graphql_name "Mutation" field :create_user, mutation: mutation end schema = Class.new(GraphQL::Schema) do query(query_type) mutation(mutation_type) end expected = <<~SCHEMA.chomp # Object type comment type CreateUserError { # Field comment message: String! } # Input object comment input CreateUserInput { # Argument comment firstName: String! # Argument comment role: UserRole! } """ Autogenerated return type of CreateUser. """ type CreateUserPayload { payload: CreateUserResponse! } # Union comment union CreateUserResponse = CreateUserError | CreateUserSuccess type CreateUserSuccess { user: User } # Scalar comment scalar DateTime type Mutation { # Mutation comment createUser( # Input argument comment input: CreateUserInput! ): CreateUserPayload } # Interface comment interface MyInterface type Query implements MyInterface { # Field comment issue( dateTime: DateTime! # Argument comment number: Int! ): Int } type User { # Field comment firstName: String } # Enum comment enum UserRole { ADMIN # Enum value comment VIEWER } SCHEMA assert_equal( expected, printer.print(schema.to_document), ) end it "handles large ints" do query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :issue, Integer do argument :number, Integer end def issue(number:) number end end schema = Class.new(GraphQL::Schema) do query(query_type) end query_str = "query {\n issue(number: 9999.9e999)\n}" printed_query_str = "query {\n issue(number: Infinity)\n}" assert_equal printed_query_str, GraphQL.parse(query_str).to_query_string result = schema.execute(query_str) expected_err = "Argument 'number' on Field 'issue' has an invalid value. Expected type 'Int!'." assert_equal [expected_err], result["errors"].map { |e| e["message"] } end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/equality_spec.rb
spec/graphql/language/equality_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::Nodes::AbstractNode do describe ".eql?" do let(:document1) { GraphQL.parse(query_string1) } let(:document2) { GraphQL.parse(query_string2) } describe "large identical document" do let(:query_string1) {%| query getStuff($someVar: Int = 1, $anotherVar: [String!], $skipNested: Boolean! = false) @skip(if: false) { myField: someField(someArg: $someVar, ok: 1.4) @skip(if: $anotherVar) @thing(or: "Whatever") anotherField(someArg: [1, 2, 3]) { nestedField ...moreNestedFields @skip(if: $skipNested) } ... on OtherType @include(unless: false) { field(arg: [{ key: "value", anotherKey: 0.9, anotherAnotherKey: WHATEVER }]) anotherField } ... { id } } fragment moreNestedFields on NestedType @or(something: "ok") { anotherNestedField } |} let(:query_string2) { query_string1 } it "should be equal" do assert document1 == document2 assert document2 == document1 end end describe "different operations" do let(:query_string1) { "query { field }" } let(:query_string2) { "mutation { setField }" } it "should not be equal" do refute document1 == document2 refute document2 == document1 end end describe "different query fields" do let(:query_string1) { "query { foo }" } let(:query_string2) { "query { bar }" } it "should not be equal" do refute document1 == document2 refute document2 == document1 end end describe "different schemas" do let(:query_string1) {%| schema { query: Query } type Query { field: String! } |} let(:query_string2) {%| schema { query: Query } type Query { field: Int! } |} it "should not be equal" do refute document1.eql?(document2) refute document2.eql?(document1) end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/parser_spec.rb
spec/graphql/language/parser_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::Parser do subject { GraphQL } it "returns an error on bad UTF-8" do err = assert_raises GraphQL::ParseError do subject.parse("{ foo(query: \"\xBF\") }") end expected_message = if USING_C_PARSER 'Parse error on bad Unicode escape sequence: "{ foo(query: \"\xBF\") }" (error) at [1, 1]' else 'Parse error on bad Unicode escape sequence' end assert_equal expected_message, err.message end it "rejects newlines in single-quoted strings unless escaped" do nl_query_string_1 = "{ doStuff(arg: \" abc\") }" nl_query_string_2 = "{ doStuff(arg: \"\rabc\") }" assert_raises(GraphQL::ParseError) { GraphQL.parse(nl_query_string_2) } assert_raises(GraphQL::ParseError) { GraphQL.parse(nl_query_string_2) } assert GraphQL.parse(GraphQL::Language.escape_single_quoted_newlines(nl_query_string_1)) assert GraphQL.parse(GraphQL::Language.escape_single_quoted_newlines(nl_query_string_2)) example_query_str = "mutation { createRecord(data: { dynamicFields: { string_test: \"avenue 1st 2nd line\"} }) { id, dynamicFields } }" assert_raises GraphQL::ParseError do GraphQL.parse(example_query_str) end escaped_query_str = GraphQL::Language.escape_single_quoted_newlines(example_query_str) expected_escaped_query_str = "mutation { createRecord(data: { dynamicFields: { string_test: \"avenue 1st\\n2nd line\"} }) { id, dynamicFields } }" assert_equal expected_escaped_query_str, escaped_query_str assert GraphQL.parse(escaped_query_str ) end it "parses single-quoted strings with escaped newlines" do example_query_str = 'mutation { createRecord(data: { dynamicFields: { string_test: "avenue 1st\n2nd line"} }) { id, dynamicFields } }' assert GraphQL.parse(example_query_str) end it "can replace single-quoted newlines" do replacements = { "{ a(\"\n abc\n\") }" => '{ a("\\n abc\\n") }', "{ a(\"\r\n ab\rc\n\") }" => '{ a("\\r\\n ab\\rc\\n") }', "{ a(\"\n abc\n\") b(\"\n \\\"abc\n\") }" => '{ a("\\n abc\\n") b("\\n \\"abc\\n") }', # No modification to block strings: "{ a(\"\"\"\n abc\n\"\"\") }" => "{ a(\"\"\"\n abc\n\"\"\") }", "{ a(\"\"\"\r\n abc\r\n\"\"\") }" => "{ a(\"\"\"\r\n abc\r\n\"\"\") }", } replacements.each_with_index do |(before_str, after_str), idx| assert_equal after_str, GraphQL::Language.escape_single_quoted_newlines(before_str), "It works for example pair ##{idx + 1} (#{after_str})" end end it "can parse strings with null bytes" do assert GraphQL.parse("{ a(b: \"\\u0000\") }") end it "raises a parse error when there's a dangling close curly brace" do assert_raises(GraphQL::ParseError) { GraphQL.parse('{ foo } }') } end it "raises a parse error when there's a dangling identifier" do assert_raises(GraphQL::ParseError) { GraphQL.parse('{ foo } fooagain') } end it "raises a parse error for invalid type modification on inline fragment spread" do assert_raises(GraphQL::ParseError) { GraphQL.parse("{ ... on Foo! { id } }") } end it "raises a parse error for invalid type modification on fragment definition" do assert_raises(GraphQL::ParseError) { GraphQL.parse("fragment on Foo! { id }") } end describe "when there are no selections" do it 'raises a ParseError' do assert_raises(GraphQL::ParseError) { GraphQL.parse('# comment') } end end it "parses directives on variable definitions" do ast = GraphQL.parse("query($var: Int = 1 @special) { do(something: $var) }") assert_equal ["special"], ast.definitions.first.variables.first.directives.map(&:name) end it "allows fragments, fields and arguments named null" do assert GraphQL.parse("{ field(null: false) ... null } fragment null on Query { null }") end it "allows fields, arguments, and enum values named on and directive" do assert GraphQL.parse("{ on(on: on) directive(directive: directive)}") end it "allows fields, arguments, and enum values named extend" do assert GraphQL.parse("{ extend(extend: extend) }") end it "allows fields, arguments, and enum values named type" do doc = GraphQL.parse("{ type(type: type) }") assert_instance_of GraphQL::Language::Nodes::Enum, doc.definitions.first.selections.first.arguments.first.value end it "handles invalid minus signs" do err = assert_raises GraphQL::ParseError do GraphQL.parse("{ a(b: -c) }") end expected_message = if USING_C_PARSER "syntax error, unexpected invalid token (\"-\") at [1, 8]" else "Expected type 'number', but it was malformed: \"-c\"." end assert_equal expected_message, err.message end it "handles invalid minus signs in variable default values" do err = assert_raises GraphQL::ParseError do GraphQL.parse("query($something: Int = -foo) { }") end expected_message = if USING_C_PARSER "syntax error, unexpected invalid token (\"-\") at [1, 25]" else "Expected type 'number', but it was malformed: \"-foo\"." end assert_equal expected_message, err.message end it "handles invalid minus signs in deeply nested input objects" do err = assert_raises GraphQL::ParseError do GraphQL.parse("{ doSomething(a: { b: { c: { d: -foo } } }) }") end expected_message = if USING_C_PARSER "syntax error, unexpected invalid token (\"-\") at [1, 33]" else "Expected type 'number', but it was malformed: \"-foo\"." end assert_equal expected_message, err.message end it "handles invalid minus signs in schema definitions" do err = assert_raises GraphQL::ParseError do GraphQL.parse(" type Query { someField(a: Int = -foo): Int } ") end expected_message = if USING_C_PARSER "syntax error, unexpected invalid token (\"-\") at [3, 28]" else "Expected type 'number', but it was malformed: \"-foo\"." end assert_equal expected_message, err.message end it "handles invalid minus signs in list literals" do err = assert_raises GraphQL::ParseError do GraphQL.parse("{ a1: a(b: [1,2,3]) a2: a(b: [1, 2, -foo]) }") end expected_message = if USING_C_PARSER "syntax error, unexpected invalid token (\"-\") at [3, 25]" else "Expected type 'number', but it was malformed: \"-foo\"." end assert_equal expected_message, err.message end it "allows operation names to match operation types" do doc = GraphQL.parse("query subscription { foo }") assert_equal "subscription", doc.definitions.first.name end it "raises an error for bad variables definition" do err = assert_raises(GraphQL::ParseError) do GraphQL.parse("query someQuery($someVariable: ,) { account { id } }") end expected_msg = if USING_C_PARSER "syntax error, unexpected RPAREN (\")\") at [1, 33]" else "Missing type definition for variable: $someVariable at [1, 33]" end assert_equal expected_msg, err.message end it "raises an error when unicode is used as names" do err = assert_raises(GraphQL::ParseError) { GraphQL.parse('query 😘 { a b }') } expected_msg = if USING_C_PARSER "syntax error, unexpected invalid token (\"\\xF0\"), expecting LCURLY at [1, 7]" else "Expected NAME, actual: UNKNOWN_CHAR (\"\\xF0\") at [1, 7]" end assert_equal expected_msg, err.message end it "can reject name start at the end of numbers" do prev_reject_numers_followed_by_names = GraphQL.reject_numbers_followed_by_names GraphQL.reject_numbers_followed_by_names = false assert GraphQL.parse("{ a(b: 123cde: 456)}"), "It accepts invalid constructions ... for now" GraphQL.reject_numbers_followed_by_names = true err = assert_raises GraphQL::ParseError do GraphQL.parse("{ a(b: 123cde: 456)}") end assert_equal "Name after number is not allowed (in `123cde`)", err.message err = assert_raises GraphQL::ParseError do GraphQL.parse("{ a(b: 12.3e5cfg: 456)}") end assert_equal "Name after number is not allowed (in `12.3e5cfg`)", err.message err2 = assert_raises GraphQL::ParseError do GraphQL.parse("query($input: SomeInput = { i1: 12i2: 15}) { t }") end assert_equal "Name after number is not allowed (in `12i2`)", err2.message ensure GraphQL.reject_numbers_followed_by_names = prev_reject_numers_followed_by_names end it "can replace namestart at the end of numbers" do expected_transforms = { "{ a(b: 123cde: 456)}" => "{ a(b: 123 cde: 456)}", "{ a(b: 12.3e5cde: 456)}" => "{ a(b: 12.3e5 cde: 456)}", "{ a(b: 123e56cde: 456)}" => "{ a(b: 123e56 cde: 456)}", "{ a(b: 123e5) }" => nil, "{ a(b: 123e5 ) }" => nil, "{ a(b: 12.3e5) }" => nil, "{ a(b: 12.3e5 ) }" => nil, "query($obj: Input = { a: 1e5b: 2c: 3e-1}) { t }" => "query($obj: Input = { a: 1e5 b: 2 c: 3e-1}) { t }" , } expected_transforms.each do |(start_str, finish_str)| changed_str = GraphQL::Language.add_space_between_numbers_and_names(start_str) if finish_str.nil? assert start_str.equal?(changed_str), "#{start_str.inspect} is unchanged (was: #{changed_str.inspect})" else assert_equal finish_str, changed_str, "Expected #{start_str.inspect} to become #{finish_str.inspect}" assert_equal finish_str, GraphQL::Language.add_space_between_numbers_and_names(finish_str), "Expected #{finish_str.inspect} not to change" end end end it "handles hyphens with errors" do err = assert_raises(GraphQL::ParseError) { GraphQL.parse("{ field(argument:a-b) }") } expected_msg = if USING_C_PARSER "syntax error, unexpected invalid token (\"-\") at [1, 19]" else "Expected type 'number', but it was malformed: \"-b\"." end assert_equal expected_msg, err.message end describe "anonymous fragment extension" do let(:document) { GraphQL.parse(query_string) } let(:query_string) {%| fragment on NestedType @or(something: "ok") { anotherNestedField } |} let(:fragment) { document.definitions.first } it "creates an anonymous fragment definition" do assert fragment.is_a?(GraphQL::Language::Nodes::FragmentDefinition) assert_nil fragment.name assert_equal 1, fragment.selections.length assert_equal "NestedType", fragment.type.name assert_equal 1, fragment.directives.length assert_equal [2, 7], fragment.position end end describe "string description" do it "is parsed for scalar definitions" do document = subject.parse <<-GRAPHQL "Thing description" scalar Thing GRAPHQL thing_defn = document.definitions[0] assert_equal "Thing", thing_defn.name assert_equal "Thing description", thing_defn.description end it "is parsed for object definitions, field definitions, and input value definitions" do document = subject.parse <<-GRAPHQL "Thing description" type Thing { "field description" field("arg description" arg: Stuff @yikes): Stuff @wow } GRAPHQL thing_defn = document.definitions[0] assert_equal "Thing", thing_defn.name assert_equal "Thing description", thing_defn.description field_defn = thing_defn.fields[0] assert_equal "field", field_defn.name assert_equal "field description", field_defn.description assert_equal ["wow"], field_defn.directives.map(&:name) arg_defn = field_defn.arguments[0] assert_equal "arg", arg_defn.name assert_equal "arg description", arg_defn.description assert_equal ["yikes"], arg_defn.directives.map(&:name) end it "is parsed for interface definitions" do document = subject.parse <<-GRAPHQL "Thing description" interface Thing {} GRAPHQL thing_defn = document.definitions[0] assert_equal "Thing", thing_defn.name assert_equal "Thing description", thing_defn.description end it "is parsed for union definitions" do document = subject.parse <<-GRAPHQL "Thing description" union Thing = Int | String GRAPHQL thing_defn = document.definitions[0] assert_equal "Thing", thing_defn.name assert_equal "Thing description", thing_defn.description end it "is parsed for enum definitions and enum value definitions" do document = subject.parse <<-GRAPHQL "Thing description" enum Thing { "VALUE description" VALUE type } GRAPHQL thing_defn = document.definitions[0] assert_equal "Thing", thing_defn.name assert_equal "Thing description", thing_defn.description value_defn = thing_defn.values[0] assert_equal "VALUE", value_defn.name assert_equal "VALUE description", value_defn.description value_defn = thing_defn.values[1] assert_equal "type", value_defn.name assert_nil value_defn.description end it "is parsed for directive definitions" do document = subject.parse <<-GRAPHQL "thing description" directive @thing repeatable on FIELD GRAPHQL thing_defn = document.definitions[0] assert_equal "thing", thing_defn.name assert_equal true, thing_defn.repeatable assert_equal "thing description", thing_defn.description end end it "parses query without arguments" do strings = [ "{ field { inner } }" ] strings.each do |query_str| doc = subject.parse(query_str) field = doc.definitions.first.selections.first assert_equal 0, field.arguments.length assert_equal 1, field.selections.length end end it "parses backslashes in arguments" do document = subject.parse <<-GRAPHQL query { item(text: "a", otherText: "b\\\\") { text otherText } } GRAPHQL assert_equal "b\\", document.definitions[0].selections[0].arguments[1].value end it "parses backslashes in non-last arguments" do document = subject.parse <<-GRAPHQL query { item(text: "b\\\\", otherText: "a") { text otherText } } GRAPHQL assert_equal "b\\", document.definitions[0].selections[0].arguments[0].value end it "parses a great big object type" do str = <<-GRAPHQL """ Query root of the system """ type Query { allAnimal: [Animal]! allAnimalAsCow: [AnimalAsCow]! allDairy(executionErrorAtIndex: Int): [DairyProduct] allEdible: [Edible] allEdibleAsMilk: [EdibleAsMilk] """ Find a Dummy::Cheese by id """ cheese(id: Int!): Cheese """ Find the only Dummy::Cow """ cow: Cow """ Find the only Dummy::Dairy """ dairy: Dairy deepNonNull: DeepNonNull! """ Raise an error """ error: String executionError: String executionErrorWithExtensions: Int executionErrorWithOptions: Int """ My favorite food """ favoriteEdible: Edible """ Cheese from source """ fromSource(oldSource: String @deprecated, source: DairyAnimal = COW): [Cheese] hugeInteger: Int maybeNull: MaybeNull """ Find a Dummy::Milk by id """ milk(id: ID!): Milk multipleErrorsOnNonNullableField: String! multipleErrorsOnNonNullableListField: [String!]! root: String """ Find dairy products matching a description """ searchDairy(expiresAfter: Time, oldProduct: [DairyProductInput!] @deprecated, product: [DairyProductInput] = [{source: SHEEP}], productIds: [String!] @deprecated, singleProduct: DairyProductInput): DairyProduct! tracingScalar: TracingScalar valueWithExecutionError: Int! } GRAPHQL doc = subject.parse(str) assert_equal str.chomp, doc.to_query_string end it "parses input types" do doc = subject.parse <<~GRAPHQL input ReplaceValuesInput { values: [Int!]! } GRAPHQL input_t = doc.definitions.first assert_equal "ReplaceValuesInput", input_t.name assert_equal ["values"], input_t.fields.map(&:name) assert_equal [nil], input_t.fields.map(&:description) end it "parses the test schema" do schema = Dummy::Schema schema_string = GraphQL::Schema::Printer.print_schema(schema) document = subject.parse(schema_string) assert_equal schema_string.chomp, document.to_query_string end it "parses various implements" do doc = subject.parse <<-GRAPHQL type Milk implements AnimalProduct & Edible & EdibleAsMilk & LocalProduct { executionError: String } GRAPHQL expected_names = ["AnimalProduct", "Edible", "EdibleAsMilk", "LocalProduct"] assert_equal expected_names, doc.definitions.first.interfaces.map(&:name) doc2 = subject.parse <<-GRAPHQL type Milk implements & AnimalProduct & Edible & EdibleAsMilk & LocalProduct { executionError: String } GRAPHQL assert_equal expected_names, doc2.definitions.first.interfaces.map(&:name) doc3 = subject.parse <<-GRAPHQL type Milk implements AnimalProduct, Edible, EdibleAsMilk LocalProduct { executionError: String } GRAPHQL assert_equal expected_names, doc3.definitions.first.interfaces.map(&:name) end it "parses union types with leading pipes" do doc = subject.parse("union U =\n | A\n | B") assert_equal ["A", "B"], doc.definitions.first.types.map(&:name) end describe "parse errors" do it "raises parse errors for nil" do assert_raises(GraphQL::ParseError) { GraphQL.parse(nil) } end it 'raises parse errors for empty argument sets' do # Regression spec from https://github.com/rmosolgo/graphql-ruby/pull/2344 query_with_empty_arguments = '{ node() { id } }' assert_raises(GraphQL::ParseError) { subject.parse(query_with_empty_arguments) } end it 'raises parse errors for argument sets without value' do # Regression spec from https://github.com/rmosolgo/graphql-ruby/pull/2344 query_with_malformed_argument_value = '{ node(id:) { name } }' assert_raises(GraphQL::ParseError) { pp subject.parse(query_with_malformed_argument_value) } end end describe ".parse_file" do it "assigns filename to all nodes" do example_filename = "spec/support/parser/filename_example.graphql" doc = GraphQL.parse_file(example_filename) assert_equal example_filename, doc.filename field = doc.definitions[0].selections[0].selections[0] assert_equal example_filename, field.filename end it "raises errors with filename" do error_filename = "spec/support/parser/filename_example_error_1.graphql" err = assert_raises(GraphQL::ParseError) { GraphQL.parse_file(error_filename) } assert_includes err.message, error_filename error_filename_2 = "spec/support/parser/filename_example_error_2.graphql" err_2 = assert_raises(GraphQL::ParseError) { GraphQL.parse_file(error_filename_2) } assert_includes err_2.message, error_filename_2 assert_includes err_2.message, "3, 11" end end describe "#tokens_count" do it "counts parsed token" do str = "type Query { f1: Int }" parser = GraphQL::Language::Parser.new(str) assert_equal 7, parser.tokens_count end end module ParserTrace TRACES = [] def parse(query_string:) TRACES << (trace = { key: "parse", query_string: query_string }) result = super trace[:result] = result result end def lex(query_string:) TRACES << (trace = { key: "lex", query_string: query_string }) result = super trace[:result] = result result end def self.clear TRACES.clear end def self.traces TRACES end end it "serves traces" do ParserTrace.clear schema = Class.new(GraphQL::Schema) do trace_with(ParserTrace) end query = GraphQL::Query.new(schema, "{ t: __typename }") subject.parse("{ t: __typename }", trace: query.current_trace) traces = ParserTrace.traces expected_traces = if USING_C_PARSER 2 else 1 end assert_equal expected_traces, traces.length lex_trace, parse_trace = traces if USING_C_PARSER assert_equal "{ t: __typename }", lex_trace[:query_string] assert_equal "lex", lex_trace[:key] assert_instance_of Array, lex_trace[:result] else parse_trace = lex_trace end assert_equal "{ t: __typename }", parse_trace[:query_string] assert_equal "parse", parse_trace[:key] assert_instance_of GraphQL::Language::Nodes::Document, parse_trace[:result] end it "returns a parse error for var types without type names" do err = assert_raises GraphQL::ParseError do GraphQL.parse <<-GRAPHQL query GetStuff($things: []) { stuff } GRAPHQL end expected_message = if USING_C_PARSER "syntax error, unexpected RBRACKET (\"]\") at [1, 34]" else "Missing type definition for variable: $things at [1, 35]" end assert_equal expected_message, err.message err = assert_raises GraphQL::ParseError do GraphQL.parse <<-GRAPHQL query GetStuff($things: !) { stuff } GRAPHQL end expected_message = if USING_C_PARSER "syntax error, unexpected BANG (\"!\") at [1, 33]" else "Missing type definition for variable: $things at [1, 33]" end assert_equal expected_message, err.message end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/clexer_spec.rb
spec/graphql/language/clexer_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./lexer_examples" if defined?(GraphQL::CParser::Lexer) describe GraphQL::CParser::Lexer do subject { GraphQL::CParser::Lexer } def assert_bad_unicode(string, _message = nil) assert_equal :BAD_UNICODE_ESCAPE, subject.tokenize(string).first[0] end it "makes tokens like the other lexer" do str = "{ f1(type: \"str\") ...F2 }\nfragment F2 on SomeType { f2 }" tokens = GraphQL.scan_with_c(str).map { |t| [*t.first(4), t[3].encoding] } old_tokens = GraphQL.scan_with_ruby(str).map { |t| [*t, t[3].encoding] } assert_equal [ [:LCURLY, 1, 1, "{", Encoding::UTF_8], [:IDENTIFIER, 1, 3, "f1", Encoding::UTF_8], [:LPAREN, 1, 5, "(", Encoding::UTF_8], [:TYPE, 1, 6, "type", Encoding::UTF_8], [:COLON, 1, 10, ":", Encoding::UTF_8], [:STRING, 1, 12, "str", Encoding::UTF_8], [:RPAREN, 1, 17, ")", Encoding::UTF_8], [:ELLIPSIS, 1, 19, "...", Encoding::UTF_8], [:IDENTIFIER, 1, 22, "F2", Encoding::UTF_8], [:RCURLY, 1, 25, "}", Encoding::UTF_8], [:FRAGMENT, 2, 1, "fragment", Encoding::UTF_8], [:IDENTIFIER, 2, 10, "F2", Encoding::UTF_8], [:ON, 2, 13, "on", Encoding::UTF_8], [:IDENTIFIER, 2, 16, "SomeType", Encoding::UTF_8], [:LCURLY, 2, 25, "{", Encoding::UTF_8], [:IDENTIFIER, 2, 27, "f2", Encoding::UTF_8], [:RCURLY, 2, 30, "}", Encoding::UTF_8] ], tokens assert_equal(old_tokens, tokens) end it "makes frozen strings when using SchemaParser" do str = "type Query { f1: Int }" schema_ast = GraphQL::CParser::SchemaParser.new(str, nil, GraphQL::Tracing::NullTrace, nil).result default_ast = GraphQL::CParser::Parser.new(str, nil, GraphQL::Tracing::NullTrace, nil).result # Equivalent ASTs: assert_equal schema_ast, default_ast # But this one is frozen: assert_equal "Query", schema_ast.definitions.first.name assert schema_ast.definitions.first.name.frozen? # And this one isn't: assert_equal "Query", default_ast.definitions.first.name refute default_ast.definitions.first.name.frozen? end it "exposes tokens_count" do str = "type Query { f1: Int }" parser = GraphQL::CParser::Parser.new(str, nil, GraphQL::Tracing::NullTrace, nil) assert_equal 7, parser.tokens_count end include LexerExamples end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/lexer_spec.rb
spec/graphql/language/lexer_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./lexer_examples" describe GraphQL::Language::Lexer do subject { GraphQL::Language::Lexer } include LexerExamples def assert_bad_unicode(string, expected_err_message = "Parse error on bad Unicode escape sequence") err = assert_raises(GraphQL::ParseError) do subject.tokenize(string) end assert_equal expected_err_message, err.message end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/language/lexer_examples.rb
spec/graphql/language/lexer_examples.rb
# frozen_string_literal: true module TokenMethods refine Array do def name self[0] end def value self[3] end def to_s self[3] end def line self[1] end def col self[2] end def inspect "(#{name} #{value.inspect} [#{line}:#{col}])" end end end using TokenMethods module LexerExamples def self.included(child_mod) child_mod.module_eval do describe ".tokenize" do let(:query_string) {%| { query getCheese { cheese(id: 1) { ... cheeseFields } } } |} let(:tokens) { subject.tokenize(query_string) } it "force encodes to utf-8" do # string that will be invalid utf-8 once force encoded string = "vandflyver \xC5rhus".dup.force_encoding("ASCII-8BIT") assert_bad_unicode(string) end it "makes utf-8 arguments named type" do str = "{ a(type: 1) }" tokens = subject.tokenize(str) assert_equal Encoding::UTF_8, tokens[2].value.encoding end it "handles integers with a leading zero" do tokens = subject.tokenize("{ a(id: 04) }") assert_equal :INT, tokens[5].name end it "allows escaped quotes in strings" do tokens = subject.tokenize('"a\\"b""c"') assert_equal 'a"b', tokens[0].value assert_equal 'c', tokens[1].value end it "handles escaped backslashes before escaped quotes" do tokens = subject.tokenize('text: "b\\\\", otherText: "a"') assert_equal ['text', ':', 'b\\', 'otherText', ':', 'a',], tokens.map(&:value) end describe "block strings" do let(:query_string) { %|{ a(b: """\nc\n \\""" d\n""" """""e""""")}|} it "tokenizes them" do assert_equal "c\n \\\"\"\" d", tokens[5].value assert_equal "\"\"e\"\"", tokens[6].value end it "tokenizes 10 quote edge case correctly" do tokens = subject.tokenize('""""""""""') assert_equal '""', tokens[0].value # first 8 quotes are a valid block string """""""" assert_equal '', tokens[1].value # last 2 quotes are a valid string "" end it "tokenizes with nested single quote strings correctly" do tokens = subject.tokenize('"""{"x"}"""') assert_equal '{"x"}', tokens[0].value tokens = subject.tokenize('"""{"foo":"bar"}"""') assert_equal '{"foo":"bar"}', tokens[0].value end it "tokenizes empty block strings correctly" do empty_block_string = '""""""' tokens = subject.tokenize(empty_block_string) assert_equal '', tokens[0].value end it "tokenizes escaped backslashes at the end of blocks" do query_str = <<-GRAPHQL text: """b\\\\""", otherText: "a" GRAPHQL tokens = subject.tokenize(query_str) assert_equal ['text', ':', 'b\\\\', 'otherText', ':', 'a',], tokens.map(&:value) end end it "unescapes escaped characters" do assert_equal "\" \\ / \b \f \n \r \t", subject.tokenize('"\\" \\\\ \\/ \\b \\f \\n \\r \\t"').first.to_s end it "unescapes escaped unicode characters" do assert_equal "\t", subject.tokenize('"\\u0009"').first.to_s assert_equal "\t", subject.tokenize('"\\u{0009}"').first.to_s assert_equal "𐘑", subject.tokenize('"\\u{10611}"').first.to_s assert_equal "💩", subject.tokenize('"\\u{1F4A9}"').first.to_s assert_equal "💩", subject.tokenize('"\\uD83D\\uDCA9"').first.to_s end it "accepts the full range of unicode" do assert_equal "💩", subject.tokenize('"💩"').first.to_s assert_equal "⌱", subject.tokenize('"⌱"').first.to_s assert_equal "🂡\n🂢", subject.tokenize('"""🂡 🂢"""').first.to_s end it "doesn't accept unicode outside strings or comments" do assert_equal :UNKNOWN_CHAR, subject.tokenize('😘 ').first.name end it "rejects bad unicode, even when there's good unicode in the string" do assert_bad_unicode('"\\u0XXF \\u0009"', "Bad unicode escape in \"\\\\u0XXF \\\\u0009\"") end it "rejects truly invalid UTF-8 bytes" do error_filename = "spec/support/parser/filename_example_invalid_utf8.graphql" text = File.read(error_filename) assert_bad_unicode(text) end it "rejects unicode that's well-formed but results in invalidly-encoded strings" do # when the string here gets tokenized into an actual `:STRING`, it results in `valid_encoding?` being false for # the ruby string so application code usually blows up trying to manipulate it text1 = '"\\udc00\\udf2c"' assert_bad_unicode(text1, 'Bad unicode escape in "\\xED\\xB0\\x80\\xED\\xBC\\xAC"') text2 = '"\\u{dc00}\\u{df2c}"' assert_bad_unicode(text2, 'Bad unicode escape in "\\xED\\xB0\\x80\\xED\\xBC\\xAC"') end it "counts string position properly" do tokens = subject.tokenize('{ a(b: "c")}') str_token = tokens[5] assert_equal :STRING, str_token.name assert_equal "c", str_token.value assert_equal 8, str_token.col assert_equal '(STRING "c" [1:8])', str_token.inspect rparen_token = tokens[6] assert_equal '(RPAREN ")" [1:11])', rparen_token.inspect end it "tokenizes block quotes with triple quotes correctly" do doc = <<-eos """ string with \\""" """ eos tokens = subject.tokenize doc token = tokens.first assert_equal :STRING, token.name assert_equal 'string with \"""', token.value end it "counts block string line properly" do str = <<-GRAPHQL """ Here is a multiline description """ type Query { a: B } "Here's another description" type B { a: B } """ And another multiline description """ type C { a: B } GRAPHQL tokens = subject.tokenize(str) string_tok, type_keyword_tok, query_name_tok, _curly, _ident, _colon, _ident, _curly, string_tok_2, type_keyword_tok_2, b_name_tok, _curly, _ident, _colon, _ident, _curly, string_tok_3, type_keyword_tok_3, c_name_tok = tokens assert_equal 1, string_tok.line assert_equal 5, type_keyword_tok.line assert_equal 5, query_name_tok.line # Make sure it handles the empty spaces, too assert_equal 9, string_tok_2.line assert_equal 11, type_keyword_tok_2.line assert_equal 11, b_name_tok.line assert_equal 15, string_tok_3.line assert_equal 21, type_keyword_tok_3.line assert_equal 21, c_name_tok.line end it "halts after max_tokens" do query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :x, Integer end parent_schema = Class.new(GraphQL::Schema) do query(query_type) end child_schema = Class.new(parent_schema) do max_query_string_tokens(5000) end assert_nil parent_schema.max_query_string_tokens assert_equal 5000, child_schema.max_query_string_tokens query_str = 3_000.times.map { |n| "query Q#{n} { __typename }" }.join("\n") assert_equal 15_000, subject.tokenize(query_str).size assert GraphQL.parse(query_str) result = child_schema.execute(query_str) assert_equal ["This query is too large to execute."], result["errors"].map { |e| e["message"] } result2 = parent_schema.execute(query_str) assert_equal ["An operation name is required"], result2["errors"].map { |e| e["message"] } end end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/visibility_spec.rb
spec/graphql/schema/visibility_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Visibility do class VisSchema < GraphQL::Schema class BaseField < GraphQL::Schema::Field def initialize(*args, admin_only: false, **kwargs, &block) super(*args, **kwargs, &block) @admin_only = admin_only end def visible?(ctx) super && (@admin_only ? !!ctx[:is_admin] : true) end end class BaseObject < GraphQL::Schema::Object field_class(BaseField) def self.visible?(ctx) (@admin_only ? !!ctx[:is_admin] : true) && super end def self.admin_only(new_value = nil) if new_value.nil? @admin_only else @admin_only = new_value end end end class Product < BaseObject field :name, String field :price, Integer field :cost_of_goods_sold, Integer, admin_only: true end class Widget < BaseObject admin_only(true) field :name, String end class WidgetKind < GraphQL::Schema::Enum value :FOO value :BAR end class Query < BaseObject field :products, [Product] field :widget, Widget do argument :type, WidgetKind end def products [{ name: "Pool Noodle", price: 100, cost_of_goods_sold: 5 }] end end query(Query) use GraphQL::Schema::Visibility, profiles: { public: {}, admin: { is_admin: true } }, preload: true end class DynVisSchema < VisSchema use GraphQL::Schema::Visibility, profiles: { public: {}, admin: {} }, dynamic: true, preload: false end class PreloadDynVisSchema < VisSchema use GraphQL::Schema::Visibility, profiles: { public: {}, admin: {} }, dynamic: true, preload: true end def exec_query(...) VisSchema.execute(...) end describe "top-level schema caches" do it "re-uses results" do assert_equal DynVisSchema.types.object_id, DynVisSchema.types.object_id assert_equal PreloadDynVisSchema.types.object_id, PreloadDynVisSchema.types.object_id end end it "hides unused arguments" do schema_sdl = VisSchema.to_definition(context: { visibility_profile: :public }) refute_includes schema_sdl, "WidgetKind" end describe "running queries" do it "requires context[:visibility]" do err = assert_raises ArgumentError do exec_query("{ products { name } }") end expected_msg = "VisSchema expects a visibility profile, but `visibility_profile:` wasn't passed. Provide a `visibility_profile:` value or add `dynamic: true` to your visibility configuration." assert_equal expected_msg, err.message end it "requires a context[:visibility] which is on the list" do err = assert_raises ArgumentError do exec_query("{ products { name } }", visibility_profile: :nonsense ) end expected_msg = "`:nonsense` isn't allowed for `visibility_profile:` (must be one of :public, :admin). Or, add `:nonsense` to the list of profiles in the schema definition." assert_equal expected_msg, err.message end it "permits `nil` when nil is on the list" do res = DynVisSchema.execute("{ products { name } }") assert_equal 1, res["data"]["products"].size assert_nil res.context.types.name assert_equal [], DynVisSchema.visibility.cached_profiles.keys end it "uses the named visibility" do res = exec_query("{ products { name } }", visibility_profile: :public) assert_equal ["Pool Noodle"], res["data"]["products"].map { |p| p["name"] } assert_equal :public, res.context.types.name assert res.context.types.equal?(VisSchema.visibility.cached_profiles[:public]), "It uses the cached instance" res = exec_query("{ products { costOfGoodsSold } }", visibility_profile: :public) assert_equal ["Field 'costOfGoodsSold' doesn't exist on type 'Product'"], res["errors"].map { |e| e["message"] } res = exec_query("{ products { name costOfGoodsSold } }", visibility_profile: :admin) assert_equal [{ "name" => "Pool Noodle", "costOfGoodsSold" => 5}], res["data"]["products"] end it "works with subclasses" do child_schema = Class.new(VisSchema) do query(VisSchema::Query) end res = child_schema.execute("{ products { name } }", visibility_profile: :public) assert_equal ["Pool Noodle"], res["data"]["products"].map { |p| p["name"] } assert_equal :public, res.context.types.name end end describe "preloading profiles" do it "preloads when true" do assert_equal [:public, :admin], VisSchema.visibility.cached_profiles.keys, "preload: true" assert_equal 0, DynVisSchema.visibility.cached_profiles.size, "preload: false" end describe "when no profile is defined" do class NoProfileSchema < GraphQL::Schema class ExampleExtension < GraphQL::Schema::FieldExtension; end class OtherExampleExtension < GraphQL::Schema::FieldExtension; end class Query < GraphQL::Schema::Object field :str do type(String) extension(ExampleExtension) end end class Mutation < GraphQL::Schema::Object field :str do type(String) extension(ExampleExtension) end end class Subscription < GraphQL::Schema::Object field :str do type(String) extension(ExampleExtension) end end class OrphanType < GraphQL::Schema::Object field :str do type(String) extension(ExampleExtension) extension(OtherExampleExtension) end end # This one is added before `Visibility` subscription(Subscription) use GraphQL::Schema::Visibility, preload: true query { Query } mutation { Mutation } orphan_types(OrphanType) module CustomIntrospection class DynamicFields < GraphQL::Introspection::DynamicFields field :__hello do type(String) extension(OtherExampleExtension) end end end end it "still preloads" do assert_equal [NoProfileSchema::ExampleExtension], NoProfileSchema::Query.all_field_definitions.first.extensions.map(&:class) assert_equal [NoProfileSchema::ExampleExtension], NoProfileSchema::Mutation.all_field_definitions.first.extensions.map(&:class) assert_equal [NoProfileSchema::ExampleExtension], NoProfileSchema::Subscription.all_field_definitions.first.extensions.map(&:class) assert_equal [NoProfileSchema::ExampleExtension, NoProfileSchema::OtherExampleExtension], NoProfileSchema::OrphanType.all_field_definitions.first.extensions.map(&:class) custom_int_field = NoProfileSchema::CustomIntrospection::DynamicFields.all_field_definitions.find { |f| f.original_name == :__hello } assert_equal [], custom_int_field.extensions NoProfileSchema.introspection(NoProfileSchema::CustomIntrospection) assert_equal [NoProfileSchema::OtherExampleExtension], custom_int_field.extensions.map(&:class) end end end describe "lazy-loading root types" do class NoVisSchema < GraphQL::Schema self.visibility = nil @use_visibility_profile = false end class LazyLoadingSchema < NoVisSchema class ExampleExtension < GraphQL::Schema::FieldExtension; end class OtherExampleExtension < GraphQL::Schema::FieldExtension; end class Query < GraphQL::Schema::Object field :str, fallback_value: "Query field" do type(String) extension(ExampleExtension) end end class Mutation < GraphQL::Schema::Object field :str, fallback_value: "Mutation field" do type(String) extension(ExampleExtension) end end class Subscription < GraphQL::Schema::Object field :str do type(String) extension(ExampleExtension) end end class OrphanType < GraphQL::Schema::Object field :str do type(String) extension(ExampleExtension) extension(OtherExampleExtension) end end # This one is added before `Visibility` subscription(Subscription) use GraphQL::Schema::Visibility, preload: false query { Query } mutation { Mutation } orphan_types(OrphanType) end it "loads types as-needed" do assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Subscription.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::Query.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::Mutation.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::OrphanType.all_field_definitions.first.extensions.map(&:class) res = LazyLoadingSchema.execute("{ __typename }") assert_equal "Query", res["data"]["__typename"] assert_equal [], LazyLoadingSchema::Query.all_field_definitions.first.extensions.map(&:class) assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Subscription.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::Mutation.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::OrphanType.all_field_definitions.first.extensions.map(&:class) res = LazyLoadingSchema.execute("{ str }") assert_equal "Query field", res["data"]["str"] assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Query.all_field_definitions.first.extensions.map(&:class) assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Subscription.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::Mutation.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::OrphanType.all_field_definitions.first.extensions.map(&:class) res = LazyLoadingSchema.execute("mutation { str }") assert_equal "Mutation field", res["data"]["str"] assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Query.all_field_definitions.first.extensions.map(&:class) assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Subscription.all_field_definitions.first.extensions.map(&:class) assert_equal [LazyLoadingSchema::ExampleExtension], LazyLoadingSchema::Mutation.all_field_definitions.first.extensions.map(&:class) assert_equal [], LazyLoadingSchema::OrphanType.all_field_definitions.first.extensions.map(&:class) end end describe "interfaces thru superclass" do class InterfaceSuperclassSchema < GraphQL::Schema module Node include GraphQL::Schema::Interface field :id, ID end class NodeObject < GraphQL::Schema::Object implements Node end class Thing < NodeObject field :name, String end class Query < GraphQL::Schema::Object field :node, Node def node { id: "101", name: "Hat" } end field :thing, Thing end query(Query) def self.resolve_type(...); Thing; end use GraphQL::Schema::Visibility end end it "Can use interface relationship properly" do res = InterfaceSuperclassSchema.execute("{ node { id ... on Thing { name } } }") assert_equal "Hat", res["data"]["node"]["name"] end it "defaults to preload: true for Rails.env.staging?" do if defined?(Rails) prev_rails = Rails Object.send :remove_const, :Rails end mock_env = OpenStruct.new(:staging? => true) Object.const_set(:Rails, OpenStruct.new(env: mock_env)) schema = Class.new(GraphQL::Schema) do use GraphQL::Schema::Visibility end assert Rails.env.staging? assert schema.visibility.preload? mock_env[:staging?] = false mock_env[:test?] = true schema = Class.new(GraphQL::Schema) do use GraphQL::Schema::Visibility end assert Rails.env.test? refute Rails.env.staging? refute schema.visibility.preload? ensure Object.send(:remove_const, :Rails) if prev_rails Object.const_set(:Rails, prev_rails) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/union_spec.rb
spec/graphql/schema/union_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Union do let(:union) { Jazz::PerformingAct } describe ".path" do it "is the name" do assert_equal "PerformingAct", union.path end end describe "type info" do it "has some" do assert_equal 2, union.possible_types.size end end describe "filter_possible_types" do it "filters types" do assert_equal [Jazz::Musician], union.possible_types(context: { hide_ensemble: true }) end end describe "in queries" do it "works" do query_str = <<-GRAPHQL { nowPlaying { ... on Musician { name instrument { family } } ... on Ensemble { name } } } GRAPHQL res = Jazz::Schema.execute(query_str) expected_data = { "name" => "Bela Fleck and the Flecktones" } assert_graphql_equal expected_data, res["data"]["nowPlaying"] end it "does not allow querying filtered types" do query_str = <<-GRAPHQL { nowPlaying { ... on Musician { name instrument { family } } ... on Ensemble { name } } } GRAPHQL res = Jazz::Schema.execute(query_str, context: { hide_ensemble: true }) assert_equal 1, res.to_h["errors"].count assert_equal "Fragment on Ensemble can't be spread inside PerformingAct", res.to_h["errors"].first["message"] end describe "type resolution" do Box = Struct.new(:value) class Schema < GraphQL::Schema class A < GraphQL::Schema::Object field :a, String, null: false, method: :itself end class B < GraphQL::Schema::Object field :b, String, method: :itself end class C < GraphQL::Schema::Object field :c, Boolean, method: :itself end class UnboxedUnion < GraphQL::Schema::Union possible_types A, C def self.resolve_type(object, ctx) case object when FalseClass C else A end end end class BoxedUnion < GraphQL::Schema::Union possible_types A, B, C def self.resolve_type(object, ctx) case object.value when "return-nil" [B, nil] when FalseClass [C, object.value] else [A, object.value] end end end class Query < GraphQL::Schema::Object field :boxed_union, BoxedUnion def boxed_union Box.new(context[:value]) end field :unboxed_union, UnboxedUnion def unboxed_union context[:value] end end query(Query) end describe "two-value resolution" do it "can cast the object after resolving the type" do query_str = <<-GRAPHQL { boxedUnion { ... on A { a } } } GRAPHQL res = Schema.execute(query_str, context: { value: "unwrapped" }) assert_equal({ 'data' => { 'boxedUnion' => { 'a' => 'unwrapped' } } }, res.to_h) end it "uses `false` when returned from resolve_type" do query_str = <<-GRAPHQL { boxedUnion { ... on C { c } } } GRAPHQL res = Schema.execute(query_str, context: { value: false }) assert_equal({ 'data' => { 'boxedUnion' => { 'c' => false } } }, res.to_h) end it "uses `nil` when returned from resolve_type" do query_str = <<-GRAPHQL { boxedUnion { ... on B { b } } } GRAPHQL res = Schema.execute(query_str, context: { value: "return-nil" }) assert_equal({ 'data' => { 'boxedUnion' => { 'b' => nil } } }, res.to_h) end end describe "single-value resolution" do it "can cast the object after resolving the type" do query_str = <<-GRAPHQL { unboxedUnion { ... on A { a } } } GRAPHQL res = Schema.execute(query_str, context: { value: "string" }) assert_equal({ 'data' => { 'unboxedUnion' => { 'a' => 'string' } } }, res.to_h) end it "works with literal false values" do query_str = <<-GRAPHQL { unboxedUnion { ... on C { c } } } GRAPHQL res = Schema.execute(query_str, context: { value: false }) assert_equal({ 'data' => { 'unboxedUnion' => { 'c' => false } } }, res.to_h) end end end end it "doesn't allow adding non-object types" do object_type = Class.new(GraphQL::Schema::Object) do graphql_name "SomeObject" end err = assert_raises ArgumentError do Class.new(GraphQL::Schema::Union) do graphql_name "SomeUnion" possible_types object_type, GraphQL::Types::Int end end expected_message = "Union possible_types can only be object types (not SCALAR, " assert_includes err.message, expected_message input_type = Class.new(GraphQL::Schema::InputObject) do graphql_name "SomeInput" argument :arg, GraphQL::Types::Int end err = assert_raises ArgumentError do Class.new(GraphQL::Schema::Union) do graphql_name "SomeUnion" possible_types object_type, input_type end end expected_message = "Union possible_types can only be object types (not INPUT_OBJECT, " assert_includes err.message, expected_message err = assert_raises ArgumentError do Class.new(GraphQL::Schema::Union) do graphql_name "SomeUnion" possible_types object_type, 1234 end end expected_message = "Union possible_types can only be class-based GraphQL types (not 1234 (Integer))." assert_includes err.message, expected_message end it "doesn't allow adding interface" do object_type = Class.new(GraphQL::Schema::Object) do graphql_name "SomeObject" end interface_type = Module.new { include GraphQL::Schema::Interface graphql_name "SomeInterface" } err = assert_raises ArgumentError do Class.new(GraphQL::Schema::Union) do graphql_name "SomeUnion" possible_types object_type, interface_type end end expected_message = /Union possible_types can only be object types \(not interface types\), remove SomeInterface \(#<Module:0x[a-f0-9]+>\)/ assert_match expected_message, err.message union_type = Class.new(GraphQL::Schema::Union) do graphql_name "SomeUnion" possible_types object_type, GraphQL::Schema::LateBoundType.new("SomeInterface") end object_type.field(:u, union_type) object_type.field(:i, interface_type) err2 = assert_raises ArgumentError do Class.new(GraphQL::Schema) do query(object_type) end.to_definition end assert_match expected_message, err2.message end describe "migrate legacy tests" do describe "#resolve_type" do let(:result) { Dummy::Schema.execute(query_string) } let(:query_string) {%| { allAnimal { type: __typename ... on Cow { cowName: name } ... on Goat { goatName: name } } allAnimalAsCow { type: __typename ... on Cow { name } } } |} it 'returns correct types for general schema and specific union' do expected_result = { # When using Query#resolve_type "allAnimal" => [ { "type" => "Cow", "cowName" => "Billy" }, { "type" => "Goat", "goatName" => "Gilly" } ], # When using UnionType#resolve_type "allAnimalAsCow" => [ { "type" => "Cow", "name" => "Billy" }, { "type" => "Cow", "name" => "Gilly" } ] } assert_graphql_equal expected_result, result["data"] end end describe "typecasting from union to union" do let(:result) { Dummy::Schema.execute(query_string) } let(:query_string) {%| { allDairy { dairyName: __typename ... on Beverage { bevName: __typename ... on Milk { flavors } } } } |} it "casts if the object belongs to both unions" do expected_result = [ {"dairyName"=>"Cheese"}, {"dairyName"=>"Cheese"}, {"dairyName"=>"Cheese"}, {"dairyName"=>"Milk", "bevName"=>"Milk", "flavors"=>["Natural", "Chocolate", "Strawberry"]}, ] assert_graphql_equal expected_result, result["data"]["allDairy"] end end describe "list of union type" do describe "fragment spreads" do let(:result) { Dummy::Schema.execute(query_string) } let(:query_string) {%| { allDairy { __typename ... milkFields ... cheeseFields } } fragment milkFields on Milk { id source origin flavors } fragment cheeseFields on Cheese { id source origin flavor } |} it "resolves the right fragment on the right item" do all_dairy = result["data"]["allDairy"] cheeses = all_dairy.first(3) cheeses.each do |cheese| assert_equal "Cheese", cheese["__typename"] assert_equal ["__typename", "id", "source", "origin", "flavor"], cheese.keys end milks = all_dairy.last(1) milks.each do |milk| assert_equal "Milk", milk["__typename"] assert_equal ["__typename", "id", "source", "origin", "flavors"], milk.keys end end end end end describe "use with loads:" do class UnionLoadsSchema < GraphQL::Schema class Image < GraphQL::Schema::Object field :title, String end class Video < GraphQL::Schema::Object field :title, String end class Post < GraphQL::Schema::Object field :title, String end class MediaItem < GraphQL::Schema::Union possible_types Image, Video end class Query < GraphQL::Schema::Object field :media_item_type, String do argument :id, ID, loads: MediaItem, as: :media_item end def media_item_type(media_item:) media_item[:type] end end query(Query) def self.object_from_id(id, ctx) type, title = id.split("/") { type: type, title: title } end def self.resolve_type(abs_type, obj, ctx) UnionLoadsSchema.const_get(obj[:type]) end end it "restricts to members of the union" do query_str = "query($mediaId: ID!) { mediaItemType(id: $mediaId) }" res = UnionLoadsSchema.execute(query_str, variables: { mediaId: "Image/Family Photo" }) assert_equal "Image", res["data"]["mediaItemType"] res = UnionLoadsSchema.execute(query_str, variables: { mediaId: "Video/Christmas Pageant" }) assert_equal "Video", res["data"]["mediaItemType"] res = UnionLoadsSchema.execute(query_str, variables: { mediaId: "Post/Year in Review" }) assert_nil res["data"]["mediaItemType"] assert_equal ["No object found for `id: \"Post/Year in Review\"`"], res["errors"].map { |e| e["message"] } end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator_spec.rb
spec/graphql/schema/validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator/validator_helpers" describe GraphQL::Schema::Validator do include ValidatorHelpers class CustomValidator < GraphQL::Schema::Validator def initialize(equal_to:, **rest) @equal_to = equal_to super(**rest) end def validate(object, context, value) if value == @equal_to nil else "%{validated} doesn't have the right the right value" end end end class CustomErrorValidator < GraphQL::Schema::Validator def validate(obj, ctx, value) if value != 7 raise GraphQL::ExecutionError.new("#{@validated.path} must be `7`, not `#{value}`", extensions: { requiredValue: 7, actualValue: value }) end end end before do GraphQL::Schema::Validator.install(:custom, CustomValidator) GraphQL::Schema::Validator.install(:custom_error, CustomErrorValidator) end after do GraphQL::Schema::Validator.uninstall(:custom) GraphQL::Schema::Validator.uninstall(:custom_error) end build_tests(CustomValidator, Integer, [ { name: "with a validator class as name", config: { equal_to: 2 }, cases: [ { query: "{ validated(value: 2) }", error_messages: [], result: 2 }, { query: "{ validated(value: 3) }", error_messages: ["value doesn't have the right the right value"], result: nil }, ] } ]) build_tests(:custom, Integer, [ { name: "with an installed symbol name", config: { equal_to: 4 }, cases: [ { query: "{ validated(value: 4) }", error_messages: [], result: 4 }, { query: "{ validated(value: 3) }", error_messages: ["value doesn't have the right the right value"], result: nil }, ] } ]) it "works with custom raised errors" do schema = build_schema(Integer, { custom_error: {} }) res = schema.execute("{ validated(value: 7) }") assert_equal 7, res["data"]["validated"] res = schema.execute("{ validated(value: 77) }") expected_error = { "message"=>"Query.validated.value must be `7`, not `77`", "locations"=>[{"line"=>1, "column"=>3}], "path"=>["validated"], "extensions"=>{"requiredValue"=>7, "actualValue"=>77} } assert_equal [expected_error], res["errors"] end it "does something with multiple validators" do schema = build_schema(String, { length: { minimum: 5 }, inclusion: { in: ["0", "123456", "678910"] }}) # Both validators pass: res = schema.execute("{ validated(value: \"123456\") }") assert_nil res["errors"] assert_equal "123456", res["data"]["validated"] # The length validator fails: res2 = schema.execute("{ validated(value: \"0\") }") assert_nil res2["data"]["validated"] assert_equal ["value is too short (minimum is 5)"], res2["errors"].map { |e| e["message"] } # The inclusion validator fails: res3 = schema.execute("{ validated(value: \"00000000\") }") assert_nil res3["data"]["validated"] assert_equal ["value is not included in the list"], res3["errors"].map { |e| e["message"] } # Both validators fail: res4 = schema.execute("{ validated(value: \"1\") }") assert_nil res4["data"]["validated"] errs = [ "value is too short (minimum is 5), value is not included in the list", ] assert_equal errs, res4["errors"].map { |e| e["message"] } # Two fields with different errors res5 = schema.execute("{ v1: validated(value: \"0\") v2: validated(value: \"123456\") v3: validated(value: \"abcdefg\") }") expected_data = {"v1"=>nil, "v2"=>"123456", "v3"=>nil} assert_graphql_equal expected_data, res5["data"] errs = [ { "message" => "value is too short (minimum is 5)", "locations" => [{"line"=>1, "column"=>3}], "path" => ["v1"] }, { "message" => "value is not included in the list", "locations" => [{"line"=>1, "column"=>60}], "path" => ["v3"] } ] assert_equal errs, res5["errors"] end it "validates each item in the list" do schema = build_schema(Integer, { numericality: { greater_than: 5 } }) res = schema.execute("{ list { validated(value: 6) } }") expected_data = { "list" => [ { "validated" => 6 }, { "validated" => 6 }, { "validated" => 6 }, ] } assert_graphql_equal expected_data, res["data"] res = schema.execute("{ list { validated(value: 3) } }") expected_response = { "data" => { "list" => [ { "validated" => nil }, { "validated" => nil }, { "validated" => nil }, ] }, "errors" => [ {"message"=>"value must be greater than 5", "locations"=>[{"line"=>1, "column"=>10}], "path"=>["list", 0, "validated"]}, {"message"=>"value must be greater than 5", "locations"=>[{"line"=>1, "column"=>10}], "path"=>["list", 1, "validated"]}, {"message"=>"value must be greater than 5", "locations"=>[{"line"=>1, "column"=>10}], "path"=>["list", 2, "validated"]}, ] } assert_equal expected_response, res end describe "Validator inheritance" do class ValidationInheritanceSchema < GraphQL::Schema class BaseValidatedInput < GraphQL::Schema::InputObject argument :int, Integer, required: false argument :other_int, Integer, required: false validates required: { one_of: [:int, :other_int] } end class IntInput < BaseValidatedInput graphql_name "IntInput" end class BaseValidatedResolver < GraphQL::Schema::Resolver argument :int, Integer, required: false argument :other_int, Integer, required: false validates required: { one_of: [:int, :other_int] } type Integer, null: true def resolve(int: nil, other_int: nil) int || other_int end end class IntResolver < BaseValidatedResolver end class Query < GraphQL::Schema::Object field :int_input, Int do argument :input, IntInput end def int_input(input:) input[:int] || input[:other_int] end field :int, resolver: IntResolver end query(Query) end it "works with input objects" do res = ValidationInheritanceSchema.execute("{ intInput(input: { int: 1 }) }") assert_equal 1, res["data"]["intInput"] res = ValidationInheritanceSchema.execute("{ intInput(input: { int: 1, otherInt: 2 }) }") assert_nil res["data"]["intInput"] assert_equal ["IntInput must include exactly one of the following arguments: int, otherInt."], res["errors"].map { |e| e["message"] } end it "works with resolvers" do res = ValidationInheritanceSchema.execute("{ int(int: 1) }") assert_equal 1, res["data"]["int"] res = ValidationInheritanceSchema.execute("{ int(int: 1, otherInt: 2) }") assert_nil res["data"]["int"] assert_equal ["int must include exactly one of the following arguments: int, otherInt."], res["errors"].map { |e| e["message"] } end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/interface_spec.rb
spec/graphql/schema/interface_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Interface do let(:interface) { Jazz::GloballyIdentifiableType } describe ".path" do it "is the name" do assert_equal "GloballyIdentifiable", interface.path end end describe "type info" do it "tells its type info" do assert_equal "GloballyIdentifiable", interface.graphql_name assert_equal 2, interface.fields.size end module NewInterface1 include Jazz::GloballyIdentifiableType end module NewInterface2 include Jazz::GloballyIdentifiableType def new_method end end it "can override methods" do new_object_1 = Class.new(GraphQL::Schema::Object) do implements NewInterface1 end assert_equal 2, new_object_1.fields.size assert new_object_1.method_defined?(:id) new_object_2 = Class.new(GraphQL::Schema::Object) do graphql_name "XYZ" implements NewInterface2 field :id, "ID", null: false, description: "The ID !!!!!" end assert_equal 2, new_object_2.fields.size # It got the new method assert new_object_2.method_defined?(:new_method) # And the inherited method assert new_object_2.method_defined?(:id) # It gets an overridden description: assert_equal "The ID !!!!!", new_object_2.fields["id"].description end end describe "using `include`" do it "raises" do err = assert_raises RuntimeError do Class.new(GraphQL::Schema::Object) do include(Jazz::GloballyIdentifiableType) end end assert_includes err.message, "implements(Jazz::GloballyIdentifiableType)" end end describe "in queries" do it "works" do query_str = <<-GRAPHQL { piano: find(id: "Instrument/Piano") { id upcasedId ... on Instrument { family } } } GRAPHQL res = Jazz::Schema.execute(query_str) expected_piano = { "id" => "Instrument/Piano", "upcasedId" => "INSTRUMENT/PIANO", "family" => "KEYS", } assert_equal(expected_piano, res["data"]["piano"]) end it "applies custom field attributes" do query_str = <<-GRAPHQL { find(id: "Ensemble/Bela Fleck and the Flecktones") { upcasedId ... on Ensemble { name } } } GRAPHQL res = Jazz::Schema.execute(query_str) expected_data = { "upcasedId" => "ENSEMBLE/BELA FLECK AND THE FLECKTONES", "name" => "Bela Fleck and the Flecktones" } assert_equal(expected_data, res["data"]["find"]) end end describe ':DefinitionMethods' do module InterfaceA include GraphQL::Schema::Interface definition_methods do def some_method 42 end end end module InterfaceB include GraphQL::Schema::Interface end module InterfaceC include GraphQL::Schema::Interface definition_methods do end end module InterfaceD include InterfaceA definition_methods do def some_method 'not 42' end end end module InterfaceE include InterfaceD end it "doesn't overwrite them when including multiple interfaces" do def_methods = InterfaceC::DefinitionMethods InterfaceC.module_eval do include InterfaceA include InterfaceB end assert_equal(InterfaceC::DefinitionMethods, def_methods) end it "follows the normal Ruby ancestor chain when including other interfaces" do assert_equal('not 42', InterfaceE.some_method) end end describe "comments" do class SchemaWithInterface < GraphQL::Schema module InterfaceWithComment include GraphQL::Schema::Interface comment "Interface comment" end class Query < GraphQL::Schema::Object implements InterfaceWithComment end query(Query) end it "assigns comment to the interface" do assert_equal("Interface comment", SchemaWithInterface::Query.interfaces[0].comment) end end describe "can implement other interfaces" do class InterfaceImplementsSchema < GraphQL::Schema module InterfaceA include GraphQL::Schema::Interface field :a, String def a; "a"; end end module InterfaceB include GraphQL::Schema::Interface implements InterfaceA field :b, String def b; "b"; end end class Query < GraphQL::Schema::Object implements InterfaceB end query(Query) end it "runs queries on inherited interfaces" do result = InterfaceImplementsSchema.execute("{ a b }") assert_equal "a", result["data"]["a"] assert_equal "b", result["data"]["b"] result2 = InterfaceImplementsSchema.execute(<<-GRAPHQL) { ... on InterfaceA { ... on InterfaceB { f1: a f2: b } } } GRAPHQL assert_equal "a", result2["data"]["f1"] assert_equal "b", result2["data"]["f2"] end it "shows up in introspection" do result = InterfaceImplementsSchema.execute("{ __type(name: \"InterfaceB\") { interfaces { name } } }") assert_equal ["InterfaceA"], result["data"]["__type"]["interfaces"].map { |i| i["name"] } end it "has the right structure" do expected_schema = <<-SCHEMA interface InterfaceA { a: String } interface InterfaceB implements InterfaceA { a: String b: String } type Query implements InterfaceA & InterfaceB { a: String b: String } SCHEMA assert_equal expected_schema, InterfaceImplementsSchema.to_definition end end describe "transitive implementation of same interface twice" do class TransitiveInterfaceSchema < GraphQL::Schema module Node include GraphQL::Schema::Interface field :id, ID def id; "id"; end end module Named include GraphQL::Schema::Interface implements Node field :name, String def name; "name"; end end module Timestamped include GraphQL::Schema::Interface implements Node field :timestamp, String def timestamp; "ts"; end end class BaseObject < GraphQL::Schema::Object implements Named implements Timestamped end class Thing < BaseObject implements Named implements Timestamped end class Query < GraphQL::Schema::Object field :thing, Thing def thing {} end end query(Query) end it "allows running queries on transitive interfaces" do result = TransitiveInterfaceSchema.execute("{ thing { id name timestamp } }") thing = result.dig("data", "thing") assert_equal "id", thing["id"] assert_equal "name", thing["name"] assert_equal "ts", thing["timestamp"] result2 = TransitiveInterfaceSchema.execute(<<-GRAPHQL) { thing { ...on Node { id } ...on Named { nid: id name ...on Node { nnid: id } } ... on Timestamped { tid: id timestamp } } } GRAPHQL thing2 = result2.dig("data", "thing") assert_equal "id", thing2["id"] assert_equal "id", thing2["nid"] assert_equal "id", thing2["tid"] assert_equal "name", thing2["name"] assert_equal "ts", thing2["timestamp"] end it "has the right structure" do expected_schema = <<-SCHEMA interface Named implements Node { id: ID name: String } interface Node { id: ID } type Query { thing: Thing } type Thing implements Named & Node & Timestamped { id: ID name: String timestamp: String } interface Timestamped implements Node { id: ID timestamp: String } SCHEMA assert_equal expected_schema, TransitiveInterfaceSchema.to_definition end it "only lists each implemented interface once when introspecting" do introspection = TransitiveInterfaceSchema.as_json thing_type = introspection.dig("data", "__schema", "types").find do |type| type["name"] == "Thing" end interfaces_names = thing_type["interfaces"].map { |i| i["name"] }.sort assert_equal ["Named", "Node", "Timestamped"], interfaces_names end it "doesn't return interfaces as possible types" do pts = TransitiveInterfaceSchema.possible_types(TransitiveInterfaceSchema::Node) assert_equal ["Thing"], pts.map(&:graphql_name) end end describe "supplying a fallback_value to a field" do DATABASE = [ {id: "1", name: "Hash thing"}, {id: "2"}, {id: "3", name: nil}, OpenStruct.new(id: "4", name: "OpenStruct thing"), OpenStruct.new(id: "5"), {id: "6", custom_name: "Hash Key Name"} ] class FallbackValueSchema < GraphQL::Schema module NodeWithFallbackInterface include GraphQL::Schema::Interface field :id, ID, null: false field :name, String, fallback_value: "fallback" end module NodeWithHashKeyFallbackInterface include GraphQL::Schema::Interface field :id, ID, null: false field :name, String, hash_key: :custom_name, fallback_value: "hash-key-fallback" end module NodeWithoutFallbackInterface include GraphQL::Schema::Interface field :id, ID, null: false field :name, String end module NodeWithNilFallbackInterface include GraphQL::Schema::Interface field :id, ID, null: false field :name, String, fallback_value: nil end class NodeWithFallbackType < GraphQL::Schema::Object implements NodeWithFallbackInterface end class NodeWithHashKeyFallbackType < GraphQL::Schema::Object implements NodeWithHashKeyFallbackInterface end class NodeWithNilFallbackType < GraphQL::Schema::Object implements NodeWithNilFallbackInterface end class NodeWithoutFallbackType < GraphQL::Schema::Object implements NodeWithoutFallbackInterface end class Query < GraphQL::Schema::Object field :fallback, [NodeWithFallbackType] def fallback DATABASE end field :hash_key_fallback, [NodeWithHashKeyFallbackType] def hash_key_fallback DATABASE end field :no_fallback, [NodeWithoutFallbackType] def no_fallback DATABASE end field :nil_fallback, [NodeWithNilFallbackType] def nil_fallback DATABASE end end query(Query) end it "uses fallback_value if supplied, but only if other ways don't work" do result = FallbackValueSchema.execute("{ fallback { id name } }") data = result["data"]["fallback"] expected = [ {"id"=>"1", "name"=>"Hash thing"}, {"id"=>"2", "name"=>"fallback"}, {"id"=>"3", "name"=>nil}, {"id"=>"4", "name"=>"OpenStruct thing"}, {"id"=>"5", "name"=>"fallback"}, {"id"=>"6", "name"=>"fallback"}, ] assert_equal expected, data end it "uses fallback_value if supplied when hash key isn't present" do result = FallbackValueSchema.execute("{ hashKeyFallback { id name } }") data = result["data"]["hashKeyFallback"] expected = [ {"id"=>"1", "name"=>"hash-key-fallback"}, {"id"=>"2", "name"=>"hash-key-fallback"}, {"id"=>"3", "name"=>"hash-key-fallback"}, {"id"=>"4", "name"=>"hash-key-fallback"}, {"id"=>"5", "name"=>"hash-key-fallback"}, {"id"=>"6", "name"=>"Hash Key Name"}, ] assert_equal expected, data end it "allows nil as fallback_value" do result = FallbackValueSchema.execute("{ nilFallback { id name } }") data = result["data"]["nilFallback"] expected = [ {"id"=>"1", "name"=>"Hash thing"}, {"id"=>"2", "name"=>nil}, {"id"=>"3", "name"=>nil}, {"id"=>"4", "name"=>"OpenStruct thing"}, {"id"=>"5", "name"=>nil}, {"id"=>"6", "name"=>nil}, ] assert_equal expected, data end it "errors if no fallback_value is supplied and other ways don't work" do err = assert_raises RuntimeError do FallbackValueSchema.execute("{ noFallback { id name } }") end assert_includes err.message, "Failed to implement" # Doesn't error until it gets to the OpenStructs. assert_includes err.message, "OpenStruct" end end describe "migrated legacy tests" do let(:interface) { Dummy::Edible } it "has possible types" do expected_defns = [Dummy::Aspartame, Dummy::Cheese, Dummy::Honey, Dummy::Milk] assert_equal(expected_defns, Dummy::Schema.possible_types(interface).sort_by(&:graphql_name)) end describe "query evaluation" do let(:result) { Dummy::Schema.execute(query_string, variables: {"cheeseId" => 2})} let(:query_string) {%| query fav { favoriteEdible { fatContent } } |} it "gets fields from the type for the given object" do expected = {"data"=>{"favoriteEdible"=>{"fatContent"=>0.04}}} assert_equal(expected, result) end end describe "mergeable query evaluation" do let(:result) { Dummy::Schema.execute(query_string, variables: {"cheeseId" => 2})} let(:query_string) {%| query fav { favoriteEdible { fatContent } favoriteEdible { origin } } |} it "gets fields from the type for the given object" do expected = {"data"=>{"favoriteEdible"=>{"fatContent"=>0.04, "origin"=>"Antiquity"}}} assert_equal(expected, result) end end describe "fragments" do let(:query_string) {%| { favoriteEdible { fatContent ... on LocalProduct { origin } } } |} let(:result) { Dummy::Schema.execute(query_string) } it "can apply interface fragments to an interface" do expected_result = { "data" => { "favoriteEdible" => { "fatContent" => 0.04, "origin" => "Antiquity", } } } assert_equal(expected_result, result) end describe "filtering members by type" do let(:query_string) {%| { allEdible { __typename ... on LocalProduct { origin } } } |} it "only applies fields to the right object" do expected_data = [ {"__typename"=>"Cheese", "origin"=>"France"}, {"__typename"=>"Cheese", "origin"=>"Netherlands"}, {"__typename"=>"Cheese", "origin"=>"Spain"}, {"__typename"=>"Milk", "origin"=>"Antiquity"}, ] assert_graphql_equal expected_data, result["data"]["allEdible"] end end end describe "#resolve_type" do let(:result) { Dummy::Schema.execute(query_string) } let(:query_string) {%| { allEdible { __typename ... on Milk { milkFatContent: fatContent } ... on Cheese { cheeseFatContent: fatContent } } allEdibleAsMilk { __typename ... on Milk { fatContent } } } |} it 'returns correct types for general schema and specific interface' do expected_result = { # Uses schema-level resolve_type "allEdible"=>[ {"__typename"=>"Cheese", "cheeseFatContent"=>0.19}, {"__typename"=>"Cheese", "cheeseFatContent"=>0.3}, {"__typename"=>"Cheese", "cheeseFatContent"=>0.065}, {"__typename"=>"Milk", "milkFatContent"=>0.04} ], # Uses type-level resolve_type "allEdibleAsMilk"=>[ {"__typename"=>"Milk", "fatContent"=>0.19}, {"__typename"=>"Milk", "fatContent"=>0.3}, {"__typename"=>"Milk", "fatContent"=>0.065}, {"__typename"=>"Milk", "fatContent"=>0.04} ] } assert_graphql_equal expected_result, result["data"] end describe "in definition_methods when implementing another interface" do class InterfaceInheritanceSchema < GraphQL::Schema module Node include GraphQL::Schema::Interface definition_methods do def resolve_type(obj, ctx) raise "This should never be called -- it's overridden" end end end module Pet include GraphQL::Schema::Interface implements Node definition_methods do def resolve_type(obj, ctx) if obj[:name] == "Fifi" Dog else Cat end end end end class Cat < GraphQL::Schema::Object implements Pet end class Dog < GraphQL::Schema::Object implements Pet end class Query < GraphQL::Schema::Object field :pet, Pet do argument :name, String end def pet(name:) { name: name } end end query(Query) orphan_types(Cat, Dog) end it "calls the local definition, not the inherited one" do res = InterfaceInheritanceSchema.execute("{ pet(name: \"Fifi\") { __typename } }") assert_equal "Dog", res["data"]["pet"]["__typename"] res = InterfaceInheritanceSchema.execute("{ pet(name: \"Pepper\") { __typename } }") assert_equal "Cat", res["data"]["pet"]["__typename"] end end end end describe ".comment" do it "isn't inherited" do int1 = Module.new do include GraphQL::Schema::Interface graphql_name "Int1" comment "TODO: fix this" end int2 = Module.new do include int1 graphql_name "Int2" end assert_equal "TODO: fix this", int1.comment assert_nil int2.comment end end describe "when used as loads" do class InterfaceLoadsSchema < GraphQL::Schema module Sharpenable include GraphQL::Schema::Interface field :is_sharp, Boolean end class Pencil < GraphQL::Schema::Object implements Sharpenable field :color, String end class Chisel < GraphQL::Schema::Object implements Sharpenable field :width, Float end class Mallet < GraphQL::Schema::Object field :weight, Float end class Tool < GraphQL::Schema::Union possible_types(Mallet, Chisel, Pencil) end class Query < GraphQL::Schema::Object field :tool, Tool do argument :id, ID, loads: Sharpenable, as: :sharpenable_object end def tool(sharpenable_object:) sharpenable_object end end query(Query) if ADD_WARDEN use GraphQL::Schema::Warden else use GraphQL::Schema::Visibility end def self.resolve_type(abs_type, obj, ctx) obj[:object_type] end def self.object_from_id(id, ctx) case id when "chisel" { width: 5, is_sharp: true, object_type: Chisel } when "pencil" { color: "gray", is_sharp: false, object_type: Pencil } when "mallet" { weight: 16, object_type: Mallet } else nil end end end it "typechecks the loaded object" do assert_equal({ "tool" => { "__typename" => "Chisel" } }, InterfaceLoadsSchema.execute("{ tool(id: \"chisel\") { __typename } }")["data"]) assert_equal({ "tool" => { "__typename" => "Pencil" } }, InterfaceLoadsSchema.execute("{ tool(id: \"pencil\") { __typename } }")["data"]) assert_equal(["No object found for `id: \"mallet\"`"], InterfaceLoadsSchema.execute("{ tool(id: \"mallet\") { __typename } }")["errors"].map {|e| e["message"]}) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/build_from_definition_spec.rb
spec/graphql/schema/build_from_definition_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::BuildFromDefinition do # Build a schema from `definition` and assert that it # prints out the same string. # Then return the built schema. def assert_schema_and_compare_output(definition) built_schema = GraphQL::Schema.from_definition(definition) assert_equal definition, GraphQL::Schema::Printer.print_schema(built_schema) built_schema end describe '.build' do it 'can build a schema with a simple type' do schema = <<-SCHEMA schema { query: HelloScalars } type HelloScalars { bool: Boolean float: Float id: ID int: Int str: String! } SCHEMA assert_schema_and_compare_output(schema) end it 'can build a schema with underscored names' do schema = <<-SCHEMA type A_Type { f(argument_1: Int, argument_two: Int): Int } type Query { some_field: A_Type } SCHEMA assert_schema_and_compare_output(schema) end it 'can build a schema with default input object values' do schema = <<-SCHEMA input InputObject { a: Int } type Query { a(input: InputObject = {a: 1}): String } SCHEMA assert_schema_and_compare_output(schema) end it 'can build a schema with directives' do schema = <<-SCHEMA schema { query: Hello } directive @foo(arg: Int, nullDefault: Int = null) on FIELD directive @greeting(pleasant: Boolean = true) on ARGUMENT_DEFINITION | ENUM | FIELD_DEFINITION | INPUT_OBJECT | INTERFACE | OBJECT | UNION directive @greeting2 on INTERFACE directive @hashed repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION directive @language(is: String!) on ENUM_VALUE type Hello implements Secret & Secret2 @greeting { goodbye(saying: Parting @greeting): Parting humbug: Int @greeting(pleasant: false) password: Phrase @hashed password2: String str(in: Input): String } input Input @greeting { value: String @hashed } enum Parting @greeting { AU_REVOIR @language(is: "fr") ZAI_JIAN @language(is: "zh") } union Phrase @greeting = Hello | Word interface Secret implements Secret2 @greeting @greeting2 { password: String password2: String } interface Secret2 { password2: String } type Word { str: String } SCHEMA parsed_schema = GraphQL::Schema.from_definition(schema) hello_type = parsed_schema.get_type("Hello") assert_equal ["deprecated", "foo", "greeting", "greeting2", "hashed", "include", "language", "oneOf", "skip", "specifiedBy"], parsed_schema.directives.keys.sort parsed_schema.directives.values.each do |dir_class| assert dir_class < GraphQL::Schema::Directive end assert_equal true, parsed_schema.directives["hashed"].repeatable? assert_equal false, parsed_schema.directives["deprecated"].repeatable? assert_equal 1, hello_type.directives.size assert_instance_of parsed_schema.directives["greeting"], hello_type.directives.first assert_equal({ pleasant: true }, hello_type.directives.first.arguments.keyword_arguments) humbug_directives = hello_type.get_field("humbug").directives assert_equal 1, humbug_directives.size assert_instance_of parsed_schema.directives["greeting"], humbug_directives.first assert_equal({ pleasant: false }, humbug_directives.first.arguments.keyword_arguments) au_revoir_directives = parsed_schema.get_type("Parting").values["AU_REVOIR"].directives assert_equal 1, au_revoir_directives.size assert_instance_of parsed_schema.directives["language"], au_revoir_directives.first assert_equal({ is: "fr" }, au_revoir_directives.first.arguments.keyword_arguments) secret_type = parsed_schema.get_type("Secret") assert_equal 2, secret_type.directives.size assert_schema_and_compare_output(schema) end it 'supports descriptions and definition_line' do schema = <<-SCHEMA schema { query: Hello } """ This is a directive """ directive @foo( """ It has an argument """ arg: Int ) on FIELD """ With an enum """ enum Color { BLUE """ Not a creative color """ GREEN RED } """ What a great type """ type Hello implements I { anEnum(s: S): Color """ And a field to boot """ str(i: Input): String u: U } """ An interface """ interface I { str(i: Input): String } """ And an Input """ input Input { s: String } """ A scalar """ scalar S """ And a union """ union U = Hello SCHEMA assert_schema_and_compare_output(schema) # TODO: GraphQL::CParser doesn't support definition_line yet. built_schema = GraphQL::Schema.from_definition(schema, parser: GraphQL::Language::Parser) # The schema's are the same since there's no description assert_equal 1, built_schema.ast_node.line assert_equal 1, built_schema.ast_node.definition_line # These account for description: assert_equal 5, built_schema.directives["foo"].ast_node.line, "The ast_node.line points to the description" assert_equal 8, built_schema.directives["foo"].ast_node.definition_line, "The ast_node.definition_line points to the definition" arg = built_schema.directives["foo"].arguments["arg"] assert_equal 9, arg.ast_node.line assert_equal 12, arg.ast_node.definition_line enum_type = built_schema.types["Color"] assert_equal 15, enum_type.ast_node.line, "The ast_node.line points to the description" assert_equal 18, enum_type.ast_node.definition_line, "The ast_node.definition_line points to the definition" enum_value = enum_type.values["GREEN"] assert_equal 21, enum_value.ast_node.line assert_equal 24, enum_value.ast_node.definition_line obj_type = built_schema.types["Hello"] assert_equal 28, obj_type.ast_node.line, "The ast_node.line points to the description" assert_equal 31, obj_type.ast_node.definition_line, "The ast_node.definition_line points to the definition" field = obj_type.fields["str"] assert_equal 34, field.ast_node.line assert_equal 37, field.ast_node.definition_line assert_equal 41, built_schema.types["I"].ast_node.line assert_equal 44, built_schema.types["I"].ast_node.definition_line assert_equal 48, built_schema.types["Input"].ast_node.line assert_equal 51, built_schema.types["Input"].ast_node.definition_line assert_equal 55, built_schema.types["S"].ast_node.line assert_equal 58, built_schema.types["S"].ast_node.definition_line assert_equal 60, built_schema.types["U"].ast_node.line assert_equal 63, built_schema.types["U"].ast_node.definition_line end it 'handles empty type descriptions' do schema = <<-SCHEMA """ """ type Query { f1: Int } SCHEMA refute_nil GraphQL::Schema.from_definition(schema) end it 'maintains built-in directives' do schema = <<-SCHEMA schema { query: Hello } type Hello { str: String } SCHEMA built_schema = GraphQL::Schema.from_definition(schema) assert_equal ['deprecated', 'include', 'oneOf', 'skip', 'specifiedBy'], built_schema.directives.keys.sort end it 'supports overriding built-in directives' do schema = <<-SCHEMA schema { query: Hello } directive @skip on FIELD directive @include on FIELD directive @deprecated on FIELD_DEFINITION type Hello { str: String } SCHEMA built_schema = GraphQL::Schema.from_definition(schema) refute built_schema.directives['skip'] == GraphQL::Schema::Directive::Skip refute built_schema.directives['include'] == GraphQL::Schema::Directive::Include refute built_schema.directives['deprecated'] == GraphQL::Schema::Directive::Deprecated end it 'supports adding directives while maintaining built-in directives' do schema = <<-SCHEMA schema @custom(thing: true) { query: Hello } directive @foo(arg: Int) on FIELD directive @custom(thing: Boolean) on SCHEMA type Hello { str: String } SCHEMA built_schema = GraphQL::Schema.from_definition(schema) assert built_schema.directives.keys.include?('skip') assert built_schema.directives.keys.include?('include') assert built_schema.directives.keys.include?('deprecated') assert built_schema.directives.keys.include?('foo') end it 'supports type modifiers' do schema = <<-SCHEMA schema { query: HelloScalars } type HelloScalars { listOfNonNullStrs: [String!] listOfStrs: [String] nonNullListOfNonNullStrs: [String!]! nonNullListOfStrs: [String]! nonNullStr: String! } SCHEMA assert_schema_and_compare_output(schema) end it 'supports recursive type' do schema = <<-SCHEMA schema { query: Recurse } type Recurse { recurse: Recurse str: String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports two types circular' do schema = <<-SCHEMA schema { query: TypeOne } type TypeOne { str: String typeTwo: TypeTwo } type TypeTwo { str: String typeOne: TypeOne } SCHEMA assert_schema_and_compare_output(schema) end it 'supports single argument fields' do schema = <<-SCHEMA schema { query: Hello } type Hello { booleanToStr(bool: Boolean): String floatToStr(float: Float): String idToStr(id: ID): String str(int: Int): String strToStr(bool: String): String } SCHEMA assert_schema_and_compare_output(schema) end it 'properly understands connections' do schema = <<-SCHEMA schema { query: Type } type Organization { email: String } """ The connection type for Organization. """ type OrganizationConnection { """ A list of edges. """ edges: [OrganizationEdge] """ A list of nodes. """ nodes: [Organization] """ Information to aid in pagination. """ pageInfo: PageInfo! """ Identifies the total count of items in the connection. """ totalCount: Int! } """ An edge in a connection. """ type OrganizationEdge { """ A cursor for use in pagination. """ cursor: String! """ The item at the end of the edge. """ node: Organization } """ Information about pagination in a connection. """ type PageInfo { """ When paginating forwards, the cursor to continue. """ endCursor: String """ When paginating forwards, are there more items? """ hasNextPage: Boolean! """ When paginating backwards, are there more items? """ hasPreviousPage: Boolean! """ When paginating backwards, the cursor to continue. """ startCursor: String } type Type { name: String organization( """ The login of the organization to find. """ login: String! ): Organization """ A list of organizations the user belongs to. """ organizations( """ Returns the elements in the list that come after the specified cursor. """ after: String """ Returns the elements in the list that come before the specified cursor. """ before: String """ Returns the first _n_ elements from the list. """ first: Int """ Returns the last _n_ elements from the list. """ last: Int ): OrganizationConnection! } SCHEMA built_schema = assert_schema_and_compare_output(schema) obj = built_schema.types["Type"] refute obj.fields["organization"].connection? assert obj.fields["organizations"].connection? end it 'supports simple type with multiple arguments' do schema = <<-SCHEMA schema { query: Hello } type Hello { str(bool: Boolean, int: Int): String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple type with interface' do schema = <<-SCHEMA schema { query: Hello } type Hello implements WorldInterface { str: String } interface WorldInterface { str: String } SCHEMA assert_schema_and_compare_output(schema) end it "supports interfaces that implement interfaces" do schema = <<-SCHEMA interface Named implements Node { id: ID name: String } interface Node { id: ID } type Query { thing: Thing } type Thing implements Named & Node { id: ID name: String } SCHEMA assert_schema_and_compare_output(schema) end it "only adds the interface to the type once" do schema = <<-SCHEMA interface Named implements Node { id: ID name: String } interface Node { id: ID } type Query { thing: Thing } type Thing implements Named & Node & Timestamped { id: ID name: String timestamp: String } interface Timestamped implements Node { id: ID timestamp: String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple output enum' do schema = <<-SCHEMA schema { query: OutputEnumRoot } enum Hello { WORLD } type OutputEnumRoot { hello: Hello } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple input enum' do schema = <<-SCHEMA schema { query: InputEnumRoot } enum Hello { WORLD } type InputEnumRoot { str(hello: Hello): String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports multiple value enum' do schema = <<-SCHEMA schema { query: OutputEnumRoot } enum Hello { RLD WO } type OutputEnumRoot { hello: Hello } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple union' do schema = <<-SCHEMA schema { query: Root } union Hello = World type Root { hello: Hello } type World { str: String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports multiple union' do schema = <<-SCHEMA schema { query: Root } union Hello = WorldOne | WorldTwo type Root { hello: Hello } type WorldOne { str: String } type WorldTwo { str: String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports redefining built-in scalars' do schema = <<-SCHEMA schema { query: Root } scalar ID type Root { builtInScalar: ID } SCHEMA built_schema = assert_schema_and_compare_output(schema) id_scalar = built_schema.types["ID"] assert_equal true, id_scalar.valid_isolated_input?("123") end it 'supports custom scalar' do schema = <<-SCHEMA schema { query: Root } scalar CustomScalar type Root { customScalar: CustomScalar } SCHEMA built_schema = assert_schema_and_compare_output(schema) custom_scalar = built_schema.types["CustomScalar"] assert_equal true, custom_scalar.valid_isolated_input?("anything") assert_equal true, custom_scalar.valid_isolated_input?(12345) end it 'supports input object' do schema = <<-SCHEMA schema { query: Root } input Input { int: Int nullDefault: Int = null } type Root { field(in: Input): String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple argument field with default value' do schema = <<-SCHEMA schema { query: Hello } enum Color { BLUE RED } type Hello { hello(color: Color = RED): String nullable(color: Color = null): String str(int: Int = 2): String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple type with mutation' do schema = <<-SCHEMA schema { query: HelloScalars mutation: Mutation } type HelloScalars { bool: Boolean int: Int str: String } type Mutation { addHelloScalars(bool: Boolean, int: Int, str: String): HelloScalars } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple type with mutation and default values' do schema = <<-SCHEMA enum Color { BLUE RED } type Mutation { hello(color: Color = RED, int: Int, nullDefault: Int = null, str: String): String } type Query { str: String } SCHEMA assert_schema_and_compare_output(schema) end it 'supports simple type with subscription' do schema = <<-SCHEMA schema { query: HelloScalars subscription: Subscription } type HelloScalars { bool: Boolean int: Int str: String } type Subscription { subscribeHelloScalars(bool: Boolean, int: Int, str: String): HelloScalars } SCHEMA assert_schema_and_compare_output(schema) end it 'supports unreferenced type implementing referenced interface' do schema = <<-SCHEMA type Concrete implements Iface { key: String } interface Iface { key: String } type Query { iface: Iface } SCHEMA assert_schema_and_compare_output(schema) end it 'supports unreferenced type implementing referenced union' do schema = <<-SCHEMA type Concrete { key: String } type Query { union: Union } union Union = Concrete SCHEMA assert_schema_and_compare_output(schema) end it 'supports @deprecated' do schema = <<-SCHEMA directive @directiveWithDeprecatedArg(deprecatedArg: Boolean @deprecated(reason: "Don't use me!")) on OBJECT enum MyEnum { OLD_VALUE @deprecated OTHER_VALUE @deprecated(reason: "Terrible reasons") VALUE } input MyInput { int: Int @deprecated(reason: "This is not the argument you're looking for") string: String } type Query { enum: MyEnum field1: String @deprecated field2: Int @deprecated(reason: "Because I said so") field3(deprecatedArg: MyInput @deprecated(reason: "Use something else")): String } SCHEMA assert_schema_and_compare_output(schema) end it "tracks original AST node" do schema_definition = <<-GRAPHQL schema @custom(thing: true) { query: Query } enum Enum { VALUE } type Query { field(argument: Enum): Interface deprecatedField(argument: Input): Union @deprecated(reason: "Test") } interface Interface { field(argument: String): String } union Union = Query scalar Scalar input Input { argument: String } directive @Directive ( # Argument argument: String ) on SCHEMA directive @custom(thing: Boolean) on SCHEMA type Type implements Interface { field(argument: Scalar): Type } GRAPHQL schema = GraphQL::Schema.from_definition(schema_definition) assert_equal [1, 1], schema.ast_node.position assert_equal [1, 8], schema.ast_node.directives.first.position assert_equal [5, 1], schema.types["Enum"].ast_node.position assert_equal [6, 3], schema.types["Enum"].values["VALUE"].ast_node.position assert_equal [9, 1], schema.types["Query"].ast_node.position assert_equal [10, 3], schema.types["Query"].fields["field"].ast_node.position assert_equal [10, 9], schema.types["Query"].fields["field"].arguments["argument"].ast_node.position assert_equal [11, 43], schema.types["Query"].fields["deprecatedField"].ast_node.directives[0].position assert_equal [11, 55], schema.types["Query"].fields["deprecatedField"].ast_node.directives[0].arguments[0].position assert_equal [14, 1], schema.types["Interface"].ast_node.position assert_equal [15, 3], schema.types["Interface"].fields["field"].ast_node.position assert_equal [15, 9], schema.types["Interface"].fields["field"].arguments["argument"].ast_node.position assert_equal [18, 1], schema.types["Union"].ast_node.position assert_equal [20, 1], schema.types["Scalar"].ast_node.position assert_equal [22, 1], schema.types["Input"].ast_node.position assert_equal [23, 3], schema.types["Input"].arguments["argument"].ast_node.position assert_equal [26, 1], schema.directives["Directive"].ast_node.position assert_equal [28, 3], schema.directives["Directive"].arguments["argument"].ast_node.position assert_equal [33, 22], schema.types["Type"].ast_node.interfaces[0].position end it 'can build a schema from a file path' do schema = <<-SCHEMA schema { query: HelloScalars } type HelloScalars { bool: Boolean float: Float id: ID int: Int str: String! } SCHEMA Tempfile.create(['test', '.graphql']) do |file| file.write(schema) file.close built_schema = GraphQL::Schema.from_definition(file.path) assert_equal schema, GraphQL::Schema::Printer.print_schema(built_schema) end end end describe 'Failures' do it 'Requires a schema definition or Query type' do schema = <<-SCHEMA type Hello { bar: Bar } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Must provide schema definition with query type or a type named Query.', err.message end it 'Allows only a single schema definition' do schema = <<-SCHEMA schema { query: Hello } schema { query: Hello } type Hello { bar: Bar } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Must provide only one schema definition.', err.message end it 'Requires a query type' do schema = <<-SCHEMA schema { mutation: Hello } type Hello { bar: Bar } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Must provide schema definition with query type or a type named Query.', err.message end it 'Unknown type referenced' do schema = <<-SCHEMA schema { query: Hello } type Hello { bar: Bar } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Type "Bar" not found in document.', err.message end it 'Unknown type in interface list' do schema = <<-SCHEMA schema { query: Hello } type Hello implements Bar { str: String } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Type "Bar" not found in document.', err.message end it 'Unknown type in union list' do schema = <<-SCHEMA schema { query: Hello } union TestUnion = Bar type Hello { testUnion: TestUnion } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Type "Bar" not found in document.', err.message end it 'Unknown query type' do schema = <<-SCHEMA schema { query: Wat } type Hello { str: String } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Specified query type "Wat" not found in document.', err.message end it 'Unknown mutation type' do schema = <<-SCHEMA schema { query: Hello mutation: Wat } type Hello { str: String } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Specified mutation type "Wat" not found in document.', err.message end it 'Unknown subscription type' do schema = <<-SCHEMA schema { query: Hello mutation: Wat subscription: Awesome } type Hello { str: String } type Wat { str: String } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Specified subscription type "Awesome" not found in document.', err.message end it 'Does not consider operation names' do schema = <<-SCHEMA schema { query: Foo } query Foo { field } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Specified query type "Foo" not found in document.', err.message end it 'Does not consider fragment names' do schema = <<-SCHEMA schema { query: Foo } fragment Foo on Type { field } SCHEMA err = assert_raises(GraphQL::Schema::InvalidDocumentError) do GraphQL::Schema.from_definition(schema) end assert_equal 'Specified query type "Foo" not found in document.', err.message end end describe "executable schema with resolver maps" do class Something def capitalize(args) args[:word].upcase end end let(:definition) { <<-GRAPHQL scalar Date scalar UndefinedScalar type Something { capitalize(word:String!): String } type A { a: String } type B { b: String } union Thing = A | B type Query { hello: Something thing: Thing add_week(in: Date!): Date! undefined_scalar(str: String, int: Int): UndefinedScalar } GRAPHQL } let(:resolvers) { { Date: { coerce_input: ->(val, ctx) { Time.at(Float(val)) }, coerce_result: ->(val, ctx) { val.to_f } }, resolve_type: ->(type, obj, ctx) { return ctx.schema.types['A'] }, Query: { add_week: ->(o,a,c) { raise "No Time" unless a[:in].is_a? Time a[:in] }, hello: ->(o,a,c) { Something.new }, thing: ->(o,a,c) { OpenStruct.new({a: "a"}) }, undefined_scalar: ->(o,a,c) { a.values.first } } } } let(:schema) { GraphQL::Schema.from_definition(definition, default_resolve: resolvers) } it "resolves unions" do result = schema.execute("query { thing { ... on A { a } } }") assert_equal(result.to_json,'{"data":{"thing":{"a":"a"}}}') end it "resolves scalars" do result = schema.execute("query { add_week(in: 392277600.0) }") assert_equal(result.to_json,'{"data":{"add_week":392277600.0}}') end it "passes args from graphql to the object" do result = schema.execute("query { hello { capitalize(word: \"hello\") }}") assert_equal(result.to_json,'{"data":{"hello":{"capitalize":"HELLO"}}}') end it "handles undefined scalar resolution with identity function" do result = schema.execute <<-GRAPHQL { str: undefined_scalar(str: "abc") int: undefined_scalar(int: 123) } GRAPHQL assert_equal({ "str" => "abc", "int" => 123 }, result["data"]) end it "doesn't warn about method conflicts" do assert_output "", "" do GraphQL::Schema.from_definition " type Query { int(method: Int): Int } " end end end describe "executable schemas from string" do let(:schema_defn) { <<-GRAPHQL type Todo {text: String, from_context: String} type Query { all_todos: [Todo]} type Mutation { todo_add(text: String!): Todo} GRAPHQL } Todo = Struct.new(:text, :from_context) class RootResolver attr_accessor :todos def initialize @todos = [Todo.new("Pay the bills.")] end def all_todos @todos end def todo_add(args, ctx) # this is a method and accepting arguments todo = Todo.new(args[:text], ctx[:context_value]) @todos << todo todo end end it "calls methods with args if args are defined" do schema = GraphQL::Schema.from_definition(schema_defn) root_values = RootResolver.new schema.execute("mutation { todoAdd: todo_add(text: \"Buy Milk\") { text } }", root_value: root_values, context: {context_value: "bar"}) result = schema.execute("query { allTodos: all_todos { text, from_context } }", root_value: root_values) assert_equal(result.to_json, '{"data":{"allTodos":[{"text":"Pay the bills.","from_context":null},{"text":"Buy Milk","from_context":"bar"}]}}') end describe "hash of resolvers with defaults" do let(:todos) { [Todo.new("Pay the bills.")] } let(:schema) { GraphQL::Schema.from_definition(schema_defn, default_resolve: resolve_hash) } let(:resolve_hash) { h = base_hash h["Query"] ||= {} h["Query"]["all_todos"] = ->(obj, args, ctx) { obj } h["Mutation"] ||= {} h["Mutation"]["todo_add"] = ->(obj, args, ctx) { todo = Todo.new(args[:text], ctx[:context_value]) obj << todo todo } h } let(:base_hash) { # Fallback is to resolve by sending the field name Hash.new { |h, k| h[k] = Hash.new { |h2, k2| ->(obj, args, ctx) { obj.public_send(k2) } } } } it "accepts a hash of resolve functions" do schema.execute("mutation { todoAdd: todo_add(text: \"Buy Milk\") { text } }", context: {context_value: "bar"}, root_value: todos) result = schema.execute("query { allTodos: all_todos { text, from_context } }", root_value: todos) assert_equal(result.to_json, '{"data":{"allTodos":[{"text":"Pay the bills.","from_context":null},{"text":"Buy Milk","from_context":"bar"}]}}') end end describe "custom resolve behavior" do class AppResolver def initialize @todos = [Todo.new("Pay the bills.")] @resolves = { "Query" => { "all_todos" => ->(obj, args, ctx) { @todos }, }, "Mutation" => { "todo_add" => ->(obj, args, ctx) { todo = Todo.new(args[:text], ctx[:context_value]) @todos << todo todo }, }, "Todo" => { "text" => ->(obj, args, ctx) { obj.text }, "from_context" => ->(obj, args, ctx) { obj.from_context }, } } end def call(type, field, obj, args, ctx) @resolves .fetch(type.graphql_name) .fetch(field.graphql_name) .call(obj, args, ctx) end end it "accepts a default_resolve callable" do schema = GraphQL::Schema.from_definition(schema_defn, default_resolve: AppResolver.new) schema.execute("mutation { todoAdd: todo_add(text: \"Buy Milk\") { text } }", context: {context_value: "bar"}) result = schema.execute("query { allTodos: all_todos { text, from_context } }") assert_equal('{"data":{"allTodos":[{"text":"Pay the bills.","from_context":null},{"text":"Buy Milk","from_context":"bar"}]}}', result.to_json) end end describe "custom parser behavior" do module BadParser ParseError = Class.new(StandardError) def self.parse(string) raise ParseError end end it 'accepts a parser callable' do assert_raises(BadParser::ParseError) do GraphQL::Schema.from_definition(schema_defn, parser: BadParser) end end end describe "relay behaviors" do let(:schema_defn) { <<-GRAPHQL interface Node { id: ID! } type Query { node(id: ID!): Node } type Thing implements Node { id: ID! name: String! otherThings(after: String, first: Int): ThingConnection! } type ThingConnection { edges: [ThingEdge!]! } type ThingEdge { cursor: String! node: Thing! } GRAPHQL } let(:query_string) {' { node(id: "taco") { ... on Thing { name otherThings { edges { node { name } cursor } } } } } '} it "doesn't try to add them" do default_resolve = { "Query" => { "node" => ->(obj, args, ctx) { OpenStruct.new( name: "taco-thing", otherThings: OpenStruct.new( edges: [ OpenStruct.new(cursor: "a", node: OpenStruct.new(name: "other-thing-a")), OpenStruct.new(cursor: "b", node: OpenStruct.new(name: "other-thing-b")), ] ) ) } }, "resolve_type" => ->(type, obj, ctx) { ctx.query.get_type("Thing") } } schema = GraphQL::Schema.from_definition(schema_defn, default_resolve: default_resolve) result = schema.execute(query_string) expected_data = { "node" => { "name" => "taco-thing", "otherThings" => { "edges" => [ {"node" => {"name" => "other-thing-a"}, "cursor" => "a"}, {"node" => {"name" => "other-thing-b"}, "cursor" => "b"}, ] } } }
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
true
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/relay_classic_mutation_spec.rb
spec/graphql/schema/relay_classic_mutation_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::RelayClassicMutation do describe ".input_object_class" do it "is inherited, with a default" do custom_input = Class.new(GraphQL::Schema::InputObject) mutation_base_class = Class.new(GraphQL::Schema::RelayClassicMutation) do input_object_class(custom_input) end mutation_subclass = Class.new(mutation_base_class) assert_equal GraphQL::Schema::InputObject, GraphQL::Schema::RelayClassicMutation.input_object_class assert_equal custom_input, mutation_base_class.input_object_class assert_equal custom_input, mutation_subclass.input_object_class end end describe ".field" do it "removes inherited field definitions, creating one with the mutation as the owner" do assert_equal Jazz::RenameEnsemble, Jazz::RenameEnsemble.fields["ensemble"].owner assert_equal Jazz::RenameEnsemble, Jazz::RenameEnsemble.payload_type.fields["ensemble"].owner assert_equal Jazz::RenameEnsembleAsBand, Jazz::RenameEnsembleAsBand.fields["ensemble"].owner assert_equal Jazz::RenameEnsembleAsBand, Jazz::RenameEnsembleAsBand.payload_type.fields["ensemble"].owner end end describe ".input_type" do it "has a reference to the mutation" do mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do graphql_name "Test" end assert_equal mutation, mutation.input_type.mutation end end describe ".null" do it "is inherited as true" do mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do graphql_name "Test" end assert mutation.null end end describe "input argument" do it "sets a description for the input argument" do mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do graphql_name "SomeMutation" end field = GraphQL::Schema::Field.new(name: "blah", resolver_class: mutation) assert_equal "Parameters for SomeMutation", field.get_argument("input").description end end describe "execution" do after do Jazz::Models.reset end it "works with no arguments" do res = Jazz::Schema.execute <<-GRAPHQL mutation { addSitar(input: {}) { instrument { name } } } GRAPHQL assert_equal "Sitar", res["data"]["addSitar"]["instrument"]["name"] end it "works with InputObject arguments" do res = Jazz::Schema.execute <<-GRAPHQL mutation { addEnsembleRelay(input: { ensemble: { name: "Miles Davis Quartet" } }) { ensemble { name } } } GRAPHQL assert_equal "Miles Davis Quartet", res["data"]["addEnsembleRelay"]["ensemble"]["name"] end it "supports extras" do res = Jazz::Schema.execute <<-GRAPHQL mutation { hasExtras(input: {}) { nodeClass int } } GRAPHQL assert_equal "GraphQL::Language::Nodes::Field", res["data"]["hasExtras"]["nodeClass"] assert_nil res["data"]["hasExtras"]["int"] # Also test with given args res = Jazz::Schema.execute <<-GRAPHQL mutation { hasExtras(input: {int: 5}) { nodeClass int } } GRAPHQL assert_equal "GraphQL::Language::Nodes::Field", res["data"]["hasExtras"]["nodeClass"] assert_equal 5, res["data"]["hasExtras"]["int"] end it "supports field extras" do res = Jazz::Schema.execute <<-GRAPHQL mutation { hasFieldExtras(input: {}) { lookaheadClass int } } GRAPHQL assert_equal "GraphQL::Execution::Lookahead", res["data"]["hasFieldExtras"]["lookaheadClass"] assert_nil res["data"]["hasFieldExtras"]["int"] # Also test with given args res = Jazz::Schema.execute <<-GRAPHQL mutation { hasFieldExtras(input: {int: 5}) { lookaheadClass int } } GRAPHQL assert_equal "GraphQL::Execution::Lookahead", res["data"]["hasFieldExtras"]["lookaheadClass"] assert_equal 5, res["data"]["hasFieldExtras"]["int"] end it "can strip out extras" do ctx = {} res = Jazz::Schema.execute <<-GRAPHQL, context: ctx mutation { hasExtrasStripped(input: {}) { int } } GRAPHQL assert_equal true, ctx[:has_lookahead] assert_equal 51, res["data"]["hasExtrasStripped"]["int"] end end describe "loading multiple application objects" do let(:query_str) { <<-GRAPHQL mutation($ids: [ID!]!) { upvoteEnsembles(input: {ensembleIds: $ids}) { ensembles { id } } } GRAPHQL } it "loads arguments as objects of the given type and strips `_ids` suffix off argument name and appends `s`" do res = Jazz::Schema.execute(query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]}) assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["upvoteEnsembles"]["ensembles"].map { |e| e["id"] } end it "uses the `as:` name when loading" do as_bands_query_str = query_str.sub("upvoteEnsembles", "upvoteEnsemblesAsBands") res = Jazz::Schema.execute(as_bands_query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]}) assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["upvoteEnsemblesAsBands"]["ensembles"].map { |e| e["id"] } end it "doesn't append `s` to argument names that already end in `s`" do query = <<-GRAPHQL mutation($ids: [ID!]!) { upvoteEnsemblesIds(input: {ensemblesIds: $ids}) { ensembles { id } } } GRAPHQL res = Jazz::Schema.execute(query, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]}) assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["upvoteEnsemblesIds"]["ensembles"].map { |e| e["id"] } end it "returns an error instead when the ID resolves to nil" do res = Jazz::Schema.execute(query_str, variables: { ids: ["Ensemble/Nonexistent Name"], }) assert_nil res["data"].fetch("upvoteEnsembles") assert_equal ['No object found for `ensembleIds: "Ensemble/Nonexistent Name"`'], res["errors"].map { |e| e["message"] } end it "returns an error instead when the ID resolves to an object of the wrong type" do res = Jazz::Schema.execute(query_str, variables: { ids: ["Instrument/Organ"], }) assert_nil res["data"].fetch("upvoteEnsembles") assert_equal ["No object found for `ensembleIds: \"Instrument/Organ\"`"], res["errors"].map { |e| e["message"] } end it "raises an authorization error when the type's auth fails" do res = Jazz::Schema.execute(query_str, variables: { ids: ["Ensemble/Spinal Tap"], }) assert_nil res["data"].fetch("upvoteEnsembles") # Failed silently refute res.key?("errors") end end describe "loading application objects" do let(:query_str) { <<-GRAPHQL mutation($id: ID!, $newName: String!) { renameEnsemble(input: {ensembleId: $id, newName: $newName}) { __typename ensemble { __typename name } } } GRAPHQL } it "loads arguments as objects of the given type" do res = Jazz::Schema.execute(query_str, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"}) assert_equal "August Greene", res["data"]["renameEnsemble"]["ensemble"]["name"] end it "loads arguments as objects when provided an interface type" do query = <<-GRAPHQL mutation($id: ID!, $newName: String!) { renameNamedEntity(input: {namedEntityId: $id, newName: $newName}) { namedEntity { __typename name } } } GRAPHQL res = Jazz::Schema.execute(query, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"}) assert_equal "August Greene", res["data"]["renameNamedEntity"]["namedEntity"]["name"] assert_equal "Ensemble", res["data"]["renameNamedEntity"]["namedEntity"]["__typename"] end it "loads arguments as objects when provided an union type" do query = <<-GRAPHQL mutation($id: ID!, $newName: String!) { renamePerformingAct(input: {performingActId: $id, newName: $newName}) { performingAct { __typename ... on Ensemble { name } } } } GRAPHQL res = Jazz::Schema.execute(query, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"}) assert_equal "August Greene", res["data"]["renamePerformingAct"]["performingAct"]["name"] assert_equal "Ensemble", res["data"]["renamePerformingAct"]["performingAct"]["__typename"] end it "uses the `as:` name when loading" do band_query_str = query_str.sub("renameEnsemble", "renameEnsembleAsBand") res = Jazz::Schema.execute(band_query_str, variables: { id: "Ensemble/Robert Glasper Experiment", newName: "August Greene"}) assert_equal "August Greene", res["data"]["renameEnsembleAsBand"]["ensemble"]["name"] end it "returns an error instead when the ID resolves to nil" do res = Jazz::Schema.execute(query_str, variables: { id: "Ensemble/Nonexistent Name", newName: "August Greene" }) assert_nil res["data"].fetch("renameEnsemble") assert_equal ['No object found for `ensembleId: "Ensemble/Nonexistent Name"`'], res["errors"].map { |e| e["message"] } end it "returns an error instead when the ID resolves to an object of the wrong type" do res = Jazz::Schema.execute(query_str, variables: { id: "Instrument/Organ", newName: "August Greene" }) assert_nil res["data"].fetch("renameEnsemble") assert_equal ["No object found for `ensembleId: \"Instrument/Organ\"`"], res["errors"].map { |e| e["message"] } end it "raises an authorization error when the type's auth fails" do res = Jazz::Schema.execute(query_str, variables: { id: "Ensemble/Spinal Tap", newName: "August Greene" }) assert_nil res["data"].fetch("renameEnsemble") # Failed silently refute res.key?("errors") end end describe "migrated legacy tests" do describe "specifying return interfaces" do class MutationInterfaceSchema < GraphQL::Schema module ResultInterface include GraphQL::Schema::Interface field :success, Boolean, null: false field :notice, String end module ErrorInterface include GraphQL::Schema::Interface field :error, String end class BaseReturnType < GraphQL::Schema::Object implements ResultInterface, ErrorInterface end class ReturnTypeWithInterfaceTest < GraphQL::Schema::RelayClassicMutation object_class BaseReturnType field :name, String def resolve { name: "Type Specific Field", success: true, notice: "Success Interface Field", error: "Error Interface Field" } end end class Mutation < GraphQL::Schema::Object field :custom, mutation: ReturnTypeWithInterfaceTest end mutation(Mutation) def self.resolve_type(abs_type, obj, ctx) NO_OP_RESOLVE_TYPE.call(abs_type, obj, ctx) end end it 'makes the mutation type implement the interfaces' do mutation = MutationInterfaceSchema::ReturnTypeWithInterfaceTest expected_interfaces = [MutationInterfaceSchema::ResultInterface, MutationInterfaceSchema::ErrorInterface] actual_interfaces = mutation.payload_type.interfaces assert_equal(expected_interfaces, actual_interfaces) end it "returns interface values and specific ones" do result = MutationInterfaceSchema.execute('mutation { custom(input: {clientMutationId: "123"}) { name, success, notice, error, clientMutationId } }') assert_equal "Type Specific Field", result["data"]["custom"]["name"] assert_equal "Success Interface Field", result["data"]["custom"]["notice"] assert_equal true, result["data"]["custom"]["success"] assert_equal "Error Interface Field", result["data"]["custom"]["error"] assert_equal "123", result["data"]["custom"]["clientMutationId"] end end if testing_rails? describe "star wars mutation tests" do let(:query_string) {%| mutation addBagel($clientMutationId: String, $shipName: String = "Bagel") { introduceShip(input: {shipName: $shipName, factionId: "1", clientMutationId: $clientMutationId}) { clientMutationId shipEdge { node { name, id } } faction { name } } } |} let(:introspect) {%| { __schema { types { name, fields { name } } } } |} after do StarWars::DATA["Ship"].delete("9") StarWars::DATA["Faction"]["1"].ships.delete("9") end it "supports null values" do result = star_wars_query(query_string, { "clientMutationId" => "1234", "shipName" => nil }) expected = {"data" => { "introduceShip" => { "clientMutationId" => "1234", "shipEdge" => { "node" => { "name" => nil, "id" => GraphQL::Schema::UniqueWithinType.encode("Ship", "9"), }, }, "faction" => {"name" => StarWars::DATA["Faction"]["1"].name } } }} assert_equal(expected, result) end it "supports lazy resolution" do result = star_wars_query(query_string, { "clientMutationId" => "1234", "shipName" => "Slave II" }) assert_equal "Slave II", result["data"]["introduceShip"]["shipEdge"]["node"]["name"] end it "returns the result & clientMutationId" do result = star_wars_query(query_string, { "clientMutationId" => "1234" }) expected = {"data" => { "introduceShip" => { "clientMutationId" => "1234", "shipEdge" => { "node" => { "name" => "Bagel", "id" => GraphQL::Schema::UniqueWithinType.encode("Ship", "9"), }, }, "faction" => {"name" => StarWars::DATA["Faction"]["1"].name } } }} assert_equal(expected, result) end it "doesn't require a clientMutationId to perform mutations" do result = star_wars_query(query_string) new_ship_name = result["data"]["introduceShip"]["shipEdge"]["node"]["name"] assert_equal("Bagel", new_ship_name) end describe "return_field ... property:" do it "resolves correctly" do query_str = <<-GRAPHQL mutation { introduceShip(input: {shipName: "Bagel", factionId: "1"}) { aliasedFaction { name } } } GRAPHQL result = star_wars_query(query_str) faction_name = result["data"]["introduceShip"]["aliasedFaction"]["name"] assert_equal("Alliance to Restore the Republic", faction_name) end end describe "handling errors" do it "supports returning an error in resolve" do result = star_wars_query(query_string, { "clientMutationId" => "5678", "shipName" => "Millennium Falcon" }) expected = { "data" => { "introduceShip" => nil, }, "errors" => [ { "message" => "Sorry, Millennium Falcon ship is reserved", "locations" => [ { "line" => 3 , "column" => 13}], "path" => ["introduceShip"] } ] } assert_equal(expected, result) end it "supports raising an error in a lazy callback" do result = star_wars_query(query_string, { "clientMutationId" => "5678", "shipName" => "Ebon Hawk" }) expected = { "data" => { "introduceShip" => nil, }, "errors" => [ { "message" => "💥", "locations" => [ { "line" => 3 , "column" => 13}], "path" => ["introduceShip"] } ] } assert_equal(expected, result) end it "supports raising an error in the resolve function" do result = star_wars_query(query_string, { "clientMutationId" => "5678", "shipName" => "Leviathan" }) expected = { "data" => { "introduceShip" => nil, }, "errors" => [ { "message" => "🔥", "locations" => [ { "line" => 3 , "column" => 13}], "path" => ["introduceShip"] } ] } assert_equal(expected, result) end end end end end describe "authorizing arguments from superclasses" do class RelayClassicArgumentAuthSchema < GraphQL::Schema class BaseArgument < GraphQL::Schema::Argument def authorized?(_object, args, context) authed_val = context[:authorized_value] ||= Hash.new { |h,k| h[k] = {} } if (prev_val = authed_val[context[:current_path]][self.path]) raise "Duplicate `#authorized?` call on #{self.path} @ #{context[:current_path]} (was: #{prev_val.inspect}, is: #{args.inspect})" end authed_val[context[:current_path]][self.path] = args authed = context[:authorized] ||= {} authed[context[:current_path]] = super end end class NameInput < GraphQL::Schema::InputObject argument_class BaseArgument argument :name, String end class NameOne < GraphQL::Schema::RelayClassicMutation argument_class BaseArgument argument :name, String, as: :name_one field :name, String def resolve(**arguments) { name: arguments[:name_one] } end end class NameTwo < GraphQL::Schema::RelayClassicMutation input_type NameInput field :name, String def resolve(**arguments) { name: arguments[:name] } end end class NameThree < GraphQL::Schema::RelayClassicMutation input_object_class NameInput field :name, String def resolve(**arguments) { name: arguments[:name] } end end class Thing < GraphQL::Schema::Object field :name, String end class NameFour < GraphQL::Schema::RelayClassicMutation argument_class BaseArgument argument :thing_id, ID, loads: Thing field :thing, Thing def resolve(**arguments) { thing: arguments[:thing] } end end class Mutation < GraphQL::Schema::Object field :name_one, mutation: NameOne field :name_two, mutation: NameTwo field :name_three, mutation: NameThree field :name_four, mutation: NameFour end mutation(Mutation) def self.object_from_id(id, ctx) { name: id } end def self.resolve_type(abs_type, obj, ctx) Thing end end it "calls #authorized? on arguments defined on the mutation" do res = RelayClassicArgumentAuthSchema.execute("mutation { nameOne(input: { name: \"Camry\" }) { name } }") assert_equal true, res.context[:authorized][["nameOne"]] end it "calls #authorized? on arguments defined on the input_type" do res = RelayClassicArgumentAuthSchema.execute("mutation { nameTwo(input: { name: \"Camry\" }) { name } }") assert_equal true, res.context[:authorized][["nameTwo"]] end it "calls #authorized? on arguments defined on the inputObjectClass" do res = RelayClassicArgumentAuthSchema.execute("mutation { nameThree(input: { name: \"Camry\" }) { name } }") assert_equal true, res.context[:authorized][["nameThree"]] end it "calls #authorized? on loaded argument values" do res = RelayClassicArgumentAuthSchema.execute("mutation { nameFour(input: { thingId: \"Corolla\" }) { thing { name } } }") assert_equal true, res.context[:authorized][["nameFour"]] assert_equal({ name: "Corolla"}, res.context[:authorized_value][["nameFour"]]["NameFour.thingId"]) assert_equal "Corolla", res["data"]["nameFour"]["thing"]["name"] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/always_visible_spec.rb
spec/graphql/schema/always_visible_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::AlwaysVisible do class AlwaysVisibleSchema < GraphQL::Schema class Query < GraphQL::Schema::Object def self.visible?(ctx) ctx[:visible_was_called] = true false end field :one, Integer def one; 1; end end query(Query) use GraphQL::Schema::AlwaysVisible end class NotAlwaysVisibleSchema < GraphQL::Schema query(AlwaysVisibleSchema::Query) use GraphQL::Schema::Warden if ADD_WARDEN end it "Doesn't call visibility methods" do res = NotAlwaysVisibleSchema.execute("{ one }") assert res.context[:visible_was_called] assert_equal ["Schema is not configured for queries"], res["errors"].map { |err| err["message"] } res = AlwaysVisibleSchema.execute("{ one }") refute res.context[:visible_was_called] assert_equal 1, res["data"]["one"] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/non_null_spec.rb
spec/graphql/schema/non_null_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::NonNull do let(:of_type) { Jazz::Musician } let(:non_null_type) { GraphQL::Schema::NonNull.new(of_type) } it "returns list? to be false" do refute non_null_type.list? end it "returns non_null? to be true" do assert non_null_type.non_null? end it "returns kind to be GraphQL::TypeKinds::NON_NULL" do assert_equal GraphQL::TypeKinds::NON_NULL, non_null_type.kind end it "returns correct type signature" do assert_equal "Musician!", non_null_type.to_type_signature end describe "comparison operator" do it "will return false if list types 'of_type' are different" do new_of_type = Jazz::InspectableKey new_non_null_type = GraphQL::Schema::NonNull.new(new_of_type) refute_equal non_null_type, new_non_null_type end it "will return true if list types 'of_type' are the same" do new_of_type = Jazz::Musician new_non_null_type = GraphQL::Schema::NonNull.new(new_of_type) assert_equal non_null_type, new_non_null_type end end describe "double-nulling" do it "is a parse error in a query" do res = Jazz::Schema.execute " query($id: ID!!) { find(id: $id) { __typename } } " expected_err = if USING_C_PARSER "syntax error, unexpected BANG (\"!\"), expecting RPAREN or VAR_SIGN at [2, 21]" else "Expected VAR_SIGN, actual: BANG (\"!\") at [2, 21]" end assert_equal [expected_err], res["errors"].map { |e| e["message"] } end end describe "Introspection" do class NonNullIntrospectionSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :strs, [String], null: false end query Query end it "doesn't break on description" do res = NonNullIntrospectionSchema.execute(<<-GRAPHQL).to_h query IntrospectionQuery { __type(name: "Query") { fields { type { description ofType { description ofType { description } } } } } } GRAPHQL assert_equal [nil], res["data"]["__type"]["fields"].map { |f| f["description"] } end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/introspection_system_spec.rb
spec/graphql/schema/introspection_system_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::IntrospectionSystem do describe "custom introspection" do it "serves custom fields on types" do res = Jazz::Schema.execute("{ __schema { isJazzy } }") assert_equal true, res["data"]["__schema"]["isJazzy"] end it "serves overridden fields on types" do res = Jazz::Schema.execute(%|{ __type(name: "Ensemble") { name } }|) assert_equal "ENSEMBLE", res["data"]["__type"]["name"] end it "serves custom entry points" do res = Jazz::Schema.execute("{ __classname }", root_value: Set.new) assert_equal "Set", res["data"]["__classname"] end it "calls authorization methods of those types" do res = Jazz::Schema.execute(%|{ __type(name: "Ensemble") { name } }|) assert_equal "ENSEMBLE", res["data"]["__type"]["name"] unauth_res = Jazz::Schema.execute(%|{ __type(name: "Ensemble") { name } }|, context: { cant_introspect: true }) assert_nil unauth_res["data"].fetch("__type") assert_equal ["You're not allowed to introspect here"], unauth_res["errors"].map { |e| e["message"] } end it "serves custom dynamic fields" do res = Jazz::Schema.execute("{ nowPlaying { __typename __typenameLength __astNodeClass } }") assert_equal "Ensemble", res["data"]["nowPlaying"]["__typename"] assert_equal 8, res["data"]["nowPlaying"]["__typenameLength"] assert_equal "GraphQL::Language::Nodes::Field", res["data"]["nowPlaying"]["__astNodeClass"] end it "doesn't affect other schemas" do res = Dummy::Schema.execute("{ __schema { isJazzy } }") assert_equal 1, res["errors"].length res = Dummy::Schema.execute("{ __classname }", root_value: Set.new) assert_equal 1, res["errors"].length res = Dummy::Schema.execute("{ ensembles { __typenameLength } }") assert_equal 1, res["errors"].length end it "runs the introspection query" do res = Jazz::Schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) assert res query_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "QUERY" } ensembles_field = query_type["fields"].find { |f| f["name"] == "ensembles" } assert_equal [], ensembles_field["args"] end it "doesn't include invisible union types based on context" do context = { hide_ensemble: true } res = Jazz::Schema.execute('{ __type(name: "PerformingAct") { possibleTypes { name } } }', context: context) assert_equal 1, res["data"]["__type"]["possibleTypes"].length assert_equal "MUSICIAN", res["data"]["__type"]["possibleTypes"].first["name"] end it "does not include hidden interfaces by membership based on context" do context = { private: false } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { interfaces { name } } }', context: context) assert res["data"]["__type"]["interfaces"].none? { |i| i["name"] == "PRIVATENAMEENTITY" } end it "includes hidden interfaces by membership based on the context" do context = { private: true } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { interfaces { name } } }', context: context) assert res["data"]["__type"]["interfaces"].any? { |i| i["name"] == "PRIVATENAMEENTITY" } end it "does not include hidden interfaces by membership based on context" do context = { private: false } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { interfaces { name } } }', context: context) assert res["data"]["__type"]["interfaces"].none? { |i| i["name"] == "INVISIBLENAMEENTITY" } end it "includes hidden interfaces by membership based on the context" do context = { private: true } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { interfaces { name } } }', context: context) assert res["data"]["__type"]["interfaces"].any? { |i| i["name"] == "INVISIBLENAMEENTITY" } end it "does not include fields from hidden interfaces by membership based on the context" do context = { private: false } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { fields { name } } }', context: context) assert res["data"]["__type"]["fields"].none? { |i| i["name"] == "privateName" } end it "includes fields from interfaces by membership based on the context" do context = { private: true } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { fields { name } } }', context: context) assert res["data"]["__type"]["fields"].any? { |i| i["name"] == "privateName" } end it "does not include fields from hidden interfaces based on the context" do context = { private: false } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { fields { name } } }', context: context) assert res["data"]["__type"]["fields"].none? { |i| i["name"] == "invisibleName" } end it "includes fields from interfaces based on the context" do context = { private: true } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { fields { name } } }', context: context) assert res["data"]["__type"]["fields"].any? { |i| i["name"] == "invisibleName" } end it "includes fields that are defined locally on the object, even when the interface's implementation is private" do context = { private: false } res = Jazz::Schema.execute('{ __type(name: "Ensemble") { fields { name } } }', context: context) assert res["data"]["__type"]["fields"].any? { |i| i["name"] == "overriddenName" } end it "includes extra types" do res = Jazz::Schema.execute('{ __type(name: "BlogPost") { name } }') assert_equal "BLOGPOST", res["data"]["__type"]["name"] res2 = Jazz::Schema.execute("{ __schema { types { name } } }") names = res2["data"]["__schema"]["types"].map { |t| t["name"] } assert_includes names, "BLOGPOST" end end describe "copying the built-ins" do module IntrospectionCopyTest class Query < GraphQL::Schema::Object field :int, Integer, null: false end class Schema1 < GraphQL::Schema query(Query) end class Schema2 < GraphQL::Schema query(Query) end end it "makes copies of built-in types for each schema, so that local modifications don't affect the base classes" do refute_equal IntrospectionCopyTest::Schema1.types["__Type"], IntrospectionCopyTest::Schema2.types["__Type"] end end describe "#disable_introspection_entry_points" do let(:schema) { Jazz::Schema } it "allows the __schema entry point introspection by default" do res = schema.execute("{ __schema { types { name } } }") assert res types = res["data"]["__schema"]["types"] refute_empty types end it "allows the __type entry point introspection by default" do res = schema.execute('{ __type(name: "Musician") { name } }') assert res types = res["data"]["__type"]["name"] refute_empty types end describe "when entry points introspection is disabled" do let(:schema) { Jazz::SchemaWithoutIntrospection } it "returns error on __schema introspection" do res = schema.execute("{ __schema { types { name } } }") assert res assert_nil res["data"] assert_equal ["Field '__schema' doesn't exist on type 'Query'"], res["errors"].map { |e| e["message"] } end it "returns error on __type introspection" do res = schema.execute('{ __type(name: "Musician") { name } }') assert res assert_nil res["data"] assert_equal ["Field '__type' doesn't exist on type 'Query'"], res["errors"].map { |e| e["message"] } end end describe "when the __schema entry point introspection is disabled" do let(:schema) { Jazz::SchemaWithoutSchemaIntrospection } it "allows the __type entry point introspection" do res = schema.execute('{ __type(name: "Musician") { name } }') assert res types = res["data"]["__type"]["name"] refute_empty types end it "returns error" do res = schema.execute("{ __schema { types { name } } }") assert res assert_nil res["data"] assert_equal ["Field '__schema' doesn't exist on type 'Query'"], res["errors"].map { |e| e["message"] } end end describe "when __type entry point introspection is disabled" do let(:schema) { Jazz::SchemaWithoutTypeIntrospection } it "allows the __schema entry point introspection by default" do res = schema.execute("{ __schema { types { name } } }") assert res types = res["data"]["__schema"]["types"] refute_empty types end it "returns error" do res = schema.execute('{ __type(name: "Musician") { name } }') assert res assert_nil res["data"] assert_equal ["Field '__type' doesn't exist on type 'Query'"], res["errors"].map { |e| e["message"] } end end describe "when __type and __schema entry point introspection is disabled" do let(:schema) { Jazz::SchemaWithoutSchemaOrTypeIntrospection } it "returns error on __schema introspection" do res = schema.execute("{ __schema { types { name } } }") assert res assert_nil res["data"] assert_equal ["Field '__schema' doesn't exist on type 'Query'"], res["errors"].map { |e| e["message"] } end it "returns error on __type introspection" do res = schema.execute('{ __type(name: "Musician") { name } }') assert res assert_nil res["data"] assert_equal ["Field '__type' doesn't exist on type 'Query'"], res["errors"].map { |e| e["message"] } end end end describe "Dynamically hiding them" do class HidingIntrospectionSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN module HideIntrospectionByContext def visible?(ctx) super && if introspection? !ctx[:hide_introspection] else true end end end class BaseField < GraphQL::Schema::Field include HideIntrospectionByContext end module CustomIntrospection class DynamicFields < GraphQL::Introspection::DynamicFields field_class(BaseField) field :__typename, String, null: false end class EntryPoints < GraphQL::Introspection::EntryPoints field_class(BaseField) field :__type, GraphQL::Introspection::TypeType do argument :name, String end end class SchemaType < GraphQL::Introspection::SchemaType extend HideIntrospectionByContext end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int; 1; end end query(Query) introspection(CustomIntrospection) end it "can implement visible? to return false for dynamic fields" do assert_equal "Query", HidingIntrospectionSchema.execute("{ __typename }")["data"]["__typename"] error_res = HidingIntrospectionSchema.execute("{ __typename }", context: { hide_introspection: true }) assert_equal ["Field '__typename' doesn't exist on type 'Query'"], error_res["errors"].map { |e| e["message" ]} end it "can implement visible? to return false for entry points" do query_str = "{ __type(name: \"Query\") { name } }" success_res = HidingIntrospectionSchema.execute(query_str) assert_equal "Query", success_res["data"]["__type"]["name"] error_res = HidingIntrospectionSchema.execute(query_str, context: { hide_introspection: true }) assert_equal ["Field '__type' doesn't exist on type 'Query'"], error_res["errors"].map { |e| e["message" ]} end it "can implement visible? to return false for types" do query_str = "{ __schema { queryType { name } } }" success_res = HidingIntrospectionSchema.execute(query_str) assert_equal "Query", success_res["data"]["__schema"]["queryType"]["name"] error_res = HidingIntrospectionSchema.execute(query_str, context: { hide_introspection: true }) assert_equal ["Field '__schema' doesn't exist on type 'Query'"], error_res["errors"].map { |e| e["message" ]} end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/enum_spec.rb
spec/graphql/schema/enum_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Enum do let(:enum) { Jazz::Family } describe ".path" do it "is the name" do assert_equal "Family", enum.path end end describe "value methods" do class EnumWithValueMethods < GraphQL::Schema::Enum value_methods(true) value :SOMETHING value :SOMETHING_ELSE, value_method: false value :SOMETHING_CUSTOM, value_method: :custom end it "defines methods to fetch graphql names when configured" do assert_equal "SOMETHING", EnumWithValueMethods.something assert_equal "SOMETHING", EnumWithValueMethods.something end it "inherits a value_methods config" do new_enum = Class.new(EnumWithValueMethods) new_enum.value(:NEW_VALUE) assert_equal "NEW_VALUE", new_enum.new_value end describe "when value_method is configured" do it "use custom method" do assert_equal enum.respond_to?(:percussion), false assert_equal enum.precussion_custom_value_method, "PERCUSSION" end end describe "when value_method conflicts with existing method" do class ConflictEnum < GraphQL::Schema::Enum value_methods(true) end it "does not define method and emits warning" do expected_message = "Failed to define value method for :value, because ConflictEnum already responds to that method. Use `value_method:` to override the method name or `value_method: false` to disable Enum value method generation.\n" assert_warns(expected_message) do already_defined_method = ConflictEnum.method(:value) ConflictEnum.value "VALUE", "Makes conflict" assert_equal ConflictEnum.method(:value), already_defined_method end end end describe "when value_method = false" do it "does not define method" do assert_equal EnumWithValueMethods.respond_to?(:something_else), false end end it "doesn't define value methods by default" do enum = Class.new(GraphQL::Schema::Enum) { graphql_name("SomeEnum") } enum.value("SOME_VALUE") refute enum.respond_to?(:some_value) end end describe "type info" do it "tells about the definition" do assert_equal "Family", enum.graphql_name assert_equal 29, enum.description.length assert_equal 7, enum.values.size end it "returns defined enum values" do v = nil Class.new(enum) do graphql_name "TestEnum" v = value :PERCUSSION, "new description" end assert_instance_of Jazz::BaseEnumValue, v end it "inherits values and description" do new_enum = Class.new(enum) do value :Nonsense value :PERCUSSION, "new description" end # Description was inherited assert_equal 29, new_enum.description.length # values were inherited without modifying the parent assert_equal 7, enum.values.size assert_equal 8, new_enum.values.size perc_value = new_enum.values["PERCUSSION"] assert_equal "new description", perc_value.description end it "accepts a block" do assert_equal "Neither here nor there, really", enum.values["KEYS"].description end it "is the #owner of its values" do value = enum.values["STRING"] assert_equal enum, value.owner end it "disallows invalid names" do err = assert_raises GraphQL::InvalidNameError do Class.new(GraphQL::Schema::Enum) do graphql_name "Thing" value "IN/VALID" end end assert_includes err.message, "but 'IN/VALID' does not" end end describe "when it fails to coerce to a valid value" do class EnumValueCoerceSchema < GraphQL::Schema class Value < GraphQL::Schema::Enum value "ONE" value "TWO" end class Query < GraphQL::Schema::Object field :value, Value def value "THREE" end end query(Query) rescue_from StandardError do raise GraphQL::ExecutionError, "Sorry, something went wrong." end end it "calls the schema error handlers" do res = EnumValueCoerceSchema.execute("{ value }") assert_equal ["Sorry, something went wrong."], res["errors"].map { |e| e["message"] } end end describe "in queries" do it "works as return values" do query_str = "{ instruments { family } }" expected_families = ["STRING", "WOODWIND", "BRASS", "KEYS", "KEYS", "PERCUSSION"] result = Jazz::Schema.execute(query_str) assert_equal expected_families, result["data"]["instruments"].map { |i| i["family"] } end it "works as input" do query_str = "query($family: Family!) { instruments(family: $family) { name } }" expected_names = ["Piano", "Organ"] result = Jazz::Schema.execute(query_str, variables: { family: "KEYS" }) assert_equal expected_names, result["data"]["instruments"].map { |i| i["name"] } end end describe "multiple values with the same name" do class MultipleNameTestEnum < GraphQL::Schema::Enum value "A" value "B", value: :a value "B", value: :b end it "doesn't allow it from enum_values" do err = assert_raises GraphQL::Schema::DuplicateNamesError do MultipleNameTestEnum.enum_values end expected_message = "Found two visible definitions for `MultipleNameTestEnum.B`: #<GraphQL::Schema::EnumValue MultipleNameTestEnum.B @value=:a>, #<GraphQL::Schema::EnumValue MultipleNameTestEnum.B @value=:b>" assert_equal expected_message, err.message assert_equal "MultipleNameTestEnum.B", err.duplicated_name end it "returns them all in all_enum_value_definitions" do assert_equal 3, MultipleNameTestEnum.all_enum_value_definitions.size end end describe "missing values at runtime" do class EmptyEnumSchema < GraphQL::Schema class EmptyEnum < GraphQL::Schema::Enum end class Query < GraphQL::Schema::Object field :empty_enum, EmptyEnum def empty_enum :something end end query(Query) rescue_from(GraphQL::Schema::Enum::MissingValuesError) do |err, obj, args, ctx, field| if ctx[:handle_error] raise GraphQL::ExecutionError, "Something went wrong!!" else raise err end end end it "requires at least one value at runtime" do err = assert_raises GraphQL::Schema::Enum::MissingValuesError do EmptyEnumSchema.execute("{ emptyEnum }") end expected_message = "Enum types require at least one value, but EmptyEnum didn't provide any for this query. Make sure at least one value is defined and visible for this query." assert_equal expected_message, err.message end it "can be rescued by rescue_error" do res = EmptyEnumSchema.execute("{ emptyEnum }", context: { handle_error: true }) assert_equal ["Something went wrong!!"], res["errors"].map { |e| e["message"] } end end describe "legacy tests" do let(:enum) { Dummy::DairyAnimal } it "coerces names to underlying values" do assert_equal("YAK", enum.coerce_isolated_input("YAK")) assert_equal(1, enum.coerce_isolated_input("COW")) assert_nil(enum.coerce_isolated_input("NONE")) end it "coerces invalid names to nil" do assert_nil(enum.coerce_isolated_input("YAKKITY")) end it "coerces result values to value's value" do assert_equal("NONE", enum.coerce_isolated_result(nil)) assert_equal("YAK", enum.coerce_isolated_result("YAK")) assert_equal("COW", enum.coerce_isolated_result(1)) assert_equal("REINDEER", enum.coerce_isolated_result('reindeer')) assert_equal("DONKEY", enum.coerce_isolated_result(:donkey)) end it "raises a helpful error when a result value can't be coerced" do err = assert_raises(GraphQL::Schema::Enum::UnresolvedValueError) { enum.coerce_result(:nonsense, OpenStruct.new(current_path: ["thing", 0, "name"], current_field: OpenStruct.new(path: "Thing.name"))) } expected_context_message = "`Thing.name` returned `:nonsense` at `thing.0.name`, but this isn't a valid value for `DairyAnimal`. Update the field or resolver to return one of `DairyAnimal`'s values instead." assert_equal expected_context_message, err.message err2 = assert_raises(GraphQL::Schema::Enum::UnresolvedValueError) { enum.coerce_isolated_result(:nonsense) } expected_isolated_message = "`:nonsense` was returned for `DairyAnimal`, but this isn't a valid value for `DairyAnimal`. Update the field or resolver to return one of `DairyAnimal`'s values instead." assert_equal expected_isolated_message, err2.message assert_equal "Dummy::DairyAnimal::UnresolvedValueError", err2.class.name anon_enum = Class.new(GraphQL::Schema::Enum) do graphql_name "AnonEnum" value :one value :two end err3 = assert_raises(GraphQL::Schema::Enum::UnresolvedValueError) { anon_enum.coerce_isolated_result(:nonsense) } expected_anonymous_message = "`:nonsense` was returned for `AnonEnum`, but this isn't a valid value for `AnonEnum`. Update the field or resolver to return one of `AnonEnum`'s values instead." assert_equal expected_anonymous_message, err3.message assert_equal "GraphQL::Schema::Enum::UnresolvedValueError", err3.class.name end describe "resolving with a warden" do it "gets values from the warden" do # OK assert_equal("YAK", enum.coerce_isolated_result("YAK")) # NOT OK assert_raises(GraphQL::Schema::Enum::UnresolvedValueError) { enum.coerce_result("YAK", OpenStruct.new(types: NothingWarden)) } end end describe "invalid values" do it "rejects value names with a space" do assert_raises(GraphQL::InvalidNameError) { Class.new(GraphQL::Schema::Enum) do graphql_name "InvalidEnumValueTest" value("SPACE IN VALUE", "Invalid enum because it contains spaces", value: 1) end } end end describe "invalid name" do it "reject names with invalid format" do assert_raises(GraphQL::InvalidNameError) do Class.new(GraphQL::Schema::Enum) do graphql_name "Some::Invalid::Name" end end end end describe "values that are Arrays" do let(:schema) { Class.new(GraphQL::Schema) do plural = Class.new(GraphQL::Schema::Enum) do graphql_name "Plural" value 'PETS', value: ["dogs", "cats"] value 'FRUITS', value: ["apples", "oranges"] value 'PLANETS', value: ["Earth"] end query = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :names, [String], null: false do argument :things, [plural] end def names(things:) things.reduce(&:+) end end query(query) end } it "accepts them as inputs" do res = schema.execute("{ names(things: [PETS, PLANETS]) }") assert_equal ["dogs", "cats", "Earth"], res["data"]["names"] end end it "accepts a symbol as a value, but stringifies it" do enum = Class.new(GraphQL::Schema::Enum) do graphql_name 'MessageFormat' value :markdown end variant = enum.values['markdown'] assert_equal('markdown', variant.graphql_name) assert_equal('markdown', variant.value) end it "has value description" do assert_equal("Animal with horns", enum.values["GOAT"].description) end describe "validate_input with bad input" do it "returns an invalid result" do result = enum.validate_input("bad enum", GraphQL::Query::NullContext.instance) assert(!result.valid?) assert_equal( result.problems.first['explanation'], "Expected \"bad enum\" to be one of: NONE, COW, DONKEY, GOAT, REINDEER, SHEEP, YAK" ) end end end describe "when values are defined on-the-fly inside #enum_values" do class DynamicEnumValuesSchema < GraphQL::Schema class TransportationMode < GraphQL::Schema::Enum def self.enum_values(context = {}) [ GraphQL::Schema::EnumValue.new("BICYCLE", owner: self), GraphQL::Schema::EnumValue.new("CAR", owner: self), GraphQL::Schema::EnumValue.new("BUS", owner: self), GraphQL::Schema::EnumValue.new("SCOOTER", owner: self), ] end end class Query < GraphQL::Schema::Object field :mode, TransportationMode, fallback_value: "SCOOTER" end query(Query) end it "uses them" do expected_sdl = <<~GRAPHQL type Query { mode: TransportationMode } enum TransportationMode { BICYCLE BUS CAR SCOOTER } GRAPHQL assert_equal expected_sdl, DynamicEnumValuesSchema.to_definition end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/directive_spec.rb
spec/graphql/schema/directive_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive do class MultiWord < GraphQL::Schema::Directive end it "uses a downcased class name" do assert_equal "multiWord", MultiWord.graphql_name end module DirectiveTest class Secret < GraphQL::Schema::Directive argument :top_secret, Boolean class PermissionRule < GraphQL::Schema::InputObject class Permission < GraphQL::Schema::Enum value :READ value :WRITE end argument :team, String argument :permission, Permission end argument :permission_rules, [PermissionRule], required: false locations(FIELD_DEFINITION, ARGUMENT_DEFINITION) end class Thing < GraphQL::Schema::Object field :name, String, null: false do directive Secret, top_secret: true argument :nickname, Boolean, required: false do directive Secret, top_secret: false end end field :other_info, String do directive Secret, top_secret: false, permission_rules: [ { team: "admins", permission: "WRITE" }, { team: "others", permission: "READ"}, ] end end end it "can be added to schema definitions" do field = DirectiveTest::Thing.fields.values.first assert_equal [DirectiveTest::Secret], field.directives.map(&:class) assert_equal [field], field.directives.map(&:owner) assert_equal [true], field.directives.map{ |d| d.arguments[:top_secret] } argument = field.arguments.values.first assert_equal [DirectiveTest::Secret], argument.directives.map(&:class) assert_equal [argument], argument.directives.map(&:owner) assert_equal [false], argument.directives.map{ |d| d.arguments[:top_secret] } other_field = DirectiveTest::Thing.fields.values.last other_field_dir = other_field.directives.first perm_roles = other_field_dir.arguments[:permission_rules] assert_equal Array.new(2, DirectiveTest::Secret::PermissionRule), perm_roles.map(&:class) assert_equal ["WRITE", "READ"], perm_roles.map(&:permission) end it "raises an error when added to the wrong thing" do err = assert_raises ArgumentError do Class.new(GraphQL::Schema::Object) do graphql_name "Stuff" directive DirectiveTest::Secret end end expected_message = "Directive `@secret` can't be attached to Stuff because OBJECT isn't included in its locations (FIELD_DEFINITION, ARGUMENT_DEFINITION). Use `locations(OBJECT)` to update this directive's definition, or remove it from Stuff. " assert_equal expected_message, err.message end it "validates arguments" do err = assert_raises GraphQL::Schema::Directive::InvalidArgumentError do GraphQL::Schema::Field.from_options( name: :something, type: String, null: false, owner: DirectiveTest::Thing, directives: { DirectiveTest::Secret => {} } ) end assert_equal "@secret.topSecret on Thing.something is invalid (nil): Expected value to not be null", err.message end describe 'repeatable directives' do module RepeatDirectiveTest class Secret < GraphQL::Schema::Directive argument :secret, String locations OBJECT, INTERFACE repeatable true end class OtherSecret < GraphQL::Schema::Directive argument :secret, String locations OBJECT, INTERFACE repeatable false end class Thing < GraphQL::Schema::Object directive(Secret, secret: "my secret") directive(Secret, secret: "my second secret") directive(OtherSecret, secret: "other secret") directive(OtherSecret, secret: "second other secret") end end it "allows repeatable directives twice" do directives = RepeatDirectiveTest::Thing.directives secret_directives = directives.select{ |x| x.is_a?(RepeatDirectiveTest::Secret) } assert_equal 2, secret_directives.size assert_equal ["my secret", "my second secret"], secret_directives.map{ |d| d.arguments[:secret] } end it "overwrites non-repeatable directives" do directives = RepeatDirectiveTest::Thing.directives other_directives = directives.select{ |x| x.is_a?(RepeatDirectiveTest::OtherSecret) } assert_equal 1, other_directives.size assert_equal ["second other secret"], other_directives.map{ |d| d.arguments[:secret] } end end module RuntimeDirectiveTest class CountFields < GraphQL::Schema::Directive locations(FIELD, FRAGMENT_SPREAD, INLINE_FRAGMENT) def self.resolve(obj, args, ctx) path = ctx[:current_path] result = nil ctx.dataloader.run_isolated do result = yield ctx.dataloader.run end ctx[:count_fields] ||= Hash.new { |h, k| h[k] = [] } field_count = result.respond_to?(:graphql_result_data) ? result.graphql_result_data.size : 1 ctx[:count_fields][path] << field_count nil # this does nothing end end class Thing < GraphQL::Schema::Object field :name, String, null: false end module HasThings include GraphQL::Schema::Interface field :thing, Thing, null: false, extras: [:ast_node] def thing(ast_node:) context[:name_resolved_count] ||= 0 context[:name_resolved_count] += 1 { name: ast_node.alias || ast_node.name } end field :lazy_thing, Thing, null: false, extras: [:ast_node] def lazy_thing(ast_node:) -> { thing(ast_node: ast_node) } end field :dataloaded_thing, Thing, null: false, extras: [:ast_node] def dataloaded_thing(ast_node:) dataloader.with(ThingSource).load(ast_node.alias || ast_node.name) end field :lazy_things, [Thing], extras: [:ast_node] def lazy_things(ast_node:) -> { [thing(ast_node: ast_node), thing(ast_node: ast_node)]} end end Thing.implements(HasThings) class Query < GraphQL::Schema::Object implements HasThings end class ThingSource < GraphQL::Dataloader::Source def fetch(names) names.map { |n| { name: n } } end end class Schema < GraphQL::Schema query(Query) directive(CountFields) lazy_resolve(Proc, :call) use GraphQL::Dataloader end end describe "runtime directives" do it "works with fragment spreads, inline fragments, and fields" do query_str = <<-GRAPHQL { t1: dataloadedThing { t1n: name @countFields } ... @countFields { t2: thing { t2n: name } t3: thing { t3n: name } } t3: thing { t3n: name } t4: lazyThing { ...Thing @countFields } t5: thing { n5: name t5d: dataloadedThing { t5dl: lazyThing { t5dln: name @countFields } } } } fragment Thing on Thing { n1: name n2: name n3: name } GRAPHQL res = RuntimeDirectiveTest::Schema.execute(query_str) expected_data = { "t1" => { "t1n" => "t1", }, "t2"=>{"t2n"=>"t2"}, "t3"=>{"t3n"=>"t3"}, "t4" => { "n1" => "t4", "n2" => "t4", "n3" => "t4", }, "t5"=>{"n5"=>"t5", "t5d"=>{"t5dl"=>{"t5dln"=>"t5dl"}}}, } assert_graphql_equal expected_data, res["data"] expected_counts = { ["t1", "t1n"] => [1], [] => [2], ["t4"] => [3], ["t5", "t5d", "t5dl", "t5dln"] => [1], } assert_equal expected_counts, res.context[:count_fields] end it "runs things twice when they're in with-directive and without-directive parts of the query" do query_str = <<-GRAPHQL { t1: thing { name } # name_resolved_count = 1 t2: thing { name } # name_resolved_count = 2 ... @countFields { t1: thing { name } # name_resolved_count = 3 t3: thing { name } # name_resolved_count = 4 } t3: thing { name } # name_resolved_count = 5 ... { t2: thing { name @countFields } # This is merged back into `t2` above } } GRAPHQL res = RuntimeDirectiveTest::Schema.execute(query_str) expected_data = { "t1" => { "name" => "t1"}, "t2" => { "name" => "t2" }, "t3" => { "name" => "t3" } } assert_graphql_equal expected_data, res["data"] expected_counts = { [] => [2], ["t2", "name"] => [1], } assert_equal expected_counts, res.context[:count_fields] assert_equal 5, res.context[:name_resolved_count] end it "works with backtrace: true and lazy lists" do query_str = " { lazyThings @countFields { name } } " res = RuntimeDirectiveTest::Schema.execute(query_str, context: { backtrace: true }) assert_equal 2, res["data"]["lazyThings"].size end end describe "raising an error from an argument" do class DirectiveErrorSchema < GraphQL::Schema class MyDirective < GraphQL::Schema::Directive locations GraphQL::Schema::Directive::QUERY, GraphQL::Schema::Directive::FIELD argument :input, String, prepare: ->(input, ctx) { raise GraphQL::ExecutionError, "invalid argument" } end class QueryType < GraphQL::Schema::Object field :hello, String, null: false def hello "Hello World!" end end query QueryType directive MyDirective end it "halts execution and adds an error to the error key" do result = DirectiveErrorSchema.execute(<<-GQL) query @myDirective(input: "hi") { hello } GQL assert_equal({}, result["data"]) assert_equal ["invalid argument"], result["errors"].map { |e| e["message"] } assert_equal [[{"line"=>1, "column"=>13}]], result["errors"].map { |e| e["locations"] } result2 = DirectiveErrorSchema.execute(<<-GQL) query { hello hello2: hello @myDirective(input: "hi") } GQL assert_equal({ "hello" => "Hello World!" }, result2["data"]) assert_equal ["invalid argument"], result2["errors"].map { |e| e["message"] } assert_equal [[{"line"=>3, "column"=>23}]], result2["errors"].map { |e| e["locations"] } end end describe ".resolve_each" do class ResolveEachSchema < GraphQL::Schema class FilterByIndex < GraphQL::Schema::Directive locations FIELD argument :select, String def self.resolve_each(object, args, context) if context[:current_path].last.public_send(args[:select]) yield else # Don't send a value end end def self.resolve(obj, args, ctx) value = yield value.values.compact! value end end class Query < GraphQL::Schema::Object field :numbers, [Integer] def numbers [0,1,2,3,4,5] end end query(Query) directive(FilterByIndex) end it "is called for each item in a list during enumeration" do res = ResolveEachSchema.execute("{ numbers @filterByIndex(select: \"even?\")}") assert_equal [0,2,4], res["data"]["numbers"] res = ResolveEachSchema.execute("{ numbers @filterByIndex(select: \"odd?\")}") assert_equal [1,3,5], res["data"]["numbers"] end end it "parses repeated directives" do schema_sdl = <<~EOS directive @tag(name: String!) repeatable on ARGUMENT_DEFINITION | ENUM | ENUM_VALUE | FIELD_DEFINITION | INPUT_FIELD_DEFINITION | INPUT_OBJECT | INTERFACE | OBJECT | SCALAR | UNION type Query @tag(name: "t1") @tag(name: "t2") { something( arg: Boolean @tag(name: "t3") @tag(name: "t4") ): Stuff @tag(name: "t5") @tag(name: "t6") } enum Stuff { THING @tag(name: "t7") @tag(name: "t8") } EOS schema = GraphQL::Schema.from_definition(schema_sdl) query_type = schema.query assert_equal [["tag", { name: "t1" }], ["tag", { name: "t2" }]], query_type.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } field = schema.get_field("Query", "something") arg = field.get_argument("arg") assert_equal [["tag", { name: "t3"}], ["tag", { name: "t4"}]], arg.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } assert_equal [["tag", { name: "t5"}], ["tag", { name: "t6"}]], field.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } enum_value = schema.get_type("Stuff").values["THING"] assert_equal [["tag", { name: "t7"}], ["tag", { name: "t8"}]], enum_value.directives.map { |dir| [dir.graphql_name, dir.arguments.to_h] } end describe "Custom validations on definition directives" do class DirectiveValidationSchema < GraphQL::Schema class SomeEnum < GraphQL::Schema::Enum value :VALUE_ONE, value: :v1 end class ValidatedDirective < GraphQL::Schema::Directive locations OBJECT, FIELD argument :f, Float, required: false, validates: { numericality: { greater_than: 0 } } argument :s, String, required: false, validates: { format: { with: /^[a-z]{3}$/ } } argument :e, SomeEnum, required: false validates required: { one_of: [:f, :s]} end class Query < GraphQL::Schema::Object field :i, Int, fallback_value: 100 end query(Query) directive(ValidatedDirective) end it "runs custom validation during execution" do f_err_res = DirectiveValidationSchema.execute("{ i @validatedDirective(f: -10) }") assert_equal [{"message" => "f must be greater than 0", "locations" => [{"line" => 1, "column" => 5}], "path" => ["i"]}], f_err_res["errors"] s_err_res = DirectiveValidationSchema.execute("{ i @validatedDirective(s: \"wnrn\") }") assert_equal [{"message" => "s is invalid", "locations" => [{"line" => 1, "column" => 5}], "path" => ["i"]}], s_err_res["errors"] f_s_err_res = DirectiveValidationSchema.execute("{ i @validatedDirective }") assert_equal [{"message" => "validatedDirective must include exactly one of the following arguments: f, s.", "locations" => [{"line" => 1, "column" => 5}], "path" => ["i"]}], f_s_err_res["errors"] end it "works with enums with symbol values" do e_err = DirectiveValidationSchema.execute("{ i @validatedDirective(e: VALUE_BLAH, f: 1.0) }") assert_equal ["Argument 'e' on Directive 'validatedDirective' has an invalid value (VALUE_BLAH). Expected type 'SomeEnum'."], e_err["errors"].map { |e| e["message"] } e_res = DirectiveValidationSchema.execute("{ i @validatedDirective(e: VALUE_ONE, f: 1.0) }") assert_equal 100, e_res["data"]["i"] obj_type = Class.new(GraphQL::Schema::Object) obj_type.graphql_name("EnumTestObj") directive_defn = DirectiveValidationSchema::ValidatedDirective obj_type.directive(directive_defn, f: 1, e: :v1) e_err = assert_raises GraphQL::Schema::Directive::InvalidArgumentError do obj_type.directive(directive_defn, f: 1, e: :blah) end assert_equal "@validatedDirective.e on EnumTestObj is invalid (:blah): Expected \"blah\" to be one of: VALUE_ONE", e_err.message end it "runs custom validation during definition" do obj_type = Class.new(GraphQL::Schema::Object) directive_defn = DirectiveValidationSchema::ValidatedDirective obj_type.directive(directive_defn, f: 1) f_err = assert_raises GraphQL::Schema::Validator::ValidationFailedError do obj_type.directive(directive_defn, f: -1) end assert_equal "f must be greater than 0", f_err.message obj_type.directive(directive_defn, s: "abc") s_err = assert_raises GraphQL::Schema::Validator::ValidationFailedError do obj_type.directive(directive_defn, s: "defg") end assert_equal "s is invalid", s_err.message required_err = assert_raises GraphQL::Schema::Validator::ValidationFailedError do obj_type.directive(directive_defn) end assert_equal "validatedDirective must include exactly one of the following arguments: f, s.", required_err.message end end describe "Validating schema directives" do def build_sdl(size:) <<~GRAPHQL directive @tshirt(size: Size!) on INTERFACE | OBJECT type MyType @tshirt(size: #{size}) { color: String } type Query { myType: MyType } enum Size { LARGE MEDIUM SMALL } GRAPHQL end it "Raises a nice error for invalid enum values" do valid_sdl = build_sdl(size: "MEDIUM") assert_equal valid_sdl, GraphQL::Schema.from_definition(valid_sdl).to_definition typo_sdl = build_sdl(size: "BLAH") err = assert_raises GraphQL::Schema::Directive::InvalidArgumentError do GraphQL::Schema.from_definition(typo_sdl) end expected_msg = '@tshirt.size on MyType is invalid ("BLAH"): Expected "BLAH" to be one of: LARGE, MEDIUM, SMALL' assert_equal expected_msg, err.message end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/scalar_spec.rb
spec/graphql/schema/scalar_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Scalar do describe ".path" do it "is the name" do assert_equal "String", GraphQL::Types::String.path end end describe "in queries" do it "becomes output" do query_str = <<-GRAPHQL { find(id: "Musician/Herbie Hancock") { ... on Musician { name favoriteKey } } } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal "B♭", res["data"]["find"]["favoriteKey"] end it "handles infinity values" do query_str = <<-GRAPHQL { find(id: 9999.0e9999) { __typename } } GRAPHQL res = Jazz::Schema.execute(query_str) expected_errors = ["Argument 'id' on Field 'find' has an invalid value. Expected type 'ID!'."] assert_equal expected_errors, res["errors"].map { |e| e["message"] } end it "can be input" do query_str = <<-GRAPHQL { inspectKey(key: "F♯") { root isSharp isFlat } } GRAPHQL res = Jazz::Schema.execute(query_str) key_info = res["data"]["inspectKey"] assert_equal "F", key_info["root"] assert_equal true, key_info["isSharp"] assert_equal false, key_info["isFlat"] end it "can be nested JSON" do query_str = <<-GRAPHQL { echoJson(input: {foo: [{bar: "baz"}]}) } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal({"foo" => [{"bar" => "baz"}]}, res["data"]["echoJson"]) end it "can be a JSON array" do query_str = <<-GRAPHQL { echoFirstJson(input: [{foo: "bar"}, {baz: "boo"}]) } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal({"foo" => "bar"}, res["data"]["echoFirstJson"]) end it "can be a JSON array even if the GraphQL type is not an array" do query_str = <<-GRAPHQL { echoJson(input: [{foo: "bar"}]) } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal([{"foo" => "bar"}], res["data"]["echoJson"]) end it "can be JSON with a nested enum" do query_str = <<-GRAPHQL { echoJson(input: [{foo: WOODWIND}]) } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal([{"foo" => "WOODWIND"}], res["data"]["echoJson"]) end it "cannot be JSON with a nested variable" do query_str = <<-GRAPHQL { echoJson(input: [{foo: $var}]) } GRAPHQL res = Jazz::Schema.execute(query_str) assert_includes(res["errors"][0]["message"], "Argument 'input' on Field 'echoJson' has an invalid value") end end describe "raising CoercionError" do class CoercionErrorSchema < GraphQL::Schema class CustomScalar < GraphQL::Schema::Scalar def self.coerce_input(val, ctx) raise GraphQL::CoercionError, "#{val.inspect} can't be Custom value" end def self.coerce_result(val, ctx) raise GraphQL::CoercionError, "#{val.inspect} can't be Custom value" end end class Query < GraphQL::Schema::Object field :f1, String do argument :arg, CustomScalar end field :f2, CustomScalar def f2 "bad" end end query(Query) end it "makes a nice validation error for input coercion" do result = CoercionErrorSchema.execute("{ f1(arg: \"a\") }") expected_error = { "message" => "\"a\" can't be Custom value", "locations" => [{"line"=>1, "column"=>3}], "path" => ["query", "f1", "arg"], "extensions" => { "code"=>"argumentLiteralsIncompatible", "typeName"=>"CoercionError" } } assert_equal [expected_error], result["errors"] end it "makes a nice validation error for reuslt coercion" do result = CoercionErrorSchema.execute("{ f2 }") expected_error = { "message" => "\"bad\" can't be Custom value", "locations" => [{"line"=>1, "column"=>3}], "path" => ["f2"], } assert_equal [expected_error], result["errors"] end end describe "validate_input with good input" do let(:result) { GraphQL::Types::Int.validate_input(150, GraphQL::Query::NullContext.instance) } it "returns a valid result" do assert(result.valid?) end end describe "validate_input with bad input" do let(:result) { GraphQL::Types::Int.validate_input("bad num", GraphQL::Query::NullContext.instance) } it "returns an invalid result for bad input" do assert(!result.valid?) end it "has one problem" do assert_equal(result.problems.length, 1) end it "has the correct explanation" do assert(result.problems[0]["explanation"].include?("Could not coerce value")) end it "has an empty path" do assert(result.problems[0]["path"].empty?) end end describe "Custom scalars" do let(:custom_scalar) { Class.new(GraphQL::Schema::Scalar) do graphql_name "BigInt" def self.coerce_input(value, _ctx) value =~ /\d+/ ? Integer(value) : nil end def self.coerce_result(value, _ctx) value.to_s end end } let(:bignum) { 2 ** 128 } it "is not a default scalar" do assert_equal(false, custom_scalar.default_scalar?) end it "coerces nil into nil" do assert_nil(custom_scalar.coerce_isolated_input(nil)) end it "coerces input into objects" do assert_equal(bignum, custom_scalar.coerce_isolated_input(bignum.to_s)) end it "coerces result value for serialization" do assert_equal(bignum.to_s, custom_scalar.coerce_isolated_result(bignum)) end describe "custom scalar errors" do let(:result) { custom_scalar.validate_input("xyz", GraphQL::Query::NullContext.instance) } it "returns an invalid result" do assert !result.valid? assert_equal 'Could not coerce value "xyz" to BigInt', result.problems[0]["explanation"] end end end it "handles coercing null" do class CoerceNullSchema < GraphQL::Schema class CustomScalar < GraphQL::Schema::Scalar class << self def coerce_input(input_value, _context) raise GraphQL::CoercionError, "Invalid value: #{input_value.inspect}" end end end class QueryType < GraphQL::Schema::Object field :hello, String do argument :input, CustomScalar, required: false end def hello(input: nil) "hello world" end end query(QueryType) end result = CoerceNullSchema.execute('{ hello(input: 5) }') assert_equal(["Invalid value: 5"], result["errors"].map { |err| err["message"] }) null_input_result = CoerceNullSchema.execute('{ hello(input: null) }') assert_equal(["Invalid value: nil"], null_input_result["errors"].map { |err| err["message"] }) end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/field_spec.rb
spec/graphql/schema/field_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Field do describe "graphql definition" do let(:object_class) { Jazz::Query } let(:field) { object_class.fields["inspectInput"] } describe "path" do it "is the object/interface and field name" do assert_equal "Query.inspectInput", field.path assert_equal "GloballyIdentifiable.id", Jazz::GloballyIdentifiableType.fields["id"].path end end describe "inspect" do it "includes the path and return type" do assert_equal "#<Jazz::BaseField Query.inspectInput(...): [String!]!>", field.inspect end end it "can add argument directly with add_argument" do argument = Jazz::Query.fields["instruments"].arguments["family"] field.add_argument(argument) assert_equal "family", field.arguments["family"].name assert_equal Jazz::Family, field.arguments["family"].type end it "camelizes the field name, unless camelize: false" do assert_equal 'inspectInput', field.name underscored_field = GraphQL::Schema::Field.from_options(:underscored_field, String, null: false, camelize: false, owner: nil) do argument :underscored_arg, String, camelize: false end.ensure_loaded arg_name, arg_defn = underscored_field.arguments.first assert_equal 'underscored_arg', arg_name assert_equal 'underscored_arg', arg_defn.name end it "works with arbitrary hash keys" do result = Jazz::Schema.execute "{ complexHashKey }", root_value: { :'foo bar/fizz-buzz' => "OK!"} hash_val = result["data"]["complexHashKey"] assert_equal "OK!", hash_val, "It looked up the hash key" end it "exposes the method override" do object = Class.new(Jazz::BaseObject) do field :t, String, method: :tt, null: true end assert_equal :tt, object.fields["t"].method_sym assert_equal "tt", object.fields["t"].method_str end it "accepts a block for definition" do field_defn = nil object = Class.new(Jazz::BaseObject) do graphql_name "JustAName" field_defn = field :test do argument :test, String description "A Description." comment "A Comment." type String end end assert_nil field_defn.description, "The block isn't called right away" assert_nil field_defn.type, "The block isn't called right away" field_defn.ensure_loaded assert_equal "String", field_defn.type.graphql_name assert_equal "test", object.fields["test"].arguments["test"].name assert_equal "A Description.", object.fields["test"].description assert_equal "A Comment.", object.fields["test"].comment end it "sets connection? when type is given in a block" do field_defn = nil Class.new(Jazz::BaseObject) do graphql_name "JustAName" field_defn = field :instruments do type Jazz::InstrumentType.connection_type end end assert_equal false, field_defn.connection? assert_equal false, field_defn.scoped? assert_equal [], field_defn.extensions field_defn.ensure_loaded assert_equal true, field_defn.scoped? assert_equal true, field_defn.connection? assert_equal [GraphQL::Schema::Field::ScopeExtension, GraphQL::Schema::Field::ConnectionExtension], field_defn.extensions.map(&:class) end it "accepts a block for definition and yields the field if the block has an arity of one" do object = Class.new(Jazz::BaseObject) do graphql_name "JustAName" field :test, String do |field| field.argument :test, String field.description "A Description." field.comment "A Comment." end end assert_equal "test", object.fields["test"].arguments["test"].name assert_equal "A Description.", object.fields["test"].description assert_equal "A Comment.", object.fields["test"].comment end it "accepts anonymous classes as type" do type = Class.new(GraphQL::Schema::Object) do graphql_name 'MyType' end field = GraphQL::Schema::Field.from_options(:my_field, type, owner: nil, null: true) assert_equal type, field.type end describe "introspection?" do it "returns false on regular fields" do assert_equal false, field.introspection? end it "returns true on predefined introspection fields" do assert_equal true, GraphQL::Schema.types['__Type'].fields.values.first.introspection? end end describe "extras" do it "can get errors, which adds path" do query_str = <<-GRAPHQL query { find(id: "Musician/Herbie Hancock") { ... on Musician { addError } } } GRAPHQL res = Jazz::Schema.execute(query_str) err = res["errors"].first assert_equal "this has a path", err["message"] assert_equal ["find", "addError"], err["path"] assert_equal [{"line"=>4, "column"=>15}], err["locations"] end it "can get methods from the field instance" do query_str = <<-GRAPHQL { upcaseCheck1 upcaseCheck2 upcaseCheck3 upcaseCheck4 } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal "nil", res["data"].fetch("upcaseCheck1") assert_equal "false", res["data"]["upcaseCheck2"] assert_equal "TRUE", res["data"]["upcaseCheck3"] assert_equal "\"WHY NOT?\"", res["data"]["upcaseCheck4"] end it "can be read via #extras" do field = Jazz::Musician.fields["addError"] assert_equal [:execution_errors], field.extras end it "can be added by passing an array of symbols to #extras" do object = Class.new(Jazz::BaseObject) do graphql_name "JustAName" field :test, String, extras: [:lookahead] end field = object.fields['test'] field.extras([:ast_node]) assert_equal [:lookahead, :ast_node], field.extras end describe "ruby argument error" do class ArgumentErrorSchema < GraphQL::Schema class Query < GraphQL::Schema::Object def inspect "#<#{self.class}>" end field :f1, String do argument :something, Int, required: false end def f1 "OK" end field :f2, String, resolver_method: :field_2 do argument :something, Int, required: false end def field_2(something_else: nil) "ALSO OK" end field :f3, String do argument :something, Int, required: false end def f3(always_missing:) "NEVER OK" end field :f4, String def f4(never_positional, ok_optional = :ok, *ok_rest) "NEVER OK" end field :f5, String do argument :something, Int, required: false end def f5(**ok_keyrest) "OK" end end query(Query) end it "raises a nice error when missing" do assert_equal "OK", ArgumentErrorSchema.execute("{ f1 }")["data"]["f1"] assert_equal "ALSO OK", ArgumentErrorSchema.execute("{ f2 }")["data"]["f2"] err = assert_raises GraphQL::Schema::Field::FieldImplementationFailed do ArgumentErrorSchema.execute("{ f1(something: 12) }") end assert_equal "Failed to call `:f1` on #<ArgumentErrorSchema::Query> because the Ruby method params were incompatible with the GraphQL arguments: - `something: 12` was given by GraphQL but not defined in the Ruby method. Add `something:` to the method parameters. ", err.message assert_instance_of ArgumentError, err.cause err = assert_raises GraphQL::Schema::Field::FieldImplementationFailed do ArgumentErrorSchema.execute("{ f2(something: 12) }") end assert_equal "Failed to call `:field_2` on #<ArgumentErrorSchema::Query> because the Ruby method params were incompatible with the GraphQL arguments: - `something: 12` was given by GraphQL but not defined in the Ruby method. Add `something:` to the method parameters. ", err.message err = assert_raises GraphQL::Schema::Field::FieldImplementationFailed do ArgumentErrorSchema.execute("{ f3(something: 1) }") end assert_equal "Failed to call `:f3` on #<ArgumentErrorSchema::Query> because the Ruby method params were incompatible with the GraphQL arguments: - `something: 1` was given by GraphQL but not defined in the Ruby method. Add `something:` to the method parameters. - `always_missing:` is required by Ruby, but not by GraphQL. Consider `always_missing: nil` instead, or making this argument required in GraphQL. ", err.message err = assert_raises GraphQL::Schema::Field::FieldImplementationFailed do ArgumentErrorSchema.execute("{ f4 }") end assert_equal "Failed to call `:f4` on #<ArgumentErrorSchema::Query> because the Ruby method params were incompatible with the GraphQL arguments: - `never_positional` is required by Ruby, but GraphQL doesn't pass positional arguments. If it's meant to be a GraphQL argument, use `never_positional:` instead. Otherwise, remove it. ", err.message assert_equal "OK", ArgumentErrorSchema.execute("{ f5(something: 2) }")["data"]["f5"] end end describe "argument_details" do class ArgumentDetailsSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :argument_details, [String], null: false, extras: [:argument_details] do argument :arg1, Int, required: false argument :arg2, Int, required: false, default_value: 2 end def argument_details(argument_details:, arg1: nil, arg2:) [ argument_details.class.name, argument_details.argument_values.values.first.class.name, # `.keyword_arguments` includes extras: argument_details.keyword_arguments.keys.join("|"), # `.argument_values` includes only defined GraphQL arguments: argument_details.argument_values.keys.join("|"), argument_details.argument_values[:arg2].default_used?.inspect ] end end query(Query) end it "provides metadata about arguments" do res = ArgumentDetailsSchema.execute("{ argumentDetails }") expected_strs = [ "GraphQL::Execution::Interpreter::Arguments", "GraphQL::Execution::Interpreter::ArgumentValue", "arg2|argument_details", "arg2", "true", ] assert_equal expected_strs, res["data"]["argumentDetails"] end end end it "is the #owner of its arguments" do field = Jazz::Query.fields["find"] argument = field.arguments["id"] assert_equal field, argument.owner end it "has a reference to the object that owns it with #owner" do assert_equal Jazz::Query, field.owner end describe "type" do it "tells the return type" do assert_equal "[String!]!", field.type.to_type_signature end it "returns the type class" do field = Jazz::Query.fields["nowPlaying"] assert_equal Jazz::PerformingAct, field.type.of_type end end describe "complexity" do it "accepts a keyword argument" do object = Class.new(Jazz::BaseObject) do graphql_name "complexityKeyword" field :complexityTest, String, complexity: 25 end assert_equal 25, object.fields["complexityTest"].complexity end it "accepts a proc in the definition block" do object = Class.new(Jazz::BaseObject) do graphql_name "complexityKeyword" field :complexityTest, String do complexity ->(_ctx, _args, _child_complexity) { 52 } end end assert_equal 52, object.fields["complexityTest"].complexity.call(nil, nil, nil) end it "accepts an integer in the definition block" do object = Class.new(Jazz::BaseObject) do graphql_name "complexityKeyword" field :complexityTest, String do complexity 38 end end assert_equal 38, object.fields["complexityTest"].complexity end it 'fails if the complexity is not numeric and not a proc' do err = assert_raises(RuntimeError) do Class.new(Jazz::BaseObject) do graphql_name "complexityKeyword" field :complexityTest, String do complexity 'One hundred and eighty' end.ensure_loaded end end assert_match(/^Invalid complexity:/, err.message) end it 'fails if the proc does not accept 3 parameters' do err = assert_raises(RuntimeError) do Class.new(Jazz::BaseObject) do graphql_name "complexityKeyword" field :complexityTest, String do complexity ->(one, two) { 52 } end.ensure_loaded end end assert_match(/^A complexity proc should always accept 3 parameters/, err.message) end it 'fails if second argument is a mutation instead of a type' do mutation_class = Class.new(GraphQL::Schema::Mutation) do graphql_name "Thing" field :stuff, String, null: false end err = assert_raises(ArgumentError) do Class.new(Jazz::BaseObject) do graphql_name "complexityKeyword" field :complexityTest, mutation_class end end assert_match(/^Use `field :complexityTest, mutation: Mutation, ...` to provide a mutation to this field instead/, err.message) end end end describe "build type errors" do it "includes the full name" do thing = Class.new(GraphQL::Schema::Object) do graphql_name "Thing" # `Set` is a class but not a GraphQL type field :stuff, Set, null: false end err = assert_raises GraphQL::Schema::Field::MissingReturnTypeError do thing.fields["stuff"].type end assert_includes err.message, "Thing.stuff" assert_includes err.message, "Unexpected class/module" end it "makes a suggestion when the type is false" do err = assert_raises GraphQL::Schema::Field::MissingReturnTypeError do Class.new(GraphQL::Schema::Object) do graphql_name "Thing" # False might come from an invalid `!` field :stuff, false, null: false end end assert_includes err.message, "Thing.stuff" assert_includes err.message, "Received `false` instead of a type, maybe a `!` should be replaced with `null: true` (for fields) or `required: true` (for arguments)" end end describe "mutation" do it "passes when not including extra arguments" do mutation_class = Class.new(GraphQL::Schema::Mutation) do graphql_name "Thing" field :stuff, String, null: false end obj = Class.new(GraphQL::Schema::Object) do field(:my_field, mutation: mutation_class, null: true) end assert_equal obj.fields["myField"].mutation, mutation_class end end describe '#deprecation_reason' do it "reads and writes" do object_class = Class.new(GraphQL::Schema::Object) do graphql_name "Thing" field :stuff, String, null: false, deprecation_reason: "Broken" end field = object_class.fields["stuff"] assert_equal "Broken", field.deprecation_reason field.deprecation_reason += "!!" assert_equal "Broken!!", field.deprecation_reason end end describe "#original_name" do it "is exactly the same as the passed in name" do field = GraphQL::Schema::Field.from_options( :my_field, String, null: false, camelize: true ) assert_equal :my_field, field.original_name end end describe "generated default" do class GeneratedDefaultTestSchema < GraphQL::Schema class BaseField < GraphQL::Schema::Field def resolve_field(obj, args, ctx) resolve(obj, args, ctx) end end class Company < GraphQL::Schema::Object field :id, ID, null: false end class Query < GraphQL::Schema::Object field_class BaseField field :company, Company do argument :id, ID end def company(id:) OpenStruct.new(id: id) end end query(Query) end it "works" do res = GeneratedDefaultTestSchema.execute("{ company(id: \"1\") { id } }") assert_equal "1", res["data"]["company"]["id"] end end describe ".connection_extension" do class CustomConnectionExtension < GraphQL::Schema::Field::ConnectionExtension def apply super field.argument(:z, String, required: false) end end class CustomExtensionField < GraphQL::Schema::Field connection_extension(CustomConnectionExtension) end class CustomExtensionObject < GraphQL::Schema::Object field_class CustomExtensionField field :ints, GraphQL::Types::Int.connection_type, null: false, scope: false end it "can be customized" do field = CustomExtensionObject.fields["ints"] assert_equal [CustomConnectionExtension], field.extensions.map(&:class) assert_equal ["after", "before", "first", "last", "z"], field.arguments.keys.sort end it "can be inherited" do child_field_class = Class.new(CustomExtensionField) assert_equal CustomConnectionExtension, child_field_class.connection_extension end end describe "retrieving nested hash keys using dig" do class DigSchema < GraphQL::Schema class PersonType < GraphQL::Schema::Object field :name, String, null: false end class MovieType < GraphQL::Schema::Object field :title, String, null: false, dig: [:title] field :stars, [PersonType], null: false, dig: ["credits", "stars"] field :metascore, Float, null: false, dig: [:meta, "metascore"] field :release_date, String, null: false, dig: [:meta, :release_date] field :includes_wilhelm_scream, Boolean, null: false, dig: [:meta, "wilhelm_scream"] field :nullable_field, String, dig: [:this_should, :work_since, :dig_handles, :safe_expansion] end class QueryType < GraphQL::Schema::Object field :a_good_laugh, MovieType, null: false def a_good_laugh { :title => "Monty Python and the Holy Grail", :meta => { "metascore" => 91, :release_date => "1975-05-25T00:00:00+00:00", "wilhelm_scream" => false }, "credits" => { "stars" => [ { :name => "Graham Chapman" }, { :name => "John Cleese" } ] } } end end query(QueryType) end it "finds the expected data" do res = DigSchema.execute <<-GRAPHQL { aGoodLaugh { title includesWilhelmScream metascore nullableField releaseDate stars { name } } } GRAPHQL result = res["data"]["aGoodLaugh"] expected_result = { "title" => "Monty Python and the Holy Grail", "includesWilhelmScream" => false, "metascore" => 91.0, "nullableField" => nil, "releaseDate" => "1975-05-25T00:00:00+00:00", "stars" => [ { "name" => "Graham Chapman" }, { "name" => "John Cleese" } ] } assert_graphql_equal expected_result, result end end describe "looking up hash keys with case" do class HashKeySchema < GraphQL::Schema class ResultType < GraphQL::Schema::Object field :lowercase, String, camelize: false, null: true field :Capital, String, camelize: false, null: true field :Other, String, camelize: true, null: true field :OtherCapital, String, camelize: false, null: true, hash_key: "OtherCapital" # regression test against https://github.com/rmosolgo/graphql-ruby/issues/3944 field :method, String, camelize: false, null: false, hash_key: "some_random_key" field :stringified_hash_key, String, null: false, hash_key: :stringified_hash_key field :boolean_true_with_hash_key, Boolean, null: false, hash_key: :boolean_true_with_hash_key field :boolean_false_with_hash_key, Boolean, null: false, hash_key: :boolean_false_with_hash_key field :boolean_false_with_symbolized_hash_key, Boolean, null: false, hash_key: :boolean_false_with_symbolized_hash_key end class QueryType < GraphQL::Schema::Object field :search_results, ResultType, null: false def search_results { "lowercase" => "lowercase-works", "Capital" => "capital-camelize-false-works", "Other" => "capital-camelize-true-works", "OtherCapital" => "explicit-hash-key-works", "some_random_key" => "hash-key-works-when-underlying-object-responds-to-field-name", "stringified_hash_key" => "hash-key-is-tried-as-string", "boolean_true_with_hash_key" => true, "boolean_false_with_hash_key" => false, :boolean_false_with_symbolized_hash_key => false } end field :ostruct_results, ResultType, null: false def ostruct_results OpenStruct.new(search_results) end end query(QueryType) end it "finds exact matches by hash key" do res = HashKeySchema.execute <<-GRAPHQL { searchResults { method lowercase Capital Other OtherCapital stringifiedHashKey booleanTrueWithHashKey booleanFalseWithHashKey booleanFalseWithSymbolizedHashKey } } GRAPHQL search_results = res["data"]["searchResults"] expected_result = { "method" => "hash-key-works-when-underlying-object-responds-to-field-name", "lowercase" => "lowercase-works", "Capital" => "capital-camelize-false-works", "Other" => "capital-camelize-true-works", "OtherCapital" => "explicit-hash-key-works", "stringifiedHashKey" => "hash-key-is-tried-as-string", "booleanTrueWithHashKey" => true, "booleanFalseWithHashKey" => false, "booleanFalseWithSymbolizedHashKey" => false } assert_graphql_equal expected_result, search_results end it "works with non-hash instances" do res = HashKeySchema.execute <<-GRAPHQL { ostructResults { method lowercase Capital Other OtherCapital stringifiedHashKey booleanTrueWithHashKey booleanFalseWithHashKey booleanFalseWithSymbolizedHashKey } } GRAPHQL search_results = res["data"]["ostructResults"] expected_result = { "method" => "hash-key-works-when-underlying-object-responds-to-field-name", "lowercase" => "lowercase-works", "Capital" => "capital-camelize-false-works", "Other" => "capital-camelize-true-works", "OtherCapital" => "explicit-hash-key-works", "stringifiedHashKey" => "hash-key-is-tried-as-string", "booleanTrueWithHashKey" => true, "booleanFalseWithHashKey" => false, "booleanFalseWithSymbolizedHashKey" => false } assert_graphql_equal expected_result, search_results end it "populates `method_str`" do hash_key_field = HashKeySchema.get_field("Result", "method") assert_equal "some_random_key", hash_key_field.method_str end end describe "when the owner is nil" do it "raises a descriptive error" do bad_field = GraphQL::Schema::Field.new(name: "something", owner: nil, type: String) assert_nil bad_field.owner err = assert_raises GraphQL::InvariantError do bad_field.owner_type end expected_message = "Field \"something\" (graphql name: \"something\") has no owner, but all fields should have an owner. How did this happen?! This is probably a bug in GraphQL-Ruby, please report this error on GitHub: https://github.com/rmosolgo/graphql-ruby/issues/new?template=bug_report.md" assert_equal expected_message, err.message end end it "Delegates many properties to its @resolver_class" do resolver = Class.new(GraphQL::Schema::Resolver) do description "description 1" comment "comment 1" type [GraphQL::Types::Float], null: true argument :b, GraphQL::Types::Float end field = GraphQL::Schema::Field.new(name: "blah", owner: nil, resolver_class: resolver, extras: [:blah]) do argument :a, GraphQL::Types::Int end field.ensure_loaded assert_equal "description 1", field.description assert_equal "comment 1", field.comment assert_equal "[Float!]", field.type.to_type_signature assert_equal 1, field.complexity assert_equal :resolve_with_support, field.resolver_method assert_nil field.broadcastable? assert_equal false, field.has_max_page_size? assert_nil field.max_page_size assert_equal [:blah], field.extras assert_equal [:b, :a], field.all_argument_definitions.map(&:keyword) assert_equal true, field.scoped? resolver.description("description 2") resolver.comment("comment 2") resolver.type(GraphQL::Types::String, null: false) resolver.complexity(5) resolver.resolver_method(:blah) resolver.broadcastable(true) resolver.max_page_size(100) resolver.extras([:foo]) resolver.argument(:c, GraphQL::Types::Boolean) assert_equal "description 2", field.description assert_equal "comment 2", field.comment assert_equal "String!", field.type.to_type_signature assert_equal 5, field.complexity assert_equal :blah, field.resolver_method assert_equal true, field.broadcastable? assert_equal true, field.has_max_page_size? assert_equal 100, field.max_page_size assert_equal [:blah, :foo], field.extras assert_equal [:b, :c, :a], field.all_argument_definitions.map(&:keyword) assert_equal false, field.scoped? end it "accepts partial overrides for type an nullability" do nonnull_float_resolver = Class.new(GraphQL::Schema::Resolver) do type GraphQL::Types::Float, null: false end nullable_field = GraphQL::Schema::Field.new(name: "blah", owner: nil, resolver_class: nonnull_float_resolver, null: true) assert_equal "Float", nullable_field.type.to_type_signature int_field = GraphQL::Schema::Field.new(name: "blah", owner: nil, resolver_class: nonnull_float_resolver, type: GraphQL::Types::Int) assert_equal "Int!", int_field.type.to_type_signature end class ResolverConnectionOverrideSchema < GraphQL::Schema class Query < GraphQL::Schema::Object class Resolver < GraphQL::Schema::Resolver type [Int], null: false def resolve [1, 2, 3] end end field :f, GraphQL::Types::Int.connection_type, resolver: Resolver end query(Query) end it "uses the overridden type for detecting connections" do res = ResolverConnectionOverrideSchema.execute("{ f { nodes } }") assert_equal [1,2,3], res["data"]["f"]["nodes"] end it "has a consistent Object shape" do # This test will be inherently flaky: the `Field` instances # on the heap depends on what tests ran before this one and # whether or not GC ran since then. shapes = Set.new # This is custom state added by some test schemas: custom_ivars = [:@upcase, :@future_schema, :@visible, :@allow_for, :@metadata, :@admin_only] # Remove any invalid (non-retained) field instances from the heap GC.start ObjectSpace.each_object(GraphQL::Schema::Field) do |field_obj| field_ivars = field_obj.instance_variables custom_ivars.each do |ivar| if field_ivars.delete(ivar) && field_obj.class == GraphQL::Schema::Field raise "Invariant: a built-in-based field instance has an ivar that was expected to be custom state(#{ivar.inspect}): #{field_obj.path} (#{field_obj.inspect})" end end shapes.add(field_ivars) end # To see the different shapes, uncomment this: # File.open("field_shapes.txt", "wb+") do |f| # shapes.to_a.each do |shape| # f.puts(shape.inspect + "\n") # end # end default_field_shape = GraphQL::Introspection::TypeType.get_field("name").instance_variables assert_equal [default_field_shape], shapes.to_a end it "works with implicit hash key and default value" do class HashDefautSchema < GraphQL::Schema class Example < GraphQL::Schema::Object field :implicit_lookup, [String, null: true] field :explicit_lookup, [String, null: true], hash_key: :nonexistent end class Query < GraphQL::Schema::Object field :example, Example, null: false def example Hash.new { [] } end end query(Query) end res = HashDefautSchema.execute('query { example { implicitLookup explicitLookup } }').to_h assert_equal({ "implicitLookup" => [], "explicitLookup" => [] }, res["data"]["example"]) end module FieldConnectionTest class SomeConnection < GraphQL::Schema::Object; end class Connection < GraphQL::Schema::Object; end end it "Automatically detects connection, but can be overridden" do field = GraphQL::Schema::Field.new(name: "blah", owner: nil, type: FieldConnectionTest::SomeConnection) assert field.connection? field = GraphQL::Schema::Field.new(name: "blah", owner: nil, type: FieldConnectionTest::SomeConnection, connection: false) refute field.connection? field = GraphQL::Schema::Field.new(name: "blah", owner: nil, type: FieldConnectionTest::Connection) refute field.connection? field = GraphQL::Schema::Field.new(name: "blah", owner: nil, type: FieldConnectionTest::Connection, connection: true) assert field.connection? end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/loader_spec.rb
spec/graphql/schema/loader_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Loader do Boolean = "Boolean" ID = "ID" Int = "Int" let(:schema) { node_type = Module.new do include GraphQL::Schema::Interface graphql_name "Node" field :id, ID, null: false end choice_type = Class.new(GraphQL::Schema::Enum) do graphql_name "Choice" value "FOO", value: :foo value "BAR", deprecation_reason: "Don't use BAR" value "foo" end sub_input_type = Class.new(GraphQL::Schema::InputObject) do graphql_name "Sub" argument :string, String, required: false end big_int_type = Class.new(GraphQL::Schema::Scalar) do graphql_name "BigInt" specified_by_url "https://bigint.com" def self.coerce_input(value, _ctx) value =~ /\d+/ ? Integer(value) : nil end def self.coerce_result(value, _ctx) value.to_s end end variant_input_type = Class.new(GraphQL::Schema::InputObject) do graphql_name "Varied" argument :id, ID, required: false argument :int, Int, required: false argument :bigint, big_int_type, required: false, default_value: 2**54 argument :float, Float, required: false argument :bool, Boolean, required: false argument :enum, choice_type, required: false argument :sub, [sub_input_type], required: false argument :deprecated_arg, String, required: false, deprecation_reason: "Don't use Varied.deprecatedArg" end variant_input_type_with_nulls = Class.new(GraphQL::Schema::InputObject) do graphql_name "VariedWithNulls" argument :id, ID, required: false, default_value: nil argument :int, Int, required: false, default_value: nil argument :bigint, big_int_type, required: false, default_value: nil argument :float, Float, required: false, default_value: nil argument :bool, Boolean, required: false, default_value: nil argument :enum, choice_type, required: false, default_value: nil argument :sub, [sub_input_type], required: false, default_value: nil end comment_type = Class.new(GraphQL::Schema::Object) do graphql_name "Comment" description "A blog comment" implements node_type field :body, String, null: false field :field_with_arg, Int do argument :bigint, big_int_type, default_value: 2**54, required: false end end media_type = Module.new do include GraphQL::Schema::Interface graphql_name "Media" description "!!!" field :type, String, null: false end video_type = Class.new(GraphQL::Schema::Object) do graphql_name "Video" implements media_type end audio_type = Class.new(GraphQL::Schema::Object) do graphql_name "Audio" implements media_type end post_type = Class.new(GraphQL::Schema::Object) do graphql_name "Post" description "A blog post" field :id, ID, null: false field :title, String, null: false field :summary, String, deprecation_reason: "Don't use Post.summary" field :body, String, null: false field :comments, [comment_type] field :attachment, media_type end content_type = Class.new(GraphQL::Schema::Union) do graphql_name "Content" description "A post or comment" possible_types post_type, comment_type end query_root = Class.new(GraphQL::Schema::Object) do graphql_name "Query" description "The query root of this schema" field :post, post_type do argument :id, ID argument :varied, variant_input_type, required: false, default_value: { id: "123", int: 234, float: 2.3, enum: :foo, sub: [{ string: "str" }] } argument :variedWithNull, variant_input_type_with_nulls, required: false, default_value: { id: nil, int: nil, float: nil, enum: nil, sub: nil, bigint: nil, bool: nil } argument :variedArray, [variant_input_type], required: false, default_value: [{ id: "123", int: 234, float: 2.3, enum: :foo, sub: [{ string: "str" }] }] argument :enum, choice_type, required: false, default_value: :foo argument :array, [String], required: false, default_value: ["foo", "bar"] argument :deprecated_arg, String, required: false, deprecation_reason: "Don't use Varied.deprecatedArg" end field :content, content_type end ping_mutation = Class.new(GraphQL::Schema::RelayClassicMutation) do graphql_name "Ping" end mutation_root = Class.new(GraphQL::Schema::Object) do graphql_name "Mutation" field :ping, mutation: ping_mutation end repeatable_transform = Class.new(GraphQL::Schema::Directive::Transform) do graphql_name "repeatableTransform" repeatable(true) end Class.new(GraphQL::Schema) do query query_root mutation mutation_root orphan_types audio_type, video_type description "A schema for loader_spec.rb" directives repeatable_transform end } let(:schema_json) { schema.execute(GraphQL::Introspection.query(include_deprecated_args: true, include_schema_description: true, include_specified_by_url: true, include_is_repeatable: true)) } describe "load" do def assert_equal_or_nil(expected_value, actual_value) if expected_value.nil? assert_nil actual_value else assert_equal expected_value, actual_value end end def assert_deep_equal(expected_type, actual_type) if actual_type.is_a?(Array) actual_type.each_with_index do |obj, index| assert_deep_equal expected_type[index], obj end elsif actual_type.is_a?(GraphQL::Schema::Field) assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.deprecation_reason, actual_type.deprecation_reason assert_equal_or_nil expected_type.arguments.keys.sort, actual_type.arguments.keys.sort assert_deep_equal expected_type.arguments.values.sort_by(&:graphql_name), actual_type.arguments.values.sort_by(&:graphql_name) elsif actual_type.is_a?(GraphQL::Schema::EnumValue) assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.deprecation_reason, actual_type.deprecation_reason elsif actual_type.is_a?(GraphQL::Schema::Argument) assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.deprecation_reason, actual_type.deprecation_reason assert_deep_equal expected_type.type, actual_type.type elsif actual_type.is_a?(GraphQL::Schema::NonNull) || actual_type.is_a?(GraphQL::Schema::List) assert_equal_or_nil expected_type.class, actual_type.class assert_deep_equal expected_type.of_type, actual_type.of_type elsif actual_type < GraphQL::Schema assert_equal_or_nil expected_type.query.graphql_name, actual_type.query.graphql_name assert_equal_or_nil expected_type.mutation.graphql_name, actual_type.mutation.graphql_name assert_equal_or_nil expected_type.directives.keys.sort, actual_type.directives.keys.sort assert_deep_equal expected_type.directives.values.sort_by(&:graphql_name), actual_type.directives.values.sort_by(&:graphql_name) assert_equal_or_nil expected_type.types.keys.sort, actual_type.types.keys.sort assert_deep_equal expected_type.types.values.sort_by(&:graphql_name), actual_type.types.values.sort_by(&:graphql_name) assert_equal_or_nil expected_type.description, actual_type.description elsif actual_type < GraphQL::Schema::Object assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.interfaces.map(&:graphql_name).sort, actual_type.interfaces.map(&:graphql_name).sort assert_deep_equal expected_type.interfaces.sort_by(&:graphql_name), actual_type.interfaces.sort_by(&:graphql_name) assert_equal_or_nil expected_type.fields.keys.sort, actual_type.fields.keys.sort assert_deep_equal expected_type.fields.values.sort_by(&:graphql_name), actual_type.fields.values.sort_by(&:graphql_name) elsif actual_type < GraphQL::Schema::Interface assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.fields.keys.sort, actual_type.fields.keys.sort assert_deep_equal expected_type.fields.values.sort_by(&:graphql_name), actual_type.fields.values.sort_by(&:graphql_name) elsif actual_type < GraphQL::Schema::Union assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.possible_types.map(&:graphql_name).sort, actual_type.possible_types.map(&:graphql_name).sort assert_deep_equal expected_type.possible_types.sort_by(&:graphql_name), actual_type.possible_types.sort_by(&:graphql_name) elsif actual_type < GraphQL::Schema::Scalar assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.specified_by_url, actual_type.specified_by_url elsif actual_type < GraphQL::Schema::Enum assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_deep_equal expected_type.values.values.sort_by(&:graphql_name), actual_type.values.values.sort_by(&:graphql_name) elsif actual_type < GraphQL::Schema::InputObject assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.arguments.keys.sort, actual_type.arguments.keys.sort assert_deep_equal expected_type.arguments.values.sort_by(&:graphql_name), actual_type.arguments.values.sort_by(&:graphql_name) elsif actual_type < GraphQL::Schema::Directive assert_equal_or_nil expected_type.graphql_name, actual_type.graphql_name assert_equal_or_nil expected_type.description, actual_type.description assert_equal_or_nil expected_type.repeatable?, actual_type.repeatable? assert_equal_or_nil expected_type.locations.sort, actual_type.locations.sort assert_equal_or_nil expected_type.arguments.keys.sort, actual_type.arguments.keys.sort assert_deep_equal expected_type.arguments.values.sort_by(&:graphql_name), actual_type.arguments.values.sort_by(&:graphql_name) else assert_equa_or_nil expected_type, actual_type end end let(:loaded_schema) { GraphQL::Schema.from_introspection(schema_json) } it "returns the schema without warnings" do assert_warns("") do assert_deep_equal(schema, loaded_schema) end end it "can export the loaded schema" do assert loaded_schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) end it "has no-op coerce functions" do custom_scalar = loaded_schema.types["BigInt"] assert_equal true, custom_scalar.valid_isolated_input?("anything") assert_equal true, custom_scalar.valid_isolated_input?(12345) end it "sets correct default values on custom scalar arguments" do type = loaded_schema.types["Comment"] field = type.fields['fieldWithArg'] arg = field.arguments['bigint'] assert_equal((2**54).to_s, arg.default_value) end it "sets correct default values on custom scalar input fields" do type = loaded_schema.types["Varied"] field = type.arguments['bigint'] assert_equal((2**54).to_s, field.default_value) end it "sets correct default values for complex field arguments" do type = loaded_schema.types['Query'] field = type.fields['post'] varied = field.arguments['varied'] assert_equal varied.default_value, { 'id' => "123", 'int' => 234, 'float' => 2.3, 'enum' => "FOO", 'sub' => [{ 'string' => "str" }] } assert !varied.default_value.key?('bool'), 'Omits default value for unspecified arguments' variedArray = field.arguments['variedArray'] assert_equal variedArray.default_value, [{ 'id' => "123", 'int' => 234, 'float' => 2.3, 'enum' => "FOO", 'sub' => [{ 'string' => "str" }] }] assert !variedArray.default_value.first.key?('bool'), 'Omits default value for unspecified arguments' array = field.arguments['array'] assert_equal array.default_value, ["foo", "bar"] end it "does not set default value when there are none on input fields" do type = loaded_schema.types['Varied'] assert !type.arguments['id'].default_value? assert !type.arguments['int'].default_value? assert type.arguments['bigint'].default_value? assert !type.arguments['float'].default_value? assert !type.arguments['bool'].default_value? assert !type.arguments['enum'].default_value? assert !type.arguments['sub'].default_value? end it "sets correct default values `null` on input fields" do type = loaded_schema.types['VariedWithNulls'] assert type.arguments['id'].default_value? assert type.arguments['id'].default_value.nil? assert type.arguments['int'].default_value? assert type.arguments['int'].default_value.nil? assert type.arguments['bigint'].default_value? assert type.arguments['bigint'].default_value.nil? assert type.arguments['float'].default_value? assert type.arguments['float'].default_value.nil? assert type.arguments['bool'].default_value? assert type.arguments['bool'].default_value.nil? assert type.arguments['enum'].default_value? assert type.arguments['enum'].default_value.nil? assert type.arguments['sub'].default_value? assert type.arguments['sub'].default_value.nil? end it "works with underscored names" do schema_sdl = <<-GRAPHQL type A_Type { f(argument_1: Int, argument_two: Int): Int } type Query { some_field: A_Type } GRAPHQL introspection_res = GraphQL::Schema.from_definition(schema_sdl).as_json rebuilt_schema = GraphQL::Schema.from_introspection(introspection_res) assert_equal schema_sdl, rebuilt_schema.to_definition end it "doesnt warn about method conflicts (because it doesn't make method accesses)" do assert_output "", "" do GraphQL::Schema.from_introspection({ "data" => { "__schema" => { "queryType" => { "name" => "Query" }, "mutationType" => nil, "subscriptionType" => nil, "types" => [ { "kind" => "OBJECT", "name" => "Query", "description" => nil, "fields" => [ { "name" => "int", "description" => nil, "args" => [ { "name" => "method", "description" => nil, "type" => { "kind" => "SCALAR", "name" => "Int", "ofType" => nil }, "defaultValue" => nil } ], "type" => { "kind" => "SCALAR", "name" => "Int", "ofType" => nil }, "isDeprecated" => false, "deprecationReason" => nil } ], "inputFields" => nil, "interfaces" => [ ], "enumValues" => nil, "possibleTypes" => nil }, { "kind" => "SCALAR", "name" => "Int", "description" => "Represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.", "fields" => nil, "inputFields" => nil, "interfaces" => nil, "enumValues" => nil, "possibleTypes" => nil }, ] } } }) end end it "sets correct default values `nil` on complex field arguments" do type = loaded_schema.types['Query'] field = type.fields['post'] arg = field.arguments['variedWithNull'] assert_equal arg.default_value, { 'id' => nil, 'int' => nil, 'float' => nil, 'enum' => nil, 'sub' => nil, 'bool' => nil, 'bigint' => nil } end end it "validates field argument names" do json = { "data" => { "__schema" => { "queryType" => { "name" => "Query" }, "mutationType" => nil, "subscriptionType" => nil, "types" => [ { "kind" => "OBJECT", "name" => "Query", "description" => nil, "fields" => [ { "name" => "int", "description" => nil, "type" => { "kind" => "SCALAR", "name" => "Int", "ofType" => nil, }, "args" => [ { "name" => "something-wrong", "description" => nil, "type" => { "kind" => "SCALAR", "name" => "Int", "ofType" => nil }, "defaultValue" => nil } ], } ] } ] } } } err = assert_raises GraphQL::InvalidNameError do GraphQL::Schema.from_introspection(json) end assert_includes err.message, "something-wrong" end it "validates field names" do json = { "data" => { "__schema" => { "queryType" => { "name" => "Query" }, "mutationType" => nil, "subscriptionType" => nil, "types" => [ { "kind" => "OBJECT", "name" => "Query", "description" => nil, "fields" => [ { "name" => "bad.int", "description" => nil, "type" => { "kind" => "SCALAR", "name" => "Int", "ofType" => nil, }, "args" => [], } ] } ] } } } err = assert_raises GraphQL::InvalidNameError do GraphQL::Schema.from_introspection(json) end assert_includes err.message, "bad.int" end it "validates input object argument names" do json = { "data" => { "__schema" => { "queryType" => { "name" => "Query" }, "mutationType" => nil, "subscriptionType" => nil, "types" => [ { "kind" => "OBJECT", "name" => "Query", "description" => nil, "fields" => [ { "name" => "int", "description" => nil, "type" => { "kind" => "SCALAR", "name" => "Int", "ofType" => nil, }, "args" => [ { "name" => "inputObject", "description" => nil, "type" => { "kind" => "INPUT_OBJECT", "name" => "SomeInputObject", "ofType" => nil }, "defaultValue" => nil } ], } ] }, { "kind" => "INPUT_OBJECT", "name" => "SomeInputObject", "description" => nil, "inputFields" => [ { "name"=>"bad, input", "type"=> { "kind" => "SCALAR", "name" => "String"}, "defaultValue"=> nil, "description" => nil, }, ] } ] } } } err = assert_raises GraphQL::InvalidNameError do GraphQL::Schema.from_introspection(json) end assert_includes err.message, "bad, input" end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/instrumentation_spec.rb
spec/graphql/schema/instrumentation_spec.rb
# frozen_string_literal: true require "spec_helper" module InstrumentationSpec module SomeInterface include GraphQL::Schema::Interface field :never_called, String, null: false def never_called "should never be called" end end class SomeType < GraphQL::Schema::Object implements SomeInterface end class Query < GraphQL::Schema::Object field :some_field, [SomeInterface] def some_field nil end end class Schema < GraphQL::Schema query Query orphan_types [SomeType] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/base_64_encoder_spec.rb
spec/graphql/schema/base_64_encoder_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Base64Encoder do describe ".decode" do it "decodes base64 encoded strings" do string = "12345" encoded_string = GraphQL::Schema::Base64Encoder.encode(string) decoded_string = GraphQL::Schema::Base64Encoder.decode(encoded_string) assert_equal(string, decoded_string) end it "raises an execution error when an invalid cursor is given" do assert_raises(GraphQL::ExecutionError) do GraphQL::Schema::Base64Encoder.decode("12345") end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/unique_within_type_spec.rb
spec/graphql/schema/unique_within_type_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::UniqueWithinType do describe 'encode / decode' do it 'Converts typename and ID to and from ID' do global_id = GraphQL::Schema::UniqueWithinType.encode("SomeType", 123) type_name, id = GraphQL::Schema::UniqueWithinType.decode(global_id) assert_equal("SomeType", type_name) assert_equal("123", id) end it "allows you specify default separator" do GraphQL::Schema::UniqueWithinType.default_id_separator = '|' global_id = GraphQL::Schema::UniqueWithinType.encode("Type-With-UUID", "250cda0e-a89d-41cf-99e1-2872d89f1100") type_name, id = GraphQL::Schema::UniqueWithinType.decode(global_id) assert_equal("Type-With-UUID", type_name) assert_equal("250cda0e-a89d-41cf-99e1-2872d89f1100", id) GraphQL::Schema::UniqueWithinType.default_id_separator = '-' end it "allows you to specify the separator" do custom_separator = "---" global_id = GraphQL::Schema::UniqueWithinType.encode("Type-With-UUID", "250cda0e-a89d-41cf-99e1-2872d89f1100", separator: custom_separator) type_name, id = GraphQL::Schema::UniqueWithinType.decode(global_id, separator: custom_separator) assert_equal("Type-With-UUID", type_name) assert_equal("250cda0e-a89d-41cf-99e1-2872d89f1100", id) end it "allows using the separator in the ID" do global_id = GraphQL::Schema::UniqueWithinType.encode("SomeUUIDType", "250cda0e-a89d-41cf-99e1-2872d89f1100") type_name, id = GraphQL::Schema::UniqueWithinType.decode(global_id) assert_equal("SomeUUIDType", type_name) assert_equal("250cda0e-a89d-41cf-99e1-2872d89f1100", id) end it "raises an execution error if invalid string is decoded" do err = assert_raises(GraphQL::ExecutionError) { GraphQL::Schema::UniqueWithinType.decode("Invalid-String*") } assert_includes err.message, "Invalid input: \"Invalid-String*\"" end it "raises an error if you try and use a reserved character in the typename" do err = assert_raises(RuntimeError) { GraphQL::Schema::UniqueWithinType.encode("Best-Thing", "234-567") } assert_includes err.message, "encode(Best-Thing, 234-567) contains reserved characters `-` in the type name" end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/mutation_spec.rb
spec/graphql/schema/mutation_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Mutation do let(:mutation) { Jazz::AddInstrument } after do Jazz::Models.reset end it "Doesn't override !" do assert_equal false, !mutation end describe "definition" do it "passes along description" do assert_equal "Register a new musical instrument in the database", Jazz::Mutation.get_field("addInstrument").description assert_equal "Autogenerated return type of AddInstrument.", mutation.payload_type.description end end describe "argument prepare" do it "calls methods on the mutation, uses `as:`" do query_str = "mutation { prepareInput(input: 4) }" res = Jazz::Schema.execute(query_str) assert_equal 16, res["data"]["prepareInput"], "It's squared by the prepare method" end end describe "a derived field" do it "has a reference to the mutation" do test_setup = self t = Class.new(GraphQL::Schema::Object) do field :x, mutation: test_setup.mutation end f = t.get_field("x") assert_equal mutation, f.mutation # Make sure it's also present in the schema f2 = Jazz::Schema.find("Mutation.addInstrument") assert_equal mutation, f2.mutation end end describe ".payload_type" do it "has a reference to the mutation" do assert_equal mutation, mutation.payload_type.mutation end end describe ".object_class" do it "can override & inherit the parent class" do obj_class = Class.new(GraphQL::Schema::Object) mutation_class = Class.new(GraphQL::Schema::Mutation) do object_class(obj_class) end mutation_subclass = Class.new(mutation_class) assert_equal(GraphQL::Schema::Object, GraphQL::Schema::Mutation.object_class) assert_equal(obj_class, mutation_class.object_class) assert_equal(obj_class, mutation_subclass.object_class) end end describe ".argument_class" do it "can override & inherit the parent class" do arg_class = Class.new(GraphQL::Schema::Argument) mutation_class = Class.new(GraphQL::Schema::Mutation) do argument_class(arg_class) end mutation_subclass = Class.new(mutation_class) assert_equal(GraphQL::Schema::Argument, GraphQL::Schema::Mutation.argument_class) assert_equal(arg_class, mutation_class.argument_class) assert_equal(arg_class, mutation_subclass.argument_class) end end describe "evaluation" do it "runs mutations" do query_str = <<-GRAPHQL mutation { addInstrument(name: "trombone", family: BRASS) { instrument { name family } entries { name } ee } } GRAPHQL response = Jazz::Schema.execute(query_str) assert_equal "Trombone", response["data"]["addInstrument"]["instrument"]["name"] assert_equal "BRASS", response["data"]["addInstrument"]["instrument"]["family"] errors_class = "GraphQL::Execution::Interpreter::ExecutionErrors" assert_equal errors_class, response["data"]["addInstrument"]["ee"] assert_equal 7, response["data"]["addInstrument"]["entries"].size end it "accepts a list of errors as a valid result" do query_str = "mutation { returnsMultipleErrors { dummyField { name } } }" response = Jazz::Schema.execute(query_str) assert_equal 2, response["errors"].length, "It should return two errors" end it "raises a mutation-specific invalid null error" do query_str = "mutation { returnInvalidNull { int } }" response = Jazz::Schema.execute(query_str) assert_equal ["Cannot return null for non-nullable field ReturnInvalidNullPayload.int"], response["errors"].map { |e| e["message"] } end end describe ".null" do it "overrides whether or not the field can be null" do non_nullable_mutation_class = Class.new(GraphQL::Schema::Mutation) do graphql_name "Thing1" null(false) end nullable_mutation_class = Class.new(GraphQL::Schema::Mutation) do graphql_name "Thing2" null(true) end default_mutation_class = Class.new(GraphQL::Schema::Mutation) do graphql_name "Thing3" end example_mutation_type = Class.new(GraphQL::Schema::Object) do field :non_nullable_mutation, mutation: non_nullable_mutation_class field :nullable_mutation, mutation: nullable_mutation_class field :default_mutation, mutation: default_mutation_class end refute example_mutation_type.get_field("defaultMutation").type.non_null? refute example_mutation_type.get_field("nullableMutation").type.non_null? assert example_mutation_type.get_field("nonNullableMutation").type.non_null? end it "should inherit and override in subclasses" do base_mutation = Class.new(GraphQL::Schema::Mutation) do null(false) end inheriting_mutation = Class.new(base_mutation) do graphql_name "Thing" end override_mutation = Class.new(base_mutation) do graphql_name "Thing2" null(true) end f1 = GraphQL::Schema::Field.new(name: "f1", resolver_class: inheriting_mutation) assert_equal true, f1.type.non_null? f2 = GraphQL::Schema::Field.new(name: "f2", resolver_class: override_mutation) assert_equal false, f2.type.non_null? end end it "warns once for possible conflict methods" do expected_warning = "X's `field :module` conflicts with a built-in method, use `hash_key:` or `method:` to pick a different resolve behavior for this field (for example, `hash_key: :module_value`, and modify the return hash). Or use `method_conflict_warning: false` to suppress this warning.\n" assert_output "", expected_warning do # This should warn: mutation = Class.new(GraphQL::Schema::Mutation) do graphql_name "X" field :module, String end # This should not warn again, when generating the payload type with the same fields: mutation.payload_type end assert_output "", "" do mutation = Class.new(GraphQL::Schema::Mutation) do graphql_name "X" field :module, String, hash_key: :module_value end mutation.payload_type end end class InterfaceMutationSchema < GraphQL::Schema class SignIn < GraphQL::Schema::Mutation argument :login, String argument :password, String field :success, Boolean, null: false def resolve(login:, password:) { success: login == password } end end module Auth include GraphQL::Schema::Interface field :sign_in, mutation: SignIn end class Mutation < GraphQL::Schema::Object implements Auth end mutation(Mutation) query(Mutation) end it "works when mutations are added via interfaces" do result = InterfaceMutationSchema.execute("mutation { signIn(login: \"abc\", password: \"abc\") { success } }") assert_equal true, result["data"]["signIn"]["success"] end it "returns manually-configured return types" do mutation = Class.new(GraphQL::Schema::Mutation) do graphql_name "DoStuff" type(String) end field = GraphQL::Schema::Field.new(name: "f", owner: nil, resolver_class: mutation) assert_equal "String", field.type.graphql_name assert_equal GraphQL::Types::String, field.type end it "inherits arguments even when parent classes aren't attached to the schema" do parent_mutation = Class.new(GraphQL::Schema::Mutation) do graphql_name "ParentMutation" argument :thing_id, "ID" field :inputs, String def resolve(**inputs) { inputs: inputs.inspect } end end child_mutation = Class.new(parent_mutation) do graphql_name "ChildMutation" argument :thing_name, String end mutation_type = Class.new(GraphQL::Schema::Object) do graphql_name "Mutation" field :child, mutation: child_mutation end schema = Class.new(GraphQL::Schema) do mutation(mutation_type) end assert_equal ["thingId", "thingName"], child_mutation.arguments.keys assert_equal ["thingId", "thingName"], child_mutation.all_argument_definitions.map(&:graphql_name) assert_equal ["thingId", "thingName"], schema.mutation.fields["child"].all_argument_definitions.map(&:graphql_name) res = schema.execute("mutation { child(thingName: \"abc\", thingId: \"123\") { inputs } }") expected_result = { thing_id: "123", thing_name: "abc" }.inspect assert_equal expected_result, res["data"]["child"]["inputs"] end describe "flushing dataloader cache" do class MutationDataloaderCacheSchema < GraphQL::Schema module Database DATA = {} def self.get(id) value = DATA[id] ||= 0 OpenStruct.new(id: id, value: value) end def self.increment(id) DATA[id] ||= 0 DATA[id] += 1 end def self.clear DATA.clear end end class CounterSource < GraphQL::Dataloader::Source def fetch(ids) ids.map { |id| Database.get(id) } end end class CounterType < GraphQL::Schema::Object def self.authorized?(obj, ctx) # Just force the load here, too: ctx.dataloader.with(CounterSource).load(obj.id) true end field :value, Integer end class Increment < GraphQL::Schema::Mutation field :counter, CounterType argument :counter_id, ID, loads: CounterType def resolve(counter:) Database.increment(counter.id) { counter: dataloader.with(CounterSource).load(counter.id) } end end class ReadyCounter < GraphQL::Schema::Mutation field :id, ID argument :counter_id, ID def ready?(counter_id:) # Just fill the cache: dataloader.with(CounterSource).load(counter_id) true end def resolve(counter_id:) { id: counter_id } end end class Mutation < GraphQL::Schema::Object field :increment, mutation: Increment field :ready_counter, mutation: ReadyCounter end mutation(Mutation) def self.object_from_id(id, ctx) ctx.dataloader.with(CounterSource).load(id) end def self.resolve_type(abs_type, obj, ctx) CounterType end use GraphQL::Dataloader end it "clears the cache after authorized and loads" do MutationDataloaderCacheSchema::Database.clear res = MutationDataloaderCacheSchema.execute("mutation { increment(counterId: \"4\") { counter { value } } }") assert_equal 1, res["data"]["increment"]["counter"]["value"] res2 = MutationDataloaderCacheSchema.execute("mutation { increment(counterId: \"4\") { counter { value } } }") assert_equal 2, res2["data"]["increment"]["counter"]["value"] end it "uses a fresh cache for `ready?` calls" do multiplex = [ { query: "mutation { r1: readyCounter(counterId: 1) { id } }" }, { query: "mutation { r2: readyCounter(counterId: 1) { id } }" }, { query: "mutation { r3: readyCounter(counterId: 1) { id } }" }, ] result = MutationDataloaderCacheSchema.multiplex(multiplex) assert_equal ["1", "1", "1"], result.map { |r| r["data"].first.last["id"] } end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/finder_spec.rb
spec/graphql/schema/finder_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Finder do let(:finder) { GraphQL::Schema::Finder.new(Jazz::Schema) } describe "#find" do it "finds a valid object type" do type = finder.find("Ensemble") assert_equal "Ensemble", type.graphql_name end it "raises when finding an invalid object type" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("DoesNotExist") end assert_match(/Could not find type `DoesNotExist` in schema./, exception.message) end it "finds a valid directive" do directive = finder.find("@include") assert_equal "include", directive.graphql_name end it "raises when finding an invalid directive" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("@yolo") end assert_match(/Could not find directive `@yolo` in schema./, exception.message) end it "finds a valid field" do field = finder.find("Ensemble.musicians") assert_equal "musicians", field.graphql_name end it "finds a meta field" do field = finder.find("Ensemble.__typename") assert_equal "__typename", field.graphql_name end it "raises when finding an in valid field" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("Ensemble.nope") end assert_match(/Could not find field `nope` on object type `Ensemble`./, exception.message) end it "finds a valid argument" do arg = finder.find("Query.find.id") assert_equal "id", arg.graphql_name end it "raises when finding an invalid argument" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("Query.find.thisArgumentIsInvalid") end assert_match(/Could not find argument `thisArgumentIsInvalid` on field `find`./, exception.message) end it "raises when selecting on an argument" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("Query.find.id.whyYouDoThis") end assert_match(/Cannot select member `whyYouDoThis` on a field./, exception.message) end it "finds a valid interface" do type = finder.find("NamedEntity") assert_equal "NamedEntity", type.graphql_name end it "finds a valid input type" do type = finder.find("LegacyInput") assert_equal "LegacyInput", type.graphql_name end it "finds a valid input field" do input_field = finder.find("LegacyInput.intValue") assert_equal "intValue", input_field.graphql_name end it "raises when finding an invalid input field" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("LegacyInput.wat") end assert_match(/Could not find input field `wat` on input object type `LegacyInput`./, exception.message) end it "finds a valid union type" do type = finder.find("PerformingAct") assert_equal "PerformingAct", type.graphql_name end it "raises when selecting a possible type" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("PerformingAct.Musician") end assert_match(/Cannot select union possible type `Musician`. Select the type directly instead./, exception.message) end it "finds a valid enum type" do type = finder.find("Family") assert_equal "Family", type.graphql_name end it "finds a valid enum value" do value = finder.find("Family.BRASS") assert_equal "BRASS", value.graphql_name end it "raises when finding an invalid enum value" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("Family.THISISNOTASTATUS") end assert_match(/Could not find enum value `THISISNOTASTATUS` on enum type `Family`./, exception.message) end it "raises when selecting on an enum value" do exception = assert_raises GraphQL::Schema::Finder::MemberNotFoundError do finder.find("Family.BRASS.wat") end assert_match(/Cannot select member `wat` on an enum value./, exception.message) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/subscription_spec.rb
spec/graphql/schema/subscription_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Subscription do class SubscriptionFieldSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN TOOTS = [] ALL_USERS = { "dhh" => {handle: "dhh", private: false}, "matz" => {handle: "matz", private: false}, "_why" => {handle: "_why", private: true}, } USERS = {} class User < GraphQL::Schema::Object field :handle, String, null: false field :private, Boolean, null: false end class Toot < GraphQL::Schema::Object field :handle, String, null: false field :body, String, null: false def self.visible?(context) !context[:legacy_schema] end end class LegacyToot < Toot field :likes_count, Int, null: false def self.visible?(context) !!context[:legacy_schema] end end class Query < GraphQL::Schema::Object field :toots, [Toot], null: false field :toots, [LegacyToot], null: false def toots TOOTS end end class BaseSubscription < GraphQL::Schema::Subscription end class TootWasTooted < BaseSubscription argument :handle, String, loads: User, as: :user, camelize: false field :toot, Toot, null: false field :user, User, null: false def self.visible?(context) !context[:legacy_schema] end # Can't subscribe to private users def authorized?(user:, path:, query:) if user[:private] context[:last_path] = path false else true end end def subscribe(user:, **args) if context[:prohibit_subscriptions] raise GraphQL::ExecutionError, "You don't have permission to subscribe" else # Default is to return :no_response super end end def update(user:, **args) if context[:viewer] == user # don't update for one's own toots. # (IRL it would make more sense to implement this in `#subscribe`) NO_UPDATE elsif context[:update_and_unsubscribe] unsubscribe(super) elsif context[:update_error_and_unsubscribe] unsubscribe(GraphQL::ExecutionError.new("Boom!")) else # This assumes that trigger object can fulfill `{toot:, user:}`, # for testing that the default implementation is `return object` super end end end class LegacyTootWasTooted < TootWasTooted field :toot, LegacyToot def self.visible?(context) !!context[:legacy_schema] end end class DirectTootWasTooted < BaseSubscription subscription_scope :viewer field :toot, Toot, null: false field :user, User, null: false end class DirectTootWasTootedWithOptionalScope < DirectTootWasTooted subscription_scope :viewer, optional: true end # Test initial response, which returns all users class UsersJoined < BaseSubscription class UsersJoinedManualPayload < GraphQL::Schema::Object field :users, [User], description: "Includes newly-created users, or all users on the initial load" end payload_type UsersJoinedManualPayload def subscribe { users: USERS.values } end # Test returning a custom object from #update def update { users: object[:new_users] } end end # Like above, but doesn't override #subscription, # to make sure it works without arguments class NewUsersJoined < BaseSubscription field :users, [User], description: "Includes newly-created users, or all users on the initial load" end class Subscription < GraphQL::Schema::Object field :toot_was_tooted, subscription: TootWasTooted, extras: [:path, :query] field :toot_was_tooted, subscription: LegacyTootWasTooted, extras: [:path, :query] field :direct_toot_was_tooted, subscription: DirectTootWasTooted field :direct_toot_was_tooted_with_optional_scope, subscription: DirectTootWasTootedWithOptionalScope field :users_joined, subscription: UsersJoined field :new_users_joined, subscription: NewUsersJoined end class Mutation < GraphQL::Schema::Object field :toot, Toot, null: false do argument :body, String end def toot(body:) handle = context[:viewer][:handle] toot = { handle: handle, body: body } TOOTS << toot SubscriptionFieldSchema.trigger(:toot_was_tooted, {handle: handle}, toot) end end query(Query) mutation(Mutation) subscription(Subscription) rescue_from(StandardError) { |err, *rest| if err.is_a?(GraphQL::Subscriptions::SubscriptionScopeMissingError) raise err else err2 = RuntimeError.new("This should never happen: #{err.class}: #{err.message}") err2.set_backtrace(err.backtrace) raise err2 end } def self.object_from_id(id, ctx) USERS[id] end def self.resolve_type(type, obj, ctx) User end def self.unauthorized_field(err) path = err.context[:last_path] raise GraphQL::ExecutionError, "Can't subscribe to private user (#{path})" end class InMemorySubscriptions < GraphQL::Subscriptions SUBSCRIPTION_REGISTRY = {} EVENT_REGISTRY = Hash.new { |h, k| h[k] = [] } def write_subscription(query, events) query.context[:subscription_mailbox] = [] subscription_id = build_id events.each do |ev| EVENT_REGISTRY[ev.topic] << subscription_id end SUBSCRIPTION_REGISTRY[subscription_id] = [query, events] end def execute_all(event, object) EVENT_REGISTRY[event.topic].each do |sub_id| execute(sub_id, event, object) end end def read_subscription(subscription_id) query, _events = SUBSCRIPTION_REGISTRY[subscription_id] { query_string: query.query_string, context: query.context.to_h, variables: query.provided_variables, operation_name: query.selected_operation_name, } end def deliver(subscription_id, result) query, _events = SUBSCRIPTION_REGISTRY[subscription_id] query.context[:subscription_mailbox] << result end def delete_subscription(subscription_id) _query, events = SUBSCRIPTION_REGISTRY.delete(subscription_id) events.each do |ev| EVENT_REGISTRY[ev.topic].delete(subscription_id) end end end use InMemorySubscriptions end def exec_query(*args, **kwargs) SubscriptionFieldSchema.execute(*args, **kwargs) end def in_memory_subscription_count SubscriptionFieldSchema::InMemorySubscriptions::SUBSCRIPTION_REGISTRY.size end before do # Reset databases SubscriptionFieldSchema::TOOTS.clear # Reset in order: SubscriptionFieldSchema::USERS.clear SubscriptionFieldSchema::ALL_USERS.map do |k, v| SubscriptionFieldSchema::USERS[k] = v.dup end SubscriptionFieldSchema::InMemorySubscriptions::SUBSCRIPTION_REGISTRY.clear SubscriptionFieldSchema::InMemorySubscriptions::EVENT_REGISTRY.clear end it "generates a return type" do return_type = SubscriptionFieldSchema::TootWasTooted.payload_type assert_equal "TootWasTootedPayload", return_type.graphql_name assert_equal ["toot", "user"], return_type.fields.keys end it "can use a premade `payload_type`" do return_type = SubscriptionFieldSchema::UsersJoined.payload_type assert_equal "UsersJoinedManualPayload", return_type.graphql_name assert_equal ["users"], return_type.fields.keys assert_equal SubscriptionFieldSchema::UsersJoined::UsersJoinedManualPayload, return_type end describe "initial subscription" do it "calls #subscribe for the initial subscription and returns the result" do res = exec_query <<-GRAPHQL subscription { usersJoined { users { handle } } } GRAPHQL assert_equal ["dhh", "matz", "_why"], res["data"]["usersJoined"]["users"].map { |u| u["handle"] } assert_equal 1, in_memory_subscription_count # It works a second time res = exec_query <<-GRAPHQL subscription { usersJoined { users { handle } } } GRAPHQL assert_equal ["dhh", "matz", "_why"], res["data"]["usersJoined"]["users"].map { |u| u["handle"] } assert_equal 2, in_memory_subscription_count end it "rejects the subscription if #subscribe raises an error" do res = exec_query <<-GRAPHQL, context: { prohibit_subscriptions: true } subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL expected_response = { "data"=>nil, "errors"=>[ { "message"=>"You don't have permission to subscribe", "locations"=>[{"line"=>2, "column"=>9}], "path"=>["tootWasTooted"] } ] } assert_equal(expected_response, res) assert_equal 0, in_memory_subscription_count end it "doesn't subscribe if `loads:` fails" do res = exec_query <<-GRAPHQL subscription { tootWasTooted(handle: "jack") { toot { body } } } GRAPHQL expected_response = { "data" => nil, "errors" => [ { "message"=>"No object found for `handle: \"jack\"`", "locations"=>[{"line"=>2, "column"=>9}], "path"=>["tootWasTooted"] } ] } assert_equal(expected_response, res) assert_equal 0, in_memory_subscription_count end it "rejects if #authorized? fails" do res = exec_query <<-GRAPHQL subscription { tootWasTooted(handle: "_why") { toot { body } } } GRAPHQL expected_response = { "data"=>nil, "errors"=>[ { "message"=>"Can't subscribe to private user ([\"tootWasTooted\"])", "locations"=>[{"line"=>2, "column"=>9}], "path"=>["tootWasTooted"] }, ], } assert_equal(expected_response, res) end it "sends no initial response if :no_response is returned, which is the default" do assert_equal 0, in_memory_subscription_count res = exec_query <<-GRAPHQL subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL assert_equal({"data" => {}}, res) assert_equal 1, in_memory_subscription_count end it "works when there are no arguments" do assert_equal 0, in_memory_subscription_count res = exec_query <<-GRAPHQL subscription { newUsersJoined { users { handle } } } GRAPHQL assert_equal({"data" => {}}, res) assert_equal 1, in_memory_subscription_count end end describe "updates" do it "updates with `object` by default" do res = exec_query <<-GRAPHQL subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count obj = OpenStruct.new(toot: { body: "I am a C programmer" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) mailbox = res.context[:subscription_mailbox] update_payload = mailbox.first assert_equal "I am a C programmer", update_payload["data"]["tootWasTooted"]["toot"]["body"] end it "updates with the returned value" do res = exec_query <<-GRAPHQL subscription { usersJoined { users { handle } } } GRAPHQL assert_equal 1, in_memory_subscription_count SubscriptionFieldSchema.subscriptions.trigger(:users_joined, {}, {new_users: [{handle: "eileencodes"}, {handle: "tenderlove"}]}) update = res.context[:subscription_mailbox].first assert_equal [{"handle" => "eileencodes"}, {"handle" => "tenderlove"}], update["data"]["usersJoined"]["users"] end it "skips the update if `NO_UPDATE` is returned, but updates other subscribers" do query_str = <<-GRAPHQL subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL res1 = exec_query(query_str) res2 = exec_query(query_str, context: { viewer: SubscriptionFieldSchema::USERS["matz"] }) assert_equal 2, in_memory_subscription_count obj = OpenStruct.new(toot: { body: "Merry Christmas, here's a new Ruby version" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) mailbox1 = res1.context[:subscription_mailbox] mailbox2 = res2.context[:subscription_mailbox] # The anonymous viewer got an update: assert_equal "Merry Christmas, here's a new Ruby version", mailbox1.first["data"]["tootWasTooted"]["toot"]["body"] # But not matz: assert_equal [], mailbox2 # `NO_UPDATE` doesn't cause an unsubscribe assert_equal 2, in_memory_subscription_count end it "can unsubscribe with a final update" do res = exec_query(<<-GRAPHQL, context: { update_and_unsubscribe: true }) subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count toot = OpenStruct.new(toot: { body: "Merry Christmas, here's a new Ruby version" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, toot) mailbox = res.context[:subscription_mailbox] assert_equal ["Merry Christmas, here's a new Ruby version"], mailbox.map { |m| m["data"]["tootWasTooted"]["toot"]["body"] } assert_equal 0, in_memory_subscription_count end it "can unsubscribe with an error" do res = exec_query(<<-GRAPHQL, context: { update_error_and_unsubscribe: true }) subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count toot = OpenStruct.new(toot: { body: "Merry Christmas, here's a new Ruby version" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, toot) mailbox = res.context[:subscription_mailbox] assert_equal ["Boom!"], mailbox.map { |m| m["errors"][0]["message"] } assert_equal 0, in_memory_subscription_count end it "unsubscribes if a `loads:` argument is not found" do res = exec_query <<-GRAPHQL subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count obj = OpenStruct.new(toot: { body: "I am a C programmer" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) # Get 1 successful update mailbox = res.context[:subscription_mailbox] assert_equal 1, mailbox.size update_payload = mailbox.first assert_equal "I am a C programmer", update_payload["data"]["tootWasTooted"]["toot"]["body"] # Then cause a not-found and update again matz = SubscriptionFieldSchema::USERS.delete("matz") obj = OpenStruct.new(toot: { body: "Merry Christmas, here's a new Ruby version" }, user: matz) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) # there was no subsequent update assert_equal 1, mailbox.size # The database was cleaned up assert_equal 0, in_memory_subscription_count end it "sends an error if `#authorized?` fails" do res = exec_query <<-GRAPHQL subscription { tootWasTooted(handle: "matz") { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count matz = SubscriptionFieldSchema::USERS["matz"] obj = OpenStruct.new(toot: { body: "I am a C programmer" }, user: matz) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) # Get 1 successful update mailbox = res.context[:subscription_mailbox] assert_equal 1, mailbox.size update_payload = mailbox.first assert_equal "I am a C programmer", update_payload["data"]["tootWasTooted"]["toot"]["body"] # Cause an authorized failure matz[:private] = true obj = OpenStruct.new(toot: { body: "Merry Christmas, here's a new Ruby version" }, user: matz) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) assert_equal 2, mailbox.size assert_equal ["Can't subscribe to private user ([\"tootWasTooted\"])"], mailbox.last["errors"].map { |e| e["message"] } # The subscription remains in place assert_equal 1, in_memory_subscription_count end it "support dynamic schema with custom context" do res = exec_query <<-GRAPHQL, context: { legacy_schema: true } subscription { tootWasTooted(handle: "matz") { toot { likesCount } } } GRAPHQL assert_equal 1, in_memory_subscription_count matz = SubscriptionFieldSchema::USERS["matz"] obj = OpenStruct.new(toot: { likes_count: 42 }, user: matz) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) # Get 1 successful update mailbox = res.context[:subscription_mailbox] assert_equal 1, mailbox.size update_payload = mailbox.first assert_equal 42, update_payload["data"]["tootWasTooted"]["toot"]["likesCount"] end end describe "applying `loads:`" do it "uses the original argument name in the event topic" do assert_equal [], SubscriptionFieldSchema::InMemorySubscriptions::EVENT_REGISTRY.keys matz = SubscriptionFieldSchema::USERS["matz"] obj = OpenStruct.new(toot: { body: "I am a C programmer" }, user: matz) SubscriptionFieldSchema.subscriptions.trigger(:toot_was_tooted, {handle: "matz"}, obj) assert_equal [":tootWasTooted:handle:matz"], SubscriptionFieldSchema::InMemorySubscriptions::EVENT_REGISTRY.keys end end describe "`subscription_scope` method" do it "provides a subscription scope that is recognized in the schema" do scoped_subscription = SubscriptionFieldSchema::get_field("Subscription", "directTootWasTooted") assert_equal :viewer, scoped_subscription.subscription_scope end it "requires subscription scope for subscribe and update by default" do err = assert_raises GraphQL::Subscriptions::SubscriptionScopeMissingError do exec_query <<-GRAPHQL subscription { directTootWasTooted { toot { body } } } GRAPHQL end expected_message = "Subscription.directTootWasTooted (SubscriptionFieldSchema::DirectTootWasTooted) requires a `scope:` value to trigger updates (Set `subscription_scope ..., optional: true` to disable this requirement)" assert_equal expected_message, err.message assert_equal 0, in_memory_subscription_count exec_query <<-GRAPHQL, context: { viewer: :me } subscription { directTootWasTooted { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count obj = OpenStruct.new(toot: { body: "Hello from matz!" }, user: SubscriptionFieldSchema::USERS["matz"]) err = assert_raises GraphQL::Subscriptions::SubscriptionScopeMissingError do SubscriptionFieldSchema.subscriptions.trigger(:direct_toot_was_tooted, {}, obj) end assert_equal expected_message, err.message end it "doesn't require subscription scope if `optional: true`" do res = exec_query <<-GRAPHQL, context: { viewer: :me } subscription { directTootWasTootedWithOptionalScope { toot { body } } } GRAPHQL res2 = exec_query <<-GRAPHQL subscription { directTootWasTootedWithOptionalScope { toot { body } } } GRAPHQL assert_equal 2, in_memory_subscription_count obj = OpenStruct.new(toot: { body: "Hello from matz!" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:direct_toot_was_tooted_with_optional_scope, {}, obj) assert_equal 0, res.context[:subscription_mailbox].length assert_equal 1, res2.context[:subscription_mailbox].length SubscriptionFieldSchema.subscriptions.trigger(:direct_toot_was_tooted_with_optional_scope, {}, obj, scope: :me) assert_equal 1, res.context[:subscription_mailbox].length assert_equal 1, res2.context[:subscription_mailbox].length end it "provides a subscription scope that is used in execution" do res = exec_query <<-GRAPHQL, context: { viewer: :me } subscription { directTootWasTooted { toot { body } } } GRAPHQL assert_equal 1, in_memory_subscription_count # Only the subscription with scope :me should be in the mailbox obj = OpenStruct.new(toot: { body: "Hello from matz!" }, user: SubscriptionFieldSchema::USERS["matz"]) SubscriptionFieldSchema.subscriptions.trigger(:direct_toot_was_tooted, {}, obj, scope: :me) SubscriptionFieldSchema.subscriptions.trigger(:direct_toot_was_tooted, {}, obj, scope: :not_me) mailbox = res.context[:subscription_mailbox] assert_equal 1, mailbox.length expected_response = { "data" => { "directTootWasTooted" => { "toot" => { "body" => "Hello from matz!" } } } } assert_equal expected_response, mailbox.first end it "allows for proper inheritance of the class's configuration in subclasses" do # Make a subclass without an explicit configuration class DirectTootSubclass < SubscriptionFieldSchema::DirectTootWasTooted end # Then check if the field options got the inherited value field = GraphQL::Schema::Field.new(name: "blah", resolver_class: DirectTootSubclass) assert_equal :viewer, field.subscription_scope end it "allows for setting the subscription scope value to nil" do class PrivateSubscription < SubscriptionFieldSchema::BaseSubscription subscription_scope :private end PrivateSubscription.subscription_scope nil assert_nil PrivateSubscription.subscription_scope end end describe "writing during resolution" do class DirectWriteSchema < GraphQL::Schema class WriteCheckSubscriptions def use(schema) schema.subscriptions = self end def write_subscription(query, events) query.context[:write_subscription_count] ||= 0 query.context[:write_subscription_count] += 1 evs = query.context[:written_events] ||= [] evs << events nil end end class ImplicitWrite < GraphQL::Schema::Subscription type String def subscribe "#{context[:written_events]&.size.inspect} / #{context[:write_subscription_count].inspect} / #{subscription_written?}" end end class DirectWrite < ImplicitWrite type String def subscribe write_subscription super end end class DirectWriteTwice < DirectWrite type String def subscribe write_subscription super end end class Subscription < GraphQL::Schema::Object field :direct, subscription: DirectWrite field :implicit, subscription: ImplicitWrite field :direct_twice, subscription: DirectWriteTwice end use WriteCheckSubscriptions.new subscription(Subscription) end it "only calls write_subscription once" do res = DirectWriteSchema.execute("subscription { direct }") assert_equal "1 / 1 / true", res["data"]["direct"] assert_equal 1, res.context[:write_subscription_count] assert_equal [1], res.context[:written_events].map(&:size) assert_equal true, res.context.namespace(:subscriptions)[:subscriptions].values.first.subscription_written? res = DirectWriteSchema.execute("subscription { implicit }") assert_equal "nil / nil / false", res["data"]["implicit"] assert_equal 1, res.context[:write_subscription_count] assert_equal [1], res.context[:written_events].map(&:size) assert_equal false, res.context.namespace(:subscriptions)[:subscriptions].values.first.subscription_written? end it "raises if write_subscription is called twice" do err = assert_raises GraphQL::Error do DirectWriteSchema.execute("subscription { directTwice }") end assert_equal "`write_subscription` was called but `DirectWriteSchema::DirectWriteTwice#subscription_written?` is already true. Remove a call to `write subscription`.", err.message end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/input_object_spec.rb
spec/graphql/schema/input_object_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::InputObject do let(:input_object) { Jazz::EnsembleInput } describe ".path" do it "is the name" do assert_equal "EnsembleInput", input_object.path end it "is used in argument paths" do assert_equal "EnsembleInput.name", input_object.arguments["name"].path end end describe "type info" do it "has it" do assert_equal "EnsembleInput", input_object.graphql_name assert_nil input_object.description assert_equal 1, input_object.arguments.size end it "returns newly-added argument definitions" do arg = nil Class.new(GraphQL::Schema::InputObject) do arg = argument(:int, Integer) end assert_instance_of GraphQL::Schema::Argument, arg end it "is the #owner of its arguments" do argument = input_object.arguments["name"] assert_equal input_object, argument.owner end it "inherits arguments" do base_class = Class.new(GraphQL::Schema::InputObject) do argument :arg1, String argument :arg2, String end subclass = Class.new(base_class) do argument :arg2, Integer argument :arg3, Integer end ensemble_class = Class.new(subclass) do argument :ensemble_id, GraphQL::Types::ID, required: false, loads: Jazz::Ensemble end assert_equal 3, subclass.arguments.size assert_equal ["arg1", "arg2", "arg3"], subclass.arguments.keys assert_equal ["String!", "Int!", "Int!"], subclass.arguments.values.map { |a| a.type.to_type_signature } assert_equal ["String!", "Int!", "Int!", "ID"], ensemble_class.arguments.values.map { |a| a.type.to_type_signature } assert_equal :ensemble, ensemble_class.arguments["ensembleId"].keyword end end describe "camelizing with numbers" do module InputObjectWithNumbers class InputObject < GraphQL::Schema::InputObject argument :number_arg1, Integer, required: false argument :number_arg_2, Integer, required: false argument :number_arg3, Integer, required: false, camelize: false argument :number_arg_4, Integer, required: false, camelize: false argument :numberArg5, Integer, required: false argument :numberArg6, Integer, required: false, camelize: false end end it "accepts leading underscores or _no_ underscores" do input_obj = InputObjectWithNumbers::InputObject assert_equal ["numberArg1", "numberArg2", "number_arg3", "number_arg_4", "numberArg5", "numberArg6"], input_obj.arguments.keys assert_equal ["numberArg1", "numberArg2", "number_arg3", "number_arg_4", "numberArg5", "numberArg6"], input_obj.arguments.values.map(&:graphql_name) assert_equal :number_arg1, input_obj.arguments["numberArg1"].keyword assert_equal :number_arg_2, input_obj.arguments["numberArg2"].keyword assert_equal :number_arg3, input_obj.arguments["number_arg3"].keyword assert_equal :number_arg_4, input_obj.arguments["number_arg_4"].keyword assert_equal :numberArg5, input_obj.arguments["numberArg5"].keyword assert_equal :numberArg6, input_obj.arguments["numberArg6"].keyword end end describe "prepare with camelized inputs" do class PrepareCamelizedSchema < GraphQL::Schema class CamelizedInput < GraphQL::Schema::InputObject argument :inputString, String, camelize: false, as: :input_string, prepare: ->(val, ctx) { val.upcase } end class Query < GraphQL::Schema::Object field :input_test, String, null: false do argument :camelized_input, CamelizedInput end def input_test(camelized_input:) camelized_input[:input_string] end end query(Query) end it "calls the prepare proc" do res = PrepareCamelizedSchema.execute("{ inputTest(camelizedInput: { inputString: \"abc\" }) }") assert_equal "ABC", res["data"]["inputTest"] end end describe "prepare: / loads: / as:" do module InputObjectPrepareTest class InputObj < GraphQL::Schema::InputObject argument :a, Integer argument :b, Integer, as: :b2 argument :c, Integer, prepare: :prep, validates: { exclusion: { in: [5, 10] } } argument :d, Integer, prepare: :prep, as: :d2 argument :e, Integer, prepare: ->(val, ctx) { val * ctx[:multiply_by] * 2 }, as: :e2 argument :instrument_id, ID, loads: Jazz::InstrumentType argument :danger, Integer, required: false, prepare: ->(val, ctx) { raise GraphQL::ExecutionError.new('boom!') } argument :nested, self, required: false, validates: { allow_null: true }, prepare: :echo def prep(val) val * context[:multiply_by] end def echo(val) val end end class Thing < GraphQL::Schema::Object field :name, String end class PreparedInputObj < GraphQL::Schema::InputObject argument :thing_id, ID, loads: Thing, prepare: ->(val, ctx) { "thing-#{val}" } end class ResolverPrepares < GraphQL::Schema::Resolver argument :input_object, PreparedInputObj argument :thing_id, ID, loads: Thing, prepare: ->(val, ctx) { "thing-#{val}" } type [String], null: false def resolve(thing:, input_object:) [thing.name, input_object[:thing].name] end end class Query < GraphQL::Schema::Object field :inputs, [String], null: false do argument :input, InputObj end def inputs(input:) [input.to_kwargs.inspect, input.instrument.name] end field :multiple_prepares, [String] do argument :input_object, PreparedInputObj argument :thing_id, ID, loads: Thing, prepare: ->(val, ctx) { "thing-#{val}" } end def multiple_prepares(thing:, input_object:) [thing.name, input_object[:thing].name] end field :resolver_prepares, resolver: ResolverPrepares field :t, Thing end class Mutation < GraphQL::Schema::Object class InstrumentInput < GraphQL::Schema::InputObject argument :instrument_id, ID, loads: Jazz::InstrumentType end class TouchInstrument < GraphQL::Schema::Mutation argument :input_obj, InstrumentInput field :instrument_name_method, String, null: false field :instrument_name_key, String, null: false def resolve(input_obj:) # Make sure both kinds of access work the same: { instrument_name_method: input_obj.instrument.name, instrument_name_key: input_obj[:instrument].name, } end end class InstrumentByNameInput < GraphQL::Schema::InputObject argument :instrument_name, ID, loads: Jazz::InstrumentType, as: :instrument def self.load_instrument(instrument_name, context) -> { instruments = Jazz::Models.data["Instrument"] instruments.find { |i| i.name == instrument_name } } end end class TouchInstrumentByName < TouchInstrument argument :input_obj, InstrumentByNameInput end field :touch_instrument, mutation: TouchInstrument field :touch_instrument_by_name, mutation: TouchInstrumentByName class ListInstruments < GraphQL::Schema::Mutation argument :list, [InstrumentInput] field :resolved_list, String, null: false def resolve(list:) { resolved_list: list.map(&:to_kwargs).inspect } end end field :list_instruments, mutation: ListInstruments end class Schema < GraphQL::Schema query(Query) mutation(Mutation) lazy_resolve(Proc, :call) def self.object_from_id(id, ctx) -> { if id.start_with?("thing-") OpenStruct.new(name: id) else Jazz::GloballyIdentifiableType.find(id) end } end def self.resolve_type(type, obj, ctx) type end max_complexity 100 end end it "always prepares before loading" do res = InputObjectPrepareTest::Schema.execute("{ resolverPrepares(thingId: \"abc\", inputObject: { thingId: \"def\" }) }") assert_equal ["thing-abc", "thing-def"], res["data"]["resolverPrepares"] res = InputObjectPrepareTest::Schema.execute("{ multiplePrepares(thingId: \"abc\", inputObject: { thingId: \"def\" }) }") assert_equal ["thing-abc", "thing-def"], res["data"]["multiplePrepares"] end it "calls methods on the input object" do query_str = <<-GRAPHQL { inputs(input: { a: 1, b: 2, c: 3, d: 4, e: 5, instrumentId: "Instrument/Drum Kit" }) } GRAPHQL res = InputObjectPrepareTest::Schema.execute(query_str, context: { multiply_by: 3 }) expected_obj = [{ a: 1, b2: 2, c: 9, d2: 12, e2: 30, instrument: Jazz::Models::Instrument.new("Drum Kit", "PERCUSSION") }.inspect, "Drum Kit"] assert_equal expected_obj, res["data"]["inputs"] query_str2 = <<-GRAPHQL { inputs(input: { a: 1, b: 2, c: 3, d: 4, e: 5, instrumentId: "Instrument/Drum Kit", nested: { a: 2, b: 4, c: 6, d: 8, e: 10, instrumentId: "Instrument/Drum Kit" } }) } GRAPHQL res2 = InputObjectPrepareTest::Schema.execute(query_str2, context: { multiply_by: 3 }) expected_hash_values = { a: 2, b2: 4, c: 6, d2: 8, e2: 60 }.inspect.sub("{", "").sub("}", "") assert_includes res2["data"]["inputs"][0], expected_hash_values end it "calls load_ methods for arguments when they're present" do query_str = <<-GRAPHQL mutation { touchInstrumentByName(inputObj: { instrumentName: "Flute" }) { instrumentNameMethod instrumentNameKey } } GRAPHQL res = InputObjectPrepareTest::Schema.execute(query_str) assert_equal "Flute", res["data"]["touchInstrumentByName"]["instrumentNameMethod"] assert_equal "Flute", res["data"]["touchInstrumentByName"]["instrumentNameKey"] end it "handles exceptions preparing variable input objects" do query_str = <<-GRAPHQL query($input: InputObj!){ inputs(input: $input) } GRAPHQL input = { "a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5, "instrumentId" => "Instrument/Drum Kit", "danger" => 1 } res = InputObjectPrepareTest::Schema.execute(query_str, context: { multiply_by: 3 }, variables: { input: input}) assert_nil(res["data"]) assert_equal("boom!", res["errors"][0]["message"]) assert_equal([{ "line" => 1, "column" => 33 }], res["errors"][0]["locations"]) end it "handles not-found with max complexity analyzer running" do query_str = <<-GRAPHQL { inputs(input: {a: 1, b: 2, c: 3, d: 4, e: 6, instrumentId: "Instrument/Nonsense"}) } GRAPHQL res = InputObjectPrepareTest::Schema.execute( query_str, context: { multiply_by: 3 } ) assert_equal ["No object found for `instrumentId: \"Instrument/Nonsense\"`"], res["errors"].map { |e| e["message"] } end it "loads input object arguments" do query_str = <<-GRAPHQL mutation { touchInstrument(inputObj: { instrumentId: "Instrument/Drum Kit" }) { instrumentNameMethod instrumentNameKey } } GRAPHQL res = InputObjectPrepareTest::Schema.execute(query_str) assert_equal "Drum Kit", res["data"]["touchInstrument"]["instrumentNameMethod"] assert_equal "Drum Kit", res["data"]["touchInstrument"]["instrumentNameKey"] end it "loads nested input object arguments" do query_str = <<-GRAPHQL mutation { listInstruments(list: [{ instrumentId: "Instrument/Drum Kit" }]) { resolvedList } } GRAPHQL res = InputObjectPrepareTest::Schema.execute(query_str) expected_obj = [{ instrument: Jazz::Models::Instrument.new("Drum Kit", "PERCUSSION") }].inspect assert_equal expected_obj, res["data"]["listInstruments"]["resolvedList"] end end describe "prepare (entire input object)" do module InputObjectPrepareObjectTest class RangeInput < GraphQL::Schema::InputObject argument :min, Integer argument :max, Integer, required: false def self.authorized?(obj, arg, ctx) if arg.end <= 100 super else ctx.add_error(GraphQL::ExecutionError.new("Range too big")) false end end def prepare min..max end end class OnlyOnePrepareInputObject < GraphQL::Schema::InputObject argument :i, Int attr_reader :prepared_count def prepare @prepared_count ||= 0 @prepared_count += 1 super end end class SmallIntegerArgument < GraphQL::Schema::Argument def authorized?(obj, val, ctx) if val > 100 raise GraphQL::ExecutionError, "#{path} too big" else super end end end class HashInput < GraphQL::Schema::InputObject argument_class SmallIntegerArgument argument :k1, Integer argument :k2, Integer end class HashInputResolver < GraphQL::Schema::Resolver argument :input, HashInput, prepare: ->(val, ctx) { val.to_h } type String, null: true def resolve(input:) "#{input.class}, #{input.inspect}" end end class Thing < GraphQL::Schema::Object field :name, String end class PrepareAndLoadInput < GraphQL::Schema::InputObject argument :value, String argument :thing_id, ID, loads: Thing def prepare { value: "Prepared: #{value}", thing: thing } end end class Query < GraphQL::Schema::Object field :inputs, String do argument :input, RangeInput end def inputs(input:) input.inspect end field :hash_input, resolver: HashInputResolver field :prepare_once, Int do argument :input, OnlyOnePrepareInputObject end def prepare_once(input:) input.prepared_count end field :prepare_list, [Int] do argument :input, [OnlyOnePrepareInputObject] end def prepare_list(input:) input.map(&:prepared_count) end field :prepare_and_load, String do argument :input, PrepareAndLoadInput end def prepare_and_load(input:) "#{input[:value]}/#{input[:thing][:name]}" end field :prepare_list_of_lists, [[Int]] do argument :input, [[OnlyOnePrepareInputObject]] end def prepare_list_of_lists(input:) input.map { |i| i.map(&:prepared_count) } end field :example_thing, Thing end class Schema < GraphQL::Schema query(Query) def self.resolve_type(_abs_t, _obj, _ctx) Thing end def self.object_from_id(id, _ctx) { name: "Thing #{id}"} end end end it "calls prepare and loads" do query_str = "{ prepareAndLoad(input: { value: \"Hello\", thingId: \"123\"}) }" res = InputObjectPrepareObjectTest::Schema.execute(query_str) assert_equal "Prepared: Hello/Thing 123", res["data"]["prepareAndLoad"] end it "calls prepare on the input object (literal)" do query_str = <<-GRAPHQL { inputs(input: { min: 5, max: 10 }) } GRAPHQL res = InputObjectPrepareObjectTest::Schema.execute(query_str) assert_equal "5..10", res["data"]["inputs"] end it "only prepares once" do res = InputObjectPrepareObjectTest::Schema.execute("{ prepareOnce( input: { i: 1 } ) }") assert_equal 1, res["data"]["prepareOnce"] end it "calls prepare on lists of input objects" do res = InputObjectPrepareObjectTest::Schema.execute("{ prepareList( input:[{ i: 1 }, { i: 1}]) }") assert_equal [1, 1], res["data"]["prepareList"] res = InputObjectPrepareObjectTest::Schema.execute("{ prepareListOfLists( input:[[{ i: 1 }, { i: 1}], [{i: 2}, {i: 2}]]) }") assert_equal [[1, 1], [1, 1]], res["data"]["prepareListOfLists"] end it "calls prepare on the input object (variable)" do query_str = <<-GRAPHQL query ($input: RangeInput!){ inputs(input: $input) } GRAPHQL res = InputObjectPrepareObjectTest::Schema.execute(query_str, variables: { input: { min: 5, max: 10 } }) assert_equal "5..10", res["data"]["inputs"] end it "authorizes the prepared value" do query_str = <<-GRAPHQL query ($input: RangeInput!){ inputs(input: $input) } GRAPHQL res = InputObjectPrepareObjectTest::Schema.execute(query_str, variables: { input: { min: 5, max: 101 } }) assert_nil res["data"]["inputs"] assert_equal ["Range too big"], res["errors"].map { |e| e["message"] } end it "authorizes Hashes returned from prepare:" do query_str = "{ hashInput(input: { k1: 5, k2: 12 }) }" res = InputObjectPrepareObjectTest::Schema.execute(query_str) expected_str = { k1: 5, k2: 12 }.inspect assert_equal "Hash, #{expected_str}", res["data"]["hashInput"] query_str = "{ hashInput(input: { k1: 500, k2: 12 }) }" res = InputObjectPrepareObjectTest::Schema.execute(query_str) assert_equal ["HashInput.k1 too big"], res["errors"].map { |e| e["message"] } assert_nil res["data"]["hashInput"] end end describe "loading application object(s)" do module InputObjectLoadsTest class BaseArgument < GraphQL::Schema::Argument def authorized?(obj, val, ctx) if contains_spinal_tap?(val) false else true end end def contains_spinal_tap?(val) if val.is_a?(Array) val.any? { |v| contains_spinal_tap?(v) } else val.is_a?(Jazz::Models::Ensemble) && val.name == "Spinal Tap" end end end class SingleLoadInputObj < GraphQL::Schema::InputObject argument_class BaseArgument argument :instrument_id, ID, loads: Jazz::InstrumentType end class MultiLoadInputObj < GraphQL::Schema::InputObject argument_class BaseArgument argument :instrument_ids, [ID], loads: Jazz::InstrumentType end class Query < GraphQL::Schema::Object field :single_load_input, Jazz::InstrumentType do argument :input, SingleLoadInputObj end field :multi_load_input, [Jazz::InstrumentType] do argument :input, MultiLoadInputObj end def single_load_input(input:) input.instrument end def multi_load_input(input:) input.instruments end end class Schema < GraphQL::Schema query(Query) def self.object_from_id(id, ctx) Jazz::GloballyIdentifiableType.find(id) end def self.resolve_type(type, obj, ctx) type end end end let(:single_query_str) { <<-GRAPHQL query($id: ID!) { singleLoadInput(input: {instrumentId: $id}) { id } } GRAPHQL } let(:multi_query_str) { <<-GRAPHQL query($ids: [ID!]!) { multiLoadInput(input: {instrumentIds: $ids}) { id } } GRAPHQL } it "loads arguments as objects of the given type and strips `_id` suffix off argument name" do res = InputObjectLoadsTest::Schema.execute(single_query_str, variables: { id: "Ensemble/Robert Glasper Experiment" }) assert_equal "Ensemble/Robert Glasper Experiment", res["data"]["singleLoadInput"]["id"] end it "loads arguments as objects of the given type and strips `_ids` suffix off argument name and appends `s`" do res = InputObjectLoadsTest::Schema.execute(multi_query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"]}) assert_equal ["Ensemble/Robert Glasper Experiment", "Ensemble/Bela Fleck and the Flecktones"], res["data"]["multiLoadInput"].map { |e| e["id"] } end it "authorizes based on loaded objects" do res = InputObjectLoadsTest::Schema.execute(single_query_str, variables: { id: "Ensemble/Spinal Tap" }) assert_nil res["data"]["singleLoadInput"] res2 = InputObjectLoadsTest::Schema.execute(multi_query_str, variables: { ids: ["Ensemble/Robert Glasper Experiment", "Ensemble/Spinal Tap"]}) assert_nil res2["data"]["multiLoadInput"] end end describe "in queries" do it "is passed to the field method" do query_str = <<-GRAPHQL { inspectInput(input: { stringValue: "ABC", legacyInput: { intValue: 4 }, nestedInput: { stringValue: "xyz"}, ensembleId: "Ensemble/Robert Glasper Experiment" }) } GRAPHQL res = Jazz::Schema.execute(query_str, context: { message: "hi" }) expected_info = [ "Jazz::InspectableInput", "hi, ABC, 4, (hi, xyz, -, (-))", "ABC", "ABC", "true", "ABC", Jazz::Models::Ensemble.new("Robert Glasper Experiment").to_s, "true", ] assert_equal expected_info, res["data"]["inspectInput"] end it "works with given nil values for nested inputs" do query_str = <<-GRAPHQL query($input: InspectableInput!){ inspectInput(input: $input) } GRAPHQL input = { "nestedInput" => nil, "stringValue" => "xyz" } res = Jazz::Schema.execute(query_str, variables: { input: input }, context: { message: "hi" }) assert res["data"]["inspectInput"] end it "uses empty object when no variable value is given" do query_str = <<-GRAPHQL query($input: InspectableInput){ inspectInput(input: { nestedInput: $input, stringValue: "xyz" }) } GRAPHQL res = Jazz::Schema.execute(query_str, variables: { input: nil }, context: { message: "hi" }) expected_info = [ "Jazz::InspectableInput", "hi, xyz, -, (-)", "xyz", "xyz", "true", "xyz", "No ensemble", "false" ] assert_equal expected_info, res["data"]["inspectInput"] end it "handles camelized booleans" do res = Jazz::Schema.execute("query($input: CamelizedBooleanInput!){ inputObjectCamelization(input: $input) }", variables: { input: { camelizedBoolean: false } }) expected_res = { camelized_boolean: false }.inspect assert_equal expected_res, res["data"]["inputObjectCamelization"] end end describe "when used with default_value" do it "comes as an instance" do res = Jazz::Schema.execute("{ defaultValueTest }") expected_res = { string_value: "S" }.inspect assert_equal "Jazz::InspectableInput -> #{expected_res}", res["data"]["defaultValueTest"] end it "works with empty objects" do res = Jazz::Schema.execute("{ defaultValueTest2 }") assert_equal "Jazz::FullyOptionalInput -> {}", res["data"]["defaultValueTest2"] end it "introspects in GraphQL language with enums" do class InputDefaultSchema < GraphQL::Schema class Letter < GraphQL::Schema::Enum value "A", value: 1 value "B", value: 2 end class InputObj < GraphQL::Schema::InputObject argument :arg_a, Letter, required: false argument :arg_b, Letter, required: false end class Query < GraphQL::Schema::Object field :i, Int do argument :arg, InputObj, required: false, default_value: { arg_a: 1, arg_b: 2 } end end query(Query) end res = InputDefaultSchema.execute " { __type(name: \"Query\") { fields { name args { name defaultValue } } } } " assert_equal "{argA: A, argB: B}", res["data"]["__type"]["fields"].first["args"].first["defaultValue"] end end describe "#dig" do module InputObjectDigTest class TestInput1 < GraphQL::Schema::InputObject graphql_name "TestInput1" argument :d, Int argument :e, Int end class TestInput2 < GraphQL::Schema::InputObject graphql_name "TestInput2" argument :a, Int argument :b, Int argument :c, TestInput1, as: :inputObject end end arg_values = { a: 1, b: 2, inputObject: InputObjectDigTest::TestInput1.new(nil, ruby_kwargs: { d: 3, e: 4 }, context: nil, defaults_used: Set.new) } input_object = InputObjectDigTest::TestInput2.new( nil, ruby_kwargs: arg_values, context: GraphQL::Query::NullContext.instance, defaults_used: Set.new ) it "returns the value at that key" do assert_equal 1, input_object.dig(:a) assert input_object.dig(:inputObject).is_a?(GraphQL::Schema::InputObject) end it "works with nested keys" do assert_equal 3, input_object.dig(:inputObject, :d) end it "returns nil for missing keys" do assert_nil input_object.dig("z") assert_nil input_object.dig(7) end end describe "pattern matching" do module InputObjectPatternTest class TestInput1 < GraphQL::Schema::InputObject graphql_name "TestInput1" argument :d, Int argument :e, Int end class TestInput2 < GraphQL::Schema::InputObject graphql_name "TestInput2" argument :a, Int argument :b, Int argument :c, TestInput1, as: :inputObject end end arg_values = { a: 1, b: 2, inputObject: InputObjectPatternTest::TestInput1.new(nil, ruby_kwargs: { d: 3, e: 4 }, context: nil, defaults_used: Set.new) } input_object = InputObjectPatternTest::TestInput2.new( nil, ruby_kwargs: arg_values, context: GraphQL::Query::NullContext.instance, defaults_used: Set.new ) it "matches the value at that key" do assert case input_object in { a: 1 } true else false end assert input_object.dig(:inputObject).is_a?(GraphQL::Schema::InputObject) end it "matches nested input objects" do assert case input_object in { inputObject: { d: 3 } } true else false end end it "does not match missing keys" do assert case input_object in { z: } false else true end end end describe "introspection" do it "returns input fields" do res = Jazz::Schema.execute(' { __type(name: "InspectableInput") { name inputFields { name } } __schema { types { name inputFields { name } } } }') # Test __type assert_equal ["ensembleId", "stringValue", "nestedInput", "legacyInput"], res["data"]["__type"]["inputFields"].map { |f| f["name"] } # Test __schema { types } # It's upcased to test custom introspection input_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "INSPECTABLEINPUT" } assert_equal ["ensembleId", "stringValue", "nestedInput", "legacyInput"], input_type["inputFields"].map { |f| f["name"] } end end describe "nested objects inside lists" do class NestedInputObjectSchema < GraphQL::Schema class ItemInput < GraphQL::Schema::InputObject argument :str, String end class NestedStuff < GraphQL::Schema::RelayClassicMutation argument :items, [ItemInput] field :str, String, null: false def resolve(items:) { str: items.map { |i| i.class.name }.join(", ") } end end class Mutation < GraphQL::Schema::Object field :nested_stuff, mutation: NestedStuff end mutation(Mutation) end it "properly wraps them in instances" do res = NestedInputObjectSchema.execute " mutation($input: NestedStuffInput!) { nestedStuff(input: $input) { str } } ", variables: { input: { "items" => [{ "str" => "1"}, { "str" => "2"}]}} assert_equal "NestedInputObjectSchema::ItemInput, NestedInputObjectSchema::ItemInput", res["data"]["nestedStuff"]["str"] end end describe 'default values' do describe 'when the type is an enum with underlying ruby values' do it 'provides the default value' do class TestEnum < GraphQL::Schema::Enum value 'A', 'Represents an authorized agent in our system.', value: 'a' value 'B', 'Agent is disabled, web app access is denied.', value: 'b' end class TestInput < GraphQL::Schema::InputObject argument :foo, TestEnum, 'TestEnum', required: false, default_value: 'a' end test_input_type = TestInput default_test_input_value = test_input_type.coerce_isolated_input({}) assert_equal default_test_input_value[:foo], 'a' end end describe "when it's an empty object" do it "is passed in" do input_obj = Class.new(GraphQL::Schema::InputObject) do graphql_name "InputObj" argument :s, String, required: false end query = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :f, String do argument :arg, input_obj, required: false, default_value: {} end def f(arg:) arg.to_h.inspect end end schema = Class.new(GraphQL::Schema) do query(query) end res = schema.execute("{ f } ") assert_equal "{}", res["data"]["f"] end end end describe "tests from legacy input_object_type" do let(:input_object) { Dummy::DairyProductInput } def validate_isolated_input(t, input) t.validate_input(input, GraphQL::Query::NullContext.instance) end describe "input validation" do it "Accepts anything that yields key-value pairs to #all?" do values_obj = MinimumInputObject.new({"source" => "COW", "fatContent" => 0.4}) assert input_object.valid_isolated_input?(values_obj) end describe "validate_input with non-enumerable input" do it "returns a valid result for MinimumInputObject" do result = validate_isolated_input(input_object, MinimumInputObject.new({"source" => "COW", "fatContent" => 0.4})) assert(result.valid?) end it "returns an invalid result for MinimumInvalidInputObject" do invalid_input = MinimumInputObject.new({"source" => "KOALA", "fatContent" => 0.4}) result = validate_isolated_input(input_object, invalid_input) assert(!result.valid?) end end describe "validate_input with null" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { a(input: ExampleInputObject): Int } input ExampleInputObject { a: String b: Int! } |) } let(:input_type) { schema.types['ExampleInputObject'] } it "returns an invalid result when value is null for non-null argument" do invalid_input = MinimumInputObject.new({"a" => "Test", "b" => nil}) result = validate_isolated_input(input_type, invalid_input) assert(!result.valid?) end it "returns valid result when value is null for nullable argument" do invalid_input = MinimumInputObject.new({"a" => nil, "b" => 1}) result = validate_isolated_input(input_type, invalid_input) assert(result.valid?) end end describe "validate_input with enumerable input" do describe "with good input" do it "returns a valid result" do input = { "source" => "COW", "fatContent" => 0.4 } result = validate_isolated_input(input_object, input) assert(result.valid?) end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
true
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/object_spec.rb
spec/graphql/schema/object_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Object do describe "class attributes" do let(:object_class) { Jazz::Ensemble } it "tells type data" do assert_equal "Ensemble", object_class.graphql_name assert_equal "A group of musicians playing together", object_class.description assert_equal 9, object_class.fields.size assert_equal [ "GloballyIdentifiable", "HasMusicians", "InvisibleNameEntity", "NamedEntity", "PrivateNameEntity", ], object_class.interfaces.map(&:graphql_name).sort # It filters interfaces, too assert_equal [ "GloballyIdentifiable", "HasMusicians", "NamedEntity" ], object_class.interfaces({}).map(&:graphql_name).sort # Compatibility methods are delegated to the underlying BaseType assert object_class.respond_to?(:connection_type) end describe "path" do it "is the type name" do assert_equal "Ensemble", object_class.path end end it "inherits fields and interfaces" do new_object_class = Class.new(object_class) do field :newField, String field :name, String, description: "The new description", null: true end # one more than the parent class assert_equal 10, new_object_class.fields.size # inherited interfaces are present expected_interface_names = [ "GloballyIdentifiable", "HasMusicians", "InvisibleNameEntity", "NamedEntity", "PrivateNameEntity", ] assert_equal expected_interface_names, object_class.interfaces.map(&:graphql_name).sort assert_equal expected_interface_names, new_object_class.interfaces.map(&:graphql_name).sort # The new field is present assert new_object_class.fields.key?("newField") # The overridden field is present: name_field = new_object_class.fields["name"] assert_equal "The new description", name_field.description end it "inherits name and description" do # Manually assign a name since `.name` isn't populated for dynamic classes new_subclass_1 = Class.new(object_class) do graphql_name "NewSubclass" end new_subclass_2 = Class.new(new_subclass_1) assert_equal "NewSubclass", new_subclass_1.graphql_name assert_equal "NewSubclass", new_subclass_2.graphql_name assert_equal object_class.description, new_subclass_2.description end it "implements visibility constrained interface when context is private" do found_interfaces = object_class.interfaces({ private: true }) assert_equal 5, found_interfaces.count assert found_interfaces.any? { |int| int.graphql_name == 'PrivateNameEntity' } end it "should take Ruby name (without Type suffix) as default graphql name" do TestingClassType = Class.new(GraphQL::Schema::Object) assert_equal "TestingClass", TestingClassType.graphql_name end it "raise on anonymous class without declared graphql name" do anonymous_class = Class.new(GraphQL::Schema::Object) assert_raises GraphQL::RequiredImplementationMissingError do anonymous_class.graphql_name end end class OverrideNameObject < GraphQL::Schema::Object class << self def default_graphql_name "Override" end end end it "can override the default graphql_name" do override_name_object = OverrideNameObject assert_equal "Override", override_name_object.graphql_name end end describe "implementing interfaces" do it "raises an error when trying to implement a non-interface module" do object_type = Class.new(GraphQL::Schema::Object) module NotAnInterface end err = assert_raises do object_type.implements(NotAnInterface) end message = "NotAnInterface cannot be implemented since it's not a GraphQL Interface. Use `include` for plain Ruby modules." assert_equal message, err.message end it "does not inherit singleton methods from base interface when implementing another interface" do object_type = Class.new(GraphQL::Schema::Object) methods = object_type.singleton_methods method_defs = Hash[methods.zip(methods.map{|method| object_type.method(method.to_sym)})] module InterfaceType include GraphQL::Schema::Interface end object_type.implements(InterfaceType) new_method_defs = Hash[methods.zip(methods.map{|method| object_type.method(method.to_sym)})] assert_equal method_defs, new_method_defs end end it "doesnt convolute field names that differ with underscore" do interface = Module.new do include GraphQL::Schema::Interface graphql_name 'TestInterface' description 'Requires an id' field :id, GraphQL::Types::ID, null: false end object = Class.new(GraphQL::Schema::Object) do graphql_name 'TestObject' implements interface global_id_field :id field :_id, String, description: 'database id', null: true end assert_equal 2, object.fields.size end describe "wrapping a Hash" do it "automatically looks up symbol and string keys" do query_str = <<-GRAPHQL { hashyEnsemble { musicians { name } formedAt } } GRAPHQL res = Jazz::Schema.execute(query_str) ensemble = res["data"]["hashyEnsemble"] assert_equal ["Jerry Garcia"], ensemble["musicians"].map { |m| m["name"] } assert_equal "May 5, 1965", ensemble["formedAt"] end it "works with strings and symbols" do query_str = <<-GRAPHQL { hashByString { falsey } hashBySym { falsey } } GRAPHQL res = Jazz::Schema.execute(query_str) assert_equal false, res["data"]["hashByString"]["falsey"] assert_equal false, res["data"]["hashBySym"]["falsey"] end end describe "wrapping `nil`" do it "doesn't wrap nil in lists" do query_str = <<-GRAPHQL { namedEntities { name } } GRAPHQL res = Jazz::Schema.execute(query_str) expected_items = [{"name" => "Bela Fleck and the Flecktones"}, nil] assert_equal expected_items, res["data"]["namedEntities"] end end describe "in queries" do after { Jazz::Models.reset } it "returns data" do query_str = <<-GRAPHQL { ensembles { name } instruments { name } } GRAPHQL res = Jazz::Schema.execute(query_str) expected_ensembles = [ {"name" => "Bela Fleck and the Flecktones"}, {"name" => "ROBERT GLASPER Experiment"}, ] assert_equal expected_ensembles, res["data"]["ensembles"] assert_equal({"name" => "Banjo"}, res["data"]["instruments"].first) end it "does mutations" do mutation_str = <<-GRAPHQL mutation AddEnsemble($name: String!) { addEnsemble(input: { name: $name }) { id } } GRAPHQL query_str = <<-GRAPHQL query($id: ID!) { find(id: $id) { ... on Ensemble { name } } } GRAPHQL res = Jazz::Schema.execute(mutation_str, variables: { name: "Miles Davis Quartet" }) new_id = res["data"]["addEnsemble"]["id"] res2 = Jazz::Schema.execute(query_str, variables: { id: new_id }) assert_equal "Miles Davis Quartet", res2["data"]["find"]["name"] end it "initializes root wrappers once" do query_str = " { oid1: objectId oid2: objectId }" res = Jazz::Schema.execute(query_str) assert_equal res["data"]["oid1"], res["data"]["oid2"] end it "skips fields properly" do query_str = "{ find(id: \"MagicalSkipId\") { __typename } }" res = Jazz::Schema.execute(query_str) skip_value = {} assert_equal({"data" => skip_value }, res.to_h) end end describe "when fields conflict with built-ins" do it "warns when no override" do expected_warning = "X's `field :method` conflicts with a built-in method, use `resolver_method:` to pick a different resolver method for this field (for example, `resolver_method: :resolve_method` and `def resolve_method`). Or use `method_conflict_warning: false` to suppress this warning.\n" assert_output "", expected_warning do Class.new(GraphQL::Schema::Object) do graphql_name "X" field :method, String end end end it "warns when override matches field name" do expected_warning = "X's `field :object` conflicts with a built-in method, use `resolver_method:` to pick a different resolver method for this field (for example, `resolver_method: :resolve_object` and `def resolve_object`). Or use `method_conflict_warning: false` to suppress this warning.\n" assert_output "", expected_warning do Class.new(GraphQL::Schema::Object) do graphql_name "X" field :object, String, resolver_method: :object end end end it "doesn't warn with a resolver_method: override" do assert_output "", "" do Class.new(GraphQL::Schema::Object) do graphql_name "X" field :method, String, resolver_method: :resolve_method end end end it "doesn't warn with a method: override" do assert_output "", "" do Class.new(GraphQL::Schema::Object) do graphql_name "X" field :module, String, method: :mod end end end it "doesn't warn with a suppression" do assert_output "", "" do Class.new(GraphQL::Schema::Object) do graphql_name "X" field :method, String, method_conflict_warning: false end end end it "doesn't warn when parsing a schema" do assert_output "", "" do schema = GraphQL::Schema.from_definition <<-GRAPHQL type Query { method: String } GRAPHQL assert_equal ["method"], schema.query.fields.keys end end it "doesn't warn when passing object through using resolver_method" do assert_output "", "" do Class.new(GraphQL::Schema::Object) do graphql_name "X" field :thing, String, resolver_method: :object end end end end describe "type-specific invalid null errors" do class ObjectInvalidNullSchema < GraphQL::Schema module Numberable include GraphQL::Schema::Interface field :float, Float, null: false def float nil end end class Query < GraphQL::Schema::Object implements Numberable field :int, Integer, null: false def int nil end end query(Query) def self.type_error(err, ctx) raise err end end it "raises them when invalid nil is returned" do assert_raises(ObjectInvalidNullSchema::Query::InvalidNullError) do ObjectInvalidNullSchema.execute("{ int }") end end it "raises them for fields inherited from interfaces" do assert_raises(ObjectInvalidNullSchema::Query::InvalidNullError) do ObjectInvalidNullSchema.execute("{ float }") end end end it "has a consistent object shape" do type_defn_shapes = Set.new example_shapes_by_name = {} ObjectSpace.each_object(Class) do |cls| if cls < GraphQL::Schema::Object shape = cls.instance_variables # these are from a custom test shape.delete(:@configs) shape.delete(:@future_schema) shape.delete(:@metadata) shape.delete(:@admin_only) if type_defn_shapes.add?(shape) example_shapes_by_name[cls.graphql_name] = shape end end end # Uncomment this to debug shapes: # File.open("shapes.txt", "w+") do |f| # f.puts(type_defn_shapes.to_a.map { |ary| ary.inspect }.join("\n")) # example_shapes_by_name.each do |name, sh| # f.puts("#{name} ==> #{sh.inspect}") # end # end default_shape = Class.new(GraphQL::Schema::Object).instance_variables default_type_with_connection_type = Class.new(GraphQL::Schema::Object) { graphql_name("Thing") } default_type_with_connection_type.connection_type # initialize the relay metadata default_shape_with_connection_type = default_type_with_connection_type.instance_variables default_edge_shape = Class.new(GraphQL::Types::Relay::BaseEdge).instance_variables default_connection_shape = Class.new(GraphQL::Types::Relay::BaseConnection).instance_variables default_mutation_payload_shape = Class.new(GraphQL::Schema::RelayClassicMutation) { graphql_name("DoSomething") }.payload_type.instance_variables default_visibility_shape = Class.new(GraphQL::Schema::Object).instance_variables expected_default_shapes = [ default_shape, default_shape_with_connection_type, default_edge_shape, default_connection_shape, default_mutation_payload_shape, default_visibility_shape ] type_defn_shapes_a = type_defn_shapes.to_a assert type_defn_shapes_a.find { |sh| sh == default_shape }, "There's a match for default_shape" assert type_defn_shapes_a.find { |sh| sh == default_shape_with_connection_type }, "There's a match for default_shape_with_connection_type" assert type_defn_shapes_a.find { |sh| sh == default_edge_shape }, "There's a match for default_edge_shape" assert type_defn_shapes_a.find { |sh| sh == default_connection_shape }, "There's a match for default_connection_shape" assert type_defn_shapes_a.find { |sh| sh == default_mutation_payload_shape }, "There's a match for default_mutation_payload_shape" assert type_defn_shapes_a.find { |sh| sh == default_visibility_shape }, "There's a match for default_visibility_shape" extra_shapes = type_defn_shapes_a - expected_default_shapes extra_shapes_by_name = {} extra_shapes.each do |shape| name = example_shapes_by_name.key(shape) extra_shapes_by_name[name] = shape end assert_equal({}, extra_shapes_by_name, "There aren't any extra shape profiles") end describe "overriding wrap" do class WrapOverrideSchema < GraphQL::Schema module LogTrace def trace(key, data) if ((q = data[:query]) && (c = q.context)) c[:log] << key end yield end ["parse", "lex", "validate", "analyze_query", "analyze_multiplex", "execute_query", "execute_multiplex", "execute_field", "execute_field_lazy", "authorized", "authorized_lazy", "resolve_type", "resolve_type_lazy", "execute_query_lazy"].each do |method_name| define_method(method_name) do |**data, &block| trace(method_name, data, &block) end end end class SimpleMethodCallField < GraphQL::Schema::Field def resolve(obj, args, ctx) obj.public_send("resolve_#{@original_name}") end end module CustomIntrospection class DynamicFields < GraphQL::Introspection::DynamicFields field_class(SimpleMethodCallField) field :__typename, String def self.wrap(obj, ctx) OpenStruct.new(resolve___typename: "Wrapped") end end end class Query < GraphQL::Schema::Object field_class(SimpleMethodCallField) def self.wrap(obj, ctx) OpenStruct.new(resolve_int: 5) end field :int, Integer, null: false end query(Query) introspection(CustomIntrospection) trace_with(LogTrace) end it "avoids calls to Object.authorized? and uses the returned object" do log = [] res = WrapOverrideSchema.execute("{ __typename int }", context: { log: log }) assert_equal "Wrapped", res["data"]["__typename"] assert_equal 5, res["data"]["int"] expected_log = [ "validate", "analyze_query", "execute_query", "execute_field", "execute_field", "execute_query_lazy" ] assert_equal expected_log, log end end describe ".comment" do it "isn't inherited and can be set to nil" do obj1 = Class.new(GraphQL::Schema::Object) do graphql_name "Obj1" comment "TODO: fix this" end obj2 = Class.new(obj1) do graphql_name("Obj2") end assert_equal "TODO: fix this", obj1.comment assert_nil obj2.comment obj1.comment(nil) assert_nil obj1.comment end end describe "when defined with no fields" do class NoFieldsSchema < GraphQL::Schema class NoFieldsThing < GraphQL::Schema::Object end class NoFieldsCompatThing < GraphQL::Schema::Object has_no_fields(true) end class Query < GraphQL::Schema::Object field :no_fields_thing, NoFieldsThing field :no_fields_compat_thing, NoFieldsCompatThing end query(Query) end it "raises an error at runtime and printing" do refute NoFieldsSchema::NoFieldsThing.has_no_fields? expected_message = "Object types must have fields, but NoFieldsThing doesn't have any. Define a field for this type, remove it from your schema, or add `has_no_fields(true)` to its definition. This will raise an error in a future GraphQL-Ruby version. " res = assert_warns(expected_message) do NoFieldsSchema.execute("{ noFieldsThing { blah } }") end assert_equal ["Field 'blah' doesn't exist on type 'NoFieldsThing'"], res["errors"].map { |err| err["message"] } assert_warns(expected_message) do NoFieldsSchema.to_definition end assert_warns(expected_message) do NoFieldsSchema.to_json end end it "doesn't raise an error if has_no_fields(true)" do assert NoFieldsSchema::NoFieldsCompatThing.has_no_fields? res = assert_warns "" do NoFieldsSchema.execute("{ noFieldsCompatThing { blah } }") end assert_equal ["Field 'blah' doesn't exist on type 'NoFieldsCompatThing'"], res["errors"].map { |e| e["message"] } end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/addition_spec.rb
spec/graphql/schema/addition_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Addition do it "handles duplicate types with cycles" do duplicate_types_schema = Class.new(GraphQL::Schema) duplicate_types_schema.use_visibility_profile = false duplicate_types = 2.times.map { Class.new(GraphQL::Schema::Object) do graphql_name "Thing" field :thing, self end } duplicate_types_schema.orphan_types(duplicate_types) assert_equal 2, duplicate_types_schema.send(:own_types)["Thing"].size end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/printer_spec.rb
spec/graphql/schema/printer_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Printer do class PrinterTestSchema < GraphQL::Schema module Node include GraphQL::Schema::Interface field :id, ID, null: false end class HiddenDirective < GraphQL::Schema::Directive def self.visible?(ctx); false; end locations(GraphQL::Schema::Directive::ENUM_VALUE) end class Choice < GraphQL::Schema::Enum value "FOO", value: :foo value "BAR", value: :bar, directives: { HiddenDirective => {} } value "BAZ", deprecation_reason: <<-REASON Use "BAR" instead. It's the replacement for this value. REASON value "WOZ", deprecation_reason: GraphQL::Schema::Directive::DEFAULT_DEPRECATION_REASON end class Sub < GraphQL::Schema::InputObject description "Test" argument :string, String, required: false, description: "Something" argument :int, Int, required: false, description: "Something", deprecation_reason: "Do something else" end class Varied < GraphQL::Schema::InputObject argument :id, ID, required: false argument :int, Int, required: false argument :float, Float, required: false argument :bool, Boolean, required: false argument :some_enum, Choice, required: false, default_value: :foo argument :sub, [Sub, null: true], required: false end class Comment < GraphQL::Schema::Object description "A blog comment" implements Node field :id, ID, null: false end class Post < GraphQL::Schema::Object description "A blog post" field :id, ID, null: false field :title, String, null: false field :body, String, null: false field :comments, [Comment] field :comments_count, Int, null: false, deprecation_reason: "Use \"comments\".", camelize: false end class Audio < GraphQL::Schema::Object field :id, ID, null: false field :name, String, null: false field :duration, Int, null: false end class Image < GraphQL::Schema::Object field :id, ID, null: false field :name, String, null: false field :width, Int, null: false field :height, Int, null: false end class Media < GraphQL::Schema::Union description "Media objects" possible_types Image, Audio end class MediaRating < GraphQL::Schema::Enum value :AWESOME value :MEH value :BOO_HISS end class NoFields < GraphQL::Schema::Object has_no_fields(true) end class NoArguments < GraphQL::Schema::InputObject has_no_arguments(true) end class Query < GraphQL::Schema::Object description "The query root of this schema" field :post, Post do argument :id, ID, description: "Post ID" argument :varied, Varied, required: false, default_value: { id: "123", int: 234, float: 2.3, some_enum: :foo, sub: [{ string: "str" }] } argument :varied_with_nulls, Varied, required: false, default_value: { id: nil, int: nil, float: nil, some_enum: nil, sub: nil } argument :deprecated_arg, String, required: false, deprecation_reason: "Use something else" end field :no_fields_type, NoFields do argument :no_arguments_input, NoArguments end field :example_media, Media end class CreatePost < GraphQL::Schema::RelayClassicMutation description "Create a blog post" argument :title, String argument :body, String field :post, Post end class Mutation < GraphQL::Schema::Object field :create_post, mutation: CreatePost end class Subscription < GraphQL::Schema::Object field :post, Post do argument :id, ID end end query(Query) mutation(Mutation) subscription(Subscription) extra_types [MediaRating] if !use_visibility_profile? use GraphQL::Schema::Warden end end let(:schema) { PrinterTestSchema } describe ".print_introspection_schema" do it "returns the schema as a string for the introspection types" do # From https://github.com/graphql/graphql-js/blob/6a0e00fe46951767287f2cc62e1a10b167b2eaa6/src/utilities/__tests__/schemaPrinter-test.js#L599 expected = <<-GRAPHQL schema { query: Root } """ Marks an element of a GraphQL schema as no longer supported. """ directive @deprecated( """ Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted in [Markdown](https://daringfireball.net/projects/markdown/). """ reason: String = "No longer supported" ) on ARGUMENT_DEFINITION | ENUM_VALUE | FIELD_DEFINITION | INPUT_FIELD_DEFINITION """ Directs the executor to include this field or fragment only when the `if` argument is true. """ directive @include( """ Included when true. """ if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT """ Requires that exactly one field must be supplied and that field must not be `null`. """ directive @oneOf on INPUT_OBJECT """ Directs the executor to skip this field or fragment when the `if` argument is true. """ directive @skip( """ Skipped when true. """ if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT """ Exposes a URL that specifies the behavior of this scalar. """ directive @specifiedBy( """ The URL that specifies the behavior of this scalar. """ url: String! ) on SCALAR """ A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document. In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor. """ type __Directive { args(includeDeprecated: Boolean = false): [__InputValue!]! description: String isRepeatable: Boolean locations: [__DirectiveLocation!]! name: String! onField: Boolean! @deprecated(reason: "Use `locations`.") onFragment: Boolean! @deprecated(reason: "Use `locations`.") onOperation: Boolean! @deprecated(reason: "Use `locations`.") } """ A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies. """ enum __DirectiveLocation { """ Location adjacent to an argument definition. """ ARGUMENT_DEFINITION """ Location adjacent to an enum definition. """ ENUM """ Location adjacent to an enum value definition. """ ENUM_VALUE """ Location adjacent to a field. """ FIELD """ Location adjacent to a field definition. """ FIELD_DEFINITION """ Location adjacent to a fragment definition. """ FRAGMENT_DEFINITION """ Location adjacent to a fragment spread. """ FRAGMENT_SPREAD """ Location adjacent to an inline fragment. """ INLINE_FRAGMENT """ Location adjacent to an input object field definition. """ INPUT_FIELD_DEFINITION """ Location adjacent to an input object type definition. """ INPUT_OBJECT """ Location adjacent to an interface definition. """ INTERFACE """ Location adjacent to a mutation operation. """ MUTATION """ Location adjacent to an object type definition. """ OBJECT """ Location adjacent to a query operation. """ QUERY """ Location adjacent to a scalar definition. """ SCALAR """ Location adjacent to a schema definition. """ SCHEMA """ Location adjacent to a subscription operation. """ SUBSCRIPTION """ Location adjacent to a union definition. """ UNION """ Location adjacent to a variable definition. """ VARIABLE_DEFINITION } """ One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string. """ type __EnumValue { deprecationReason: String description: String isDeprecated: Boolean! name: String! } """ Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type. """ type __Field { args(includeDeprecated: Boolean = false): [__InputValue!]! deprecationReason: String description: String isDeprecated: Boolean! name: String! type: __Type! } """ Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value. """ type __InputValue { """ A GraphQL-formatted string representing the default value for this input value. """ defaultValue: String deprecationReason: String description: String isDeprecated: Boolean! name: String! type: __Type! } """ A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations. """ type __Schema { description: String """ A list of all directives supported by this server. """ directives: [__Directive!]! """ If this server supports mutation, the type that mutation operations will be rooted at. """ mutationType: __Type """ The type that query operations will be rooted at. """ queryType: __Type! """ If this server support subscription, the type that subscription operations will be rooted at. """ subscriptionType: __Type """ A list of all types supported by this server. """ types: [__Type!]! } """ The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum. Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types. """ type __Type { description: String enumValues(includeDeprecated: Boolean = false): [__EnumValue!] fields(includeDeprecated: Boolean = false): [__Field!] inputFields(includeDeprecated: Boolean = false): [__InputValue!] interfaces: [__Type!] isOneOf: Boolean! kind: __TypeKind! name: String ofType: __Type possibleTypes: [__Type!] specifiedByURL: String } """ An enum describing what kind of type a given `__Type` is. """ enum __TypeKind { """ Indicates this type is an enum. `enumValues` is a valid field. """ ENUM """ Indicates this type is an input object. `inputFields` is a valid field. """ INPUT_OBJECT """ Indicates this type is an interface. `fields` and `possibleTypes` are valid fields. """ INTERFACE """ Indicates this type is a list. `ofType` is a valid field. """ LIST """ Indicates this type is a non-null. `ofType` is a valid field. """ NON_NULL """ Indicates this type is an object. `fields` and `interfaces` are valid fields. """ OBJECT """ Indicates this type is a scalar. """ SCALAR """ Indicates this type is a union. `possibleTypes` is a valid field. """ UNION } GRAPHQL assert_equal expected.chomp, GraphQL::Schema::Printer.print_introspection_schema end end describe ".print_schema" do it "includes schema definition when query root name doesn't match convention" do custom_query = Class.new(PrinterTestSchema::Query) { graphql_name "MyQueryRoot" } custom_schema = Class.new(PrinterTestSchema) { query(custom_query) } expected = <<SCHEMA schema { query: MyQueryRoot mutation: Mutation subscription: Subscription } SCHEMA assert_match expected, GraphQL::Schema::Printer.print_schema(custom_schema) end it "includes schema definition when mutation root name doesn't match convention" do custom_mutation = Class.new(PrinterTestSchema::Mutation) { graphql_name "MyMutationRoot" } custom_schema = Class.new(PrinterTestSchema) { mutation(custom_mutation) } expected = <<SCHEMA schema { query: Query mutation: MyMutationRoot subscription: Subscription } SCHEMA assert_match expected, GraphQL::Schema::Printer.print_schema(custom_schema) end it "includes schema definition when subscription root name doesn't match convention" do custom_subscription = Class.new(PrinterTestSchema::Subscription) { graphql_name "MySubscriptionRoot" } custom_schema = Class.new(PrinterTestSchema) { subscription(custom_subscription) } expected = <<GRAPHQL schema { query: Query mutation: Mutation subscription: MySubscriptionRoot } GRAPHQL assert_match expected, GraphQL::Schema::Printer.print_schema(custom_schema) end it "returns the schema as a string for the defined types" do expected = <<GRAPHQL type Audio { duration: Int! id: ID! name: String! } enum Choice { BAR BAZ @deprecated(reason: "Use \\\"BAR\\\" instead.\\n\\nIt's the replacement for this value.\\n") FOO WOZ @deprecated } """ A blog comment """ type Comment implements Node { id: ID! } """ Autogenerated input type of CreatePost """ input CreatePostInput { body: String! """ A unique identifier for the client performing the mutation. """ clientMutationId: String title: String! } """ Autogenerated return type of CreatePost. """ type CreatePostPayload { """ A unique identifier for the client performing the mutation. """ clientMutationId: String post: Post } type Image { height: Int! id: ID! name: String! width: Int! } """ Media objects """ union Media = Audio | Image enum MediaRating { AWESOME BOO_HISS MEH } type Mutation { """ Create a blog post """ createPost( """ Parameters for CreatePost """ input: CreatePostInput! ): CreatePostPayload } input NoArguments type NoFields interface Node { id: ID! } """ A blog post """ type Post { body: String! comments: [Comment!] comments_count: Int! @deprecated(reason: "Use \\\"comments\\\".") id: ID! title: String! } """ The query root of this schema """ type Query { exampleMedia: Media noFieldsType(noArgumentsInput: NoArguments!): NoFields post( deprecatedArg: String @deprecated(reason: "Use something else") """ Post ID """ id: ID! varied: Varied = {id: "123", int: 234, float: 2.3, someEnum: FOO, sub: [{string: "str"}]} variedWithNulls: Varied = {id: null, int: null, float: null, someEnum: null, sub: null} ): Post } """ Test """ input Sub { """ Something """ int: Int @deprecated(reason: "Do something else") """ Something """ string: String } type Subscription { post(id: ID!): Post } input Varied { bool: Boolean float: Float id: ID int: Int someEnum: Choice = FOO sub: [Sub] } GRAPHQL assert_equal expected, GraphQL::Schema::Printer.print_schema(schema) end it 'prints a schema without directives' do query_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Query' field :foobar, Integer, null: false def foobar 152 end end schema = Class.new(GraphQL::Schema) do query query_type end expected = "type Query {\n foobar: Int!\n}\n" assert_equal expected, GraphQL::Schema::Printer.new(schema).print_schema end end it "applies an `only` filter" do expected = <<SCHEMA enum MediaRating { AWESOME BOO_HISS MEH } """ A blog post """ type Post { body: String! id: ID! title: String! } """ The query root of this schema """ type Query { post(deprecatedArg: String @deprecated(reason: "Use something else")): Post } SCHEMA custom_filter_schema = Class.new(schema) do use GraphQL::Schema::Warden if ADD_WARDEN def self.visible?(member, ctx) case member when Module if !member.respond_to?(:kind) super else case member.kind.name when "SCALAR" true when "OBJECT", "UNION", "INTERFACE" ctx[:names].include?(member.graphql_name) || member.introspection? else member.introspection? end end when GraphQL::Schema::Argument member.graphql_name != "id" else if member.respond_to?(:deprecation_reason) member.deprecation_reason.nil? end end end end context = { names: ["Query", "Post"] } assert_equal expected, custom_filter_schema.to_definition(context: context) end it "applies an `except` filter" do expected = <<SCHEMA type Audio { duration: Int! id: ID! name: String! } """ A blog comment """ type Comment implements Node { id: ID! } """ Autogenerated input type of CreatePost """ input CreatePostInput { body: String! """ A unique identifier for the client performing the mutation. """ clientMutationId: String title: String! } """ Autogenerated return type of CreatePost. """ type CreatePostPayload { """ A unique identifier for the client performing the mutation. """ clientMutationId: String post: Post } """ Media objects """ union Media = Audio enum MediaRating { AWESOME BOO_HISS MEH } type Mutation { """ Create a blog post """ createPost( """ Parameters for CreatePost """ input: CreatePostInput! ): CreatePostPayload } input NoArguments type NoFields interface Node { id: ID! } """ A blog post """ type Post { body: String! comments: [Comment!] id: ID! title: String! } """ The query root of this schema """ type Query { exampleMedia: Media noFieldsType(noArgumentsInput: NoArguments!): NoFields post( """ Post ID """ id: ID! ): Post } type Subscription { post(id: ID!): Post } SCHEMA custom_filter_schema = Class.new(schema) do use GraphQL::Schema::Warden if ADD_WARDEN def self.visible?(member, ctx) super && (!(ctx[:names].include?(member.graphql_name) || (member.respond_to?(:deprecation_reason) && member.deprecation_reason))) end end context = { names: ["Varied", "Image", "Sub"] } assert_equal expected, custom_filter_schema.to_definition(context: context) end describe "#print_type" do it "returns the type schema as a string" do expected = <<SCHEMA """ A blog post """ type Post { body: String! comments: [Comment!] comments_count: Int! @deprecated(reason: "Use \\\"comments\\\".") id: ID! title: String! } SCHEMA assert_equal expected.chomp, GraphQL::Schema::Printer.new(schema).print_type(schema.types['Post']) end it "can print non-object types" do expected = <<SCHEMA """ Test """ input Sub { """ Something """ int: Int @deprecated(reason: "Do something else") """ Something """ string: String } SCHEMA assert_equal expected.chomp, GraphQL::Schema::Printer.new(schema).print_type(schema.types['Sub']) end class DefaultValueTestSchema < GraphQL::Schema BackingObject = Struct.new(:value) class SomeType < GraphQL::Schema::Scalar graphql_name "SomeType" def self.coerce_input(value, ctx) BackingObject.new(value) end def self.coerce_result(obj, ctx) obj.value end end class Query < GraphQL::Schema::Object description "The query root of this schema" field :example, SomeType do argument :input, SomeType, default_value: BackingObject.new("Howdy"), required: false end def example(input:) input end end query(Query) end it "can print arguments that use non-standard Ruby objects as default values" do expected = <<SCHEMA """ The query root of this schema """ type Query { example(input: SomeType = "Howdy"): SomeType } SCHEMA assert_equal expected.chomp, GraphQL::Schema::Printer.new(DefaultValueTestSchema).print_type(DefaultValueTestSchema::Query) end end describe "#print_directive" do it "prints the deprecation reason in a single line escaped string including line breaks" do expected = <<SCHEMA.chomp enum Choice { BAR BAZ @deprecated(reason: "Use \\\"BAR\\\" instead.\\n\\nIt's the replacement for this value.\\n") FOO WOZ @deprecated } SCHEMA assert_includes GraphQL::Schema::Printer.new(schema).print_schema, expected end end it "prints schemas from class" do class TestPrintSchema < GraphQL::Schema class OddlyNamedQuery < GraphQL::Schema::Object field :int, Int, null: false end query(OddlyNamedQuery) end str = GraphQL::Schema::Printer.print_schema TestPrintSchema assert_equal "schema {\n query: OddlyNamedQuery\n}\n\ntype OddlyNamedQuery {\n int: Int!\n}\n", str end it "prints directives parsed from IDL" do input = <<-GRAPHQL directive @a(a: Letter) on ENUM_VALUE directive @b(b: BInput) on ENUM_VALUE directive @customDirective on FIELD_DEFINITION directive @directiveWithDeprecatedArg(deprecatedArg: Boolean @deprecated(reason: "Don't use me!")) on OBJECT directive @intDir(a: Int!) on INPUT_FIELD_DEFINITION directive @someDirective on OBJECT input BInput { b: Letter } input I { i1: Int @intDir(a: 1) } enum Letter { A B } type Query @someDirective { e(i: I): Thing i: Int! @customDirective } enum Thing { A @a(a: A) B @b(b: {b: B}) } GRAPHQL schema = GraphQL::Schema.from_definition(input) assert_equal input, GraphQL::Schema::Printer.print_schema(schema) end describe "when Union is used in extra_types" do it "can be included" do obj_1 = Class.new(GraphQL::Schema::Object) { graphql_name("Obj1"); field(:f1, String)} obj_2 = Class.new(GraphQL::Schema::Object) { graphql_name("Obj2"); field(:f2, obj_1) } union_type = Class.new(GraphQL::Schema::Union) do graphql_name "Union1" possible_types(obj_1, obj_2) end assert_equal "union Union1 = Obj1 | Obj2\n", Class.new(GraphQL::Schema) { extra_types(union_type) }.to_definition expected_defn = <<~GRAPHQL type Obj1 { f1: String } type Obj2 { f2: Obj1 } union Union1 = Obj1 | Obj2 GRAPHQL assert_equal expected_defn, Class.new(GraphQL::Schema) { extra_types(union_type, obj_1, obj_2) }.to_definition end end it "works with interfaces and @oneOf directive" do class SomeInputObject < GraphQL::Schema::InputObject one_of argument :a, Integer, required: false argument :b, String, required: false end module SomeInterface include GraphQL::Schema::Interface field :id, ID end class SomeObject < GraphQL::Schema::Object implements SomeInterface field :some_field, Boolean do argument :input, SomeInputObject end end class SomeQueryType < GraphQL::Schema::Object field :some_object, SomeObject, method: :some_object end class SomeSchema < GraphQL::Schema query SomeQueryType end GraphQL::Schema::Printer.new(SomeSchema).print_type(SomeObject) end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/timeout_spec.rb
spec/graphql/schema/timeout_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Timeout do module OtherTrace def execute_field(query:, **opts) query.context[:other_trace_worked] = true super end end class CustomTimeout < GraphQL::Schema::Timeout def handle_timeout(error, query) if query.context[:disable_timeout] disable_timeout(query) end super end end let(:max_seconds) { 1 } let(:timeout_class) { CustomTimeout } let(:timeout_schema) { nested_sleep_type = Class.new(GraphQL::Schema::Object) do graphql_name "NestedSleep" field :seconds, Float def seconds object end field :nested_sleep, self do argument :seconds, Float end def nested_sleep(seconds:) sleep(seconds) seconds end end query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :sleep_for, Float do argument :seconds, Float argument :disable_timeout, "Boolean", default_value: false end def sleep_for(seconds:, disable_timeout:) if disable_timeout context[:disable_timeout] = true end sleep(seconds) seconds end field :nested_sleep, nested_sleep_type do argument :seconds, Float end def nested_sleep(seconds:) sleep(seconds) seconds end end schema = Class.new(GraphQL::Schema) do query query_type trace_with OtherTrace end schema.use timeout_class, max_seconds: max_seconds schema } let(:query_context) { {} } let(:result) { timeout_schema.execute(query_string, context: query_context) } describe "timeout part-way through" do let(:query_string) {%| { a: sleepFor(seconds: 0.4) b: sleepFor(seconds: 0.4) c: sleepFor(seconds: 0.4) d: sleepFor(seconds: 0.4) e: sleepFor(seconds: 0.4) } |} it "returns a partial response and error messages" do expected_data = { "a"=>0.4, "b"=>0.4, "c"=>0.4, "d"=>nil, "e"=>nil, } expected_errors = [ { "message"=>"Timeout on Query.sleepFor", "locations"=>[{"line"=>6, "column"=>9}], "path"=>["d"] }, { "message"=>"Timeout on Query.sleepFor", "locations"=>[{"line"=>7, "column"=>9}], "path"=>["e"] }, ] assert_graphql_equal expected_data, result["data"] assert_equal expected_errors, result["errors"] assert_equal true, result.context[:other_trace_worked], "It works with other traces" end end describe "timeout in nested fields" do let(:query_string) {%| { a: nestedSleep(seconds: 0.3) { seconds b: nestedSleep(seconds: 0.3) { seconds c: nestedSleep(seconds: 0.3) { seconds d: nestedSleep(seconds: 0.4) { seconds e: nestedSleep(seconds: 0.4) { seconds } } } } } } |} it "returns a partial response and error messages" do expected_data = { "a" => { "seconds" => 0.3, "b" => { "seconds" => 0.3, "c" => { "seconds"=>0.3, "d" => { "seconds"=>nil, "e"=>nil } } } } } expected_errors = [ { "message"=>"Timeout on NestedSleep.seconds", "locations"=>[{"line"=>10, "column"=>15}], "path"=>["a", "b", "c", "d", "seconds"] }, { "message"=>"Timeout on NestedSleep.nestedSleep", "locations"=>[{"line"=>11, "column"=>15}], "path"=>["a", "b", "c", "d", "e"] }, ] assert_graphql_equal expected_data, result["data"] assert_equal expected_errors, result["errors"] end end describe "long-running fields" do let(:query_string) {%| { a: sleepFor(seconds: 0.2) b: sleepFor(seconds: 0.2) c: sleepFor(seconds: 0.8) d: sleepFor(seconds: 0.1) } |} it "doesn't terminate long-running field execution" do expected_data = { "a"=>0.2, "b"=>0.2, "c"=>0.8, "d"=>nil, } expected_errors = [ { "message"=>"Timeout on Query.sleepFor", "locations"=>[{"line"=>6, "column"=>9}], "path"=>["d"] }, ] assert_graphql_equal expected_data, result["data"] assert_equal expected_errors, result["errors"] end end describe "with a custom block" do let(:timeout_class) do Class.new(GraphQL::Schema::Timeout) do def handle_timeout(err, query) raise("Query timed out after 2s: #{err.message}") end end end let(:query_string) {%| { a: sleepFor(seconds: 0.4) b: sleepFor(seconds: 0.4) c: sleepFor(seconds: 0.4) d: sleepFor(seconds: 0.4) e: sleepFor(seconds: 0.4) } |} it "calls the block" do err = assert_raises(RuntimeError) { result } assert_equal "Query timed out after 2s: Timeout on Query.sleepFor", err.message end end describe "query-specific timeout duration" do let(:timeout_class) { Class.new(GraphQL::Schema::Timeout) do def max_seconds(query) query.context[:max_seconds] end def handle_timeout(err, query) max_s = query.context[:max_seconds] raise(GraphQL::ExecutionError, "Query timed out after #{max_s}s: #{err.message}") end end } let(:query_context) { { max_seconds: 1.9 } } let(:query_string) {%| { a: sleepFor(seconds: 0.5) b: sleepFor(seconds: 0.5) c: sleepFor(seconds: 0.5) d: sleepFor(seconds: 0.5) e: sleepFor(seconds: 0.5) } |} it "uses the configured #max_seconds(query) method" do expected_data = {"a"=>0.5, "b"=>0.5, "c"=>0.5, "d"=>0.5, "e"=>nil} assert_equal(expected_data, result["data"]) errors = result["errors"] expected_message = "Query timed out after 1.9s: Timeout on Query.sleepFor" assert_equal [expected_message], errors.map { |e| e["message"] } end describe "when max_seconds returns false" do let(:query_context) { {max_seconds: false} } it "doesn't apply any timeout" do expected_data = {"a"=>0.5, "b"=>0.5, "c"=>0.5, "d"=>0.5, "e"=>0.5} assert_equal(expected_data, result["data"]) end end end describe "disabling the timeout" do let(:query_string) {%| query GetTimeouts($disable: Boolean) { a: sleepFor(seconds: 0.4) b: sleepFor(seconds: 0.4) c: sleepFor(seconds: 0.4, disableTimeout: $disable) d: sleepFor(seconds: 0.4) e: sleepFor(seconds: 0.4) } |} it "can be disabled" do expected_data = { "a"=>0.4, "b"=>0.4, "c"=>0.4, "d"=>nil, "e"=>nil, } assert_graphql_equal expected_data, result["data"] disabled_timeout_result = timeout_schema.execute(query_string, context: query_context, variables: { disable: true }) expected_disabled_data = { "a"=>0.4, "b"=>0.4, "c"=>0.4, "d"=>0.4, "e"=>0.4, } assert_graphql_equal expected_disabled_data, disabled_timeout_result["data"] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/argument_spec.rb
spec/graphql/schema/argument_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Argument do module SchemaArgumentTest class UnauthorizedInstrumentType < Jazz::InstrumentType def self.authorized?(_object, _context) false end end class ContextInput < GraphQL::Schema::InputObject argument :context, String end class LoadUnauthorizedInstruments < GraphQL::Schema::Resolver argument :ids, [ID], as: :instruments, required: false, loads: UnauthorizedInstrumentType def load_instruments(ids) ids.map { |id| context.schema.object_from_id(id, context).call } end type Integer, null: true def resolve(instruments:) instruments.size end end class Query < GraphQL::Schema::Object field :field, String do argument :arg, String, description: "test", comment: "test comment", required: false argument :deprecated_arg, String, deprecation_reason: "don't use me!", required: false argument :arg_with_block, String, required: false do description "test" comment "test comment" end argument :required_with_default_arg, Int, default_value: 1 argument :aliased_arg, String, required: false, as: :renamed argument :prepared_arg, Int, required: false, prepare: :multiply argument :prepared_by_proc_arg, Int, required: false, prepare: ->(val, context) { context[:multiply_by] * val } argument :exploding_prepared_arg, Int, required: false, prepare: ->(val, context) do raise GraphQL::ExecutionError.new('boom!') end argument :unauthorized_prepared_arg, Int, required: false, prepare: ->(val, context) do raise GraphQL::UnauthorizedError.new('no access') end argument :keys, [String], required: false argument :instrument_id, ID, required: false, loads: Jazz::InstrumentType argument :instrument_ids, [ID], required: false, loads: Jazz::InstrumentType argument :unauthorized_instrument_id, ID, required: false, loads: UnauthorizedInstrumentType class Multiply def call(val, context) context[:multiply_by] * val end end argument :prepared_by_callable_arg, Int, required: false, prepare: Multiply.new end def field(**args) # sort the fields so that they match the output of the new interpreter sorted_keys = args.keys.sort sorted_args = {} sorted_keys.each {|k| sorted_args[k] = args[k] } sorted_args.inspect end def multiply(val) context[:multiply_by] * val end field :context_arg_test, [String], null: false do argument :input, ContextInput end def context_arg_test(input:) [input.context, input.context.class, self.context.class] end field :other_unauthorized_instruments, resolver: LoadUnauthorizedInstruments end class Schema < GraphQL::Schema query(Query) lazy_resolve(Proc, :call) def self.object_from_id(id, ctx) -> { Jazz::GloballyIdentifiableType.find(id) } end def self.resolve_type(type, obj, ctx) -> { type } # just for `loads:` end end end describe "#keys" do it "is not overwritten by the 'keys' argument" do expected_keys = ["aliasedArg", "arg", "argWithBlock", "deprecatedArg", "explodingPreparedArg", "instrumentId", "instrumentIds", "keys", "preparedArg", "preparedByCallableArg", "preparedByProcArg", "requiredWithDefaultArg", "unauthorizedInstrumentId", "unauthorizedPreparedArg"] assert_equal expected_keys, SchemaArgumentTest::Query.fields["field"].arguments.keys.sort end end describe "#path" do it "includes type, field and argument names" do assert_equal "Query.field.argWithBlock", SchemaArgumentTest::Query.fields["field"].arguments["argWithBlock"].path end end describe "#name" do it "reflects camelization" do assert_equal "argWithBlock", SchemaArgumentTest::Query.fields["field"].arguments["argWithBlock"].name end end describe "#type" do let(:argument) { SchemaArgumentTest::Query.fields["field"].arguments["arg"] } it "returns the type" do assert_equal GraphQL::Types::String, argument.type end end describe "graphql definition" do it "calls block" do assert_equal "test", SchemaArgumentTest::Query.fields["field"].arguments["argWithBlock"].description end end describe "#description" do let(:arg) { SchemaArgumentTest::Query.fields["field"].arguments["arg"] } it "sets description" do arg.description "new description" assert_equal "new description", arg.description end it "returns description" do assert_equal "test", SchemaArgumentTest::Query.fields["field"].arguments["argWithBlock"].description end it "has an assignment method" do arg.description = "another new description" assert_equal "another new description", arg.description end end describe "#comment" do let(:arg) { SchemaArgumentTest::Query.fields["field"].arguments["arg"] } it "sets comment" do arg.comment "new comment" assert_equal "new comment", arg.comment end it "returns comment" do assert_equal "test comment", SchemaArgumentTest::Query.fields["field"].arguments["argWithBlock"].comment end it "has an assignment method" do arg.comment = "another new comment" assert_equal "another new comment", arg.comment end end describe "as:" do it "uses that Symbol for Ruby kwargs" do query_str = <<-GRAPHQL { field(aliasedArg: "x") } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) # Make sure it's getting the renamed symbol: assert_equal({renamed: "x", required_with_default_arg: 1}.inspect, res["data"]["field"]) end end describe "prepare:" do it "calls the method on the field's owner" do query_str = <<-GRAPHQL { field(preparedArg: 5) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3}) # Make sure it's getting the renamed symbol: assert_equal({ prepared_arg: 15, required_with_default_arg: 1}.inspect, res["data"]["field"]) end it "calls the method on the provided Proc" do query_str = <<-GRAPHQL { field(preparedByProcArg: 5) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3}) # Make sure it's getting the renamed symbol: assert_equal({prepared_by_proc_arg: 15, required_with_default_arg: 1 }.inspect, res["data"]["field"]) end it "calls the method on the provided callable object" do query_str = <<-GRAPHQL { field(preparedByCallableArg: 5) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3}) # Make sure it's getting the renamed symbol: assert_equal({prepared_by_callable_arg: 15, required_with_default_arg: 1}.inspect, res["data"]["field"]) end it "handles exceptions raised by prepare" do query_str = <<-GRAPHQL { f1: field(arg: "echo"), f2: field(explodingPreparedArg: 5) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3}) assert_equal({ 'f1' => {arg: "echo", required_with_default_arg: 1}.inspect, 'f2' => nil }, res['data']) assert_equal(res['errors'][0]['message'], 'boom!') assert_equal(res['errors'][0]['path'], ['f2']) end it "handles unauthorized exception raised by prepare" do query_str = <<-GRAPHQL { f1: field(arg: "echo"), f2: field(unauthorizedPreparedArg: 5) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str, context: {multiply_by: 3}) assert_equal({ 'f1' => {arg: "echo", required_with_default_arg: 1}.inspect, 'f2' => nil }, res['data']) assert_nil(res['errors']) end end describe "default_value:" do it 'uses default_value: with no input' do query_str = <<-GRAPHQL { field } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) assert_equal({required_with_default_arg: 1}.inspect, res["data"]["field"]) end it 'uses provided input value' do query_str = <<-GRAPHQL { field(requiredWithDefaultArg: 2) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) assert_equal({ required_with_default_arg: 2 }.inspect, res["data"]["field"]) end it 'respects non-null type' do query_str = <<-GRAPHQL { field(requiredWithDefaultArg: null) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) assert_equal "Argument 'requiredWithDefaultArg' on Field 'field' has an invalid value (null). Expected type 'Int!'.", res['errors'][0]['message'] end end describe 'loads' do it "loads input object arguments" do query_str = <<-GRAPHQL query { field(instrumentId: "Instrument/Drum Kit") } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) assert_equal({instrument: Jazz::Models::Instrument.new("Drum Kit", "PERCUSSION"), required_with_default_arg: 1}.inspect, res["data"]["field"]) query_str2 = <<-GRAPHQL query { field(instrumentIds: ["Instrument/Organ"]) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str2) assert_equal({instruments: [Jazz::Models::Instrument.new("Organ", "KEYS")], required_with_default_arg: 1}.inspect, res["data"]["field"]) end it "returns nil when no ID is given and `required: false`" do query_str = <<-GRAPHQL mutation($ensembleId: ID) { loadAndReturnEnsemble(input: {ensembleId: $ensembleId}) { ensemble { name } } } GRAPHQL res = Jazz::Schema.execute(query_str, variables: { ensembleId: "Ensemble/Robert Glasper Experiment" }) assert_equal "ROBERT GLASPER Experiment", res["data"]["loadAndReturnEnsemble"]["ensemble"]["name"] res2 = Jazz::Schema.execute(query_str, variables: { ensembleId: nil }) assert_nil res2["data"]["loadAndReturnEnsemble"].fetch("ensemble") query_str2 = <<-GRAPHQL mutation { loadAndReturnEnsemble(input: {ensembleId: null}) { ensemble { name } } } GRAPHQL res3 = Jazz::Schema.execute(query_str2, variables: { ensembleId: nil }) assert_nil res3["data"]["loadAndReturnEnsemble"].fetch("ensemble") query_str3 = <<-GRAPHQL mutation { loadAndReturnEnsemble(input: {}) { ensemble { name } } } GRAPHQL res4 = Jazz::Schema.execute(query_str3, variables: { ensembleId: nil }) assert_nil res4["data"]["loadAndReturnEnsemble"].fetch("ensemble") query_str4 = <<-GRAPHQL query { nullableEnsemble(ensembleId: null) { name } } GRAPHQL res5 = Jazz::Schema.execute(query_str4) assert_nil res5["data"].fetch("nullableEnsemble") end it "handles unauthorized exception raised when object is resolved and returns nil" do query_str = <<-GRAPHQL query { field(unauthorizedInstrumentId: "Instrument/Drum Kit") } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) assert_nil res["errors"] assert_nil res["data"].fetch("field") end it "handles applies authorization even when a custom load method is provided" do query_str = <<-GRAPHQL query { otherUnauthorizedInstruments(ids: ["Instrument/Drum Kit"]) } GRAPHQL res = SchemaArgumentTest::Schema.execute(query_str) assert_nil res["errors"] assert_nil res["data"].fetch("otherUnauthorizedInstruments") end end describe "deprecation_reason:" do let(:arg) { SchemaArgumentTest::Query.fields["field"].arguments["arg"] } let(:required_arg) { SchemaArgumentTest::Query.fields["field"].arguments["requiredWithDefaultArg"] } it "sets deprecation reason" do arg.deprecation_reason "new deprecation reason" assert_equal "new deprecation reason", arg.deprecation_reason end it "returns the deprecation reason" do assert_equal "don't use me!", SchemaArgumentTest::Query.fields["field"].arguments["deprecatedArg"].deprecation_reason end it "has an assignment method" do arg.deprecation_reason = "another new deprecation reason" assert_equal "another new deprecation reason", arg.deprecation_reason assert_equal 1, arg.directives.size arg.deprecation_reason = "something else" assert_equal "something else", arg.deprecation_reason assert_equal 1, arg.directives.size arg.deprecation_reason = nil assert_nil arg.deprecation_reason assert_equal 0, arg.directives.size end it "disallows deprecating required arguments in the constructor" do err = assert_raises ArgumentError do Class.new(GraphQL::Schema::InputObject) do graphql_name 'MyInput' argument :foo, String, deprecation_reason: "Don't use me" end end assert_equal "Required arguments cannot be deprecated: MyInput.foo.", err.message end it "disallows deprecating required arguments in deprecation_reason=" do assert_raises ArgumentError do required_arg.deprecation_reason = "Don't use me" end end it "disallows deprecating required arguments in deprecation_reason" do assert_raises ArgumentError do required_arg.deprecation_reason("Don't use me") end end it "disallows deprecated required arguments whose type is a string" do input_obj = Class.new(GraphQL::Schema::InputObject) do graphql_name 'MyInput2' argument :foo, "String!", required: false, deprecation_reason: "Don't use me" end query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :f, String do argument :arg, input_obj, required: false end end err = assert_raises ArgumentError do Class.new(GraphQL::Schema) do query(query_type) end.to_definition end assert_equal "Required arguments cannot be deprecated: MyInput2.foo.", err.message end end describe "invalid input types" do class InvalidArgumentTypeSchema < GraphQL::Schema class InvalidArgumentType < GraphQL::Schema::Object end class InvalidArgumentObject < GraphQL::Schema::Object field :invalid, Boolean, null: false do argument :object_ref, InvalidArgumentType, required: false end end class InvalidLazyArgumentObject < GraphQL::Schema::Object field :invalid, Boolean, null: false do argument :lazy_object_ref, "InvalidArgumentTypeSchema::InvalidArgumentType", required: false end end end it "rejects them" do err = assert_raises ArgumentError do Class.new(InvalidArgumentTypeSchema) do query(InvalidArgumentTypeSchema::InvalidArgumentObject) end.to_definition end expected_message = "Invalid input type for InvalidArgumentObject.invalid.objectRef: InvalidArgument. Must be scalar, enum, or input object, not OBJECT." assert_equal expected_message, err.message err = assert_raises ArgumentError do Class.new(InvalidArgumentTypeSchema) do query(InvalidArgumentTypeSchema::InvalidLazyArgumentObject) end.to_definition end expected_message = "Invalid input type for InvalidLazyArgumentObject.invalid.lazyObjectRef: InvalidArgument. Must be scalar, enum, or input object, not OBJECT." assert_equal expected_message, err.message end end describe "validating default values" do it "raises when field argument default values are invalid" do query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :f1, Integer, null: false do argument :arg1, Integer, default_value: nil end end err = assert_raises GraphQL::Schema::Argument::InvalidDefaultValueError do Class.new(GraphQL::Schema) do query(query_type) end.to_definition end expected_message = "`Query.f1.arg1` has an invalid default value: `nil` isn't accepted by `Int!`; update the default value or the argument type." assert_equal expected_message, err.message end it "raises when input argument default values are invalid" do input_obj = Class.new(GraphQL::Schema::InputObject) do graphql_name "InputObj" argument :arg1, [String, null: false], default_value: [nil], required: false end query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :f1, Integer, null: false do argument :input, input_obj end end err = assert_raises GraphQL::Schema::Argument::InvalidDefaultValueError do Class.new(GraphQL::Schema) do query(query_type) end.to_definition end expected_message = "`InputObj.arg1` has an invalid default value: `[nil]` isn't accepted by `[String!]`; update the default value or the argument type." assert_equal expected_message, err.message end it "raises when directive argument default values are invalid" do lang = Class.new(GraphQL::Schema::Enum) do graphql_name "Language" value "EN" value "JA" end localize = Class.new(GraphQL::Schema::Directive) do graphql_name "localize" locations GraphQL::Schema::Directive::FIELD argument :lang, lang, default_value: "ZH", required: false end err = assert_raises GraphQL::Schema::Argument::InvalidDefaultValueError do Class.new(GraphQL::Schema) do directive(localize) end.to_definition end expected_message = "`@localize.lang` has an invalid default value: `\"ZH\"` isn't accepted by `Language`; update the default value or the argument type." assert_equal expected_message, err.message end it "raises when parsing a schema from a string" do schema_str = <<-GRAPHQL type Query { f1(arg1: Int! = null): Int! } GRAPHQL err = assert_raises GraphQL::Schema::Argument::InvalidDefaultValueError do GraphQL::Schema.from_definition(schema_str) end expected_message = "`Query.f1.arg1` has an invalid default value: `nil` isn't accepted by `Int!`; update the default value or the argument type." assert_equal expected_message, err.message directive_schema_str = <<-GRAPHQL enum Language { EN JA } directive @localize(lang: Language = "ZH") on FIELD type Query { f1: Int } GRAPHQL err2 = assert_raises GraphQL::Schema::Argument::InvalidDefaultValueError do GraphQL::Schema.from_definition(directive_schema_str).to_definition end expected_message = "`@localize.lang` has an invalid default value: `\"ZH\"` isn't accepted by `Language`; update the default value or the argument type." assert_equal expected_message, err2.message input_obj_schema_str = <<-GRAPHQL input InputObj { arg1: [String!] = [null] } type Query { f1(arg1: InputObj): Int } GRAPHQL err3 = assert_raises GraphQL::Schema::Argument::InvalidDefaultValueError do GraphQL::Schema.from_definition(input_obj_schema_str) end expected_message = "`InputObj.arg1` has an invalid default value: `[nil]` isn't accepted by `[String!]`; update the default value or the argument type." assert_equal expected_message, err3.message end end it "works with arguments named context" do res = SchemaArgumentTest::Schema.execute("{ contextArgTest(input: { context: \"abc\" }) }") assert_equal ["abc", "String", "GraphQL::Query::Context"], res["data"]["contextArgTest"] end describe "required: :nullable" do class RequiredNullableSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :echo, String do argument :str, String, required: :nullable end def echo(str:) str end end query(Query) end it "requires a value, even if it's null" do res = RequiredNullableSchema.execute('{ echo(str: "ok") }') assert_equal "ok", res["data"]["echo"] res = RequiredNullableSchema.execute('{ echo(str: null) }') assert_nil res["data"].fetch("echo") res = RequiredNullableSchema.execute('{ echo }') assert_equal ["echo must include the following argument: str."], res["errors"].map { |e| e["message"] } end end describe "replace_null_with_default: true" do class ReplaceNullWithDefaultSchema < GraphQL::Schema class Add < GraphQL::Schema::Resolver argument :left, Integer, required: false, default_value: 5, replace_null_with_default: true argument :right, Integer type Integer, null: false def resolve(left:, right:) right + left end end class AddInput < GraphQL::Schema::InputObject argument :left, Integer, required: false, default_value: 5, replace_null_with_default: true argument :right, Integer end class Query < GraphQL::Schema::Object field :add1, Integer do argument :left, Integer, required: false, default_value: 5, replace_null_with_default: true argument :right, Integer end def add1(left:, right:) left + right end field :add2, resolver: Add field :add3, Integer do argument :input, AddInput end def add3(input:) input[:left] + input[:right] end end query(Query) end it "works for fields, resolvers, and input objects" do res1 = ReplaceNullWithDefaultSchema.execute("{ r1: add1(left: null, right: 2) r2: add1(right: 0)}") assert_equal 7, res1["data"]["r1"] assert_equal 5, res1["data"]["r2"] res2 = ReplaceNullWithDefaultSchema.execute("{ r1: add2(left: null, right: 1) r2: add2(right: 3) }") assert_equal 6, res2["data"]["r1"] assert_equal 8, res2["data"]["r2"] res3 = ReplaceNullWithDefaultSchema.execute("{ r1: add3(input: { left: null, right: 5 }) r2: add3(input: { right: 6 }) }") assert_equal 10, res3["data"]["r1"] assert_equal 11, res3["data"]["r2"] end end it "can get default_value and prepare from method calls in the config block" do type = Class.new(GraphQL::Schema::Object) do field :f, String do argument :arg, String do default_value "blah" prepare -> { :stuff } end end end arg = type.get_field("f").get_argument("arg") assert_equal "blah", arg.default_value assert_equal :stuff, arg.prepare.call end describe "multiple argument definitions with default values" do class MultipleArgumentDefaultValuesSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN class BaseArgument < GraphQL::Schema::Argument def initialize(*args, use_if:, **kwargs, &block) @use_if = use_if super(*args, **kwargs, &block) end def visible?(ctx) ctx[:use_if] == @use_if end end class BaseField < GraphQL::Schema::Field argument_class BaseArgument end class Query < GraphQL::Schema::Object field_class BaseField field :echo, String do argument :input, String, required: false, default_value: "argument-default-1", use_if: :visible_1 argument :input, String, required: false, default_value: "argument-default-2", use_if: :visible_2 argument :input, String, required: false, default_value: nil, use_if: :visible_3 end def echo(input: "method-default") input || "dynamic-fallback" end end query(Query) end def get_echo_for(use_if) res = MultipleArgumentDefaultValuesSchema.execute("{ echo }", context: { use_if: use_if }) res["data"]["echo"] end it "uses the default value from the matching argument if there is one" do assert_equal "argument-default-1", get_echo_for(:visible_1) assert_equal "argument-default-2", get_echo_for(:visible_2) assert_equal "dynamic-fallback", get_echo_for(:visible_3) assert_equal "method-default", get_echo_for(:visible_4) # no match end end describe "multiple argument validations with rescue_from" do let(:schema) do Class.new(GraphQL::Schema) do rescue_from(StandardError) do |exception, _obj, _args, _context, _field| raise exception end query_type = Class.new(GraphQL::Schema::Object) do graphql_name 'TestQueryType' field :test, Integer, null: false do argument :a, Integer, validates: { numericality: { greater_than_or_equal_to: 1 } } argument :b, Integer, validates: { numericality: { greater_than_or_equal_to: 1 } } end def test; end end query(query_type) lazy_resolve(Proc, :call) end end it 'validates both arguments' do expected_errors = [ { "message"=>"a must be greater than or equal to 1", "locations"=>[{ "line"=>1, "column"=>3 }], "path"=>["test"] }, { "message"=>"b must be greater than or equal to 1", "locations"=>[{"line"=>1, "column"=>3}], "path"=>["test"] } ] query = "{ test(a: -4, b: -5) }" assert_equal expected_errors, schema.execute(query).to_h['errors'] end end describe "default values for non-null input object arguments when not present in variables" do class InputObjectArgumentWithDefaultValueSchema < GraphQL::Schema class Add < GraphQL::Schema::Resolver class AddInput < GraphQL::Schema::InputObject argument :a, Integer argument :b, Integer argument :c, Integer, default_value: 10 end argument :input, AddInput type(Integer, null: false) def resolve(input:) input[:a] + input[:b] + input[:c] end end class Query < GraphQL::Schema::Object field :add, resolver: Add end query(Query) end it "uses the default value" do res1 = InputObjectArgumentWithDefaultValueSchema.execute("{ add(input: { a: 1, b: 2 })}") assert_equal 13, res1["data"]["add"] res2 = InputObjectArgumentWithDefaultValueSchema.execute("query Add($input: AddInput!) { add(input: $input) }", variables: { input: { a: 1, b: 4 } }) assert_equal 15, res2["data"]["add"] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/resolver_spec.rb
spec/graphql/schema/resolver_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Resolver do module ResolverTest class SpecialError < StandardError attr_accessor :id end class LazyBlock def initialize(&block) @get_value = block end def value @get_value.call end end class BaseResolver < GraphQL::Schema::Resolver end class Resolver1 < BaseResolver argument :value, Integer, required: false type [Integer, null: true], null: false def initialize(object:, context:, field:) super if defined?(@value) raise "The instance should start fresh" end @value = [100] end def resolve(value: nil) @value << value @value end end class Resolver2 < Resolver1 argument :extra_value, Integer def resolve(extra_value:, **_rest) value = super(**_rest) value << extra_value value end end class Resolver3 < Resolver1 end class Resolver4 < BaseResolver type Integer, null: false description "Adds object.value to ast_node.name.size" extras [:ast_node] def resolve(ast_node:) object.value + ast_node.name.size end end class ResolverWithPath < BaseResolver type String, null: false extras [:path] def resolve(path:) path.inspect end end class Resolver5 < Resolver4 end class Resolver6 < Resolver1 type Integer, null: false def resolve self.class.complexity end end class Resolver7 < Resolver6 complexity 2 end class Resolver8 < Resolver7 end class GreetingExtension < GraphQL::Schema::FieldExtension def resolve(object:, arguments:, **rest) name = yield(object, arguments) "#{options[:greeting]}, #{name}!" end end class ResolverWithExtension < BaseResolver type String, null: false extension GreetingExtension, greeting: "Hi" def resolve "Robert" end end class PrepResolver1 < BaseResolver argument :int, Integer def load_int(i) i * 10 end type Integer, null: false def resolve(int:) int end private def check_for_magic_number(int) if int == 13 raise GraphQL::ExecutionError, "13 is unlucky!" elsif int > 99 raise GraphQL::UnauthorizedError, "Top secret big number: #{int}" else int end end end class PrepResolver2 < PrepResolver1 def load_int(i) LazyBlock.new { super - 35 } end end class PrepResolver3 < PrepResolver1 type Integer, null: true def load_int(i) check_for_magic_number(i) end end class PrepResolver4 < PrepResolver3 def load_int(i) LazyBlock.new { super } end end class PrepResolver5 < PrepResolver1 type Integer, null: true def ready?(int:) check_for_magic_number(int) end end class PrepResolver6 < PrepResolver5 def ready?(**args) LazyBlock.new { super } end end class PrepResolver7 < GraphQL::Schema::Mutation argument :int, Integer field :errors, [String] field :int, Integer def ready?(int:) if int == 13 return false, { errors: ["Bad number!"] } else true end end def resolve(int:) { int: int } end end class ResolverWithFalseyValueReady < BaseResolver type Boolean, null: true def ready? return false, false end def resolve true end end class ResolverWithInvalidReady < GraphQL::Schema::Mutation argument :int, Integer field :int, Integer def ready?(**args) return [1,2,3] end def resolve(int:) { int: int } end end module HasValue include GraphQL::Schema::Interface field :value, Integer, null: false def self.resolve_type(obj, ctx) LazyBlock.new { if obj.is_a?(Integer) IntegerWrapper elsif obj == :resolve_type_as_wrong_type GraphQL::Types::String else raise "Unexpected: #{obj.inspect}" end } end end class IntegerWrapper < GraphQL::Schema::Object implements HasValue field :value, Integer, null: false, method: :itself def self.authorized?(value, ctx) if ctx[:max_value] && value > ctx[:max_value] false else true end end end class PrepResolver9 < BaseResolver argument :int_id, ID, loads: HasValue # Make sure the lazy object is resolved properly: type HasValue, null: true def object_from_id(type, id, ctx) # Make sure a lazy object is handled appropriately LazyBlock.new { # Make sure that the right type ends up here id.to_i + type.graphql_name.length } end def resolve(int:) int * 3 end def unauthorized_object(err) if context[:use_replacement] context[:use_replacement] else raise GraphQL::ExecutionError, "Unauthorized #{err.type.graphql_name} loaded for #{err.context[:current_path].join(".")}" end end end class PrepResolver9Array < BaseResolver argument :int_ids, [ID], loads: HasValue, as: :ints # Make sure the lazy object is resolved properly: type [HasValue], null: false def object_from_id(type, id, ctx) # Make sure a lazy object is handled appropriately LazyBlock.new { # Make sure that the right type ends up here id.to_i + type.graphql_name.length } end def resolve(ints:) ints.map { |int| int * 3} end end class ResolverWithErrorHandler < BaseResolver argument :int, ID, loads: HasValue type HasValue, null: true def object_from_id(type, id, ctx) LazyBlock.new { if id == "failed_to_find" nil elsif id == "resolve_type_as_wrong_type" :resolve_type_as_wrong_type else id.length end } end def resolve(int:) int ? int * 4 : nil end def load_application_object_failed(err) if (next_obj = err.context[:fallback_object]) next_obj elsif err.context[:return_nil_on_load_failed] nil elsif err.context[:reraise_special_error] spec_err = SpecialError.new spec_err.id = err.id raise(spec_err) else raise(GraphQL::ExecutionError.new("ResolverWithErrorHandler failed for id: #{err.id.inspect} (#{err.object.inspect}) (#{err.class.name})")) end end end class PrepResolver10 < BaseResolver argument :int1, Integer argument :int2, Integer, as: :integer_2 type Integer, null: true def authorized?(int1:, integer_2:) if int1 + integer_2 > context[:max_int] raise GraphQL::ExecutionError, "Inputs too big" elsif context[:min_int] && (int1 + integer_2 < context[:min_int]) false else true end end def resolve(int1:, integer_2:) int1 + integer_2 end end class PrepResolver11 < PrepResolver10 def authorized?(int1:, integer_2:) LazyBlock.new { super(int1: int1 * 2, integer_2: integer_2) } end end class ResolverWithFalseyValueAuthorized < BaseResolver type Boolean, null: true def authorized? return false, false end def resolve true end end class PrepResolver12 < GraphQL::Schema::Mutation argument :int1, Integer argument :int2, Integer field :error_messages, [String] field :value, Integer def authorized?(int1:, int2:) if int1 + int2 > context[:max_int] return false, { error_messages: ["Inputs must be less than #{context[:max_int]} (but you provided #{int1 + int2})"] } else true end end def resolve(int1:, int2:) { value: int1 + int2 } end end class PrepResolver13 < PrepResolver12 def authorized?(int1:, int2:) # Increment the numbers so we can be sure they're passing through here LazyBlock.new { super(int1: int1 + 1, int2: int2 + 1) } end end class PrepResolver14 < GraphQL::Schema::RelayClassicMutation field :number, Integer, null: false def authorized? true end def resolve { number: 1 } end end class ResolverWithAuthArgs < GraphQL::Schema::RelayClassicMutation argument :number_s, String, prepare: ->(v, ctx) { v.to_i } argument :loads_id, ID, loads: IntegerWrapper field :result, Integer, null: false def authorized?(**_args) if arguments[:number_s] == 1 && arguments[:loads] == 1 true else raise GraphQL::ExecutionError, "Auth failed (#{arguments[:number_s].inspect})" end end def resolve(number_s:, loads:) { result: number_s + loads } end end class MutationWithNullableLoadsArgument < GraphQL::Schema::Mutation argument :label_id, ID, required: false, loads: HasValue argument :label_ids, [ID], required: false, loads: HasValue field :inputs, String, null: false def resolve(**inputs) { inputs: JSON.dump(inputs) } end end class MutationWithRequiredLoadsArgument < GraphQL::Schema::Mutation argument :label_id, ID, loads: HasValue field :inputs, String, null: false def resolve(**inputs) { inputs: JSON.dump(inputs) } end end class Mutation < GraphQL::Schema::Object field :mutation_with_nullable_loads_argument, mutation: MutationWithNullableLoadsArgument field :mutation_with_required_loads_argument, mutation: MutationWithRequiredLoadsArgument field :resolver_with_invalid_ready, resolver: ResolverWithInvalidReady end class Query < GraphQL::Schema::Object class CustomField < GraphQL::Schema::Field def resolve_field(*args) value = super if @name == "resolver3" value << -1 end value end def resolve(*) value = super if @name == "resolver3" value << -1 end value end end field_class(CustomField) field :resolver_1, resolver: Resolver1 field :resolver_2, resolver: Resolver2 field :resolver_3, resolver: Resolver3 field :resolver_3_again, resolver: Resolver3, description: "field desc" field :resolver_4, "Positional description", resolver: Resolver4 field :resolver_5, resolver: Resolver5 field :resolver_6, resolver: Resolver6 field :resolver_7, resolver: Resolver7 field :resolver_8, resolver: Resolver8 field :resolver_with_extension, resolver: ResolverWithExtension field :resolver_with_path, resolver: ResolverWithPath field :prep_resolver_1, resolver: PrepResolver1 field :prep_resolver_2, resolver: PrepResolver2 field :prep_resolver_3, resolver: PrepResolver3 field :prep_resolver_4, resolver: PrepResolver4 field :prep_resolver_5, resolver: PrepResolver5 field :prep_resolver_6, resolver: PrepResolver6 field :prep_resolver_7, resolver: PrepResolver7 field :prep_resolver_9, resolver: PrepResolver9 field :prep_resolver_9_array, resolver: PrepResolver9Array field :prep_resolver_10, resolver: PrepResolver10 field :prep_resolver_11, resolver: PrepResolver11 field :prep_resolver_12, resolver: PrepResolver12 field :prep_resolver_13, resolver: PrepResolver13 field :prep_resolver_14, resolver: PrepResolver14 field :resolver_with_falsey_value_ready, resolver: ResolverWithFalseyValueReady field :resolver_with_falsey_value_authorized, resolver: ResolverWithFalseyValueAuthorized field :resolver_with_auth_args, resolver: ResolverWithAuthArgs field :resolver_with_error_handler, resolver: ResolverWithErrorHandler end class Schema < GraphQL::Schema query(Query) mutation(Mutation) lazy_resolve LazyBlock, :value orphan_types IntegerWrapper def self.object_from_id(id, ctx) if id == "invalid" nil else 1 end end def self.resolve_type(type, obj, ctx) type # This will work for loaded objects well enough end rescue_from SpecialError do |err| raise GraphQL::ExecutionError, "A special error was raised from #{err.id.inspect}" end end end def exec_query(*args, **kwargs) ResolverTest::Schema.execute(*args, **kwargs) end it "can access self.arguments inside authorized?" do res = exec_query("{ resolverWithAuthArgs(input: { numberS: \"1\", loadsId: 1 }) { result } }") assert_equal 2, res["data"]["resolverWithAuthArgs"]["result"] # Test auth failure: res = exec_query("{ resolverWithAuthArgs(input: { numberS: \"2\", loadsId: 1 }) { result } }") assert_equal ["Auth failed (2)"], res["errors"].map { |e| e["message"] } end describe ".path" do it "is the name" do assert_equal "Resolver1", ResolverTest::Resolver1.path end it "is used for arguments and fields" do assert_equal "Resolver1.value", ResolverTest::Resolver1.arguments["value"].path assert_equal "PrepResolver7.int", ResolverTest::PrepResolver7.fields["int"].path end it "works on instances" do r = ResolverTest::Resolver1.new(object: nil, context: GraphQL::Query::NullContext.instance, field: nil) assert_equal "Resolver1", r.path end end it "gets initialized for each resolution" do # State isn't shared between calls: res = exec_query " { r1: resolver1(value: 1) r2: resolver1 }" assert_equal [100, 1], res["data"]["r1"] assert_equal [100, nil], res["data"]["r2"] end it "inherits type and arguments" do res = exec_query " { r1: resolver2(value: 1, extraValue: 2) r2: resolver2(extraValue: 3) }" assert_equal [100, 1, 2], res["data"]["r1"] assert_equal [100, nil, 3], res["data"]["r2"] end it "uses the object's field_class" do res = exec_query " { r1: resolver3(value: 1) r2: resolver3 }" assert_equal [100, 1, -1], res["data"]["r1"] assert_equal [100, nil, -1], res["data"]["r2"] end describe "resolve method" do it "has access to the application object" do res = exec_query " { resolver4 } ", root_value: OpenStruct.new(value: 4) assert_equal 13, res["data"]["resolver4"] end it "gets extras" do res = exec_query " { resolver4 } ", root_value: OpenStruct.new(value: 0) assert_equal 9, res["data"]["resolver4"] end it "gets path from extras" do res = exec_query " { resolverWithPath } ", root_value: OpenStruct.new(value: 0) assert_equal '["resolverWithPath"]', res["data"]["resolverWithPath"] end end describe "load_application_object_failed hook" do it "isn't called for successful queries" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "abcd") { value } } GRAPHQL res = exec_query(query_str) assert_equal 16, res["data"]["resolverWithErrorHandler"]["value"] refute res.key?("errors") end describe "when the id doesn't find anything" do it "passes an error to the handler" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "failed_to_find") { value } } GRAPHQL res = exec_query(query_str) assert_nil res["data"].fetch("resolverWithErrorHandler") expected_err = "ResolverWithErrorHandler failed for id: \"failed_to_find\" (nil) (GraphQL::LoadApplicationObjectFailedError)" assert_equal [expected_err], res["errors"].map { |e| e["message"] } end it "uses rescue_from handlers" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "failed_to_find") { value } } GRAPHQL res = exec_query(query_str, context: { reraise_special_error: true }) assert_nil res["data"].fetch("resolverWithErrorHandler") expected_err = "A special error was raised from \"failed_to_find\"" assert_equal [expected_err], res["errors"].map { |e| e["message"] } end it "uses the new value from lookup" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "failed_to_find") { value } } GRAPHQL res = exec_query(query_str, context: { fallback_object: 212 }) assert_equal 848, res["data"]["resolverWithErrorHandler"]["value"] refute res.key?("errors") end it "halts silently when it returns nil" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "failed_to_find") { value } } GRAPHQL res = exec_query(query_str, context: { return_nil_on_load_failed: true }) assert_nil res["data"].fetch("resolverWithErrorHandler") refute res.key?("errors") end end describe "when resolve_type returns a no-good type" do it "calls the handler" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "resolve_type_as_wrong_type") { value } } GRAPHQL res = exec_query(query_str) assert_nil res["data"].fetch("resolverWithErrorHandler") expected_err = "ResolverWithErrorHandler failed for id: \"resolve_type_as_wrong_type\" (:resolve_type_as_wrong_type) (GraphQL::LoadApplicationObjectFailedError)" assert_equal [expected_err], res["errors"].map { |e| e["message"] } end it "uses rescue_from handlers" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "resolve_type_as_wrong_type") { value } } GRAPHQL res = exec_query(query_str, context: { reraise_special_error: true }) assert_nil res["data"].fetch("resolverWithErrorHandler") expected_err = "A special error was raised from \"resolve_type_as_wrong_type\"" assert_equal [expected_err], res["errors"].map { |e| e["message"] } end it "uses a new value from resolve_type" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "resolve_type_as_wrong_type") { value } } GRAPHQL res = exec_query(query_str, context: { fallback_object: 4 }) assert_equal 16, res["data"]["resolverWithErrorHandler"]["value"] refute res.key?("errors") end it "halts silently when it returns nil" do query_str = <<-GRAPHQL { resolverWithErrorHandler(int: "resolve_type_as_wrong_type") { value } } GRAPHQL res = exec_query(query_str, context: { return_nil_on_load_failed: true }) assert_nil res["data"].fetch("resolverWithErrorHandler") refute res.key?("errors") end end end describe "extras" do it "is inherited" do res = exec_query " { resolver4 resolver5 } ", root_value: OpenStruct.new(value: 0) assert_equal 9, res["data"]["resolver4"] assert_equal 9, res["data"]["resolver5"] end end describe "complexity" do it "has default values" do res = exec_query " { resolver6 } ", root_value: OpenStruct.new(value: 0) assert_equal 1, res["data"]["resolver6"] end it "is inherited" do res = exec_query " { resolver7 resolver8 } ", root_value: OpenStruct.new(value: 0) assert_equal 2, res["data"]["resolver7"] assert_equal 2, res["data"]["resolver8"] end end describe "graphql_name" do class NameParentResolver < GraphQL::Schema::Resolver graphql_name "NameOverride" end class NameChildResolver < NameParentResolver end it "isn't inherited" do assert_equal "NameOverride", NameParentResolver.graphql_name assert_equal "NameChildResolver", NameChildResolver.graphql_name end end describe "description" do it "is inherited" do expected_desc = "Adds object.value to ast_node.name.size" assert_equal expected_desc, ResolverTest::Resolver4.description assert_equal expected_desc, ResolverTest::Resolver5.description end end describe "when applied to a field" do it "gets the field's description" do assert_nil ResolverTest::Schema.find("Query.resolver3").description assert_equal "field desc", ResolverTest::Schema.find("Query.resolver3Again").description assert_equal "Positional description", ResolverTest::Schema.find("Query.resolver4").description end it "gets the field's name" do # Matching name: assert ResolverTest::Schema.find("Query.resolver3") # Mismatched name: assert ResolverTest::Schema.find("Query.resolver3Again") end end describe "preparing inputs" do # Add assertions for a given field, assuming the behavior of `check_for_magic_number` def add_error_assertions(field_name, description) res = exec_query("{ int: #{field_name}(int: 13) }") assert_nil res["data"].fetch("int"), "#{description}: no result for execution error" assert_equal ["13 is unlucky!"], res["errors"].map { |e| e["message"] }, "#{description}: top-level error is added" res = exec_query("{ int: #{field_name}(int: 200) }") assert_nil res["data"].fetch("int"), "#{description}: No result for authorization error" refute res.key?("errors"), "#{description}: silent auth failure (no top-level error)" end it "keeps track of the `loads:` option" do arg = ResolverTest::MutationWithNullableLoadsArgument.arguments["labelId"] assert_equal ResolverTest::HasValue, arg.loads end describe "ready?" do it "can raise errors" do res = exec_query("{ int: prepResolver5(int: 5) }") assert_equal 50, res["data"]["int"] add_error_assertions("prepResolver5", "ready?") end it "can raise errors in lazy sync" do res = exec_query("{ int: prepResolver6(int: 5) }") assert_equal 50, res["data"]["int"] add_error_assertions("prepResolver6", "lazy ready?") end it "can return false and data" do res = exec_query("{ int: prepResolver7(int: 13) { errors int } }") assert_equal ["Bad number!"], res["data"]["int"]["errors"] res = exec_query("{ int: prepResolver7(int: 213) { errors int } }") assert_equal 213, res["data"]["int"]["int"] end it "can return false and falsey data" do res = exec_query("{ result: resolverWithFalseyValueReady }") assert_equal false, res["data"]["result"] # must be `false`, not just falsey assert_nil res["errors"] end it 'raises the correct error on invalid return type' do err = assert_raises(RuntimeError) do exec_query("mutation { resolverWithInvalidReady(int: 2) { int } }") end assert_match("Unexpected result from #ready?", err.message) end end describe "loading arguments" do it "calls load methods and injects the return value" do res = exec_query("{ prepResolver1(int: 5) }") assert_equal 50, res["data"]["prepResolver1"], "The load multiplier was called" end it "supports lazy values" do res = exec_query("{ prepResolver2(int: 5) }") assert_equal 15, res["data"]["prepResolver2"], "The load multiplier was called" end it "supports raising GraphQL::UnauthorizedError and GraphQL::ExecutionError" do res = exec_query("{ prepResolver3(int: 5) }") assert_equal 5, res["data"]["prepResolver3"] add_error_assertions("prepResolver3", "load_ hook") end it "supports raising errors from promises" do res = exec_query("{ prepResolver4(int: 5) }") assert_equal 5, res["data"]["prepResolver4"] add_error_assertions("prepResolver4", "lazy load_ hook") end end describe "validating arguments" do describe ".authorized?" do it "can raise an error to halt" do res = exec_query("{ prepResolver10(int1: 5, int2: 6) }", context: { max_int: 9 }) assert_equal ["Inputs too big"], res["errors"].map { |e| e["message"] } res = exec_query("{ prepResolver10(int1: 5, int2: 6) }", context: { max_int: 90 }) assert_equal 11, res["data"]["prepResolver10"] end it "uses the argument name provided in `as:`" do res = exec_query("{ prepResolver10(int1: 5, int2: 6) }", context: { max_int: 90 }) assert_equal 11, res["data"]["prepResolver10"] end it "can return a lazy object" do # This is too big because it's modified in the overridden authorized? hook: res = exec_query("{ prepResolver11(int1: 3, int2: 5) }", context: { max_int: 9 }) assert_equal ["Inputs too big"], res["errors"].map { |e| e["message"] } res = exec_query("{ prepResolver11(int1: 3, int2: 5) }", context: { max_int: 90 }) assert_equal 8, res["data"]["prepResolver11"] end it "can return data early" do res = exec_query("{ prepResolver12(int1: 9, int2: 5) { errorMessages } }", context: { max_int: 9 }) assert_equal ["Inputs must be less than 9 (but you provided 14)"], res["data"]["prepResolver12"]["errorMessages"] # This works res = exec_query("{ prepResolver12(int1: 2, int2: 5) { value } }", context: { max_int: 9 }) assert_equal 7, res["data"]["prepResolver12"]["value"] end it "can return falsey data early" do res = exec_query("{ result: resolverWithFalseyValueAuthorized }") assert_equal false, res["data"]["result"] # must be actual `false`, not just a falsey `nil` assert_nil res["errors"] end it "can return data early in a promise" do # This is too big because it's modified in the overridden authorized? hook: res = exec_query("{ prepResolver13(int1: 4, int2: 4) { errorMessages } }", context: { max_int: 9 }) assert_equal ["Inputs must be less than 9 (but you provided 10)"], res["data"]["prepResolver13"]["errorMessages"] # This works res = exec_query("{ prepResolver13(int1: 2, int2: 5) { value } }", context: { max_int: 9 }) assert_equal 7, res["data"]["prepResolver13"]["value"] end it "can return false to halt" do str = <<-GRAPHQL { prepResolver10(int1: 5, int2: 10) prepResolver11(int1: 3, int2: 5) } GRAPHQL res = exec_query(str, context: { max_int: 100, min_int: 20 }) assert_equal({ "prepResolver10" => nil, "prepResolver11" => nil }, res["data"]) end it "works with no arguments for RelayClassicMutation" do res = exec_query("{ prepResolver14(input: {}) { number } }") assert_equal 1, res["data"]["prepResolver14"]["number"] end it "uses loaded objects" do query_str = "{ prepResolver9(intId: 9) { value } }" # This will cause an unauthorized response # by `HasValue.authorized?` context = { max_value: 8 } res = exec_query(query_str, context: context) assert_nil res["data"]["prepResolver9"] assert_equal ["Unauthorized IntegerWrapper loaded for prepResolver9"], res["errors"].map { |e| e["message"] } # This is OK context = { max_value: 900 } res = exec_query(query_str, context: context) assert_equal 51, res["data"]["prepResolver9"]["value"] # This is the transformation applied by the resolver, # just make sure it matches the response assert_equal 51, (9 + "HasValue".size) * 3 # It uses the returned value from unauthorized object context = { max_value: 8, use_replacement: 2 } res = exec_query(query_str, context: context) assert_equal 6, res["data"]["prepResolver9"]["value"] refute res.key?("errors") end end end describe "load_* argument methods" do it "doesn't override inherited methods" do r1 = Class.new(GraphQL::Schema::Resolver) do def load_input(input); end end r2 = Class.new(r1) do argument :input, Integer, required: false end assert_equal r1.instance_method(:load_input).source_location, r2.instance_method(:load_input).source_location end end describe "Loading inputs" do it "calls object_from_id" do res = exec_query('{ prepResolver9(intId: "5") { value } }') # (5 + 8) * 3 assert_equal 39, res["data"]["prepResolver9"]["value"] end it "supports loading array of ids" do res = exec_query('{ prepResolver9Array(intIds: ["1", "10", "100"]) { value } }') # (1 + 8) * 3 # (10 + 8) * 3 # (100 + 8) * 3 assert_equal [27, 54, 324], res["data"]["prepResolver9Array"].map { |v| v["value"] } end it "preserves `nil` when nullable argument is provided `null`" do res = exec_query("mutation { mutationWithNullableLoadsArgument(labelId: null) { inputs } }") assert_nil res["errors"] assert_equal '{"label":null}', res["data"]["mutationWithNullableLoadsArgument"]["inputs"] end it "preserves `nil` when nullable list argument is provided `null`" do res = exec_query("mutation { mutationWithNullableLoadsArgument(labelIds: null) { inputs } }") assert_nil res["errors"] assert_equal '{"labels":null}', res["data"]["mutationWithNullableLoadsArgument"]["inputs"] end it "omits omitted nullable argument" do res = exec_query("mutation { mutationWithNullableLoadsArgument { inputs } }") assert_nil res["errors"] assert_equal "{}", res["data"]["mutationWithNullableLoadsArgument"]["inputs"] end it "returns an error when nullable argument is provided an invalid value" do res = exec_query('mutation { mutationWithNullableLoadsArgument(labelId: "invalid") { inputs } }') assert res["errors"] assert_equal 'No object found for `labelId: "invalid"`', res["errors"][0]["message"] end it "returns an error when a non-nullable argument is provided an invalid value" do res = exec_query('mutation { mutationWithRequiredLoadsArgument(labelId: "invalid") { inputs } }') assert res["errors"] assert_equal 'No object found for `labelId: "invalid"`', res["errors"][0]["message"] end end describe "extensions" do it "returns extension when no arguments passed" do assert 1, ResolverTest::ResolverWithExtension.extensions.count end it "configures extensions for field" do assert_kind_of ResolverTest::GreetingExtension, ResolverTest::Query.fields["resolverWithExtension"].extensions.first end it "uses extension to build response" do res = exec_query " { resolverWithExtension } " assert_equal "Hi, Robert!", res["data"]["resolverWithExtension"] end it "inherits extensions" do r1 = Class.new(GraphQL::Schema::Resolver) do extension(ResolverTest::GreetingExtension) end e2 = Class.new(GraphQL::Schema::FieldExtension) r2 = Class.new(r1) do extension(e2) end assert_equal 1, r1.extensions.size assert_equal 2, r2.extensions.size end end describe "max_page_size" do class NoMaxPageSizeResolver < GraphQL::Schema::Resolver end class MaxPageSizeBaseResolver < GraphQL::Schema::Resolver max_page_size 10 end class MaxPageSizeSubclass < MaxPageSizeBaseResolver end class MaxPageSizeOverrideSubclass < MaxPageSizeBaseResolver max_page_size nil end class ObjectWithMaxPageSizeResolver < GraphQL::Schema::Object field :items, [String], null: false, resolver: MaxPageSizeBaseResolver end it "defaults to absent" do assert_nil NoMaxPageSizeResolver.max_page_size
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
true
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/list_spec.rb
spec/graphql/schema/list_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::List do let(:of_type) { Jazz::Musician } let(:list_type) { GraphQL::Schema::List.new(of_type) } it "returns list? to be true" do assert list_type.list? end it "returns non_null? to be false" do refute list_type.non_null? end it "returns kind to be GraphQL::TypeKinds::LIST" do assert_equal GraphQL::TypeKinds::LIST, list_type.kind end it "returns correct type signature" do assert_equal "[Musician]", list_type.to_type_signature end describe "comparison operator" do it "will return false if list types 'of_type' are different" do new_of_type = Jazz::InspectableKey new_list_type = GraphQL::Schema::List.new(new_of_type) refute_equal list_type, new_list_type end it "will return true if list types 'of_type' are the same" do new_of_type = Jazz::Musician new_list_type = GraphQL::Schema::List.new(new_of_type) assert_equal list_type, new_list_type end end describe "handling null" do class ListNullHandlingSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :strings, [String, null: true] do argument :strings, [String, null: true], required: false end def strings(strings:) strings end end query(Query) end it "passes `nil` as `nil`" do str = "query($strings: [String]){ strings(strings: $strings) }" res = ListNullHandlingSchema.execute(str, variables: { strings: nil }) assert_nil res["data"]["strings"] end end it "Accepts \"\" as a default value from introspection" do schema = GraphQL::Schema.from_definition <<-GRAPHQL type Query { f(arg: [String] = ""): String } GRAPHQL assert_equal "", schema.query.fields["f"].arguments["arg"].default_value introspection_json = schema.as_json assert_equal '[""]', introspection_json["data"]["__schema"]["types"].find { |t| t["name"] == "Query" }["fields"].first["args"].first["defaultValue"] schema_2 = GraphQL::Schema.from_introspection(introspection_json) # since this one is from introspection, it gets a wrapped list as default value: assert_equal [""], schema_2.query.fields["f"].arguments["arg"].default_value assert_equal '[""]', schema_2.as_json["data"]["__schema"]["types"].find { |t| t["name"] == "Query" }["fields"].first["args"].first["defaultValue"] end describe "validation" do class ListValidationSchema < GraphQL::Schema class Item < GraphQL::Schema::Enum value "A" value "B" end class ItemInput < GraphQL::Schema::InputObject argument :item, Item end class NilItemsInput < GraphQL::Schema::InputObject argument :items, [Item], required: false end class Query < GraphQL::Schema::Object field :echo, [Item], null: false do argument :items, [Item] end def echo(items:) items end field :echoes, [Item], null: false do argument :items, [ItemInput] end def echoes(items:) items.map { |i| i[:item] } end field :nil_echoes, [Item, null: true] do argument :items, [NilItemsInput], required: false end def nil_echoes(items:) items.first[:items] end field :invalid_result, [String], null: false def invalid_result ["A", "B", nil] end end query(Query) end it "checks non-null lists of enums" do res = ListValidationSchema.execute "{ echo(items: [A, B, \"C\"]) }" expected_error = "Argument 'items' on Field 'echo' has an invalid value ([A, B, \"C\"]). Expected type '[Item!]!'." assert_equal [expected_error], res["errors"].map { |e| e["message"] } end it "reports when an element must be non-nil" do res = ListValidationSchema.execute "{ invalidResult }" expected_error = "Cannot return null for non-nullable element of type 'String!' for Query.invalidResult" assert_equal [expected_error], res["errors"].map { |e| e["message"] } end it "works with #valid_input?" do assert ListValidationSchema::Item.to_list_type.valid_isolated_input?(["A", "B"]) refute ListValidationSchema::Item.to_list_type.valid_isolated_input?(["A", "B", "C"]) end it "coerces single-item lists of input objects" do results = { "default value" => ListValidationSchema.execute("query($items: [ItemInput!] = {item: A}) { echoes(items: $items) }"), "literal value" => ListValidationSchema.execute("{ echoes(items: { item: A }) }"), "variable value" => ListValidationSchema.execute("query($items: [ItemInput!]!) { echoes(items: $items) }", variables: { items: { item: "A" } }), } results.each do |r_desc, r| assert_equal({"data" => { "echoes" => ["A"]}}, r, "It works for #{r_desc}") end end it "doesn't coerce nil into a list" do nil_result = ListValidationSchema.execute("query($items: [NilItemsInput!]) { nilEchoes(items: $items) }", variables: { items: { items: nil } }) assert_equal({"data" => { "nilEchoes" => nil}}, nil_result, "It works for nil")\ end end describe "when max validation errors exists" do class MaxValidationSchema < GraphQL::Schema class Item < GraphQL::Schema::Enum value "A" value "B" end class Query < GraphQL::Schema::Object field :items, [Item], null: false do argument :ids, [Int] end def items(ids:) items end end query(Query) validate_max_errors(2) end it "checks only for 2 errors and appends too many errors in the message" do res = MaxValidationSchema.execute("query($ids: [Int!]!) { items(ids: $ids) }", variables: { ids: ["1", "2", "3", "4"] }) expected_error = "Variable $ids of type [Int!]! was provided invalid value for 0 "\ "(Could not coerce value \"1\" to Int), 1 (Could not coerce value \"2\" to Int), "\ "(Too many errors processing list variable, max validation error limit reached. Execution aborted)" assert_equal [expected_error], res["errors"].map { |e| e["message"] } end it "raises only 1 error with max_validation + 1 problems" do res = MaxValidationSchema.execute("query($ids: [Int!]!) { items(ids: $ids) }", variables: { ids: ["1", "2", "3", "4"] }) assert_equal 1, res["errors"].count assert_equal 3, res["errors"][0]["extensions"]["problems"].count end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/enum_value_spec.rb
spec/graphql/schema/enum_value_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::EnumValue do describe "#path" do it "Has the owner name too" do enum = Class.new(GraphQL::Schema::Enum) do graphql_name "Abc" value(:XYZ) end assert_equal "Abc.XYZ", enum.values["XYZ"].path end end it "can accept a proc as a value" do enum = Class.new(GraphQL::Schema::Enum) do graphql_name "SortBy" value 'BY_NAME', value: ->(scope, direction: :asc) { scope.order(name: direction) } value 'BY_EMAIL', value: ->(scope, direction: :asc) { scope.order(email: direction) } end assert_instance_of Proc, enum.values["BY_NAME"].value end describe "#deprecation_reason" do it "can be written and read" do enum_value = GraphQL::Schema::EnumValue.new(:x, owner: nil) assert_nil enum_value.deprecation_reason enum_value.deprecation_reason = "No good!" assert_equal "No good!", enum_value.deprecation_reason end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/has_single_input_argument_spec.rb
spec/graphql/schema/has_single_input_argument_spec.rb
# frozen_string_literal: true require 'spec_helper' describe GraphQL::Schema::HasSingleInputArgument do describe ".input_object_class" do it "is inherited, with a default" do custom_input = Class.new(GraphQL::Schema::InputObject) mutation_base_class = Class.new(GraphQL::Schema::Mutation) do include GraphQL::Schema::HasSingleInputArgument graphql_name "Test" input_object_class(custom_input) end mutation_subclass = Class.new(mutation_base_class) assert_equal custom_input, mutation_base_class.input_object_class assert_equal custom_input, mutation_subclass.input_object_class end end describe ".input_type" do it "has a reference to the mutation" do mutation = Class.new(GraphQL::Schema::Mutation) do include GraphQL::Schema::HasSingleInputArgument graphql_name "Test" end assert_equal mutation, mutation.input_type.mutation end end describe "input argument" do it "sets a description for the input argument" do mutation = Class.new(GraphQL::Schema::Mutation) do include GraphQL::Schema::HasSingleInputArgument graphql_name "SomeMutation" end field = GraphQL::Schema::Field.new(name: "blah", resolver_class: mutation) assert_equal "Parameters for SomeMutation", field.get_argument("input").description end end describe "execution" do module HasSingleArgument class TestInput < GraphQL::Schema::InputObject argument :name, String end class NoArgumentMutation < GraphQL::Schema::Mutation include GraphQL::Schema::HasSingleInputArgument null true field :name, String, null: false def resolve { name: "name" } end end class InputObjectMutation < GraphQL::Schema::Mutation include GraphQL::Schema::HasSingleInputArgument argument :test, TestInput field :name, String def resolve(test:) { name: test[:name] } end end class SupportExtrasMutation < GraphQL::Schema::Mutation include GraphQL::Schema::HasSingleInputArgument argument :name, String extras [:ast_node] field :node_class, String field :name, String def resolve(name:, ast_node:) { name: name, node_class: ast_node.class.name } end end class SupportFieldExtrasMutation < GraphQL::Schema::Mutation include GraphQL::Schema::HasSingleInputArgument null true argument :name, String, required: false field :lookahead_class, String, null: false field :name, String def resolve(name: nil, lookahead:) { name: name, lookahead_class: lookahead.class.name } end end class CanStripOutExtrasMutation < GraphQL::Schema::Mutation include GraphQL::Schema::HasSingleInputArgument extras [:lookahead] field :name, String, null: false def resolve_with_support(lookahead: , **rest) context[:has_lookahead] = !!lookahead super(**rest) end def authorized? true end def resolve { name: 'name', } end end class Mutation < GraphQL::Schema::Object field_class GraphQL::Schema::Field field :no_argument, mutation: NoArgumentMutation field :input_object, mutation: InputObjectMutation field :support_extras, mutation: SupportExtrasMutation field :support_field_extras, mutation: SupportFieldExtrasMutation, extras: [:lookahead] field :can_strip_out_extras, mutation: CanStripOutExtrasMutation end class Schema < GraphQL::Schema mutation(Mutation) end end it "works with no arguments" do res = HasSingleArgument::Schema.execute <<-GRAPHQL mutation { noArgument(input: {}) { name } } GRAPHQL assert_equal "name", res["data"]["noArgument"]["name"] end it "works with InputObject arguments" do res = HasSingleArgument::Schema.execute <<-GRAPHQL mutation { inputObject(input: { test: { name: "test name" } }) { name } } GRAPHQL assert_equal "test name", res["data"]["inputObject"]["name"] end it "supports extras" do res = HasSingleArgument::Schema.execute <<-GRAPHQL mutation { supportExtras(input: {name: "name"}) { nodeClass name } } GRAPHQL assert_equal "GraphQL::Language::Nodes::Field", res["data"]["supportExtras"]["nodeClass"] assert_equal "name", res["data"]["supportExtras"]["name"] # Also test with given args res = Jazz::Schema.execute <<-GRAPHQL mutation { hasExtras(input: {int: 5}) { nodeClass int } } GRAPHQL assert_equal "GraphQL::Language::Nodes::Field", res["data"]["hasExtras"]["nodeClass"] assert_equal 5, res["data"]["hasExtras"]["int"] end it "supports field extras" do res = HasSingleArgument::Schema.execute <<-GRAPHQL mutation { supportFieldExtras(input: {}) { lookaheadClass name } } GRAPHQL assert_equal "GraphQL::Execution::Lookahead", res["data"]["supportFieldExtras"]["lookaheadClass"] assert_nil res["data"]["supportFieldExtras"]["name"] # Also test with given args res = HasSingleArgument::Schema.execute <<-GRAPHQL mutation { supportFieldExtras(input: {name: "name"}) { lookaheadClass name } } GRAPHQL assert_equal "GraphQL::Execution::Lookahead", res["data"]["supportFieldExtras"]["lookaheadClass"] assert_equal "name", res["data"]["supportFieldExtras"]["name"] end it "can strip out extras" do ctx = {} res = HasSingleArgument::Schema.execute <<-GRAPHQL, context: ctx mutation { canStripOutExtras(input: {}) { name } } GRAPHQL assert_equal true, ctx[:has_lookahead] assert_equal "name", res["data"]["canStripOutExtras"]["name"] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/dynamic_members_spec.rb
spec/graphql/schema/dynamic_members_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Dynamic types, fields, arguments, and enum values" do class MultifieldSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN module AppliesToFutureSchema def initialize(*args, future_schema: nil, **kwargs, &block) @future_schema = future_schema super(*args, **kwargs, &block) end def visible?(context) if context[:visible_calls] && !context[:visibility_migration_warden_running] context[:visible_calls][self] << caller end super && (@future_schema.nil? || (@future_schema == !!context[:future_schema])) end attr_accessor :future_schema class MethodInspection def initialize(method) @method = method end def path "#{@method.owner}#{@method.receiver.is_a?(Class) ? "." : "#"}#{@method.name} @ #{@method.source_location.inspect}" end end # Make sure these methods are only called once at runtime: [:fields, :get_field, :arguments, :get_argument, :enum_values, :interfaces, :possible_types].each do |dynamic_members_method_name| if RUBY_VERSION > "3" define_method(dynamic_members_method_name) do |*args, **kwargs, &block| context = args.last if context && (context.is_a?(Hash) || context.is_a?(GraphQL::Query::Context)) && context[:visible_calls] && !context[:visibility_migration_warden_running] method_obj = self.method(dynamic_members_method_name) context[:visible_calls][MethodInspection.new(method_obj)] << caller end super(*args, **kwargs, &block) end else define_method(dynamic_members_method_name) do |*args, &block| context = args.last if context && (context.is_a?(Hash) || context.is_a?(GraphQL::Query::Context)) && context[:visible_calls] && !context[:visibility_migration_warden_running] method_obj = self.method(dynamic_members_method_name) context[:visible_calls][MethodInspection.new(method_obj)] << caller end super(*args, &block) end end end end class BaseArgument < GraphQL::Schema::Argument include AppliesToFutureSchema end class BaseField < GraphQL::Schema::Field include AppliesToFutureSchema argument_class BaseArgument end class BaseObject < GraphQL::Schema::Object field_class BaseField extend AppliesToFutureSchema end module BaseInterface include GraphQL::Schema::Interface class TypeMembership < GraphQL::Schema::TypeMembership include AppliesToFutureSchema end field_class BaseField type_membership_class TypeMembership definition_methods do include AppliesToFutureSchema end end class BaseUnion < GraphQL::Schema::Union extend AppliesToFutureSchema type_membership_class BaseInterface::TypeMembership end class BaseScalar < GraphQL::Schema::Scalar extend AppliesToFutureSchema end class BaseInputObject < GraphQL::Schema::InputObject extend AppliesToFutureSchema argument_class BaseArgument end class BaseEnumValue < GraphQL::Schema::EnumValue include AppliesToFutureSchema end class BaseEnum < GraphQL::Schema::Enum enum_value_class BaseEnumValue end module Node include BaseInterface field :id, Int, null: false, future_schema: true, deprecation_reason: "Use databaseId instead" field :id, Int, null: false, future_schema: false field :database_id, Int, null: false, future_schema: true field :uuid, ID, null: false, future_schema: true end class MoneyScalar < BaseScalar graphql_name "Money" self.future_schema = false end class LegacyMoney < MoneyScalar graphql_name "LegacyMoney" end module HasCurrency include BaseInterface field :currency, String, null: false self.future_schema = true end class Money < BaseObject implements HasCurrency field :amount, Integer, null: false field :currency, String, null: false, description: "The denomination of this amount of money" self.future_schema = true end class LegacyScream < BaseScalar graphql_name "Scream" description "An all-uppercase saying" def self.coerce_input(value, ctx) if value.upcase != value raise GraphQL::CoercionError, "scream must be SCREAMING" end value end self.future_schema = false end class Scream < BaseScalar description "A saying ending with at least four exclamation points" def self.coerce_input(value, ctx) if !value.end_with?("!!!!") raise GraphQL::CoercionError, "scream must be screaming!!!!" end value end self.future_schema = true end class LegacyThing < BaseObject implements Node field :price, LegacyMoney end class Thing < LegacyThing # TODO can I get rid of `future_schema: ...` here in a way that # still only requires one call to `visible?` at runtime? field :price, Money, future_schema: true field :price, MoneyScalar, method: :legacy_price, future_schema: false end class Language < BaseEnum value "RUBY" value "PERL6", deprecation_reason: "Use RAKU instead", future_schema: true value "PERL6", future_schema: false value "RAKU", future_schema: true value "COFFEE_SCRIPT", future_schema: false end module HasCapital include BaseInterface field :capital_name, String, null: false end module HasLanguages include BaseInterface field :languages, [String], null: false end class Country < BaseObject implements HasCurrency implements HasCapital, future_schema: true implements HasLanguages, future_schema: true implements HasLanguages, future_schema: false end class Locale < BaseUnion possible_types Country, future_schema: true if GraphQL::Schema.use_visibility_profile? # Profile won't check possible_types, this must be flagged self.future_schema = true end end class Place < BaseObject implements Node self.future_schema = true field :future_place_field, String end class LegacyPlace < BaseObject implements Node graphql_name "Place" self.future_schema = false field :legacy_place_field, String end class Region < BaseUnion self.future_schema = true possible_types Country, Place, LegacyPlace end class LegacyBot < BaseObject description "Legacy bot" graphql_name "Bot" field :handle, String, null: false field :verified, Boolean, null: false self.future_schema = false end class AbstractNamedThing < BaseObject field :name, String, null: false end class Bot < AbstractNamedThing description "Future bot" field :name, String, null: false field :is_verified, Boolean, null: false self.future_schema = true end class Actor < BaseUnion possible_types Bot, LegacyBot def self.resolve_type(obj, ctx) if ctx[:future_schema] Bot else LegacyBot end end end class BaseResolver < GraphQL::Schema::Resolver argument_class BaseArgument end class Add < BaseResolver argument :left, Float, future_schema: true argument :left, Int, future_schema: false argument :right, Float, future_schema: true argument :right, Int, future_schema: false type String, null: false def resolve(left:, right:) "#{left + right}" end end class ThingIdInput < BaseInputObject argument :id, ID, future_schema: true, loads: Thing, as: :thing argument :id, Int, future_schema: false, loads: Thing, as: :thing end class Query < BaseObject field :node, Node do argument :id, ID end field :f1, String, future_schema: true field :f1, Int, future_schema: false def f1 if context[:future_schema] "abcdef" else 123 end end field :thing, Thing do argument :input, ThingIdInput end def thing(input:) input[:thing] end field :legacy_thing, LegacyThing, null: false do argument :id, ID end def legacy_thing(id:) { id: id, database_id: id, uuid: "thing-#{id}", price: "⚛︎#{id}00" } end field :favorite_language, Language, null: false do argument :lang, Language, required: false end def favorite_language(lang: nil) lang || context[:favorite_language] || "RUBY" end field :add, resolver: Add field :actor, Actor def actor { handle: "bot1", verified: false, name: "bot2", is_verified: true } end field :yell, String, null: false do # TODO: can I get rid of the requirement for `future_schema: true` here since `Scream.future_schema` is true? argument :scream, Scream, future_schema: true argument :scream, LegacyScream, future_schema: false end def yell(scream:) scream end # just to attach these to the schema: field :example_locale, Locale field :example_region, Region field :example_country, Country end class BaseMutation < GraphQL::Schema::RelayClassicMutation argument_class BaseArgument input_object_class BaseInputObject field_class BaseField end class UpdateThing < BaseMutation argument :thing_id, ID, future_schema: true argument :thing_id, Int, future_schema: false argument :price, Int field :thing, Thing, null: false, future_schema: true, method: :custom_thing field :thing, LegacyThing, null: false, hash_key: :legacy_thing, future_schema: false def resolve(thing_id:, price:) thing = { id: thing_id, uuid: thing_id, legacy_price: "£#{price}", future_price: { amount: price, currency: "£"} } thing[:price] = thing[:future_price] legacy_thing = thing.merge(price: thing[:legacy_price]) { custom_thing: thing, legacy_thing: legacy_thing, } end end class Mutation < BaseObject field :update_thing, mutation: UpdateThing end query(Query) mutation(Mutation) orphan_types(Place, LegacyPlace, Country) def self.object_from_id(id, ctx) { id: id, database_id: id, uuid: "thing-#{id}", legacy_price: "⚛︎#{id}00", price: { amount: id.to_i * 100, currency: "⚛︎" }} end def self.resolve_type(type, obj, ctx) Thing end end def check_for_multiple_visible_calls(context) if [1] != context[:visible_calls].values.map(&:size).uniq ok_visible_calls = [] not_ok_visible_calls = {} context[:visible_calls].each do |object, calls| if calls.size == 1 ok_visible_calls << object.path else not_ok_visible_calls[object] = calls end end bad_calls_text = "".dup not_ok_visible_calls.each do |object, calls| bad_calls_text << "- #{object.path}[#{object.object_id}] -> #{calls.size}\n" calls_count = Hash.new(0) calls.each do |call| calls_count[call] += 1 end calls_count.each do |call, count| bad_calls_text << " #{count}x:\n" call.each do |line| bad_calls_text << " #{line}\n" end bad_calls_text << "\n" end bad_calls_text << "\n\n" end raise <<-ERR Should be only one visible call per schema member: #{bad_calls_text} OK: #{ok_visible_calls} ERR end end VISIBLE_CALLS = Hash.new { |h, k| h[k] = [] } def exec_query(*args, **kwargs) context = kwargs[:context] ||= {} context[:visible_calls] = VISIBLE_CALLS.dup res = MultifieldSchema.execute(*args, **kwargs) check_for_multiple_visible_calls(res.context) res end def exec_future_query(*args, **kwargs) context = kwargs[:context] ||= {} context[:future_schema] = true exec_query(*args, **kwargs) end def future_schema_sdl ctx = { future_schema: true, visible_calls: VISIBLE_CALLS.dup } sdl = MultifieldSchema.to_definition(context: ctx) check_for_multiple_visible_calls(ctx) sdl end def legacy_schema_sdl ctx = { visible_calls: VISIBLE_CALLS.dup } sdl = MultifieldSchema.to_definition(context: ctx) check_for_multiple_visible_calls(ctx) sdl end it "returns different fields according context for Ruby methods, runtime, introspection, and to_definition" do # Accessing in Ruby assert_equal GraphQL::Types::Int, MultifieldSchema::Query.get_field("f1", { future_schema: nil }).type assert_equal GraphQL::Types::Int, MultifieldSchema::Query.get_field("f1", { future_schema: false }).type assert_equal GraphQL::Types::String, MultifieldSchema::Query.get_field("f1", { future_schema: true }).type assert_equal GraphQL::Types::Int, MultifieldSchema.get_field("Query", "f1", { future_schema: false }).type assert_equal GraphQL::Types::String, MultifieldSchema.get_field("Query", "f1", { future_schema: true }).type err = assert_raises GraphQL::Schema::DuplicateNamesError do MultifieldSchema::Query.get_field("f1") end assert_equal "Query.f1", err.duplicated_name expected_message = "Found two visible definitions for `Query.f1`: #<MultifieldSchema::BaseField Query.f1: String>, #<MultifieldSchema::BaseField Query.f1: Int>" assert_equal expected_message, err.message # GraphQL usage query_str = "{ f1 }" assert_equal 123, exec_query(query_str)["data"]["f1"] assert_equal "abcdef", exec_future_query(query_str)["data"]["f1"] # GraphQL Introspection introspection_query_str = '{ __type(name: "Query") { fields { name type { name } } } }' assert_equal "Int", exec_query(introspection_query_str)["data"]["__type"]["fields"].find { |f| f["name"] == "f1" }["type"]["name"] assert_equal "String", exec_future_query(introspection_query_str)["data"]["__type"]["fields"].find { |f| f["name"] == "f1" }["type"]["name"] # Schema dump legacy_query_type_str = legacy_schema_sdl[/type Query \{[^}]*\}/m] expected_legacy_query_type_str = <<-GRAPHQL.chomp type Query { actor: Actor add(left: Int!, right: Int!): String! exampleCountry: Country f1: Int favoriteLanguage(lang: Language): Language! legacyThing(id: ID!): LegacyThing! node(id: ID!): Node thing(input: ThingIdInput!): Thing yell(scream: Scream!): String! } GRAPHQL assert_equal expected_legacy_query_type_str, legacy_query_type_str assert_includes future_schema_sdl, <<-GRAPHQL type Query { actor: Actor add(left: Float!, right: Float!): String! exampleCountry: Country exampleLocale: Locale exampleRegion: Region f1: String favoriteLanguage(lang: Language): Language! legacyThing(id: ID!): LegacyThing! node(id: ID!): Node thing(input: ThingIdInput!): Thing yell(scream: Scream!): String! } GRAPHQL end it "serves interface fields according to the per-query version" do # Schema dump assert_includes legacy_schema_sdl, <<-GRAPHQL interface Node { id: Int! } GRAPHQL assert_includes future_schema_sdl, <<-GRAPHQL interface Node { databaseId: Int! id: Int! @deprecated(reason: "Use databaseId instead") uuid: ID! } GRAPHQL query_str = "{ thing(input: { id: 15 }) { databaseId id uuid } }" assert_equal ["Field 'databaseId' doesn't exist on type 'Thing'", "Field 'uuid' doesn't exist on type 'Thing'"], exec_query(query_str)["errors"].map { |e| e["message"] } res = exec_future_query(query_str) assert_equal({ "thing" => { "databaseId" => 15, "id" => 15, "uuid" => "thing-15"} }, res["data"]) end it "supports multiple implementations of the same interface" do query_str = '{ __type(name: "Country") { interfaces { name } } }' assert_equal ["HasLanguages"], exec_query(query_str)["data"]["__type"]["interfaces"].map { |i| i["name"] } assert_equal ["HasCapital", "HasCurrency", "HasLanguages"], exec_future_query(query_str)["data"]["__type"]["interfaces"].map { |i| i["name"] } end it "overrides fields from interfaces instead of multi-defining them" do f = MultifieldSchema::Money.get_field("currency") assert_equal MultifieldSchema::Money, f.owner assert_equal "The denomination of this amount of money", f.description end it "supports different versions of field arguments" do res = exec_future_query("{ thing(input: { id: \"15\" }) { id } }") assert_equal 15, res["data"]["thing"]["id"] # On legacy, `"15"` is parsed as an int, which makes it null: res = exec_query("{ thing(input: { id: \"15\" }) { id } }") assert_equal ["Argument 'id' on InputObject 'ThingIdInput' has an invalid value (\"15\"). Expected type 'Int!'."], res["errors"].map { |e| e["message"] } introspection_query = "{ __type(name: \"ThingIdInput\") { inputFields { name type { name ofType { name } } } } }" introspection_res = exec_query(introspection_query) assert_equal "Int", introspection_res["data"]["__type"]["inputFields"].find { |f| f["name"] == "id" }["type"]["ofType"]["name"] introspection_res = exec_future_query(introspection_query) assert_equal "ID", introspection_res["data"]["__type"]["inputFields"].find { |f| f["name"] == "id" }["type"]["ofType"]["name"] end it "hides fields from hidden interfaces" do # in this case, the whole interface is hidden assert MultifieldSchema::HasCurrency.visible?({ future_schema: true }) refute MultifieldSchema::HasCurrency.visible?({ future_schema: false }) refute MultifieldSchema::Country.fields({ future_schema: false }).key?("currency") assert MultifieldSchema::Country.fields({ future_schema: true }).key?("currency") assert_nil MultifieldSchema::Country.get_field("currency", { future_schema: false }) refute_nil MultifieldSchema::Country.get_field("currency", { future_schema: true }) refute_includes MultifieldSchema::Country.interfaces({ future_schema: false }), MultifieldSchema::HasCurrency assert_includes MultifieldSchema::Country.interfaces({ future_schema: true }), MultifieldSchema::HasCurrency assert_includes MultifieldSchema::Country.interfaces, MultifieldSchema::HasCurrency end it "hides hidden interface implementations" do # in this case, the interface is always visible: assert MultifieldSchema::HasCapital.visible?({ future_schema: true }) assert MultifieldSchema::HasCapital.visible?({ future_schema: false }) # but the field is sometimes hidden: refute_includes MultifieldSchema::Country.fields({ future_schema: false }), "capitalName" assert_includes MultifieldSchema::Country.fields({ future_schema: true }), "capitalName" assert_nil MultifieldSchema::Country.get_field("capitalName", { future_schema: false }) refute_nil MultifieldSchema::Country.get_field("capitalName", { future_schema: true }) # and the interface relationship is sometimes hidden: refute_includes MultifieldSchema::Country.interfaces({ future_schema: false }), MultifieldSchema::HasCapital refute_includes MultifieldSchema.possible_types(MultifieldSchema::HasCapital, { future_schema: false }), MultifieldSchema::Country assert_includes MultifieldSchema::Country.interfaces({ future_schema: true }), MultifieldSchema::HasCapital assert_includes MultifieldSchema.possible_types(MultifieldSchema::HasCapital, { future_schema: true }), MultifieldSchema::Country assert_includes MultifieldSchema::Country.interfaces, MultifieldSchema::HasCapital if GraphQL::Schema.use_visibility_profile? # filtered with `future_schema: nil` refute_includes MultifieldSchema.possible_types(MultifieldSchema::HasCapital), MultifieldSchema::Country else assert_includes MultifieldSchema.possible_types(MultifieldSchema::HasCapital), MultifieldSchema::Country end end it "hides hidden union memberships" do assert MultifieldSchema::Locale.visible?({ future_schema: true }) if GraphQL::Schema.use_visibility_profile? refute MultifieldSchema::Locale.visible?({ future_schema: false }) else # Warden will check possible types -- but Profile doesn't assert MultifieldSchema::Locale.visible?({ future_schema: false }) end # and the possible types relationship is sometimes hidden: refute_includes MultifieldSchema.possible_types(MultifieldSchema::Locale, { future_schema: false }), MultifieldSchema::Country assert_includes MultifieldSchema.possible_types(MultifieldSchema::Locale, { future_schema: true }), MultifieldSchema::Country if GraphQL::Schema.use_visibility_profile? # This type is hidden in this case assert_equal [], MultifieldSchema.possible_types(MultifieldSchema::Locale) else assert_includes MultifieldSchema.possible_types(MultifieldSchema::Locale), MultifieldSchema::Country end end it "hides hidden unions" do # in this case, the union is only sometimes visible: assert MultifieldSchema::Region.visible?({ future_schema: true }) refute MultifieldSchema::Region.visible?({ future_schema: false }) # and the possible types relationship is sometimes hidden: assert_equal [], MultifieldSchema.possible_types(MultifieldSchema::Region, { future_schema: false }) assert_equal [MultifieldSchema::Country, MultifieldSchema::Place], MultifieldSchema.possible_types(MultifieldSchema::Region, { future_schema: true }) if GraphQL::Schema.use_visibility_profile? # Filtered like `future_schema: false` assert_equal [MultifieldSchema::Country, MultifieldSchema::LegacyPlace], MultifieldSchema.possible_types(MultifieldSchema::Region) else assert_equal [MultifieldSchema::Country, MultifieldSchema::Place, MultifieldSchema::LegacyPlace], MultifieldSchema.possible_types(MultifieldSchema::Region) end end it "supports different versions of input object arguments" do res = exec_query("mutation { updateThing(input: { thingId: 12, price: 100 }) { thing { price id } } }") assert_equal "£100", res["data"]["updateThing"]["thing"]["price"] assert_equal 12, res["data"]["updateThing"]["thing"]["id"] res = exec_future_query("mutation { updateThing(input: { thingId: \"11\", price: 120 }) { thing { uuid price { amount } } } }") assert_equal "11", res["data"]["updateThing"]["thing"]["uuid"] assert_equal 120, res["data"]["updateThing"]["thing"]["price"]["amount"] introspection_query_str = "{ __type(name: \"UpdateThingInput\") { inputFields { name type { name ofType { name } } } } }" res = exec_query(introspection_query_str) assert_equal "Int", res["data"]["__type"]["inputFields"].find { |f| f["name"] == "thingId" }["type"]["ofType"]["name"] res = exec_future_query(introspection_query_str) assert_equal "ID", res["data"]["__type"]["inputFields"].find { |f| f["name"] == "thingId" }["type"]["ofType"]["name"] introspection_query_str = "{ __type(name: \"UpdateThingPayload\") { fields { name type { name ofType { name } } } } }" res = exec_query(introspection_query_str) assert_equal "LegacyThing", res["data"]["__type"]["fields"].find { |f| f["name"] == "thing" }["type"]["ofType"]["name"] res = exec_future_query(introspection_query_str) assert_equal "Thing", res["data"]["__type"]["fields"].find { |f| f["name"] == "thing" }["type"]["ofType"]["name"] update_thing_payload_sdl = <<-GRAPHQL type UpdateThingPayload { """ A unique identifier for the client performing the mutation. """ clientMutationId: String thing: %{typename}! } GRAPHQL assert_includes legacy_schema_sdl, update_thing_payload_sdl % { typename: "LegacyThing"} assert_includes future_schema_sdl, update_thing_payload_sdl % { typename: "Thing"} end it "can migrate scalars to objects" do # Schema dump assert_includes legacy_schema_sdl, "scalar Money" refute_includes legacy_schema_sdl, "type Money" assert_includes future_schema_sdl, <<-GRAPHQL type Money implements HasCurrency { amount: Int! """ The denomination of this amount of money """ currency: String! } GRAPHQL refute_includes future_schema_sdl, "scalar Money" assert_equal MultifieldSchema::MoneyScalar, MultifieldSchema.get_type("Money", { future_schema: nil }) assert_equal MultifieldSchema::MoneyScalar, MultifieldSchema.get_type("Money", { future_schema: false }) assert_equal MultifieldSchema::Money, MultifieldSchema.get_type("Money", { future_schema: true }) if GraphQL::Schema.use_visibility_profile? # Filtered like `future_schema: nil` assert_equal MultifieldSchema::MoneyScalar, MultifieldSchema.get_type("Money") else err = assert_raises GraphQL::Schema::DuplicateNamesError do assert_nil MultifieldSchema.get_type("Money") end assert_equal "Money", err.duplicated_name expected_message = "Found two visible definitions for `Money`: MultifieldSchema::Money, MultifieldSchema::MoneyScalar" assert_equal expected_message, err.message end assert_equal "⚛︎100",exec_query("{ thing( input: { id: 1 }) { price } }")["data"]["thing"]["price"] res = exec_query("{ __type(name: \"Money\") { kind name } }") assert_equal "SCALAR", res["data"]["__type"]["kind"] assert_equal "Money", res["data"]["__type"]["name"] assert_equal({ "amount" => 200, "currency" => "⚛︎" }, exec_future_query("{ thing(input: { id: 2}) { price { amount currency } } }")["data"]["thing"]["price"]) res = exec_future_query("{ __type(name: \"Money\") { name kind } }") assert_equal "OBJECT", res["data"]["__type"]["kind"] assert_equal "Money", res["data"]["__type"]["name"] end it "works with subclasses" do res = exec_query("{ legacyThing(id: 1) { price } thing(input: { id: 3 }) { price } }") assert_equal "⚛︎100", res["data"]["legacyThing"]["price"] assert_equal "⚛︎300", res["data"]["thing"]["price"] future_res = exec_future_query("{ legacyThing(id: 1) { price } thing(input: { id: 3 }) { price { amount } } }") assert_equal "⚛︎100", future_res["data"]["legacyThing"]["price"] assert_equal 300, future_res["data"]["thing"]["price"]["amount"] end it "supports different enum value definitions" do # Schema dump: legacy_schema = legacy_schema_sdl assert_includes legacy_schema, "COFFEE_SCRIPT" refute_includes legacy_schema, "RAKU" future_schema = future_schema_sdl assert_includes future_schema, "RAKU\n" assert_includes future_schema, "\"Use RAKU instead\"" refute_includes future_schema, "COFFEE_SCRIPT" # Introspection: query_str = "{ __type(name: \"Language\") { enumValues(includeDeprecated: true) { name deprecationReason } } }" legacy_res = exec_query(query_str) assert_equal ["RUBY", "PERL6", "COFFEE_SCRIPT"], legacy_res["data"]["__type"]["enumValues"].map { |v| v["name"] } assert_equal [nil, nil, nil], legacy_res["data"]["__type"]["enumValues"].map { |v| v["deprecationReason"] } future_res = exec_future_query(query_str) assert_equal ["RUBY", "PERL6", "RAKU"], future_res["data"]["__type"]["enumValues"].map { |v| v["name"] } assert_equal [nil, "Use RAKU instead", nil], future_res["data"]["__type"]["enumValues"].map { |v| v["deprecationReason"] } # Runtime return values and inputs: assert_equal "COFFEE_SCRIPT", exec_query("{ favoriteLanguage }", context: { favorite_language: "COFFEE_SCRIPT"})["data"]["favoriteLanguage"] assert_raises MultifieldSchema::Language::UnresolvedValueError do exec_future_query("{ favoriteLanguage }", context: { favorite_language: "COFFEE_SCRIPT"}) end assert_equal "COFFEE_SCRIPT", exec_query("{ favoriteLanguage(lang: COFFEE_SCRIPT) }")["data"]["favoriteLanguage"] assert_equal ["Argument 'lang' on Field 'favoriteLanguage' has an invalid value (COFFEE_SCRIPT). Expected type 'Language'."], exec_future_query("{ favoriteLanguage(lang: COFFEE_SCRIPT) }")["errors"].map { |e| e["message"] } assert_equal "RAKU", exec_future_query("{ favoriteLanguage }", context: { favorite_language: "RAKU"})["data"]["favoriteLanguage"] assert_raises MultifieldSchema::Language::UnresolvedValueError do exec_query("{ favoriteLanguage }", context: { favorite_language: "RAKU"}) end assert_equal "RAKU", exec_future_query("{ favoriteLanguage(lang: RAKU) }")["data"]["favoriteLanguage"] assert_equal ["Argument 'lang' on Field 'favoriteLanguage' has an invalid value (RAKU). Expected type 'Language'."], exec_query("{ favoriteLanguage(lang: RAKU) }")["errors"].map { |e| e["message"] } end it "supports multiple types with the same name in orphan_types" do legacy_schema = legacy_schema_sdl assert_includes legacy_schema, "legacyPlaceField" refute_includes legacy_schema, "futurePlaceField" assert_equal ["type Place"], legacy_schema.scan("type Place") future_schema = future_schema_sdl refute_includes future_schema, "legacyPlaceField" assert_includes future_schema, "futurePlaceField" assert_equal ["type Place"], future_schema.scan("type Place") end it "supports different resolver arguments" do assert_equal "4", exec_query("{ add(left: 1, right: 3) }")["data"]["add"] assert_equal ["Argument 'left' on Field 'add' has an invalid value (1.2). Expected type 'Int!'."], exec_query("{ add(left: 1.2, right: 3) }")["errors"].map { |e| e["message"] } assert_equal "4.5", exec_future_query("{ add(left: 1.2, right: 3.3) }")["data"]["add"] assert_equal "4.2", exec_future_query("{ add(left: 1.2, right: 3) }")["data"]["add"] introspection_query_str = "{ __type(name: \"Query\") { fields { name args { type { ofType { name } } } } } }" legacy_res = exec_query(introspection_query_str) assert_equal ["Int", "Int"], legacy_res["data"]["__type"]["fields"].find { |f| f["name"] == "add" }["args"].map { |a| a["type"]["ofType"]["name"] } future_res = exec_future_query(introspection_query_str) assert_equal ["Float", "Float"], future_res["data"]["__type"]["fields"].find { |f| f["name"] == "add" }["args"].map { |a| a["type"]["ofType"]["name"] } end it "supports unions with possible types of the same name" do assert_includes future_schema_sdl, "union Actor = Bot\n" assert_includes future_schema_sdl, "type Bot {\n isVerified: Boolean!\n name: String!\n}\n" assert_equal 1, future_schema_sdl.scan("type Bot").size assert_includes legacy_schema_sdl, "union Actor = Bot\n" assert_includes legacy_schema_sdl, "type Bot {\n handle: String!\n verified: Boolean!\n}\n" assert_equal 1, legacy_schema_sdl.scan("type Bot").size legacy_res = exec_query("{ actor { ... on Bot { handle } } }") assert_equal "bot1", legacy_res["data"]["actor"]["handle"] legacy_res2 = exec_query("{ actor { ... on Bot { name } } }") assert_equal ["Field 'name' doesn't exist on type 'Bot'"], legacy_res2["errors"].map { |e| e["message"] } future_res = exec_future_query("{ actor { ... on Bot { name } } }") assert_equal "bot2", future_res["data"]["actor"]["name"] future_res2 = exec_future_query("{ actor { ... on Bot { handle } } }") assert_equal ["Field 'handle' doesn't exist on type 'Bot'"], future_res2["errors"].map { |e| e["message"] } introspection_query_str = "{ __type(name: \"Actor\") { possibleTypes { description } } }" assert_equal ["Legacy bot"], exec_query(introspection_query_str)["data"]["__type"]["possibleTypes"].map { |t| t["description"] } assert_equal ["Future bot"], exec_future_query(introspection_query_str)["data"]["__type"]["possibleTypes"].map { |t| t["description"] } end it "supports different types connected by argument definitions" do future_description = "A saying ending with at least four exclamation points" legacy_description = "An all-uppercase saying" assert_includes future_schema_sdl, future_description refute_includes future_schema_sdl, legacy_description assert_includes legacy_schema_sdl, legacy_description refute_includes legacy_schema_sdl, future_description query_str = "query($scream: Scream!) { yell(scream: $scream) }" assert_equal "YIKES", exec_query(query_str, variables: { scream: "YIKES" })["data"]["yell"]
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
true
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/warden_spec.rb
spec/graphql/schema/warden_spec.rb
# frozen_string_literal: true require "spec_helper" module MaskHelpers def self.build_mask(only:, except:) ->(member, context) do visible = true if visible only.each do |filter| passes_filter = filter.call(member, context) if !passes_filter visible = false break end end end if visible except.each do |filter| passes_filter = !filter.call(member, context) if !passes_filter visible = false break end end end !visible end end # Returns true if `member.metadata` includes any of `flags` def self.has_flag?(member, *flags) if member.respond_to?(:metadata) && (m = member.metadata) if m.is_a?(Hash) flags.any? { |f| m[f] } else m.any? { |item| flags.include?(item) } end end end module HasMetadata def metadata(key = nil, value = nil) if key @metadata ||= {} @metadata[key] = value end @metadata end end class BaseArgument < GraphQL::Schema::Argument include HasMetadata end class BaseField < GraphQL::Schema::Field include HasMetadata argument_class BaseArgument end class BaseObject < GraphQL::Schema::Object extend HasMetadata field_class BaseField end class BaseEnumValue < GraphQL::Schema::EnumValue include HasMetadata end class BaseEnum < GraphQL::Schema::Enum extend HasMetadata enum_value_class BaseEnumValue end class BaseInputObject < GraphQL::Schema::InputObject extend HasMetadata argument_class BaseArgument end class BaseUnion < GraphQL::Schema::Union extend HasMetadata end module BaseInterface include GraphQL::Schema::Interface module DefinitionMethods include HasMetadata end field_class BaseField end class MannerType < BaseEnum description "Manner of articulation for this sound" metadata :hidden_input_type, true value "STOP" value "AFFRICATE" value "FRICATIVE" value "APPROXIMANT" value "VOWEL" value "TRILL" do metadata :hidden_enum_value, true end end class LanguageType < BaseObject field :name, String, null: false field :families, [String], null: false field :phonemes, "[MaskHelpers::PhonemeType]", null: false field :graphemes, "[MaskHelpers::GraphemeType]", null: false end module LanguageMemberType include BaseInterface metadata :hidden_abstract_type, true description "Something that belongs to one or more languages" field :languages, [LanguageType], null: false end class GraphemeType < BaseObject description "A building block of spelling in a given language" implements LanguageMemberType field :name, String, null: false field :glyph, String, null: false field :languages, [LanguageType], null: false end class PhonemeType < BaseObject description "A building block of sound in a given language" metadata :hidden_type, true implements LanguageMemberType field :name, String, null: false field :symbol, String, null: false field :languages, [LanguageType], null: false field :manner, MannerType, null: false end class EmicUnitType < BaseUnion description "A building block of a word in a given language" possible_types GraphemeType, PhonemeType end class WithinInputType < BaseInputObject metadata :hidden_input_object_type, true argument :latitude, Float argument :longitude, Float argument :miles, Float do metadata :hidden_input_field, true end end class CheremeInput < BaseInputObject argument :name, String, required: false end module PublicInterfaceType include BaseInterface field :other, String end class PublicType < BaseObject implements PublicInterfaceType field :test, String end class CheremeDirective < GraphQL::Schema::Directive locations(GraphQL::Schema::Directive::OBJECT) end class CheremeWithInterface < BaseObject implements PublicInterfaceType field :name, String, null: false end class Chereme < BaseObject description "A basic unit of signed communication" implements LanguageMemberType directive CheremeDirective field :name, String, null: false field :chereme_with_interface, CheremeWithInterface end class Character < BaseObject implements LanguageMemberType field :code, Int, null: false end class QueryType < BaseObject field :languages, [LanguageType], null: false do argument :within, WithinInputType, required: false, description: "Find languages nearby a point" do metadata :hidden_argument_with_input_object, true end end field :language, LanguageType do metadata :hidden_field, true argument :name, String do metadata :hidden_argument, true end end field :chereme, Chereme, null: false do metadata :hidden_field, true end field :chereme_with_interface, CheremeWithInterface, null: false do metadata :hidden_field, true end field :phonemes, [PhonemeType], null: false do argument :manners, [MannerType], required: false, description: "Filter phonemes by manner of articulation" end field :phoneme, PhonemeType do description "Lookup a phoneme by symbol" argument :symbol, String end field :unit, EmicUnitType do description "Find an emic unit by its name" argument :name, String end field :manners, [MannerType], null: false field :public_type, PublicType, null: false # Warden would exclude this when it was only referenced as a possible_type of LanguageMemberType. # But Profile always included it. This makes them behave the same field :example_character, Character do metadata :hidden_abstract_type, true end end class MutationType < BaseObject field :add_phoneme, PhonemeType do argument :symbol, String, required: false end field :add_chereme, String do argument :chereme, CheremeInput, required: false do metadata :hidden_argument, true end end end class Schema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN query QueryType mutation MutationType subscription MutationType orphan_types [Character] def self.resolve_type(type, obj, ctx) PhonemeType end def self.visible?(member, context) result = super(member, context) if result && context[:only] && !Array(context[:only]).all? { |func| func.call(member, context) } return false end if result && context[:except] && Array(context[:except]).any? { |func| func.call(member, context) } return false end result end end module Data UVULAR_TRILL = OpenStruct.new({name: "Uvular Trill", symbol: "ʀ", manner: "TRILL"}) def self.unit(name:) UVULAR_TRILL end end def self.query_with_mask(str, mask, variables: {}) run_query(str, context: { except: mask }, root_value: Data, variables: variables) end def self.run_query(str, **kwargs) filters = {} if (only = kwargs.delete(:only)) filters[:only] = only end if (except = kwargs.delete(:except)) filters[:except] = except end if !filters.empty? context = kwargs[:context] ||= {} context[:filters] = filters end Schema.execute(str, **kwargs.merge(root_value: Data)) end end describe GraphQL::Schema::Warden do def type_names(introspection_result) introspection_result["data"]["__schema"]["types"].map { |t| t["name"] } end def possible_type_names(type_by_name_result) type_by_name_result["possibleTypes"].map { |t| t["name"] } end def field_type_names(schema_result) schema_result["types"] .map {|t| t["fields"] } .flatten .map { |f| f ? get_recursive_field_type_names(f["type"]) : [] } .flatten .uniq end def get_recursive_field_type_names(field_result) case field_result when Hash [field_result["name"]].concat(get_recursive_field_type_names(field_result["ofType"])) when nil [] else raise "Unexpected field result: #{field_result}" end end def error_messages(query_result) query_result["errors"].map { |err| err["message"] } end describe "hiding root types" do let(:mask) { ->(m, ctx) { m == MaskHelpers::MutationType } } it "acts as if the root doesn't exist" do query_string = %|mutation { addPhoneme(symbol: "ϕ") { name } }| res = MaskHelpers.query_with_mask(query_string, mask) assert MaskHelpers::Schema.mutation # it _does_ exist assert_equal 1, res["errors"].length assert_equal "Schema is not configured for mutations", res["errors"][0]["message"] query_string = %|subscription { addPhoneme(symbol: "ϕ") { name } }| res = MaskHelpers.query_with_mask(query_string, mask) assert MaskHelpers::Schema.subscription # it _does_ exist assert_equal 1, res["errors"].length assert_equal "Schema is not configured for subscriptions", res["errors"][0]["message"] end it "doesn't show in introspection" do query_string = <<-GRAPHQL { __schema { queryType { name } mutationType { name } subscriptionType { name } types { name } } } GRAPHQL res = MaskHelpers.query_with_mask(query_string, mask) assert_equal "Query", res["data"]["__schema"]["queryType"]["name"] assert_nil res["data"]["__schema"]["mutationType"] assert_nil res["data"]["__schema"]["subscriptionType"] type_names = res["data"]["__schema"]["types"].map { |t| t["name"] } refute type_names.include?("Mutation") refute type_names.include?("Subscription") end end describe "hiding fields" do let(:mask) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_field, :hidden_type) } } it "hides types if no other fields are using it" do query_string = %| { Chereme: __type(name: "Chereme") { fields { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) assert_nil res["data"]["Chereme"] end it "hides types if no other fields are using it (with interface)" do query_string = %| { CheremeWithInterface: __type(name: "CheremeWithInterface") { fields { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) assert_nil res["data"]["CheremeWithInterface"] end it "hides directives if no other fields are using it" do query_string = %| { __schema { directives { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) expected_directives = ["deprecated", "include", "oneOf", "skip", "specifiedBy"] if !GraphQL::Schema.use_visibility_profile? # Not supported by Warden expected_directives.unshift("cheremeDirective") end assert_equal(expected_directives, res["data"]["__schema"]["directives"].map { |d| d["name"] }) end it "causes validation errors" do query_string = %|{ phoneme(symbol: "ϕ") { name } }| res = MaskHelpers.query_with_mask(query_string, mask) err_msg = res["errors"][0]["message"] assert_equal "Field 'phoneme' doesn't exist on type 'Query'", err_msg query_string = %|{ language(name: "Uyghur") { name } }| res = MaskHelpers.query_with_mask(query_string, mask) err_msg = res["errors"][0]["message"] assert_equal "Field 'language' doesn't exist on type 'Query' (Did you mean `languages`?)", err_msg end it "doesn't show in introspection" do query_string = %| { LanguageType: __type(name: "Language") { fields { name } } __schema { types { name fields { name } } } }| res = MaskHelpers.query_with_mask(query_string, mask) # Fields dont appear when finding the type by name language_fields = res["data"]["LanguageType"]["fields"].map {|f| f["name"] } assert_equal ["families", "graphemes", "name"], language_fields # Fields don't appear in the __schema result phoneme_fields = res["data"]["__schema"]["types"] .map { |t| (t["fields"] || []).select { |f| f["name"].start_with?("phoneme") } } .flatten assert_equal [], phoneme_fields end end describe "hiding types" do it "hides types from introspection" do query_string = %| { Phoneme: __type(name: "Phoneme") { name } EmicUnit: __type(name: "EmicUnit") { possibleTypes { name } } LanguageMember: __type(name: "LanguageMember") { possibleTypes { name } } __schema { types { name fields { type { name ofType { name ofType { name } } } } } } } | res = MaskHelpers.run_query(query_string, context: { skip_visibility_migration_error: true, except: ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_type) } }) # It's not visible by name assert_nil res["data"]["Phoneme"] # It's not visible in `__schema` all_type_names = type_names(res) assert_equal false, all_type_names.include?("Phoneme") # No fields return it refute_includes field_type_names(res["data"]["__schema"]), "Phoneme" # It's not visible as a union or interface member assert_equal false, possible_type_names(res["data"]["EmicUnit"]).include?("Phoneme") assert_equal false, possible_type_names(res["data"]["LanguageMember"]).include?("Phoneme") assert_equal ["Character", "Chereme", "Grapheme"], possible_type_names(res["data"]["LanguageMember"]).sort end it "hides interfaces if all possible types are hidden" do sdl = %| type Query { a: String repository: Repository } type Repository implements Node { id: ID! } interface Node { id: ID! } | schema = GraphQL::Schema.from_definition(sdl) schema.use(GraphQL::Schema::Warden) schema.define_singleton_method(:visible?) do |member, ctx| super(member, ctx) && (ctx[:hiding] ? member.graphql_name != "Repository" : true) end query_string = %| { Node: __type(name: "Node") { name } } | res = schema.execute(query_string) assert res["data"]["Node"] res = schema.execute(query_string, context: { hiding: true }) assert_nil res["data"]["Node"] end it "hides unions if all possible types are hidden or its references are hidden" do class PossibleTypesSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN class A < GraphQL::Schema::Object field :id, ID, null: false end class B < A; end class C < A; end class BagOfThings < GraphQL::Schema::Union possible_types A, B, C if GraphQL::Schema.use_visibility_profile? def self.visible?(ctx) ( possible_types.any? { |pt| ctx.schema.visible?(pt, ctx) } || ctx.schema.extra_types.include?(self) ) && super end end end class Query < GraphQL::Schema::Object field :bag, BagOfThings, null: false end query(Query) def self.visible?(member, context) res = super(member, context) if res && context[:except] !context[:except].call(member, context) else res end end end schema = PossibleTypesSchema query_string = %| { BagOfThings: __type(name: "BagOfThings") { name } Query: __type(name: "Query") { fields { name } } } | res = schema.execute(query_string) assert res["data"]["BagOfThings"] assert_equal ["bag"], res["data"]["Query"]["fields"].map { |f| f["name"] } # Hide the union when all its possible types are gone. This will cause the field to be hidden too. res = schema.execute(query_string, context: { except: ->(m, _) { ["A", "B", "C"].include?(m.graphql_name) } }) assert_nil res["data"]["BagOfThings"] assert_equal [], res["data"]["Query"]["fields"] res = schema.execute(query_string, context: { except: ->(m, _) { m.graphql_name == "bag" } }) assert_nil res["data"]["BagOfThings"] assert_equal [], res["data"]["Query"]["fields"] # Unreferenced but still visible because extra type schema.extra_types([schema.find("BagOfThings")]) res = schema.execute(query_string, context: { except: ->(m, _) { m.graphql_name == "bag" } }) assert res["data"]["BagOfThings"] end it "hides interfaces if all possible types are hidden or its references are hidden" do sdl = " type Query { node: Node a: A } type A implements Node { id: ID! } type B implements Node { id: ID! } type C implements Node { id: ID! } interface Node { id: ID! } " schema = GraphQL::Schema.from_definition(sdl) schema.use(GraphQL::Schema::Warden) if ADD_WARDEN schema.define_singleton_method(:visible?) do |member, context| res = super(member, context) if res && context[:except] !context[:except].call(member, context) else res end end query_string = %| { Node: __type(name: "Node") { name } Query: __type(name: "Query") { fields { name } } } | res = schema.execute(query_string) assert res["data"]["Node"] assert_equal ["a", "node"], res["data"]["Query"]["fields"].map { |f| f["name"] } res = schema.execute(query_string, context: { skip_visibility_migration_error: true, except: ->(m, _) { ["A", "B", "C"].include?(m.graphql_name) } }) if GraphQL::Schema.use_visibility_profile? # Node is still visible even though it has no possible types assert res["data"]["Node"] assert_equal [{ "name" => "node" }], res["data"]["Query"]["fields"] else # When the possible types are all hidden, hide the interface and fields pointing to it assert_nil res["data"]["Node"] assert_equal [], res["data"]["Query"]["fields"] end # Even when it's not the return value of a field, # still show the interface since it allows code reuse res = schema.execute(query_string, context: { except: ->(m, _) { m.graphql_name == "node" } }) assert_equal "Node", res["data"]["Node"]["name"] assert_equal [{"name" => "a"}], res["data"]["Query"]["fields"] end it "can't be a fragment condition" do query_string = %| { unit(name: "bilabial trill") { ... on Phoneme { name } ... f1 } } fragment f1 on Phoneme { name } | res = MaskHelpers.run_query(query_string, context: { except: ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_type) } }) expected_errors = [ "No such type Phoneme, so it can't be a fragment condition", "No such type Phoneme, so it can't be a fragment condition", ] assert_equal expected_errors, error_messages(res) end it "can't be a resolve_type result" do query_string = %| { unit(name: "Uvular Trill") { __typename } } | assert_raises(MaskHelpers::EmicUnitType::UnresolvedTypeError) { MaskHelpers.run_query(query_string, context: { except: ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_type) } }) } end describe "hiding an abstract type" do let(:mask) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_abstract_type) } } it "isn't present in a type's interfaces" do query_string = %| { __type(name: "Phoneme") { interfaces { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) interfaces_names = res["data"]["__type"]["interfaces"].map { |i| i["name"] } refute_includes interfaces_names, "LanguageMember" end it "hides implementations if they are not referenced anywhere else" do query_string = %| { __type(name: "Character") { fields { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) type = res["data"]["__type"] assert_nil type end end end describe "hiding arguments" do let(:mask) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_argument, :hidden_input_type) } } it "hides types if no other fields or arguments are using it" do query_string = %| { CheremeInput: __type(name: "CheremeInput") { fields { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) assert_nil res["data"]["CheremeInput"] end it "isn't present in introspection" do query_string = %| { Query: __type(name: "Query") { fields { name, args { name } } } } | res = MaskHelpers.query_with_mask(query_string, mask) query_field_args = res["data"]["Query"]["fields"].each_with_object({}) { |f, memo| memo[f["name"]] = f["args"].map { |a| a["name"] } } # hidden argument: refute_includes query_field_args["language"], "name" # hidden input type: refute_includes query_field_args["phoneme"], "manner" end it "isn't valid in a query" do query_string = %| { language(name: "Catalan") { name } phonemes(manners: STOP) { symbol } } | res = MaskHelpers.query_with_mask(query_string, mask) expected_errors = [ "Field 'language' doesn't accept argument 'name'", "Field 'phonemes' doesn't accept argument 'manners'", ] assert_equal expected_errors, error_messages(res) end end describe "hiding input type arguments" do let(:mask) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_input_field) } } it "isn't present in introspection" do query_string = %| { WithinInput: __type(name: "WithinInput") { inputFields { name } } }| res = MaskHelpers.query_with_mask(query_string, mask) input_field_names = res["data"]["WithinInput"]["inputFields"].map { |f| f["name"] } refute_includes input_field_names, "miles" end it "isn't a valid default value" do query_string = %| query findLanguages($nearby: WithinInput = {latitude: 1.0, longitude: 2.2, miles: 3.3}) { languages(within: $nearby) { name } }| res = MaskHelpers.query_with_mask(query_string, mask) expected_errors = ["Default value for $nearby doesn't match type WithinInput"] assert_equal expected_errors, error_messages(res) end it "isn't a valid literal input" do query_string = %| { languages(within: {latitude: 1.0, longitude: 2.2, miles: 3.3}) { name } }| res = MaskHelpers.query_with_mask(query_string, mask) expected_errors = [ "InputObject 'WithinInput' doesn't accept argument 'miles'" ] assert_equal expected_errors, error_messages(res) end it "isn't a valid variable input" do query_string = %| query findLanguages($nearby: WithinInput!) { languages(within: $nearby) { name } }| res = MaskHelpers.query_with_mask(query_string, mask, variables: { "latitude" => 1.0, "longitude" => 2.2, "miles" => 3.3}) expected_errors = ["Variable $nearby of type WithinInput! was provided invalid value"] assert_equal expected_errors, error_messages(res) end end describe "hiding input types" do let(:mask) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_input_object_type) } } it "isn't present in introspection" do query_string = %| { WithinInput: __type(name: "WithinInput") { name } Query: __type(name: "Query") { fields { name, args { name } } } __schema { types { name } } } | res = MaskHelpers.query_with_mask(query_string, mask) assert_nil res["data"]["WithinInput"], "The type isn't accessible by name" languages_arg_names = res["data"]["Query"]["fields"].find { |f| f["name"] == "languages" }["args"].map { |a| a["name"] } refute_includes languages_arg_names, "within", "Arguments that point to it are gone" type_names = res["data"]["__schema"]["types"].map { |t| t["name"] } refute_includes type_names, "WithinInput", "It isn't in the schema's types" end it "isn't a valid input" do query_string = %| query findLanguages($nearby: WithinInput!) { languages(within: $nearby) { name } } | res = MaskHelpers.query_with_mask(query_string, mask) expected_errors = [ "WithinInput isn't a defined input type (on $nearby)", "Field 'languages' doesn't accept argument 'within'", "Variable $nearby is declared by findLanguages but not used", ] assert_equal expected_errors, error_messages(res) end end describe "hiding enum values" do let(:mask) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_enum_value) } } it "isn't present in introspection" do query_string = %| { Manner: __type(name: "Manner") { enumValues { name } } __schema { types { enumValues { name } } } } | res = MaskHelpers.query_with_mask(query_string, mask) manner_values = res["data"]["Manner"]["enumValues"] .map { |v| v["name"] } schema_values = res["data"]["__schema"]["types"] .map { |t| t["enumValues"] || [] } .flatten .map { |v| v["name"] } refute_includes manner_values, "TRILL", "It's not present on __type" refute_includes schema_values, "TRILL", "It's not present in __schema" end it "isn't a valid literal input" do query_string = %| { phonemes(manners: [STOP, TRILL]) { symbol } } | res = MaskHelpers.query_with_mask(query_string, mask) # It's not a good error message ... but it's something! expected_errors = [ "Argument 'manners' on Field 'phonemes' has an invalid value ([STOP, TRILL]). Expected type '[Manner!]'.", ] assert_equal expected_errors, error_messages(res) end it "isn't a valid default value" do query_string = %| query getPhonemes($manners: [Manner!] = [STOP, TRILL]){ phonemes(manners: $manners) { symbol } } | res = MaskHelpers.query_with_mask(query_string, mask) expected_errors = ["Expected \"TRILL\" to be one of: STOP, AFFRICATE, FRICATIVE, APPROXIMANT, VOWEL"] assert_equal expected_errors, error_messages(res) end it "isn't a valid variable input" do query_string = %| query getPhonemes($manners: [Manner!]!) { phonemes(manners: $manners) { symbol } } | res = MaskHelpers.query_with_mask(query_string, mask, variables: { "manners" => ["STOP", "TRILL"] }) # It's not a good error message ... but it's something! expected_errors = [ "Variable $manners of type [Manner!]! was provided invalid value for 1 (Expected \"TRILL\" to be one of: STOP, AFFRICATE, FRICATIVE, APPROXIMANT, VOWEL)", ] assert_equal expected_errors, error_messages(res) end it "raises a runtime error" do query_string = %| { unit(name: "Uvular Trill") { ... on Phoneme { manner } } } | expected_class = MaskHelpers::MannerType::UnresolvedValueError assert_raises(expected_class) { MaskHelpers.query_with_mask(query_string, mask) } end end describe "multiple filters" do let(:visible_enum_value) { ->(member, ctx) { !MaskHelpers.has_flag?(member, :hidden_enum_value) } } let(:visible_abstract_type) { ->(member, ctx) { !MaskHelpers.has_flag?(member, :hidden_abstract_type) } } let(:hidden_input_object) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_input_object_type) } } let(:hidden_type) { ->(member, ctx) { MaskHelpers.has_flag?(member, :hidden_type) } } let(:query_str) { <<-GRAPHQL { enum: __type(name: "Manner") { enumValues { name } } input: __type(name: "WithinInput") { name } abstractType: __type(name: "Grapheme") { interfaces { name } } type: __type(name: "Phoneme") { name } } GRAPHQL } describe "multiple filters for execution" do it "applies all of them" do res = MaskHelpers.run_query( query_str, context: { except: MaskHelpers.build_mask( only: [visible_enum_value, visible_abstract_type], except: [hidden_input_object, hidden_type], ) }, ) assert_nil res["data"]["input"] enum_values = res["data"]["enum"]["enumValues"].map { |v| v["name"] } assert_equal 5, enum_values.length refute_includes enum_values, "TRILL" # These are also filtered out: assert_equal 0, res["data"]["abstractType"]["interfaces"].length assert_nil res["data"]["type"] end end describe "adding filters in instrumentation" do it "applies only/except filters" do except = MaskHelpers.build_mask( only: [visible_enum_value], except: [hidden_input_object], ) res = MaskHelpers.run_query(query_str, context: { except: except }) assert_nil res["data"]["input"] enum_values = res["data"]["enum"]["enumValues"].map { |v| v["name"] } assert_equal 5, enum_values.length refute_includes enum_values, "TRILL" # These are unaffected: assert_includes res["data"]["abstractType"]["interfaces"].map { |i| i["name"] }, "LanguageMember" assert_equal "Phoneme", res["data"]["type"]["name"] end it "applies multiple filters" do context = { only: [visible_enum_value, visible_abstract_type], except: [hidden_input_object, hidden_type], } res = MaskHelpers.run_query(query_str, context: context) assert_nil res["data"]["input"] enum_values = res["data"]["enum"]["enumValues"].map { |v| v["name"] } assert_equal 5, enum_values.length refute_includes enum_values, "TRILL" # These are also filtered out: assert_equal 0, res["data"]["abstractType"]["interfaces"].length assert_nil res["data"]["type"] end end end describe "NullWarden" do it "implements all Warden methods" do warden_methods = GraphQL::Schema::Warden.instance_methods - Object.methods warden_methods.each do |method_name| warden_params = GraphQL::Schema::Warden.instance_method(method_name).parameters assert GraphQL::Schema::Warden::NullWarden.method_defined?(method_name), "Null warden also responds to #{method_name} (#{warden_params})" assert_equal warden_params, GraphQL::Schema::Warden::NullWarden.instance_method(method_name).parameters,"#{method_name} has the same parameters" end end end describe "PassThruWarden is used when no warden is used" do it "uses PassThruWarden when a hash is used for context" do assert_equal GraphQL::Schema::Warden::PassThruWarden, GraphQL::Schema::Warden.from_context({}) end it "uses PassThruWarden when a warden on the context nor query" do context = GraphQL::Query::Context.new(query: OpenStruct.new(schema: GraphQL::Schema.new), values: {}) assert_equal GraphQL::Schema::Warden::PassThruWarden, GraphQL::Schema::Warden.from_context(context) end end it "doesn't hide subclasses of invisible objects" do identifiable = Module.new do
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
true
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/field_extension_spec.rb
spec/graphql/schema/field_extension_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::FieldExtension do module FilterTestSchema class DoubleFilter < GraphQL::Schema::FieldExtension def after_resolve(object:, value:, arguments:, context:, memo:) value * 2 end end class PowerOfFilter < GraphQL::Schema::FieldExtension def after_resolve(object:, value:, arguments:, context:, memo:) value**options.fetch(:power, 2) end end class MultiplyByOption < GraphQL::Schema::FieldExtension def after_resolve(object:, value:, arguments:, context:, memo:) value * options[:factor] end end class MultiplyByArgument < GraphQL::Schema::FieldExtension def apply field.argument(:factor, Integer) end def resolve(object:, arguments:, context:) factor = arguments[:factor] yield(object, arguments, factor) end def after_resolve(object:, value:, arguments:, context:, memo:) value * memo end end class MultiplyByArgumentUsingResolve < GraphQL::Schema::FieldExtension def apply field.argument(:factor, Integer) end # `yield` returns the user-returned value # This method's return value is passed along def resolve(object:, arguments:, context:) factor = arguments[:factor] yield(object, arguments) * factor end end class MultiplyByArgumentUsingAfterResolve < GraphQL::Schema::FieldExtension def apply field.argument(:factor, Integer) end def resolve(object:, arguments:, context:) new_arguments = arguments.dup new_arguments.delete(:factor) yield(object, new_arguments, { original_arguments: arguments}) end def after_resolve(object:, value:, arguments:, context:, memo:) value * memo[:original_arguments][:factor] end end class ExtendsArguments < GraphQL::Schema::FieldExtension def resolve(object:, arguments:, **_rest) new_args = arguments.dup new_args[:extended] = true yield(object, new_args) end def after_resolve(arguments:, context:, value:, **_rest) context[:extended_args] = arguments[:extended] value end end class ShortcutsResolve < GraphQL::Schema::FieldExtension def resolve(**_args) options[:shortcut_value] end end class ObjectClassExtension < GraphQL::Schema::FieldExtension def resolve(object:, **_args) object.class.name end def after_resolve(value:, object:, **_args) [object.class.name, value] end end class AddNestedExtensionExtension < GraphQL::Schema::FieldExtension def apply field.extension(NestedExtension) end class NestedExtension < GraphQL::Schema::FieldExtension def resolve(**_args) 1 end end end class BaseObject < GraphQL::Schema::Object end class Query < BaseObject field :doubled, Integer, null: false, resolver_method: :pass_thru do extension(DoubleFilter) argument :input, Integer end field :square, Integer, null: false, resolver_method: :pass_thru, extensions: [PowerOfFilter] do argument :input, Integer end field :cube, Integer, null: false, resolver_method: :pass_thru do extension(PowerOfFilter, power: 3) argument :input, Integer end field :tripled_by_option, Integer, null: false, resolver_method: :pass_thru do extension(MultiplyByOption, factor: 3) argument :input, Integer end field :tripled_by_option2, Integer, null: false, resolver_method: :pass_thru, extensions: [{ MultiplyByOption => { factor: 3 } }] do argument :input, Integer end field :multiply_input, Integer, null: false, resolver_method: :pass_thru, extensions: [MultiplyByArgument] do argument :input, Integer end field :multiply_input2, Integer, null: false, resolver_method: :pass_thru, extensions: [MultiplyByArgumentUsingResolve] do argument :input, Integer end def pass_thru(input:, **args) input # return it as-is, it will be modified by extensions end field :multiply_input3, Integer, null: false, resolver_method: :pass_thru_without_splat, extensions: [MultiplyByArgumentUsingAfterResolve] do argument :input, Integer end # lack of kwargs splat demonstrates the extended arguments are passed to the resolver method def pass_thru_without_splat(input:) input end field :multiple_extensions, Integer, null: false, resolver_method: :pass_thru, extensions: [DoubleFilter, { MultiplyByOption => { factor: 3 } }] do argument :input, Integer end field :extended_then_shortcut, Integer do extension ExtendsArguments extension ShortcutsResolve, shortcut_value: 3 end field :object_class_test, [String], null: false, extensions: [ObjectClassExtension] field :nested_extension, Integer, null: false, extensions: [AddNestedExtensionExtension] end class Schema < GraphQL::Schema query(Query) end end def exec_query(query_str, **kwargs) FilterTestSchema::Schema.execute(query_str, **kwargs) end describe "object" do it "is the schema type object" do res = exec_query("{ objectClassTest }") assert_equal ["FilterTestSchema::Query", "FilterTestSchema::Query"], res["data"]["objectClassTest"] end end describe "reading" do it "has a reader method" do field = FilterTestSchema::Query.fields["multiplyInput"] assert_equal 1, field.extensions.size assert_instance_of FilterTestSchema::MultiplyByArgument, field.extensions.first end end describe "passing along extended arguments" do it "works even when shortcut" do ctx = {} res = exec_query("{ extendedThenShortcut }", context: ctx) assert_equal 3, res["data"]["extendedThenShortcut"] assert_equal true, ctx[:extended_args] end end describe "modifying return values" do it "returns the modified value" do res = exec_query("{ doubled(input: 5) }") assert_equal 10, res["data"]["doubled"] end it "returns the modified value from `yield`" do res = exec_query("{ multiplyInput2(input: 5, factor: 5) }") assert_equal 25, res["data"]["multiplyInput2"] end it "has access to config options" do # The factor of three came from an option res = exec_query("{ tripledByOption(input: 4) }") assert_equal 12, res["data"]["tripledByOption"] end it "supports extension with options via extensions kwarg" do # The factor of three came from an option res = exec_query("{ tripledByOption2(input: 4) }") assert_equal 12, res["data"]["tripledByOption2"] end it "provides an empty hash as default options" do res = exec_query("{ square(input: 4) }") assert_equal 16, res["data"]["square"] res = exec_query("{ cube(input: 4) }") assert_equal 64, res["data"]["cube"] end it "can hide arguments from resolve methods" do res = exec_query("{ multiplyInput(input: 3, factor: 5) }") assert_equal 15, res["data"]["multiplyInput"] end it "calls the resolver method with the extended arguments" do res = exec_query("{ multiplyInput3(input: 3, factor: 5) }") assert_equal 15, res["data"]["multiplyInput3"] end it "supports multiple extensions via extensions kwarg" do # doubled then multiplied by 3 specified via option res = exec_query("{ multipleExtensions(input: 3) }") assert_equal 18, res["data"]["multipleExtensions"] end end describe "nested extension in apply method" do it "applies the nested extension" do res = exec_query("{ nestedExtension }") assert_equal 1, res["data"]["nestedExtension"] end end describe "after_define" do class AfterDefineThing < GraphQL::Schema::Object class AfterDefineExtension < GraphQL::Schema::FieldExtension attr_reader :apply_arguments_count, :after_define_arguments_count def apply @apply_arguments_count = field.all_argument_definitions.count end def after_define @after_define_arguments_count = field.all_argument_definitions.count end end field :with_extension, String, extensions: [AfterDefineExtension] do argument :something, ID end field :with_extension_2, String do extension(AfterDefineExtension) argument :something, ID end field :with_extension_3, String do argument :something, ID extension(AfterDefineExtension) end field :without_extension, String do argument :something, ID end end it "is applied after the define block when using `extensions: [...]`" do with_extension = AfterDefineThing.get_field("withExtension") ext = with_extension.extensions.first assert_equal 0, ext.apply_arguments_count assert_equal 1, ext.after_define_arguments_count assert ext.frozen? end it "applies in Ruby order when added in the define block" do with_extension_2_ext = AfterDefineThing.get_field("withExtension2").extensions.first assert_equal 0, with_extension_2_ext.apply_arguments_count assert_equal 1, with_extension_2_ext.after_define_arguments_count assert with_extension_2_ext.frozen? with_extension_3_ext = AfterDefineThing.get_field("withExtension3").extensions.first assert_equal 1, with_extension_3_ext.apply_arguments_count assert_equal 1, with_extension_3_ext.after_define_arguments_count assert with_extension_3_ext.frozen? end it "is called immediately when using `field.extension(...)`" do without_extension = AfterDefineThing.get_field("withoutExtension") without_extension.extension(AfterDefineThing::AfterDefineExtension) ext = without_extension.extensions.first assert_equal 1, ext.apply_arguments_count assert_equal 1, ext.after_define_arguments_count assert ext.frozen? end end describe ".default_argument" do class DefaultArgumentThing < GraphQL::Schema::Object class DefaultArgumentExtension < GraphQL::Schema::FieldExtension default_argument :query, String, required: false end field :search_1, String, extensions: [DefaultArgumentExtension] field :search_2, String, extensions: [DefaultArgumentExtension] do argument :query, String end end it "adds an argument if one wasn't given in the definition block" do search_1 = DefaultArgumentThing.get_field("search1") assert_equal [:query], search_1.extensions.first.added_default_arguments assert_equal GraphQL::Types::String, search_1.get_argument("query").type search_2 = DefaultArgumentThing.get_field("search2") assert_equal [], search_2.extensions.first.added_default_arguments assert_equal GraphQL::Types::String.to_non_null_type, search_2.get_argument("query").type end end describe ".extras" do class ExtensionExtrasSchema < GraphQL::Schema class AstNodeExtension < GraphQL::Schema::FieldExtension extras [:ast_node] def resolve(object:, arguments:, context:, **rest) context[:last_ast_node] = arguments[:ast_node] yield(object, arguments) end end class AnotherAstNodeExtension < AstNodeExtension def resolve(object:, arguments:, context:, **rest) context[:other_last_ast_node] = arguments[:ast_node] yield(object, arguments) end end class Query < GraphQL::Schema::Object field :f1, Int, extensions: [AstNodeExtension] do argument :i1, Int end def f1(i1:) i1 end field :f2, Int, extensions: [AstNodeExtension], extras: [:ast_node] def f2(ast_node:) (ast_node.alias || "").size end field :f3, Int, extensions: [AstNodeExtension, AnotherAstNodeExtension] do argument :i1, Int end def f3(i1:) i1 end end query(Query) end it "appends to the field's extras, but removes them when resolving" do assert_equal [:ast_node], ExtensionExtrasSchema::Query.get_field("f1").extras res = ExtensionExtrasSchema.execute("{ f1(i1: 1) }") assert_equal 1, res["data"]["f1"] assert_instance_of GraphQL::Language::Nodes::Field, res.context[:last_ast_node] assert_equal "f1", res.context[:last_ast_node].name end it "allows already-defined extras to pass thru" do res = ExtensionExtrasSchema.execute("{ something: f2 }") assert_equal 9, res["data"]["something"] assert_instance_of GraphQL::Language::Nodes::Field, res.context[:last_ast_node] assert_equal "f2", res.context[:last_ast_node].name end it "works with multiple extensions" do res = ExtensionExtrasSchema.execute("{ f3(i1: 3) }") assert_equal 3, res["data"]["f3"] assert_instance_of GraphQL::Language::Nodes::Field, res.context[:last_ast_node] assert_equal "f3", res.context[:last_ast_node].name assert_instance_of GraphQL::Language::Nodes::Field, res.context[:other_last_ast_node] assert_equal "f3", res.context[:other_last_ast_node].name end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/ractor_shareable_spec.rb
spec/graphql/schema/ractor_shareable_spec.rb
# frozen_string_literal: true require "spec_helper" if RUN_RACTOR_TESTS describe GraphQL::Schema::RactorShareable do class RactorExampleSchema < GraphQL::Schema class CustomError < RuntimeError; end class SomeEnum < GraphQL::Schema::Enum value :A value :B end class Query < GraphQL::Schema::Object field :i, Int, fallback_value: 1 field :e, SomeEnum, fallback_value: "A" field :error_1, String def error_1 raise GraphQL::ExecutionError, "Boom!" end field :error_2, String def error_2 raise CustomError end end query(Query) validate_timeout(nil) # Timeout doesn't work in non-main Ractors use GraphQL::Schema::Visibility, preload: true, profiles: { nil => {} } rescue_from(CustomError) { "Something went wrong" } extend GraphQL::Schema::RactorShareable end it "can access some basic GraphQL objects" do ractor = Ractor.new do parent = Ractor.receive query = GraphQL::Query.new(RactorExampleSchema, "{ __typename i e }" ) parent.send(query.class.name) result = query.result.to_h parent.send(result) rescue StandardError => err puts err.message puts err.backtrace parent.send(err) end ractor.send(Ractor.current) assert_equal "GraphQL::Query", Ractor.receive expected_result = { "data" => { "__typename" => "Query", "i" => 1, "e" => "A" } } assert_graphql_equal expected_result, Ractor.receive end it "can handle runtime errors" do ractor = Ractor.new do parent = Ractor.receive result = RactorExampleSchema.execute("{ error1 error2 }") parent.send(result.to_h) rescue StandardError => err puts err.message puts err.backtrace parent.send(err) end ractor.send(Ractor.current) expected_result = { "errors" => [ { "message" => "Boom!", "locations" => [{"line" => 1, "column" => 3}], "path" => ["error1"] } ], "data" => { "error1" => nil, "error2" => "Something went wrong" } } assert_graphql_equal expected_result, Ractor.receive end it "can get schema members by name" do ractor = Ractor.new do parent = Ractor.receive parent.send(RactorExampleSchema.get_field("Query", "__typename").class.name) parent.send(RactorExampleSchema.get_type("Query").class.name) parent.send(RactorExampleSchema.get_field("Query", "i").class.name) parent.send([ RactorExampleSchema.query.graphql_name, RactorExampleSchema.mutation ]) rescue StandardError => err puts err.message puts err.backtrace parent.send(err.message) end ractor.send(Ractor.current) assert_equal "GraphQL::Schema::Field", Ractor.receive assert_equal "Class", Ractor.receive assert_equal "GraphQL::Schema::Field", Ractor.receive assert_equal ["Query", nil], Ractor.receive end it "can parse a schema string to ast" do schema_str = Dummy::Schema.to_definition ractor = Ractor.new do parent = Ractor.receive inner_schema_str = Ractor.receive schema_ast = GraphQL.parse(inner_schema_str) Ractor.make_shareable(schema_ast) parent.send(schema_ast) end ractor.send(Ractor.current) ractor.send(schema_str) parsed_schema_ast = Ractor.receive assert_equal schema_str.chomp, parsed_schema_ast.to_query_string end it "doesn't poison other schemas" do new_schema = Class.new(GraphQL::Schema) do q = Class.new(GraphQL::Schema::Object) { graphql_name("Query") field :f, Float } query(q) end assert_equal "Query", new_schema.execute("{ __typename @include(if: true) }")["data"]["__typename"] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/type_expression_spec.rb
spec/graphql/schema/type_expression_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::TypeExpression do let(:ast_node) { document = GraphQL.parse("query dostuff($var: #{type_name}) { id } ") document.definitions.first.variables.first.type } let(:type_expression_result) { Dummy::Schema.type_from_ast(ast_node) } describe "#type" do describe "simple types" do let(:type_name) { "DairyProductInput" } it "it gets types from the provided types" do assert_equal(Dummy::DairyProductInput, type_expression_result) end end describe "non-null types" do let(:type_name) { "String!"} it "makes non-null types" do assert_equal(GraphQL::Types::String.to_non_null_type, type_expression_result) end end describe "list types" do let(:type_name) { "[DairyAnimal!]!" } it "makes list types" do expected = Dummy::DairyAnimal .to_non_null_type .to_list_type .to_non_null_type assert_equal(expected, type_expression_result) end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/build_type_spec.rb
spec/graphql/schema/member/build_type_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Member::BuildType do describe ".parse_type" do it "resolves a string type from a string" do assert_equal GraphQL::Types::String, GraphQL::Schema::Member::BuildType.parse_type("String", null: true) end it "resolves an integer type from a string" do assert_equal GraphQL::Types::Int, GraphQL::Schema::Member::BuildType.parse_type("Integer", null: true) end it "resolves a float type from a string" do assert_equal GraphQL::Types::Float, GraphQL::Schema::Member::BuildType.parse_type("Float", null: true) end it "resolves a boolean type from a string" do assert_equal GraphQL::Types::Boolean, GraphQL::Schema::Member::BuildType.parse_type("Boolean", null: true) end it "resolves an interface type from a string" do assert_equal Jazz::BaseInterface, GraphQL::Schema::Member::BuildType.parse_type("Jazz::BaseInterface", null: true) end it "resolves an object type from a class" do assert_equal Jazz::BaseObject, GraphQL::Schema::Member::BuildType.parse_type(Jazz::BaseObject, null: true) end it "resolves an object type from a string" do assert_equal Jazz::BaseObject, GraphQL::Schema::Member::BuildType.parse_type("Jazz::BaseObject", null: true) end it "resolves a nested object type from a string" do assert_equal Jazz::Introspection::NestedType, GraphQL::Schema::Member::BuildType.parse_type("Jazz::Introspection::NestedType", null: true) end it "resolves a deeply nested object type from a string" do assert_equal Jazz::Introspection::NestedType::DeeplyNestedType, GraphQL::Schema::Member::BuildType.parse_type("Jazz::Introspection::NestedType::DeeplyNestedType", null: true) end it "resolves a list type from an array of classes" do assert_instance_of GraphQL::Schema::List, GraphQL::Schema::Member::BuildType.parse_type([Jazz::BaseObject], null: true) end it "resolves a list type from an array of strings" do assert_instance_of GraphQL::Schema::List, GraphQL::Schema::Member::BuildType.parse_type(["Jazz::BaseObject"], null: true) end end describe ".to_type_name" do it "works with lists and non-nulls" do t = Class.new(GraphQL::Schema::Object) do graphql_name "T" end req_t = GraphQL::Schema::NonNull.new(t) list_req_t = GraphQL::Schema::List.new(req_t) assert_equal "T", GraphQL::Schema::Member::BuildType.to_type_name(list_req_t) end end describe ".camelize" do it "keeps a string that does not contain underscore intact" do s = "graphQL" assert_equal s, GraphQL::Schema::Member::BuildType.camelize(s) end it "keeps an underscore itself intact" do s = "_" assert_equal s, GraphQL::Schema::Member::BuildType.camelize(s) end it "converts a string that contains underscore into a camelized one" do s = "graph_ql" assert_equal "graphQl", GraphQL::Schema::Member::BuildType.camelize(s) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/has_unresolved_type_error_spec.rb
spec/graphql/schema/member/has_unresolved_type_error_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Member::HasUnresolvedTypeError do it "adds error classes to interfaces and unions" do assert_equal Jazz::NamedEntity::UnresolvedTypeError.superclass, GraphQL::UnresolvedTypeError assert_equal Jazz::PerformingAct::UnresolvedTypeError.superclass, GraphQL::UnresolvedTypeError assert Jazz::NamedEntity.const_defined?(:UnresolvedTypeError, false) assert Jazz::PerformingAct.const_defined?(:UnresolvedTypeError, false) refute Jazz::Musician.const_defined?(:UnresolvedTypeError, false) refute Jazz::Family.const_defined?(:UnresolvedTypeError, false) refute Jazz::Key.const_defined?(:UnresolvedTypeError, false) refute Jazz::InspectableInput.const_defined?(:UnresolvedTypeError, false) end it "doesn't add an error class to anonymous classes" do anon_int = Module.new do include GraphQL::Schema::Interface graphql_name "AnonInt" end obj_t = Class.new(GraphQL::Schema::Object) do graphql_name "Obj" implements anon_int end anon_union = Class.new(GraphQL::Schema::Union) do graphql_name "AnonUnion" possible_types(obj_t) end query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :anon_union, anon_union, fallback_value: 1 field :anon_int, anon_int, fallback_value: 1 end schema = Class.new(GraphQL::Schema) do query(query_type) def self.resolve_type(abs_t, obj, ctx) ctx.schema.query end end err = assert_raises do schema.execute("{ anonUnion { __typename } }") end assert_equal "GraphQL::UnresolvedTypeError", err.class.name err = assert_raises do schema.execute("{ anonInt { __typename } }") end assert_equal "GraphQL::UnresolvedTypeError", err.class.name end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/type_system_helpers_spec.rb
spec/graphql/schema/member/type_system_helpers_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Member::TypeSystemHelpers do let(:object) { Class.new(GraphQL::Schema::Object) do graphql_name "Thing" field :int, Integer field :int2, Integer, null: false field :int_list, [Integer] field :int_list2, [Integer], null: false end } let(:int_field) { object.fields["int"] } let(:int2_field) { object.fields["int2"] } let(:int_list_field) { object.fields["intList"] } let(:int_list2_field) { object.fields["intList2"] } describe "#list?" do it "is true for lists, including non-null lists, otherwise false" do assert int_list_field.type.list? assert int_list2_field.type.list? refute int_field.type.list? refute int2_field.type.list? end end describe "#non_null?" do it "is true for required types" do assert int2_field.type.non_null? assert int_list2_field.type.non_null? refute int_field.type.non_null? refute int_list_field.type.non_null? end end describe "#kind" do let(:pairs) {{ GraphQL::Schema::Object => "OBJECT", GraphQL::Schema::Union => "UNION", GraphQL::Schema::Interface => "INTERFACE", GraphQL::Schema::Enum => "ENUM", GraphQL::Schema::InputObject => "INPUT_OBJECT", GraphQL::Schema::Scalar => "SCALAR", }} it "returns the TypeKind instance" do pairs.each do |type_class, type_kind_name| type = if type_class.is_a?(Class) Class.new(type_class) else Module.new { include(type_class) } end assert_equal type_kind_name, type.kind.name end assert_equal "LIST", GraphQL::Schema::Object.to_list_type.kind.name assert_equal "NON_NULL", GraphQL::Schema::Object.to_non_null_type.kind.name end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/relay_shortcuts_spec.rb
spec/graphql/schema/member/relay_shortcuts_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Member::RelayShortcuts do describe ".connection_type_class, .edge_type_class" do class CustomBaseConnectionType < GraphQL::Types::Relay::BaseConnection end class CustomEdgeType < GraphQL::Types::Relay::BaseEdge end class ConnectionTypeBaseObject < GraphQL::Schema::Object connection_type_class CustomBaseConnectionType edge_type_class CustomEdgeType end class ImplementationTypeObject < ConnectionTypeBaseObject implements GraphQL::Types::Relay::Node end module ConnectionTypeBaseInterface include GraphQL::Schema::Interface connection_type_class CustomBaseConnectionType edge_type_class CustomEdgeType end module NodeImplementingInterface include ConnectionTypeBaseInterface implements GraphQL::Types::Relay::Node end it "uses the custom class, even when Node is implemented" do assert_equal CustomBaseConnectionType, ConnectionTypeBaseObject.connection_type_class assert_equal GraphQL::Types::Relay::BaseConnection, GraphQL::Types::Relay::Node.connection_type_class assert_equal CustomBaseConnectionType, ImplementationTypeObject.connection_type_class assert_equal CustomBaseConnectionType, ConnectionTypeBaseInterface.connection_type_class assert_equal CustomBaseConnectionType, NodeImplementingInterface.connection_type_class assert_equal CustomEdgeType, ConnectionTypeBaseObject.edge_type_class assert_equal GraphQL::Types::Relay::BaseEdge, GraphQL::Types::Relay::Node.edge_type_class assert_equal CustomEdgeType, ImplementationTypeObject.edge_type_class assert_equal CustomEdgeType, ConnectionTypeBaseInterface.edge_type_class assert_equal CustomEdgeType, NodeImplementingInterface.edge_type_class end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/scoped_spec.rb
spec/graphql/schema/member/scoped_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Member::Scoped do class ScopeSchema < GraphQL::Schema class BaseObject < GraphQL::Schema::Object end class Item < BaseObject def self.scope_items(items, context) context[:scope_calls] ||= 0 context[:scope_calls] += 1 if context[:french] items.select { |i| i.name == "Trombone" } elsif context[:english] items.select { |i| i.name == "Paperclip" } elsif context[:lazy] # return everything, but make the runtime wait for it, # and add a flag for confirming it was called ->() { context[:proc_called] = true items } else # boot everything items.reject { true } end end def self.authorized?(obj, ctx) if ctx[:allow_unscoped] true else raise "This should never be called (#{ctx[:current_path]}, #{ctx[:current_field].path})" end end reauthorize_scoped_objects(false) field :name, String, null: false end class ReauthorizeItem < Item reauthorize_scoped_objects(true) def self.authorized?(_obj, context) context[:was_authorized] = true true end end class FrenchItem < Item def self.scope_items(items, context) super(items, {french: true}) end end class Equipment < BaseObject field :designation, String, null: false, method: :name end class BaseUnion < GraphQL::Schema::Union end class Thing < BaseUnion def self.scope_items(items, context) l = context.fetch(:first_letter) items.select { |i| i.name.start_with?(l) } end possible_types Item, Equipment def self.resolve_type(item, ctx) if item.name == "Turbine" Equipment else Item end end reauthorize_scoped_objects(false) end class Query < BaseObject field :items, [Item], null: false field :unscoped_items, [Item], null: false, scope: false, resolver_method: :items field :nil_items, [Item] def nil_items nil end field :french_items, [FrenchItem], null: false, resolver_method: :items field :items_connection, Item.connection_type, null: false, resolver_method: :items def items [ OpenStruct.new(name: "Trombone"), OpenStruct.new(name: "Paperclip"), ] end field :reauthorize_items, [ReauthorizeItem], resolver_method: :items field :things, [Thing], null: false def things items + [OpenStruct.new(name: "Turbine")] end field :lazy_items, [Item], null: false field :lazy_items_connection, Item.connection_type, null: false, resolver_method: :lazy_items def lazy_items ->() { items } end end query(Query) lazy_resolve(Proc, :call) end describe ".scope_items(items, ctx)" do def get_item_names_with_context(ctx, field_name: "items") query_str = " { #{field_name} { name } } " res = ScopeSchema.execute(query_str, context: ctx) res["data"][field_name].map { |i| i["name"] } end it "applies to lists when scope: true" do assert_equal [], get_item_names_with_context({}) assert_equal ["Trombone"], get_item_names_with_context({french: true}) assert_equal ["Paperclip"], get_item_names_with_context({english: true}) end it "is bypassed when scope: false" do assert_equal ["Trombone", "Paperclip"], get_item_names_with_context({ allow_unscoped: true }, field_name: "unscopedItems") end it "returns null when the value is nil" do query_str = " { nilItems { name } } " res = ScopeSchema.execute(query_str) refute res.key?("errors") assert_nil res.fetch("data").fetch("nilItems") end it "is inherited" do assert_equal ["Trombone"], get_item_names_with_context({}, field_name: "frenchItems") end it "is called once for connection fields" do query_str = " { itemsConnection { edges { node { name } } } } " res = ScopeSchema.execute(query_str, context: {english: true}) names = res["data"]["itemsConnection"]["edges"].map { |e| e["node"]["name"] } assert_equal ["Paperclip"], names assert_equal 1, res.context[:scope_calls] query_str = " { itemsConnection { nodes { name } } } " res = ScopeSchema.execute(query_str, context: {english: true}) names = res["data"]["itemsConnection"]["nodes"].map { |e| e["name"] } assert_equal ["Paperclip"], names assert_equal 1, res.context[:scope_calls] end it "works for lazy connection values" do ctx = { lazy: true } query_str = " { itemsConnection { edges { node { name } } } } " res = ScopeSchema.execute(query_str, context: ctx) names = res["data"]["itemsConnection"]["edges"].map { |e| e["node"]["name"] } assert_equal ["Trombone", "Paperclip"], names assert_equal true, ctx[:proc_called] end it "works for lazy returned list values" do query_str = " { lazyItemsConnection { edges { node { name } } } lazyItems { name } } " res = ScopeSchema.execute(query_str, context: { french: true }) names = res["data"]["lazyItemsConnection"]["edges"].map { |e| e["node"]["name"] } assert_equal ["Trombone"], names names2 = res["data"]["lazyItems"].map { |e| e["name"] } assert_equal ["Trombone"], names2 end it "doesn't shortcut authorization when `reauthorize_scoped_objects(true)`" do query_str = "{ reauthorizeItems { name } }" res = ScopeSchema.execute(query_str, context: { french: true }) assert_equal 1, res["data"]["reauthorizeItems"].length assert_equal 1, res.context[:scope_calls] assert res.context[:was_authorized] end it "is called for abstract types" do query_str = " { things { ... on Item { name } ... on Equipment { designation } } } " res = ScopeSchema.execute(query_str, context: {first_letter: "T"}) things = res["data"]["things"] assert_equal [{ "name" => "Trombone" }, {"designation" => "Turbine"}], things end it "works with lazy values" do ctx = {lazy: true} assert_equal ["Trombone", "Paperclip"], get_item_names_with_context(ctx) assert_equal true, ctx[:proc_called] end end describe "Schema::Field.scoped?" do it "prefers the override value" do assert_equal false, ScopeSchema::Query.fields["unscopedItems"].scoped? end it "defaults to true for lists" do assert_equal true, ScopeSchema::Query.fields["items"].type.list? assert_equal true, ScopeSchema::Query.fields["items"].scoped? end it "defaults to true for connections" do assert_equal true, ScopeSchema::Query.fields["itemsConnection"].connection? assert_equal true, ScopeSchema::Query.fields["itemsConnection"].scoped? end it "defaults to false for others" do assert_equal false, ScopeSchema::Item.fields["name"].scoped? end end describe "ScopeExtension#after_resolve" do it "works outside of GraphQL execution" do ctx = GraphQL::Query.new(ScopeSchema, "{ __typename }").context field = ScopeSchema::Query.fields["items"] assert field.resolve(OpenStruct.new(object: { items: [] }), {}, ctx) end end describe "skipping authorization on scoped lists" do class SkipAuthSchema < GraphQL::Schema class Book < GraphQL::Schema::Object def self.authorized?(obj, ctx) ctx[:auth_log] << [:authorized?, obj[:title]] true end def self.scope_items(list, ctx) ctx[:auth_log] << [:scope_items, list.map { |b| b[:title]}] list.dup # Skipping authorized objects requires a new object to be returned end field :title, String end class SkipAuthorizationBook < Book reauthorize_scoped_objects(false) end class ReauthorizedBook < Book reauthorize_scoped_objects(true) end class Query < GraphQL::Schema::Object field :book, Book def book { title: "Nonsense Omnibus"} end field :books, [Book] def books [{ title: "Jayber Crow" }, { title: "Hannah Coulter" }] end field :skip_authorization_books, [SkipAuthorizationBook], resolver_method: :books field :reauthorized_books, [ReauthorizedBook], resolver_method: :books field :skip_authorization_books_connection, SkipAuthorizationBook.connection_type, resolver_method: :books end query(Query) end it "runs both authorizations by default" do log = [] SkipAuthSchema.execute("{ book { title } books { title } }", context: { auth_log: log }) expected_log = [ [:authorized?, "Nonsense Omnibus"], [:scope_items, ["Jayber Crow", "Hannah Coulter"]], [:authorized?, "Jayber Crow"], [:authorized?, "Hannah Coulter"], ] assert_equal expected_log, log end it "skips self.authorized? when configured" do log = [] SkipAuthSchema.execute("{ skipAuthorizationBooks { title } }", context: { auth_log: log }) assert_equal [[:scope_items, ["Jayber Crow", "Hannah Coulter"]]], log end it "can be re-enabled in subclasses" do log = [] SkipAuthSchema.execute("{ reauthorizedBooks { title } }", context: { auth_log: log }) expected_log = [ [:scope_items, ["Jayber Crow", "Hannah Coulter"]], [:authorized?, "Jayber Crow"], [:authorized?, "Hannah Coulter"], ] assert_equal expected_log, log end it "skips auth in connections" do log = [] SkipAuthSchema.execute("{ skipAuthorizationBooksConnection(first: 10) { nodes { title } } }", context: { auth_log: log }) assert_equal [[:scope_items, ["Jayber Crow", "Hannah Coulter"]]], log end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/has_arguments_spec.rb
spec/graphql/schema/member/has_arguments_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Member::HasArguments do class DefaultArgumentAuthSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :add, Int do argument :left, Int argument :right, Int, required: false, default_value: 1 do def authorized?(_object, _arg_value, context) !!context[:is_authorized] end end end def add(left:, right:) left + right end end query(Query) end it "doesn't require authorization when arguments with default values aren't present in the query" do assert_equal 5, DefaultArgumentAuthSchema.execute("{ add(left: 3, right: 2) }", context: { is_authorized: true })["data"].fetch("add") assert_nil DefaultArgumentAuthSchema.execute("{ add(left: 3, right: 2) }", context: { is_authorized: false })["data"].fetch("add") assert_equal 4, DefaultArgumentAuthSchema.execute("{ add(left: 3) }", context: { is_authorized: false })["data"].fetch("add") end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/member/has_dataloader_spec.rb
spec/graphql/schema/member/has_dataloader_spec.rb
# frozen_string_literal: true require "spec_helper" if testing_rails? describe GraphQL::Schema::Member::HasDataloader do class DataloaderExample include GraphQL::Schema::Member::HasDataloader def initialize(dataloader, object = nil) @context = OpenStruct.new(dataloader: dataloader) @object = object end attr_reader :context, :object end class PlusSource < GraphQL::Dataloader::Source def fetch(keys) res = keys.reduce(&:+) keys.map { |k| res } end end it_dataloads "loads records with dataload_record" do |d| example = DataloaderExample.new(d) assert_equal "Homey", example.dataload_record(Album, 4).name assert_equal 4, example.dataload_record(Album, "Homey", find_by: :name).id end it_dataloads "loads association with dataload_association" do |d| album1 = Album.find(1) example = DataloaderExample.new(d, album1) assert_equal "Vulfpeck", example.dataload_association(:band).name, "Defaults to record = object" album = Album.find(4) assert_equal "Chon", example.dataload_association(album, :band).name album.reload assert_nil example.dataload_association(album, :band, scope: Band.country) end it_dataloads "calls any source with dataload..." do |d| example = DataloaderExample.new(d) d.with(PlusSource).request(2) d.with(PlusSource).request(3) assert_equal 9, example.dataload(PlusSource, 4) assert_equal 5, example.dataload(PlusSource, 5) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/visibility/profile_spec.rb
spec/graphql/schema/visibility/profile_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Visibility::Profile do class ProfileSchema < GraphQL::Schema class Thing < GraphQL::Schema::Object field :name, String, method: :to_s end class Query < GraphQL::Schema::Object field :thing, Thing, fallback_value: :Something field :greeting, String end query(Query) use GraphQL::Schema::Visibility end it "only loads the types it needs" do query = GraphQL::Query.new(ProfileSchema, "{ thing { name } }", use_visibility_profile: true) assert_equal [], query.types.loaded_types res = query.result assert_equal "Something", res["data"]["thing"]["name"] assert_equal [], query.types.loaded_types.map(&:graphql_name).sort query = GraphQL::Query.new(ProfileSchema, "{ __schema { types { name }} }", use_visibility_profile: true) assert_equal [], query.types.loaded_types res = query.result assert_equal 12, res["data"]["__schema"]["types"].size loaded_type_names = query.types.loaded_types.map(&:graphql_name).reject { |n| n.start_with?("__") }.sort assert_equal ["Boolean", "Query", "String", "Thing"], loaded_type_names end describe "when multiple field implementations are all hidden" do class EnsureLoadedFixSchema < GraphQL::Schema class BaseField < GraphQL::Schema::Field def visible?(...) false end end class Query < GraphQL::Schema::Object field_class(BaseField) field :f1, String field :f1, String end query(Query) use GraphQL::Schema::Visibility end it "handles it without raising an error" do result = EnsureLoadedFixSchema.execute("{ f1 }") assert 1, result["errors"].size end end describe "using configured contexts" do class ProfileContextSchema < GraphQL::Schema class << self attr_accessor :modify_visibility_context attr_accessor :last_visibility_context end class Query < GraphQL::Schema::Object def self.visible?(ctx) ProfileContextSchema.last_visibility_context = JSON.dump(ctx) if ProfileContextSchema.modify_visibility_context ctx[:this] = :breaks end !!ctx[:internal] end field :inspect_context, String def inspect_context JSON.dump(context.to_h) end end query(Query) use GraphQL::Schema::Visibility, profiles: { internal: { internal: true }, public: { public: true }, public2: { public: true }, # This is for testing FrozenError below } end before do ProfileContextSchema.modify_visibility_context = false ProfileContextSchema.last_visibility_context = nil end it "uses the configured context for `visible?` calls, not the query context" do res = ProfileContextSchema.execute("{ inspectContext }", context: { visibility_profile: :internal }) assert_equal '{"visibility_profile":"internal"}', res["data"]["inspectContext"] assert_equal '{"internal":true,"visibility_profile":"internal"}', ProfileContextSchema.last_visibility_context res = ProfileContextSchema.execute("{ inspectContext }", context: { internal: true, visibility_profile: :public }) assert_equal ["Schema is not configured for queries"], res["errors"].map { |e| e["message"] } assert_equal '{"public":true,"visibility_profile":"public"}', ProfileContextSchema.last_visibility_context end it "freezes profile contexts" do ProfileContextSchema.modify_visibility_context = true assert_raises FrozenError do ProfileContextSchema.execute("{ inspectContext }", context: { visibility_profile: :public2 }) end assert_equal '{"public":true,"visibility_profile":"public2"}', ProfileContextSchema.last_visibility_context end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/field/connection_extension_spec.rb
spec/graphql/schema/field/connection_extension_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Field::ConnectionExtension do class ConnectionShortcutSchema < GraphQL::Schema class ShortcutResolveExtension < GraphQL::Schema::FieldExtension def resolve(arguments:, **rest) collection = ["a", "b", "c", "d", "e"] if (filter = arguments[:starting_with]) collection.select! { |x| x.start_with?(filter) } end collection end end class CustomStringConnection < GraphQL::Types::Relay::BaseConnection edge_type(GraphQL::Types::String.edge_type) field :argument_data, [String], null: false def argument_data [object.arguments.class.name, *object.arguments.keys.map(&:inspect).sort] end end class Query < GraphQL::Schema::Object field :names, CustomStringConnection, null: false, extensions: [ShortcutResolveExtension] do argument :starting_with, String, required: false end def names raise "This should never be called" end end query(Query) end it "implements connection handling even when resolve is shortcutted" do res = ConnectionShortcutSchema.execute("{ names(first: 2) { nodes } }") assert_equal ["a", "b"], res["data"]["names"]["nodes"] end it "assigns arguments to the connection instance" do res = ConnectionShortcutSchema.execute("{ names(first: 2, startingWith: \"a\") { nodes argumentData } }") assert_equal ["a"], res["data"]["names"]["nodes"] # This come through as symbols assert_equal ["Hash", ":first", ":starting_with"], res["data"]["names"]["argumentData"] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/exclusion_validator_spec.rb
spec/graphql/schema/validator/exclusion_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::ExclusionValidator do include ValidatorHelpers expectations = [ { config: { in: [1, 2, 3] }, cases: [ { query: "{ validated(value: 1) }", result: nil, error_messages: ["value is reserved"] }, { query: "{ validated(value: null) }", result: nil, error_messages: [] }, { query: "{ validated(value: 10) }", result: 10, error_messages: [] }, ] }, ] build_tests(:exclusion, Integer, expectations) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/required_validator_spec.rb
spec/graphql/schema/validator/required_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::RequiredValidator do include ValidatorHelpers expectations = [ { config: { one_of: [:a, :b, :secret] }, cases: [ { query: "{ validated: multiValidated(a: 1, b: 2) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, b."] }, { query: "{ validated: multiValidated(a: 1, b: 2, c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, b."] }, { query: "{ validated: multiValidated }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, b."] }, { query: "{ validated: multiValidated(c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, b."] }, { query: "{ validated: multiValidated(a: 1) }", result: 1, error_messages: [] }, { query: "{ validated: multiValidated(a: 1, c: 3) }", result: 4, error_messages: [] }, { query: "{ validated: multiValidated(b: 2) }", result: 2, error_messages: [] }, { query: "{ validated: multiValidated(b: 2, c: 3) }", result: 5, error_messages: [] }, ] }, { config: { one_of: [:a, [:b, :c]] }, cases: [ { query: "{ validated: multiValidated(a: 1) }", result: 1, error_messages: [] }, { query: "{ validated: multiValidated(b: 2, c: 3) }", result: 5, error_messages: [] }, { query: "{ validated: multiValidated }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: multiValidated(a: 1, b: 2, c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: multiValidated(a: 1, b: 2) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: multiValidated(a: 1, c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: multiValidated(c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: multiValidated(b: 2) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: a, (b and c)."] }, ] }, { name: "All options hidden, allow_all_hidden: true", config: { one_of: [:secret, :secret2], allow_all_hidden: true }, cases: [ { query: "{ validated: multiValidated(a: 1, b: 2) }", result: 3, error_messages: [] }, ], }, { name: "Definition order independence", config: { one_of: [[:a, :b], :c] }, cases: [ { query: "{ validated: multiValidated(c: 1) }", result: 1, error_messages: [] }, { query: "{ validated: multiValidated(a: 2, b: 3) }", result: 5, error_messages: [] }, { query: "{ validated: multiValidated }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: (a and b), c."] }, { query: "{ validated: multiValidated(a: 1, b: 2, c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: (a and b), c."] }, { query: "{ validated: multiValidated(a: 1, c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: (a and b), c."] }, { query: "{ validated: multiValidated(b: 2, c: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: (a and b), c."] }, { query: "{ validated: multiValidated(a: 3) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: (a and b), c."] }, { query: "{ validated: multiValidated(b: 2) }", result: nil, error_messages: ["multiValidated must include exactly one of the following arguments: (a and b), c."] }, ] }, { name: "Input object validation", config: { one_of: [:a, [:b, :c]] }, cases: [ { query: "{ validated: validatedInput(input: { a: 1 }) }", result: 1, error_messages: [] }, { query: "{ validated: validatedInput(input: { b: 2, c: 3 }) }", result: 5, error_messages: [] }, { query: "{ validated: validatedInput(input: { a: 1, b: 2, c: 3 }) }", result: nil, error_messages: ["ValidatedInput must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedInput(input: { a: 1, b: 2 }) }", result: nil, error_messages: ["ValidatedInput must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedInput(input: { a: 1, c: 3 }) }", result: nil, error_messages: ["ValidatedInput must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedInput(input: { c: 3 }) }", result: nil, error_messages: ["ValidatedInput must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedInput(input: { b: 2 }) }", result: nil, error_messages: ["ValidatedInput must include exactly one of the following arguments: a, (b and c)."] }, ] }, { name: "Resolver validation", config: { one_of: [:a, [:b, :c]] }, cases: [ { query: "{ validated: validatedResolver(a: 1) }", result: 1, error_messages: [] }, { query: "{ validated: validatedResolver(b: 2, c: 3) }", result: 5, error_messages: [] }, { query: "{ validated: validatedResolver(a: 1, b: 2, c: 3) }", result: nil, error_messages: ["validatedResolver must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedResolver(a: 1, b: 2) }", result: nil, error_messages: ["validatedResolver must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedResolver(a: 1, c: 3) }", result: nil, error_messages: ["validatedResolver must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedResolver(c: 3) }", result: nil, error_messages: ["validatedResolver must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedResolver(b: 2) }", result: nil, error_messages: ["validatedResolver must include exactly one of the following arguments: a, (b and c)."] }, { query: "{ validated: validatedResolver }", result: nil, error_messages: ["validatedResolver must include exactly one of the following arguments: a, (b and c)."] }, ] }, { name: "Single arg validation", config: { argument: :a, message: "A value must be given, even if it's `null` (not %{value})" }, cases: [ { query: "{ validated: validatedInput(input: { a: 1 }) }", result: 1, error_messages: [] }, { query: "{ validated: validatedInput(input: {}) }", result: nil, error_messages: ["A value must be given, even if it's `null` (not {})"] }, { query: "{ validated: validatedInput(input: { a: null }) }", result: 0, error_messages: [] }, ] } ] build_tests(:required, Integer, expectations) describe "when all arguments are hidden" do class RequiredHiddenSchema < GraphQL::Schema class BaseArgument < GraphQL::Schema::Argument def initialize(*args, always_hidden: false, **kwargs, &block) super(*args, **kwargs, &block) @always_hidden = always_hidden end def visible?(ctx) !@always_hidden end end class BaseField < GraphQL::Schema::Field argument_class(BaseArgument) end class Query < GraphQL::Schema::Object field_class(BaseField) field :one_argument, Int, fallback_value: 1 do argument :a, Int, required: :nullable, always_hidden: true end field :two_arguments, Int, fallback_value: 2 do validates required: { one_of: [:a, :b], allow_all_hidden: true } argument :a, Int, required: false, always_hidden: true argument :b, Int, required: false, always_hidden: true end field :two_arguments_error, Int, fallback_value: 2 do validates required: { one_of: [:a, :b] } argument :a, Int, required: false, always_hidden: true argument :b, Int, required: false, always_hidden: true end field :three_arguments, Int, fallback_value: 3 do validates required: { one_of: [:a, :b], allow_all_hidden: true } argument :a, Int, required: false, always_hidden: true argument :b, Int, required: false, always_hidden: true argument :c, Int end field :four_arguments, Int, fallback_value: 4 do validates required: { one_of: [[:a, :b], :c, :d], allow_all_hidden: true} argument :a, Int, required: false, always_hidden: true argument :b, Int, required: false, always_hidden: true argument :c, Int, required: false, always_hidden: true argument :d, Int, required: false, always_hidden: true end end query(Query) use GraphQL::Schema::Visibility end it "Doesn't require any of one_of to be present" do result = RequiredHiddenSchema.execute("{ threeArguments(c: 5) }") assert_equal 3, result["data"]["threeArguments"] result = RequiredHiddenSchema.execute("{ twoArguments }") assert_equal 2, result["data"]["twoArguments"] err = assert_raises GraphQL::Error do RequiredHiddenSchema.execute("{ twoArgumentsError }") end expected_message = "Query.twoArgumentsError validates `required: ...` but all required arguments were hidden.\n\nUpdate your schema definition to allow the client to see some fields or skip validation by adding `required: { ..., allow_all_hidden: true }`\n" assert_equal expected_message, err.message end it "doesn't require hidden arguments when required as a group" do result = RequiredHiddenSchema.execute("{ fourArguments }") assert_equal 4, result["data"]["fourArguments"] end it "Doesn't require hidden argument to be present" do result = RequiredHiddenSchema.execute("{ oneArgument }") assert_equal 1, result["data"]["oneArgument"] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/inclusion_validator_spec.rb
spec/graphql/schema/validator/inclusion_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::InclusionValidator do include ValidatorHelpers expectations = [ { config: { in: [1, 2, 3] }, cases: [ { query: "{ validated(value: 1) }", result: 1, error_messages: [] }, { query: "{ validated(value: null) }", result: nil, error_messages: ["value is not included in the list"] }, { query: "{ validated(value: 10) }", result: nil, error_messages: ["value is not included in the list"] }, ] }, { config: { in: [1, 2, 3], allow_null: true }, cases: [ { query: "{ validated(value: 1) }", result: 1, error_messages: [] }, { query: "{ validated(value: null) }", result: nil, error_messages: [] }, { query: "{ validated(value: 10) }", result: nil, error_messages: ["value is not included in the list"] }, ] }, ] build_tests(:inclusion, Integer, expectations) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/length_validator_spec.rb
spec/graphql/schema/validator/length_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::LengthValidator do include ValidatorHelpers it "allows blank and null" do schema = build_schema(String, {length: { minimum: 5 }, allow_blank: true}) blank_string = ValidatorHelpers::BlankString.new("") assert blank_string.blank? result = schema.execute("query($str: String!) { validated(value: $str) }", variables: { str: blank_string }) assert_equal "", result["data"]["validated"] refute result.key?("errors") result = schema.execute("query($str: String!) { validated(value: $str) }", variables: { str: nil }) refute result.key?("data") assert_equal ["Variable $str of type String! was provided invalid value"], result["errors"].map { |e| e["message"] } schema = build_schema(String, {length: { minimum: 5 }, allow_null: true, allow_blank: false}) result = schema.execute("{ validated(value: null) }") assert_nil result["data"]["validated"] refute result.key?("errors") result = schema.execute("query($str: String!) { validated(value: $str) }", variables: { str: blank_string }) assert_nil result["data"].fetch("validated") # This error message is weird, but it can be fixed by removing `minimum: 5`, which causes a redundant error message: assert_equal ["value is too short (minimum is 5), value can't be blank"], result["errors"].map { |e| e["message"] } # This string doesn't respond to blank: non_blank_string = ValidatorHelpers::NonBlankString.new("") refute non_blank_string.respond_to?(:blank?), "NonBlankString doesn't have a blank? method" result = schema.execute("query($str: String!) { validated(value: $str) }", variables: { str: non_blank_string }) assert_nil result["data"].fetch("validated") assert_equal ["value is too short (minimum is 5)"], result["errors"].map { |e| e["message"] } end it "validates minimum length" do schema = build_schema(String, {length: { minimum: 5 }}) result = schema.execute("{ validated(value: \"is-valid\") }") assert_equal "is-valid", result["data"]["validated"] refute result.key?("errors") result = schema.execute("{ validated(value: \"nono\") }") assert_nil result["data"].fetch("validated") assert_equal ["value is too short (minimum is 5)"], result["errors"].map { |e| e["message"] } end it "validates maximum length" do schema = build_schema(String, {length: { maximum: 8 }}) result = schema.execute("{ validated(value: \"is-valid\") }") assert_equal "is-valid", result["data"]["validated"] refute result.key?("errors") result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["value is too long (maximum is 8)"], result["errors"].map { |e| e["message"] } end it "rejects blank, even when within the maximum" do schema = build_schema(String, {length: { maximum: 8 }, allow_blank: false }) blank_string = ValidatorHelpers::BlankString.new("") result = schema.execute("query($str: String!) { validated(value: $str) }", variables: { str: blank_string }) assert_nil result["data"].fetch("validated") assert_equal ["value can't be blank"], result["errors"].map { |e| e["message"] } end it "validates within length" do schema = build_schema(String, {length: { within: 5..8 }}) result = schema.execute("{ validated(value: \"is-valid\") }") assert_equal "is-valid", result["data"]["validated"] refute result.key?("errors") result = schema.execute("{ validated(value: \"nono\") }") assert_nil result["data"].fetch("validated") assert_equal ["value is too short (minimum is 5)"], result["errors"].map { |e| e["message"] } result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["value is too long (maximum is 8)"], result["errors"].map { |e| e["message"] } end it "validates length is" do schema = build_schema(String, {length: { is: 8 }}) result = schema.execute("{ validated(value: \"is-valid\") }") assert_equal "is-valid", result["data"]["validated"] refute result.key?("errors") result = schema.execute("{ validated(value: \"nono\") }") assert_nil result["data"].fetch("validated") assert_equal ["value is the wrong length (should be 8)"], result["errors"].map { |e| e["message"] } result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["value is the wrong length (should be 8)"], result["errors"].map { |e| e["message"] } end it "applies custom messages" do schema = build_schema(String, {length: { is: 8, wrong_length: "Instead, make %{validated} have length %{count}" }}) result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["Instead, make value have length 8"], result["errors"].map { |e| e["message"] } schema = build_schema(String, {length: { minimum: 50, too_short: "Instead, make %{validated} have length at least %{count}" }}) result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["Instead, make value have length at least 50"], result["errors"].map { |e| e["message"] } schema = build_schema(String, {length: { maximum: 5, too_long: "Instead, make %{validated} have length less than %{count}" }}) result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["Instead, make value have length less than 5"], result["errors"].map { |e| e["message"] } schema = build_schema(String, {length: { minimum: 50, message: "NO, BAD! %{validated} %{count} %{value}" }}) result = schema.execute("{ validated(value: \"is-invalid\") }") assert_nil result["data"].fetch("validated") assert_equal ["NO, BAD! value 50 \"is-invalid\""], result["errors"].map { |e| e["message"] } end list_expectations = [ { config: { minimum: 3 }, cases: [ { query: "{ validated(value: [1, 2, 3, 4]) }", result: [1, 2, 3, 4], error_messages: [] }, { query: "{ validated(value: [1, 2]) }", result: nil, error_messages: ["value is too short (minimum is 3)"] }, ] }, { config: { maximum: 3 }, cases: [ { query: "{ validated(value: [1, 2]) }", result: [1, 2], error_messages: [] }, { query: "{ validated(value: [1, 2, 3, 4]) }", result: nil, error_messages: ["value is too long (maximum is 3)"] }, ] }, { config: { is: 3 }, cases: [ { query: "{ validated(value: [1, 2, 3]) }", result: [1, 2, 3], error_messages: [] }, { query: "{ validated(value: [1, 2]) }", result: nil, error_messages: ["value is the wrong length (should be 3)"] }, ] }, ] build_tests(:length, [Integer], list_expectations) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/allow_null_validator_spec.rb
spec/graphql/schema/validator/allow_null_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::AllowNullValidator do include ValidatorHelpers it "allows nil when permitted" do schema = build_schema(String, {length: { minimum: 5 }, allow_null: true}) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: nil }) assert_nil result["data"]["validated"] refute result.key?("errors") end it "rejects null by default" do schema = build_schema(String, {length: { minimum: 5 }}) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: nil }) assert_nil result["data"]["validated"] assert_equal ["value is too short (minimum is 5)"], result["errors"].map { |e| e["message"] } end it "can be used standalone" do schema = build_schema(String, { allow_null: false }) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: nil }) assert_nil result["data"]["validated"] assert_equal ["value can't be null"], result["errors"].map { |e| e["message"] } end it "allows nil when no validations are configured" do schema = build_schema(String, {}) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: nil }) assert_nil result["data"]["validated"] refute result.key?("errors") result = schema.execute("query { validated }") assert_nil result["data"]["validated"] refute result.key?("errors") end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/all_validator_spec.rb
spec/graphql/schema/validator/all_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::AllValidator do include ValidatorHelpers expectations = [ { config: { format: { with: /\A[a-z]+\Z/ } }, cases: [ { query: "{ validated(value: []) }", result: [], error_messages: [] }, { query: "{ validated(value: [\"abc\"]) }", result: ["abc"], error_messages: [] }, { query: "{ validated(value: [\"abc\", \"def\"]) }", result: ["abc", "def"], error_messages: [] }, { query: "{ validated(value: [\"ABC\"]) }", result: nil, error_messages: ["value is invalid"] }, { query: "{ validated(value: [\"abc\", \"DEF\"]) }", result: nil, error_messages: ["value is invalid"] }, { query: "{ validated(value: [\"abc\", \"DEF\", \"GHI\"]) }", result: nil, error_messages: ["value is invalid"] }, ], }, { config: { format: { with: /\A[a-z]+\Z/ }, length: { maximum: 2 } }, cases: [ { query: "{ validated(value: []) }", result: [], error_messages: [] }, { query: "{ validated(value: [\"a\"]) }", result: ["a"], error_messages: [] }, { query: "{ validated(value: [\"a\", \"bc\"]) }", result: ["a", "bc"], error_messages: [] }, { query: "{ validated(value: [\"AB\"]) }", result: nil, error_messages: ["value is invalid"] }, { query: "{ validated(value: [\"abc\"]) }", result: nil, error_messages: ["value is too long (maximum is 2)"] }, { query: "{ validated(value: [\"ABC\"]) }", result: nil, error_messages: ["value is invalid, value is too long (maximum is 2)"] }, { query: "{ validated(value: [\"ABC\", \"DEF\"]) }", result: nil, error_messages: ["value is invalid, value is too long (maximum is 2)"] }, ], }, ] build_tests(:all, [String], expectations) expectations = [ { config: { inclusion: { in: 1..3 } }, cases: [ { query: "{ validated(value: []) }", result: [], error_messages: [] }, { query: "{ validated(value: [1]) }", result: [1], error_messages: [] }, { query: "{ validated(value: [1, 2]) }", result: [1, 2], error_messages: [] }, { query: "{ validated(value: [4]) }", result: nil, error_messages: ["value is not included in the list"] }, { query: "{ validated(value: [1, 4]) }", result: nil, error_messages: ["value is not included in the list"] }, { query: "{ validated(value: [1, 4, 5]) }", result: nil, error_messages: ["value is not included in the list"] }, ], }, ] build_tests(:all, [Integer], expectations) expectations = [ { config: { allow_null: true, inclusion: { in: 1..5 }, numericality: { odd: true } }, cases: [ { query: "{ validated(value: null) }", result: nil, error_messages: [] }, { query: "{ validated(value: []) }", result: [], error_messages: [] }, { query: "{ validated(value: [1]) }", result: [1], error_messages: [] }, { query: "{ validated(value: [1, 3]) }", result: [1, 3], error_messages: [] }, { query: "{ validated(value: [4]) }", result: nil, error_messages: ["value must be odd"] }, { query: "{ validated(value: [7]) }", result: nil, error_messages: ["value is not included in the list"] }, ], }, ] build_tests(:all, [Integer], expectations) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/numericality_validator_spec.rb
spec/graphql/schema/validator/numericality_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::NumericalityValidator do include ValidatorHelpers expectations = [ { config: { less_than: 10, greater_than: 2, allow_null: true }, cases: [ { query: "{ validated(value: 8) }", result: 8, error_messages: [] }, { query: "{ validated(value: 12) }", result: nil, error_messages: ["value must be less than 10"] }, { query: "{ validated(value: 1) }", result: nil, error_messages: ["value must be greater than 2"] }, { query: "{ validated(value: null) }", result: nil, error_messages: [] }, ] }, { config: { less_than_or_equal_to: 10, greater_than_or_equal_to: 2 }, cases: [ { query: "{ validated(value: 8) }", result: 8, error_messages: [] }, { query: "{ validated(value: 10) }", result: 10, error_messages: [] }, { query: "{ validated(value: 2) }", result: 2, error_messages: [] }, { query: "{ validated(value: 12) }", result: nil, error_messages: ["value must be less than or equal to 10"] }, { query: "{ validated(value: 1) }", result: nil, error_messages: ["value must be greater than or equal to 2"] }, ] }, { config: { odd: true }, cases: [ { query: "{ validated(value: 9) }", result: 9, error_messages: [] }, { query: "{ validated(value: 8) }", result: nil, error_messages: ["value must be odd"] }, ] }, { config: { even: true }, cases: [ { query: "{ validated(value: 8) }", result: 8, error_messages: [] }, { query: "{ validated(value: 9) }", result: nil, error_messages: ["value must be even"] }, ] }, { config: { equal_to: 8 }, cases: [ { query: "{ validated(value: 8) }", result: 8, error_messages: [] }, { query: "{ validated(value: 9) }", result: nil, error_messages: ["value must be equal to 8"] }, ] }, { config: { other_than: 9 }, cases: [ { query: "{ validated(value: 8) }", result: 8, error_messages: [] }, { query: "{ validated(value: null) }", result: nil, error_messages: ["value can't be null"] }, { query: "{ validated(value: 9) }", result: nil, error_messages: ["value must be something other than 9"] }, ] }, { config: { within: 1..5, allow_null: true }, cases: [ { query: "{ validated(value: 1) }", result: 1, error_messages: [] }, { query: "{ validated(value: 5) }", result: 5, error_messages: [] }, { query: "{ validated(value: 0) }", result: nil, error_messages: ["value must be within 1..5"] }, { query: "{ validated(value: 6) }", result: nil, error_messages: ["value must be within 1..5"] }, ] }, ] build_tests(:numericality, Integer, expectations) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/validator_helpers.rb
spec/graphql/schema/validator/validator_helpers.rb
# frozen_string_literal: true module ValidatorHelpers def self.included(child_class) child_class.extend(ClassMethods) end class BlankString < String def blank? true end end class NonBlankString < String if method_defined?(:blank?) undef :blank? end end def build_schema(arg_type, validates_config) schema = Class.new(GraphQL::Schema) base_argument = Class.new(GraphQL::Schema::Argument) do def initialize(*args, secret: false, **kwargs, &block) super(*args, **kwargs, &block) @secret = secret end def visible?(_ctx) !@secret end end base_field = Class.new(GraphQL::Schema::Field) do argument_class(base_argument) end validated_input = Class.new(GraphQL::Schema::InputObject) do graphql_name "ValidatedInput" argument :a, arg_type, required: false argument :b, arg_type, required: false argument :c, arg_type, required: false validates(validates_config) def prepare self end end validated_resolver = Class.new(GraphQL::Schema::Resolver) do graphql_name "ValidatedResolver" argument :a, arg_type, required: false argument :b, arg_type, required: false argument :c, arg_type, required: false validates(validates_config) type(arg_type, null: true) def resolve(a: 0, b: 0, c: 0) a + b + c end end validated_arg_resolver = Class.new(GraphQL::Schema::Resolver) do graphql_name "ValidatedArgResolver" argument :input, arg_type, required: false, validates: validates_config type(String, null: false) def resolve(input: :NO_INPUT) input.to_s.upcase end end query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field_class(base_field) field :validated, arg_type do argument :value, arg_type, required: false, validates: validates_config end def validated(value: nil) value end field :multi_validated, arg_type, validates: validates_config do argument :a, arg_type, required: false argument :b, arg_type, required: false argument :c, arg_type, required: false argument :secret, arg_type, required: false, secret: true argument :secret2, arg_type, required: false, secret: true end def multi_validated(a: 0, b: 0, c: 0) a + b + c end field :validated_input, arg_type do argument :input, validated_input end def validated_input(input:) (input[:a] || 0) + (input[:b] || 0) + (input[:c] || 0) end field :validated_resolver, resolver: validated_resolver field :validated_arg_resolver, resolver: validated_arg_resolver field :list, [self], null: false def list [:a, :b, :c] end end schema.query(query_type) if ADD_WARDEN schema.use(GraphQL::Schema::Warden) else schema.use(GraphQL::Schema::Visibility) end schema end module ClassMethods def build_tests(validator_name, field_type, expectations) expectations.each do |expectation| name = expectation[:name] ? "#{expectation[:name]}: " : "" it "#{name}#{validator_name} on #{field_type} works with #{expectation[:config]}" do schema = build_schema(field_type, { validator_name => expectation[:config] }) expectation[:cases].each do |test_case| result = schema.execute(test_case[:query], variables: test_case[:variables]) if !result["data"] pp result refute result["errors"].map { |e| e["message"] }, test_case[:query] end assert_equal test_case[:error_messages], (result["errors"] || []).map { |e| e["message"] }, test_case[:query] if test_case[:result].nil? assert_nil result["data"]["validated"], test_case[:query] else assert_equal test_case[:result], result["data"]["validated"], test_case[:query] end end end end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/allow_blank_validator_spec.rb
spec/graphql/schema/validator/allow_blank_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::AllowBlankValidator do include ValidatorHelpers it "allows blank when configured" do schema = build_schema(String, {length: { minimum: 5 }, allow_blank: true}) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: ValidatorHelpers::BlankString.new }) assert_equal "", result["data"]["validated"] refute result.key?("errors") end it "rejects blank by default" do schema = build_schema(String, {length: { minimum: 5 }}) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: ValidatorHelpers::BlankString.new }) assert_nil result["data"]["validated"] assert_equal ["value is too short (minimum is 5)"], result["errors"].map { |e| e["message"] } end it "can be used standalone" do schema = build_schema(String, { allow_blank: false, allow_null: false }) result = schema.execute("query($str: String) { validated(value: $str) }", variables: { str: ValidatorHelpers::BlankString.new }) assert_nil result["data"]["validated"] assert_equal ["value can't be blank"], result["errors"].map { |e| e["message"] } result = schema.execute("query($str: String) { validated: validatedArgResolver(input: $str) }", variables: { str: "abc" }) assert_equal "ABC", result["data"]["validated"] result = schema.execute("query($str: String) { validated: validatedArgResolver(input: $str) }", variables: { str: ValidatorHelpers::BlankString.new }) assert_nil result.fetch("data") assert_equal ["input can't be blank"], result["errors"].map { |e| e["message"] } # The validator doesn't run if the argument isn't present: result = schema.execute("query($str: String) { validated: validatedArgResolver(input: $str) }", variables: { }) assert_equal "NO_INPUT", result["data"]["validated"] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/validator/format_validator_spec.rb
spec/graphql/schema/validator/format_validator_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./validator_helpers" describe GraphQL::Schema::Validator::FormatValidator do include ValidatorHelpers expectations = [ { config: { with: /\A[a-z]+\Z/ }, cases: [ { query: "{ validated(value: \"abcd\") }", result: "abcd", error_messages: [] }, { query: "{ validated(value: \"ABC\") }", result: nil, error_messages: ["value is invalid"] }, ] }, { config: { with: /\A[a-z]+\Z/, allow_blank: true }, cases: [ { query: "{ validated(value: \"abcd\") }", result: "abcd", error_messages: [] }, { query: "{ validated(value: \"ABC\") }", result: nil, error_messages: ["value is invalid"] }, (String.method_defined?(:blank?) ? { query: "{ validated(value: \"\") }", result: "", error_messages: [] } : { query: "{ validated(value: \"\") }", result: nil, error_messages: ["value is invalid"] } ), ] }, { config: { without: /[a-z]/ }, cases: [ { query: "{ validated(value: \"abcd\") }", result: nil, error_messages: ["value is invalid"] }, { query: "{ validated(value: null) }", result: nil, error_messages: ["value is invalid"] }, { query: "{ validated(value: \"ABC\") }", result: "ABC", error_messages: [] }, ] }, ] build_tests(:format, String, expectations) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/directive/query_level_directive_spec.rb
spec/graphql/schema/directive/query_level_directive_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Query level Directive" do class QueryDirectiveSchema < GraphQL::Schema class DirectiveInput < GraphQL::Schema::InputObject argument :val, Integer end class InitInt < GraphQL::Schema::Directive locations(GraphQL::Schema::Directive::QUERY) argument(:val, Integer, "Initial integer value.", required: false) argument(:input, DirectiveInput, required: false) def self.resolve(obj, args, ctx) ctx[:int] = args[:val] || args[:input][:val] || 0 yield end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int context[:int] ||= 0 context[:int] += 1 end end directive(InitInt) query(Query) end it "returns an error if directive is not on the query level" do str = 'query TestDirective { int1: int @initInt(val: 10) int2: int } ' res = QueryDirectiveSchema.execute(str) expected_errors = [ { "message" => "'@initInt' can't be applied to fields (allowed: queries)", "locations" => [{ "line" => 2, "column" => 17 }], "path" => ["query TestDirective", "int1"], "extensions" => { "code" => "directiveCannotBeApplied", "targetName" => "fields", "name" => "initInt" } } ] assert_equal(expected_errors, res["errors"]) end it "runs on the query level" do str = 'query TestDirective @initInt(val: 10) { int1: int int2: int } ' res = QueryDirectiveSchema.execute(str) assert_equal({ "int1" => 11, "int2" => 12 }, res["data"]) end it "works with input object arguments" do str = 'query TestDirective @initInt(input: { val: 12 }) { int1: int int2: int } ' res = QueryDirectiveSchema.execute(str) assert_equal({ "int1" => 13, "int2" => 14 }, res["data"]) error_str = 'query TestDirective @initInt(input: {val: "abc"}) { int1: int int2: int } ' error_res = QueryDirectiveSchema.execute(error_str) assert_equal(["Argument 'val' on InputObject 'DirectiveInput' has an invalid value (\"abc\"). Expected type 'Int!'."], error_res["errors"].map { |e| e["message"] }) end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/directive/transform_spec.rb
spec/graphql/schema/directive/transform_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive::Transform do class TransformSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :echo, String, null: false do argument :input, String end def echo(input:) input end end directive(GraphQL::Schema::Directive::Transform) query(Query) end it "transforms when applicable" do str = '{ normal: echo(input: "Hello") upcased: echo(input: "Hello") @transform(by: "upcase") downcased: echo(input: "Hello") @transform(by: "downcase") nonsense: echo(input: "Hello") @transform(by: "nonsense") }' res = TransformSchema.execute(str) assert_equal "Hello", res["data"]["normal"] assert_equal "HELLO", res["data"]["upcased"] assert_equal "hello", res["data"]["downcased"] assert_equal "Hello", res["data"]["nonsense"] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/directive/feature_spec.rb
spec/graphql/schema/directive/feature_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive::Feature do class FeatureSchema < GraphQL::Schema class Feature < GraphQL::Schema::Directive::Feature def self.enabled?(flag_name, obj, ctx) !!ctx[flag_name.to_sym] end end # Based on feature but uses a runtime check instead of ahead-of-time class RuntimeFeature < GraphQL::Schema::Directive locations(GraphQL::Schema::Directive::FRAGMENT_SPREAD) argument :flag, String, description: "The name of the feature to check before continuing" def self.resolve(object, arguments, context, &block) flag_name = arguments[:flag] if context[flag_name] yield else # pass end end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int context[:int] ||= 0 context[:int] += 1 end end directive(Feature) directive(RuntimeFeature) query(Query) end it "skips or runs fields" do str = '{ int1: int int2: int @feature(flag: "flag1") int3: int @feature(flag: "flag2") }' res = FeatureSchema.execute(str, context: { flag2: true }) # Int2 was not called, so `int3` is actually 2 assert_equal({"int1" => 1, "int3" => 2}, res["data"]) end it "skips or runs fragment spreads" do str = '{ ...F1 ...F2 @feature(flag: "flag1") ...F3 @feature(flag: "flag2") int4: int } fragment F1 on Query { int1: int } fragment F2 on Query { int2: int } fragment F3 on Query { int3: int } ' res = FeatureSchema.execute(str, context: { flag1: true }) # `int3` was skipped assert_equal({"int1" => 1, "int2" => 2, "int4" => 3}, res["data"]) end it "skips or runs inline fragments" do str = '{ ... { int1: int } ... @feature(flag: "flag1") { int2: int } ... @feature(flag: "flag2") { int3: int } int4: int } ' res = FeatureSchema.execute(str, context: { flag2: true }) # `int2` was skipped assert_equal({"int1" => 1, "int3" => 2, "int4" => 3}, res["data"]) end it "returns an error if it's in the wrong place" do str = ' query @feature(flag: "x") { int } ' res = FeatureSchema.execute(str) assert_equal ["'@feature' can't be applied to queries (allowed: fields, fragment spreads, inline fragments)"], res["errors"].map { |e| e["message"] } end it "runs or skips on deeply nested fragment spreads fragments" do str = "{ int ... Q1 } fragment Q1 on Query { ... Q2 } fragment Q2 on Query { ... Q3 @runtimeFeature(flag: \"x\") } fragment Q3 on Query { i2: int } " res = FeatureSchema.execute(str, context: { "x" => true }) assert_equal 1, res["data"]["int"] assert_equal 2, res["data"]["i2"] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/directive/one_of_spec.rb
spec/graphql/schema/directive/one_of_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive::OneOf do let(:schema) do this = self output_type = Class.new(GraphQL::Schema::Object) do graphql_name "OneOfOutput" field :string, GraphQL::Types::String field :int, GraphQL::Types::Int end query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :one_of_field, output_type, null: false do argument :one_of_arg, this.one_of_input_object end.ensure_loaded def one_of_field(one_of_arg:) one_of_arg end end Class.new(GraphQL::Schema) do query(query_type) end end let(:one_of_input_object) do Class.new(GraphQL::Schema::InputObject) do graphql_name "OneOfInputObject" directive GraphQL::Schema::Directive::OneOf argument :int, GraphQL::Types::Int, required: false argument :string, GraphQL::Types::String, required: false end end describe "defining oneOf input objects" do describe "with a non-null argument" do let(:one_of_input_object) do Class.new(GraphQL::Schema::InputObject) do graphql_name "OneOfInputObject" directive GraphQL::Schema::Directive::OneOf argument :int, GraphQL::Types::Int, required: true # rubocop:disable GraphQL/DefaultRequiredTrue argument :string, GraphQL::Types::String end end it "raises an error" do error = assert_raises(ArgumentError) { schema } expected_message = "Argument 'OneOfInputObject.int' must be nullable because it is part of a OneOf type, add `required: false`." assert_equal(expected_message, error.message) end end describe "when an argument has a default" do let(:one_of_input_object) do Class.new(GraphQL::Schema::InputObject) do graphql_name "OneOfInputObject" directive GraphQL::Schema::Directive::OneOf argument :int, GraphQL::Types::Int, default_value: 1, required: false argument :string, GraphQL::Types::String, required: false end end it "raises an error" do error = assert_raises(ArgumentError) { schema } expected_message = "Argument 'OneOfInputObject.int' cannot have a default value because it is part of a OneOf type, remove `default_value: ...`." assert_equal(expected_message, error.message) end end end describe "execution" do let(:query) do <<~GRAPHQL query TestQuery($oneOfInputObject: OneOfInputObject!) { oneOfField(oneOfArg: $oneOfInputObject) { string int } } GRAPHQL end it "accepts a default value with exactly one non-null key" do query = <<~GRAPHQL query TestQuery($oneOfInputObject: OneOfInputObject = { string: "default" }) { oneOfField(oneOfArg: $oneOfInputObject) { string int } } GRAPHQL result = schema.execute(query) assert_equal({ "string" => "default", "int" => nil }, result["data"]["oneOfField"]) end it "rejects a default value with multiple non-null keys" do query = <<~GRAPHQL query TestQuery($oneOfInputObject: OneOfInputObject = { string: "default", int: 2 }) { oneOfField(oneOfArg: $oneOfInputObject) { string int } } GRAPHQL result = schema.execute(query) expected_errors = ["`OneOfInputObject` is a OneOf type, so only one argument may be given (instead of 2)"] assert_equal(expected_errors, result["errors"].map { |e| e["message"] }) end it "rejects a default value with multiple nullable keys" do query = <<~GRAPHQL query TestQuery($oneOfInputObject: OneOfInputObject = { string: "default", int: null }) { oneOfField(oneOfArg: $oneOfInputObject) { string int } } GRAPHQL result = schema.execute(query) expected_errors = ["`OneOfInputObject` is a OneOf type, so only one argument may be given (instead of 2)"] assert_equal(expected_errors, result["errors"].map { |e| e["message"] }) end it "accepts a variable with exactly one non-null key" do string_result = schema.execute(query, variables: { oneOfInputObject: { string: "abc" } }) int_result = schema.execute(query, variables: { oneOfInputObject: { int: 2 } }) assert_equal({ "string" => "abc", "int" => nil }, string_result["data"]["oneOfField"]) assert_equal({ "string" => nil, "int" => 2 }, int_result["data"]["oneOfField"]) end it "rejects a variable with exactly one null key" do result = schema.execute(query, variables: { oneOfInputObject: { string: nil } }) expected_errors = ["'OneOfInputObject' requires exactly one argument, but 'string' was `null`."] assert_equal(expected_errors, result["errors"].map { |e| e["extensions"]["problems"].map { |pr| pr["explanation"] } }.flatten) end it "rejects a variable with multiple non-null keys" do result = schema.execute(query, variables: { oneOfInputObject: { string: "abc", int: 2 } }) expected_errors = ["'OneOfInputObject' requires exactly one argument, but 2 were provided."] assert_equal(expected_errors, result["errors"].map { |e| e["extensions"]["problems"].map { |pr| pr["explanation"] } }.flatten) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema/directive/flagged_spec.rb
spec/graphql/schema/directive/flagged_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema::Directive::Flagged do class FlaggedSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN module Animal include GraphQL::Schema::Interface if GraphQL::Schema.use_visibility_profile? # It won't check possible types, so it needs this directly directive GraphQL::Schema::Directive::Flagged, by: ["northPole", "southPole"] end end class PolarBear < GraphQL::Schema::Object implements Animal directive GraphQL::Schema::Directive::Flagged, by: ["northPole"] field :name, String, null: false end class Penguin < GraphQL::Schema::Object implements Animal directive GraphQL::Schema::Directive::Flagged, by: ["southPole"] field :name, String, null: false end class Query < GraphQL::Schema::Object field :animals, [Animal], null: false def animals [ context[:flags].include?("southPole") ? { type: "Penguin", name: "King Dedede" } : nil, context[:flags].include?("northPole") ? { type: "PolarBear", name: "Iorek" } : nil, ].compact end field :antarctica, Boolean, null: false, directives: { GraphQL::Schema::Directive::Flagged => { by: ["southPole"] } } def antarctica; true; end field :santas_workshop, Boolean, null: false, directives: { GraphQL::Schema::Directive::Flagged => { by: ["northPole"] } } def santas_workshop; true; end field :something_not_flagged, String end query(Query) orphan_types(PolarBear, Penguin) def self.resolve_type(abs_type, obj, ctx) case obj[:type] when "Penguin" Penguin when "PolarBear" PolarBear else raise "Unknown: #{obj}" end end end def exec_query(str, context: {}) FlaggedSchema.execute(str, context: context) end def error_messages(res) res["errors"].map { |e| e["message"] } end it "hides fields when the required flags are not present" do res = exec_query("{ __typename }") assert_equal "Query", res["data"]["__typename"] res = exec_query("{ antarctica }") assert_equal ["Field 'antarctica' doesn't exist on type 'Query'"], error_messages(res) res = exec_query("{ antarctica }", context: { flags: ["southPole"] }) assert_equal true, res["data"]["antarctica"] res = exec_query("{ antarctica santasWorkshop }", context: { flags: ["southPole"] }) assert_equal ["Field 'santasWorkshop' doesn't exist on type 'Query'"], error_messages(res) res = exec_query("{ antarctica santasWorkshop }", context: { flags: ["southPole", "northPole"] }) assert_equal true, res["data"]["antarctica"] assert_equal true, res["data"]["santasWorkshop"] end it "hides types when the required flags are not present" do res = exec_query("{ animals { __typename } }") assert_equal ["Field 'animals' doesn't exist on type 'Query'"], error_messages(res), "All implementers are hidden" res = exec_query("{ animals { ... on Penguin { name } } }", context: { flags: ["southPole"] }) assert_equal ["King Dedede"], res["data"]["animals"].map { |a| a["name"] } res = exec_query("{ animals { ... on Penguin { name } ... on PolarBear { name }} }", context: { flags: ["southPole"] }) assert_equal ["No such type PolarBear, so it can't be a fragment condition"], error_messages(res) res = exec_query("{ animals { ... on Penguin { name } ... on PolarBear { name }} }", context: { flags: ["southPole", "northPole"] }) assert_equal ["King Dedede", "Iorek"], res["data"]["animals"].map { |a| a["name"] } end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/dataloader/source_spec.rb
spec/graphql/dataloader/source_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Dataloader::Source do class FailsToLoadSource < GraphQL::Dataloader::Source def fetch(keys) dataloader.with(FailsToLoadSource).load_all(keys) end end it "raises an error when it tries too many times to sync" do dl = GraphQL::Dataloader.new dl.append_job { dl.with(FailsToLoadSource).load(1) } err = assert_raises RuntimeError do dl.run end expected_message = "FailsToLoadSource#sync tried 1000 times to load pending keys ([1]), but they still weren't loaded. There is likely a circular dependency." assert_equal expected_message, err.message dl = GraphQL::Dataloader.new(fiber_limit: 10000) dl.append_job { dl.with(FailsToLoadSource).load(1) } err = assert_raises RuntimeError do dl.run end expected_message = "FailsToLoadSource#sync tried 1000 times to load pending keys ([1]), but they still weren't loaded. There is likely a circular dependency or `fiber_limit: 10000` is set too low." assert_equal expected_message, err.message end it "is pending when waiting for false and nil" do dl = GraphQL::Dataloader.new dl.with(FailsToLoadSource).request(nil) source_cache = dl.instance_variable_get(:@source_cache) source_cache_for_source = source_cache[FailsToLoadSource] # The value of this changed in Ruby 3.3.3, see https://bugs.ruby-lang.org/issues/20180 # In previous versions, it was `[{}]`, but now it's `[]` empty_batch_key = [*[], **{}] source_inst = source_cache_for_source[empty_batch_key] assert_instance_of FailsToLoadSource, source_inst, "The cache includes a pending source (#{source_cache_for_source.inspect})" assert source_inst.pending? end class CustomKeySource < GraphQL::Dataloader::Source def result_key_for(record) record[:id] end def fetch(records) records.map { |r| r[:value] * 10 } end end it "uses a custom key when configured" do values = nil GraphQL::Dataloader.with_dataloading do |dl| first_req = dl.with(CustomKeySource).request({ id: 1, value: 10 }) second_rec = dl.with(CustomKeySource).request({ id: 2, value: 20 }) third_rec = dl.with(CustomKeySource).request({id: 1, value: 30 }) values = [ first_req.load, second_rec.load, third_rec.load ] end # There wasn't a `300` because the third requested value was de-duped to the first one. assert_equal [100, 200, 100], values end class NoDataloaderSchema < GraphQL::Schema class ThingSource < GraphQL::Dataloader::Source def fetch(ids) ids.map { |id| { name: "Thing-#{id}" } } end end class Thing < GraphQL::Schema::Object field :name, String end class Query < GraphQL::Schema::Object field :thing, Thing do argument :id, ID end def thing(id:) context.dataloader.with(ThingSource).load(id) end end query(Query) end it "raises an error when used without a dataloader" do err = assert_raises GraphQL::Error do NoDataloaderSchema.execute("{ thing(id: 1) { name } }") end expected_message = "GraphQL::Dataloader is not running -- add `use GraphQL::Dataloader` to your schema to use Dataloader sources." assert_equal expected_message, err.message end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/dataloader/nonblocking_dataloader_spec.rb
spec/graphql/dataloader/nonblocking_dataloader_spec.rb
# frozen_string_literal: true require "spec_helper" if Fiber.respond_to?(:scheduler) # Ruby 3+ describe "GraphQL::Dataloader::NonblockingDataloader" do class NonblockingSchema < GraphQL::Schema class SleepSource < GraphQL::Dataloader::Source def fetch(keys) max_sleep = keys.max # t1 = Time.now # puts "----- SleepSource => #{max_sleep} " sleep(max_sleep) # puts "----- SleepSource done #{max_sleep} after #{Time.now - t1}" keys.map { |_k| max_sleep } end end class WaitForSource < GraphQL::Dataloader::Source def initialize(tag) @tag = tag end def fetch(waits) max_wait = waits.max # puts "[#{Time.now.to_f}] Waiting #{max_wait} for #{@tag}" `sleep #{max_wait}` # puts "[#{Time.now.to_f}] Finished for #{@tag}" waits.map { |_w| @tag } end end class Sleeper < GraphQL::Schema::Object field :sleeper, Sleeper, null: false, resolver_method: :sleep do argument :duration, Float end def sleep(duration:) `sleep #{duration}` duration end field :duration, Float, null: false def duration; object; end end class Waiter < GraphQL::Schema::Object field :wait_for, Waiter, null: false do argument :tag, String argument :wait, Float end def wait_for(tag:, wait:) dataloader.with(WaitForSource, tag).load(wait) end field :tag, String, null: false def tag object end end class Query < GraphQL::Schema::Object field :sleep, Float, null: false do argument :duration, Float end field :sleeper, Sleeper, null: false, resolver_method: :sleep do argument :duration, Float end def sleep(duration:) `sleep #{duration}` duration end field :wait_for, Waiter, null: false do argument :tag, String argument :wait, Float end def wait_for(tag:, wait:) dataloader.with(WaitForSource, tag).load(wait) end end query(Query) use GraphQL::Dataloader, nonblocking: true end def with_scheduler Fiber.set_scheduler(scheduler_class.new) yield ensure Fiber.set_scheduler(nil) end module NonblockingDataloaderAssertions def self.included(child_class) child_class.class_eval do it "runs IO in parallel by default" do dataloader = GraphQL::Dataloader.new(nonblocking: true) results = {} dataloader.append_job { sleep(0.1); results[:a] = 1 } dataloader.append_job { sleep(0.2); results[:b] = 2 } dataloader.append_job { sleep(0.3); results[:c] = 3 } assert_equal({}, results, "Nothing ran yet") started_at = Time.now with_scheduler { dataloader.run } ended_at = Time.now assert_equal({ a: 1, b: 2, c: 3 }, results, "All the jobs ran") assert_in_delta 0.3, ended_at - started_at, 0.06, "IO ran in parallel" end it "works with sources" do dataloader = GraphQL::Dataloader.new(nonblocking: true) r1 = dataloader.with(NonblockingSchema::SleepSource).request(0.1) r2 = dataloader.with(NonblockingSchema::SleepSource).request(0.2) r3 = dataloader.with(NonblockingSchema::SleepSource).request(0.3) v1 = nil dataloader.append_job { v1 = r1.load } started_at = Time.now with_scheduler { dataloader.run } ended_at = Time.now assert_equal 0.3, v1 started_at_2 = Time.now # These should take no time at all since they're already resolved v2 = r2.load v3 = r3.load ended_at_2 = Time.now assert_equal 0.3, v2 assert_equal 0.3, v3 assert_in_delta 0.0, started_at_2 - ended_at_2, 0.06, "Already-loaded values returned instantly" assert_in_delta 0.3, ended_at - started_at, 0.06, "IO ran in parallel" end it "works with GraphQL" do started_at = Time.now res = with_scheduler { NonblockingSchema.execute("{ s1: sleep(duration: 0.1) s2: sleep(duration: 0.2) s3: sleep(duration: 0.3) }") } ended_at = Time.now assert_equal({"s1"=>0.1, "s2"=>0.2, "s3"=>0.3}, res["data"]) assert_in_delta 0.3, ended_at - started_at, 0.06, "IO ran in parallel" end it "nested fields don't wait for slower higher-level fields" do query_str = <<-GRAPHQL { s1: sleeper(duration: 0.1) { sleeper(duration: 0.1) { sleeper(duration: 0.1) { duration } } } s2: sleeper(duration: 0.2) { sleeper(duration: 0.1) { duration } } s3: sleeper(duration: 0.3) { duration } } GRAPHQL started_at = Time.now res = with_scheduler { NonblockingSchema.execute(query_str) } ended_at = Time.now expected_data = { "s1" => { "sleeper" => { "sleeper" => { "duration" => 0.1 } } }, "s2" => { "sleeper" => { "duration" => 0.1 } }, "s3" => { "duration" => 0.3 } } assert_graphql_equal expected_data, res["data"] assert_in_delta 0.3, ended_at - started_at, 0.06, "Fields ran without any waiting" end it "runs dataloaders in parallel across branches" do query_str = <<-GRAPHQL { w1: waitFor(tag: "a", wait: 0.2) { waitFor(tag: "b", wait: 0.2) { waitFor(tag: "c", wait: 0.2) { tag } } } # After the first, these are returned eagerly from cache w2: waitFor(tag: "a", wait: 0.2) { waitFor(tag: "a", wait: 0.2) { waitFor(tag: "a", wait: 0.2) { tag } } } w3: waitFor(tag: "a", wait: 0.2) { waitFor(tag: "b", wait: 0.2) { waitFor(tag: "d", wait: 0.2) { tag } } } w4: waitFor(tag: "e", wait: 0.6) { tag } } GRAPHQL started_at = Time.now res = with_scheduler do NonblockingSchema.execute(query_str) end ended_at = Time.now expected_data = { "w1" => { "waitFor" => { "waitFor" => { "tag" => "c" } } }, "w2" => { "waitFor" => { "waitFor" => { "tag" => "a" } } }, "w3" => { "waitFor" => { "waitFor" => { "tag" => "d" } } }, "w4" => { "tag" => "e" } } assert_graphql_equal expected_data, res["data"] # We've basically got two options here: # - Put all jobs in the same queue (fields and sources), but then you don't get predictable batching. # - Work one-layer-at-a-time, but then layers can get stuck behind one another. That's what's implemented here. assert_in_delta 1.0, ended_at - started_at, 0.5, "Sources were executed in parallel" end end end end describe "With the toy scheduler from Ruby's tests" do let(:scheduler_class) { ::DummyScheduler } include NonblockingDataloaderAssertions end if RUBY_ENGINE == "ruby" && !ENV["GITHUB_ACTIONS"] describe "With libev_scheduler" do require "libev_scheduler" let(:scheduler_class) { Libev::Scheduler } include NonblockingDataloaderAssertions end describe "with evt" do require "evt" let(:scheduler_class) { Evt::Scheduler } include NonblockingDataloaderAssertions end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/dataloader/active_record_source_spec.rb
spec/graphql/dataloader/active_record_source_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Dataloader::ActiveRecordSource do if testing_rails? describe "finding by ID" do it_dataloads "loads once, then returns from a cache when available" do |d| log = with_active_record_log(colorize: false) do r1 = d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load(1) assert_equal "Vulfpeck", r1.name end assert_includes log, 'SELECT "bands".* FROM "bands" WHERE "bands"."id" = ? [["id", 1]]' log = with_active_record_log(colorize: false) do r1 = d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load(1) assert_equal "Vulfpeck", r1.name end assert_equal "", log log = with_active_record_log(colorize: false) do records = d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load_all([1, 99, 2, 3]) assert_equal ["Vulfpeck", nil, "Tom's Story", "Chon"], records.map { |r| r&.name } end assert_includes log, '[["id", 99], ["id", 2], ["id", 3]]' end it_dataloads "casts load values to the column type" do |d| log = with_active_record_log(colorize: false) do r1 = d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load("1") assert_equal "Vulfpeck", r1.name end assert_includes log, 'SELECT "bands".* FROM "bands" WHERE "bands"."id" = ? [["id", 1]]' log = with_active_record_log(colorize: false) do d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load(1) end assert_equal "", log log = with_active_record_log(colorize: false) do d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load("1") end assert_equal "", log end end describe "finding by other columns" do it_dataloads "uses the alternative primary key" do |d| log = with_active_record_log(colorize: false) do r1 = d.with(GraphQL::Dataloader::ActiveRecordSource, AlternativeBand).load("Vulfpeck") assert_equal "Vulfpeck", r1.name if Rails::VERSION::STRING > "8" assert_equal 1, r1["id"] else assert_equal 1, r1._read_attribute("id") end end assert_includes log, 'SELECT "bands".* FROM "bands" WHERE "bands"."name" = ? [["name", "Vulfpeck"]]' end if Rails::VERSION::STRING > "7.1" # not supported in <7.1 it_dataloads "uses composite primary keys" do |d| log = with_active_record_log(colorize: false) do r1 = d.with(GraphQL::Dataloader::ActiveRecordSource, CompositeBand).load(["Chon", :rock]) assert_equal "Chon", r1.name assert_equal ["Chon", "rock"], r1.id if Rails::VERSION::STRING > "8" assert_equal 3, r1["id"] else assert_equal 3, r1._read_attribute("id") end end assert_includes log, 'SELECT "bands".* FROM "bands" WHERE "bands"."name" = ? AND "bands"."genre" = ? [["name", "Chon"], ["genre", 0]]' end end it_dataloads "uses specified find_by columns" do |d| log = with_active_record_log(colorize: false) do r1 = d.with(GraphQL::Dataloader::ActiveRecordSource, Band, find_by: :name).load("Chon") assert_equal "Chon", r1.name assert_equal 3, r1.id end assert_includes log, 'SELECT "bands".* FROM "bands" WHERE "bands"."name" = ? [["name", "Chon"]]' end end describe "warming the cache" do it_dataloads "can receive passed-in objects with a class" do |d| d.with(GraphQL::Dataloader::ActiveRecordSource, Band).merge({ 100 => Band.find(3) }) log = with_active_record_log(colorize: false) do band3 = d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load(100) assert_equal "Chon", band3.name assert_equal 3, band3.id end assert_equal "", log end it_dataloads "can infer class of passed-in objects" do |d| d.merge_records([Band.find(3), Album.find(4)]) log = with_active_record_log(colorize: false) do band3 = d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load(3) assert_equal "Chon", band3.name album4 = d.with(GraphQL::Dataloader::ActiveRecordSource, Album).load(4) assert_equal "Homey", album4.name end assert_equal "", log end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/dataloader/active_record_association_source_spec.rb
spec/graphql/dataloader/active_record_association_source_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Dataloader::ActiveRecordAssociationSource do if testing_rails? class VulfpeckSchema < GraphQL::Schema class Album < GraphQL::Schema::Object field :name, String end class Band < GraphQL::Schema::Object field :albums, [Album] do argument :genre, String, required: false argument :reverse, Boolean, required: false, default_value: false argument :unscoped, Boolean, required: false, default_value: false end def albums(genre: nil, reverse:, unscoped:) if unscoped scope = nil else scope = ::Album if genre scope = scope.where(band_genre: genre) end scope = if reverse scope.order(name: :desc) else scope.order(:name) end end dataload_association(:albums, scope: scope) end end class Query < GraphQL::Schema::Object field :band, Band do argument :name, String end def band(name:) ::Band.find_by(name: name) end end query(Query) use GraphQL::Dataloader end it "works with different scopes on the same object at runtime" do query_str = <<~GRAPHQL { band(name: "Vulfpeck") { allAlbums: albums { name } unscopedAlbums: albums(unscoped: true) { name } reverseAlbums: albums(reverse: true) { name } countryAlbums: albums(genre: "country") { name } } } GRAPHQL result = VulfpeckSchema.execute(query_str) assert_equal ["Mit Peck", "My First Car"], result["data"]["band"]["allAlbums"].map { |a| a["name"] } assert_equal ["Mit Peck", "My First Car"], result["data"]["band"]["unscopedAlbums"].map { |a| a["name"] } assert_equal ["My First Car", "Mit Peck"], result["data"]["band"]["reverseAlbums"].map { |a| a["name"] } assert_equal [], result["data"]["band"]["countryAlbums"] end it_dataloads "queries for associated records when the association isn't already loaded" do |d| my_first_car = ::Album.find(2) homey = ::Album.find(4) log = with_active_record_log(colorize: false) do vulfpeck, chon = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :band).load_all([my_first_car, homey]) assert_equal "Vulfpeck", vulfpeck.name assert_equal "Chon", chon.name end assert_includes log, '[["id", 1], ["id", 3]]' toms_story = ::Album.find(3) log = with_active_record_log(colorize: false) do vulfpeck, chon, toms_story_band = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :band).load_all([my_first_car, homey, toms_story]) assert_equal "Vulfpeck", vulfpeck.name assert_equal "Chon", chon.name assert_equal "Tom's Story", toms_story_band.name end assert_includes log, '[["id", 2]]' end it_dataloads "doesn't load records that are already cached by ActiveRecordSource" do |d| d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load_all([1,2,3]) my_first_car = ::Album.find(2) homey = ::Album.find(4) toms_story = ::Album.find(3) log = with_active_record_log(colorize: false) do vulfpeck, chon, toms_story_band = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :band).load_all([my_first_car, homey, toms_story]) assert_equal "Vulfpeck", vulfpeck.name assert_equal "Chon", chon.name assert_equal "Tom's Story", toms_story_band.name end assert_equal "", log end it_dataloads "warms the cache for ActiveRecordSource" do |d| my_first_car = ::Album.find(2) homey = ::Album.find(4) toms_story = ::Album.find(3) d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :band).load_all([my_first_car, homey, toms_story]) log = with_active_record_log(colorize: false) do d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load_all([1,2,3]) end assert_equal "", log end it_dataloads "doesn't warm the cache when a scope is given" do |d| my_first_car = ::Album.find(2) homey = ::Album.find(4) summerteeth = ::Album.find(6) results = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :band, ::Band.country).load_all([my_first_car, homey, summerteeth]) assert_equal [nil, nil, ::Band.find(4)], results log = with_active_record_log(colorize: false) do d.with(GraphQL::Dataloader::ActiveRecordSource, Band).load_all([1,2,4]) end assert_includes log, "SELECT \"bands\".* FROM \"bands\" WHERE \"bands\".\"id\" IN (?, ?, ?) [[\"id\", 1], [\"id\", 2], [\"id\", 4]]" end it_dataloads "doesn't pause when the association is already loaded" do |d| source = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :band) assert_equal 0, source.results.size assert_equal 0, source.pending.size my_first_car = ::Album.find(2) vulfpeck = my_first_car.band vulfpeck2 = source.load(my_first_car) assert_equal vulfpeck, vulfpeck2 assert_equal 0, source.results.size assert_equal 0, source.pending.size my_first_car.reload vulfpeck3 = source.load(my_first_car) assert_equal vulfpeck, vulfpeck3 assert_equal 1, source.results.size assert_equal 0, source.pending.size end it_dataloads "raises an error with a non-existent association" do |d| my_first_car = ::Album.find(2) source = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :tour_bus) assert_raises ActiveRecord::AssociationNotFoundError do source.load(my_first_car) end end it_dataloads "works with polymorphic associations" do |d| wilco = ::Band.find(4) vulfpeck = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :thing).load(wilco) assert_equal ::Band.find(1), vulfpeck end it_dataloads "works with collection associations" do |d| wilco = ::Band.find(4) chon = ::Band.find(3) albums_by_band = nil log = with_active_record_log(colorize: false) do albums_by_band = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :albums).load_all([wilco, chon]) end assert_equal [[6], [4, 5]], albums_by_band.map { |al| al.map(&:id) } assert_includes log, 'SELECT "albums".* FROM "albums" WHERE "albums"."band_id" IN (?, ?) [["band_id", 4], ["band_id", 3]]' albums = nil log = with_active_record_log(colorize: false) do albums = d.with(GraphQL::Dataloader::ActiveRecordSource, Album).load_all([3,4,5,6]) end assert_equal [3,4,5,6], albums.map(&:id) assert_includes log, 'WHERE "albums"."id" = ? [["id", 3]]' end it_dataloads "works with collection associations with scope" do |d| wilco = ::Band.find(4) chon = ::Band.find(3) albums_by_band = nil one_month_ago = nil log = with_active_record_log(colorize: false) do one_month_ago = 1.month.ago.end_of_day albums_by_band_1 = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :albums, Album.where("created_at >= ?", one_month_ago)).request(wilco) albums_by_band_2 = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :albums, Album.where("created_at >= ?", one_month_ago)).request(chon) albums_by_band_3 = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :albums, Album.where("created_at <= ?", one_month_ago)).request(wilco) albums_by_band = [albums_by_band_1.load, albums_by_band_2.load, albums_by_band_3.load] end assert_equal [[6], [4, 5], []], albums_by_band.map { |al| al.map(&:id) } expected_log = if Rails::VERSION::STRING > "8" 'SELECT "albums".* FROM "albums" WHERE (created_at >= ?) AND "albums"."band_id" IN (?, ?)' else 'SELECT "albums".* FROM "albums" WHERE (created_at >= ' + one_month_ago.utc.strftime("'%Y-%m-%d %H:%M:%S.%6N'") + ') AND "albums"."band_id" IN (?, ?)' end assert_includes log, expected_log albums = nil log = with_active_record_log(colorize: false) do albums = d.with(GraphQL::Dataloader::ActiveRecordSource, Album).load_all([3,4,5,6]) end assert_equal [3,4,5,6], albums.map(&:id) assert_includes log, 'WHERE "albums"."id" IN (?, ?, ?, ?) [["id", 3], ["id", 4], ["id", 5], ["id", 6]]' end if Rails::VERSION::STRING > "7.1" # not supported in <7.1 it_dataloads "loads with composite primary keys and warms the cache" do |d| my_first_car = ::Album.find(2) homey = ::Album.find(4) log = with_active_record_log(colorize: false) do vulfpeck, chon = d.with(GraphQL::Dataloader::ActiveRecordAssociationSource, :composite_band).load_all([my_first_car, homey]) assert_equal "Vulfpeck", vulfpeck.name assert_equal "Chon", chon.name end assert_includes log, '[["name", "Vulfpeck"], ["name", "Chon"], ["genre", 0]]' log = with_active_record_log(colorize: false) do d.with(GraphQL::Dataloader::ActiveRecordSource, CompositeBand).load_all([["Vulfpeck", "rock"], ["Chon", :rock]]) end assert_equal "", log end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/dataloader/async_dataloader_spec.rb
spec/graphql/dataloader/async_dataloader_spec.rb
# frozen_string_literal: true require "spec_helper" if RUBY_VERSION >= "3.2.0" require "async" describe GraphQL::Dataloader::AsyncDataloader do class AsyncSchema < GraphQL::Schema class SleepSource < GraphQL::Dataloader::Source def initialize(tag = nil) @tag = tag end def fetch(keys) max_sleep = keys.max # t1 = Time.now # puts "----- SleepSource => #{max_sleep} (from: #{keys})" sleep(max_sleep) # puts "----- SleepSource done #{max_sleep} after #{Time.now - t1}" keys.map { |_k| max_sleep } end end class WaitForSource < GraphQL::Dataloader::Source def initialize(tag) @tag = tag end def fetch(waits) max_wait = waits.max # puts "[#{Time.now.to_f}] Waiting #{max_wait} for #{@tag}" `sleep #{max_wait}` # puts "[#{Time.now.to_f}] Finished for #{@tag}" waits.map { |_w| @tag } end end class KeyWaitForSource < GraphQL::Dataloader::Source class << self attr_accessor :fetches def reset @fetches = [] end end def initialize(wait) @wait = wait end def fetch(keys) self.class.fetches << keys sleep(@wait) keys end end class FiberLocalContextSource < GraphQL::Dataloader::Source def fetch(keys) keys.map { |key| Thread.current[key] } end end class Sleeper < GraphQL::Schema::Object field :sleeper, Sleeper, null: false, resolver_method: :sleep do argument :duration, Float end def sleep(duration:) context[:key_i] ||= 0 new_key = context[:key_i] += 1 dataloader.with(SleepSource, new_key).load(duration) duration end field :duration, Float, null: false def duration; object; end end class Waiter < GraphQL::Schema::Object field :wait_for, Waiter, null: false do argument :tag, String argument :wait, Float end def wait_for(tag:, wait:) dataloader.with(WaitForSource, tag).load(wait) end field :tag, String, null: false def tag object end end class Query < GraphQL::Schema::Object field :sleep, Float, null: false do argument :duration, Float end field :sleeper, Sleeper, null: false, resolver_method: :sleep do argument :duration, Float end def sleep(duration:) context[:key_i] ||= 0 new_key = context[:key_i] += 1 dataloader.with(SleepSource, new_key).load(duration) duration end field :wait_for, Waiter, null: false do argument :tag, String argument :wait, Float end def wait_for(tag:, wait:) dataloader.with(WaitForSource, tag).load(wait) end class ListWaiter < GraphQL::Schema::Object field :waiter, Waiter def waiter dataloader.with(KeyWaitForSource, object[:wait]).load(object[:tag]) end end field :list_waiters, [ListWaiter] do argument :wait, Float argument :tags, [String] end def list_waiters(wait:, tags:) Kernel.sleep(0.1) tags.map { |t| { tag: t, wait: wait }} end field :fiber_local_context, String do argument :key, String end def fiber_local_context(key:) dataloader.with(FiberLocalContextSource).load(key) end end query(Query) use GraphQL::Dataloader::AsyncDataloader end module AsyncDataloaderAssertions def self.included(child_class) child_class.class_eval do it "works with sources" do dataloader = GraphQL::Dataloader::AsyncDataloader.new r1 = dataloader.with(AsyncSchema::SleepSource, :s1).request(0.1) r2 = dataloader.with(AsyncSchema::SleepSource, :s2).request(0.2) r3 = dataloader.with(AsyncSchema::SleepSource, :s3).request(0.3) v1 = nil dataloader.append_job { v1 = r1.load } started_at = Time.now dataloader.run ended_at = Time.now assert_equal 0.1, v1 started_at_2 = Time.now # These should take no time at all since they're already resolved v2 = r2.load v3 = r3.load ended_at_2 = Time.now assert_equal 0.2, v2 assert_equal 0.3, v3 assert_in_delta 0.0, started_at_2 - ended_at_2, 0.06, "Already-loaded values returned instantly" assert_in_delta 0.3, ended_at - started_at, 0.06, "IO ran in parallel" end it "works with GraphQL" do started_at = Time.now res = @schema.execute("{ s1: sleep(duration: 0.1) s2: sleep(duration: 0.2) s3: sleep(duration: 0.3) }") ended_at = Time.now assert_equal({"s1"=>0.1, "s2"=>0.2, "s3"=>0.3}, res["data"]) assert_in_delta 0.3, ended_at - started_at, 0.06, "IO ran in parallel" end it "runs fields by depth" do query_str = <<-GRAPHQL { s1: sleeper(duration: 0.1) { sleeper(duration: 0.1) { sleeper(duration: 0.1) { duration } } } s2: sleeper(duration: 0.2) { sleeper(duration: 0.1) { duration } } s3: sleeper(duration: 0.3) { duration } } GRAPHQL started_at = Time.now res = @schema.execute(query_str) ended_at = Time.now expected_data = { "s1" => { "sleeper" => { "sleeper" => { "duration" => 0.1 } } }, "s2" => { "sleeper" => { "duration" => 0.1 } }, "s3" => { "duration" => 0.3 } } assert_graphql_equal expected_data, res["data"] assert_in_delta 0.5, ended_at - started_at, 0.06, "Each depth ran in parallel" end it "runs dataloaders in parallel across branches" do query_str = <<-GRAPHQL { w1: waitFor(tag: "a", wait: 0.2) { waitFor(tag: "b", wait: 0.2) { waitFor(tag: "c", wait: 0.2) { tag } } } # After the first, these are returned eagerly from cache w2: waitFor(tag: "a", wait: 0.2) { waitFor(tag: "a", wait: 0.2) { waitFor(tag: "a", wait: 0.2) { tag } } } w3: waitFor(tag: "a", wait: 0.2) { waitFor(tag: "b", wait: 0.2) { waitFor(tag: "d", wait: 0.2) { tag } } } w4: waitFor(tag: "e", wait: 0.6) { tag } } GRAPHQL started_at = Time.now res = @schema.execute(query_str) ended_at = Time.now expected_data = { "w1" => { "waitFor" => { "waitFor" => { "tag" => "c" } } }, "w2" => { "waitFor" => { "waitFor" => { "tag" => "a" } } }, "w3" => { "waitFor" => { "waitFor" => { "tag" => "d" } } }, "w4" => { "tag" => "e" } } assert_graphql_equal expected_data, res["data"] # We've basically got two options here: # - Put all jobs in the same queue (fields and sources), but then you don't get predictable batching. # - Work one-layer-at-a-time, but then layers can get stuck behind one another. That's what's implemented here. assert_in_delta 1.0, ended_at - started_at, 0.06, "Sources were executed in parallel" end it "groups across list items" do query_str = <<-GRAPHQL { listWaiters(wait: 0.2, tags: ["a", "b", "c"]) { waiter { tag } } } GRAPHQL t1 = Time.now result = @schema.execute(query_str) t2 = Time.now assert_equal ["a", "b", "c"], result["data"]["listWaiters"].map { |lw| lw["waiter"]["tag"]} # The field itself waits 0.1 assert_in_delta 0.3, t2 - t1, 0.06, "Wait was parallel" assert_equal [["a", "b", "c"]], AsyncSchema::KeyWaitForSource.fetches, "All keys were fetched at once" end it 'copies fiber-local variables over to sources' do key = 'arbitrary_context' value = 'test' Thread.current[key] = value query_str = <<-GRAPHQL { fiberLocalContext(key: "#{key}") } GRAPHQL result = @schema.execute(query_str) assert_equal value, result['data']['fiberLocalContext'] end end end end describe "with async" do before do @schema = AsyncSchema AsyncSchema::KeyWaitForSource.reset end include AsyncDataloaderAssertions end describe "with perfetto trace turned on" do class TraceAsyncSchema < AsyncSchema trace_with GraphQL::Tracing::PerfettoTrace use GraphQL::Dataloader::AsyncDataloader end before do @schema = TraceAsyncSchema AsyncSchema::KeyWaitForSource.reset end include AsyncDataloaderAssertions include PerfettoSnapshot it "produces a trace" do query_str = <<-GRAPHQL { s1: sleeper(duration: 0.1) { sleeper(duration: 0.1) { sleeper(duration: 0.1) { duration } } } s2: sleeper(duration: 0.2) { sleeper(duration: 0.1) { duration } } s3: sleeper(duration: 0.3) { duration } } GRAPHQL res = @schema.execute(query_str) if ENV["DUMP_PERFETTO"] res.context.query.current_trace.write(file: "perfetto.dump") end json = res.context.query.current_trace.write(file: nil, debug_json: true) data = JSON.parse(json) check_snapshot(data, "example.json") end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/type_kinds/type_kind_spec.rb
spec/graphql/type_kinds/type_kind_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::TypeKinds::TypeKind do describe ".leaf?" do it "is true for enums and scalars, but false for others" do assert GraphQL::Schema::Scalar.kind.leaf? assert GraphQL::Schema::Enum.kind.leaf? refute GraphQL::Schema::Object.kind.leaf? refute GraphQL::Schema::Interface.kind.leaf? refute GraphQL::Schema::Union.kind.leaf? refute GraphQL::Schema::InputObject.kind.leaf? end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/jobs/application_job.rb
spec/dummy/app/jobs/application_job.rb
# frozen_string_literal: true class ApplicationJob < ActiveJob::Base end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/helpers/application_helper.rb
spec/dummy/app/helpers/application_helper.rb
# frozen_string_literal: true module ApplicationHelper end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/graphql/dummy_schema.rb
spec/dummy/app/graphql/dummy_schema.rb
# frozen_string_literal: true begin require "graphql-pro" rescue LoadError => err puts "Skipping GraphQL::Pro: #{err.message}" end class DummySchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :str, String, fallback_value: "hello" field :sleep, Float do argument :seconds, Float end def sleep(seconds:) Kernel.sleep(seconds) seconds end end query(Query) class Subscription < GraphQL::Schema::Object field :message, String do argument :channel, String end end subscription(Subscription) DB_NUMBER = Rails.env.test? ? 1 : 2 use GraphQL::Tracing::DetailedTrace, redis: Redis.new(db: DB_NUMBER) if defined?(GraphQL::Pro) use GraphQL::Pro::OperationStore, redis: Redis.new(db: DB_NUMBER) use GraphQL::Pro::PusherSubscriptions, redis: Redis.new(db: DummySchema::DB_NUMBER), pusher: MockPusher.new class KeyNotRequiredLimiter < GraphQL::Enterprise::RuntimeLimiter def limiter_key(query) query. context[:limiter_key] || "unlimited" end def limit_for(key, query) key == "unlimited" ? nil : super end end use KeyNotRequiredLimiter, redis: Redis.new(db: DummySchema::DB_NUMBER), limit_ms: 100 end def self.detailed_trace?(query) query.context[:profile] end end # To preview rate limiter # puts "Making Rate-limited requests..." # 3.times.map do # pp DummySchema.execute("{ sleep(seconds: 0.02) }", context: { limiter_key: "client-1" }).to_h # end # 3.times.map do # pp DummySchema.execute("{ sleep(seconds: 0.110) }", context: { limiter_key: "client-2" }).to_h # end # puts " ... done" # To preview subscription data in the dashboard: # DummySchema.subscriptions.clear # res1 = DummySchema.execute("subscription { message(channel: \"cats\") }") # res2 = DummySchema.execute("subscription { message(channel: \"dogs\") }") # DummySchema.subscriptions.trigger(:message, { channel: "cats" }, "meow")
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/graphql/mock_pusher.rb
spec/dummy/app/graphql/mock_pusher.rb
# frozen_string_literal: true class MockPusher class Channel attr_reader :id, :occupants def initialize(id) @id = id @occupants = 0 @inboxes = [[]] end def trigger(event_name, payload) if event_name != "update" raise "Invariant: GraphQL is only expected to call update, but received #{event_name.inspect}. Fix tests or implementation." end @inboxes.each do |ibx| ibx << payload end nil end def new_inbox ibx = [] @inboxes << ibx ibx end def updates @inboxes[0] end def occupant_left @occupants -= 1 if @occupants < 0 raise "Invariant: less than 0 occupants for #{self.inspect}" end nil end def occupant_entered @occupants += 1 nil end def occupied? @occupants > 0 end end def initialize @channels = Hash.new { |h, k| h[k] = Channel.new(k) } @key = "abcdef" @secret = "12345" @batch_sizes = [] end attr_reader :key, :secret, :batch_sizes # Mock pusher: def channel_info(channel_name, info: "") channel = @channels[channel_name] res = { occupied: channel.occupied? } if info.include?("subscription_count") res[:subscription_count] = channel.occupants end res end def trigger(channel_name, action, payload) @channels[channel_name].trigger(action, payload) end def trigger_batch(triggers) @batch_sizes << triggers.size triggers.each do |trigger| @channels[trigger[:channel]].trigger(trigger[:name], trigger[:data]) end end # Testing: def channel(channel_name) @channels[channel_name] end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/graphql/not_installed_schema.rb
spec/dummy/app/graphql/not_installed_schema.rb
# frozen_string_literal: true class NotInstalledSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :str, String, fallback_value: "hello" end query(Query) end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/controllers/pages_controller.rb
spec/dummy/app/controllers/pages_controller.rb
# frozen_string_literal: true class PagesController < ApplicationController def show end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/controllers/application_controller.rb
spec/dummy/app/controllers/application_controller.rb
# frozen_string_literal: true class ApplicationController < ActionController::Base protect_from_forgery with: :exception end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/channels/graphql_channel.rb
spec/dummy/app/channels/graphql_channel.rb
# frozen_string_literal: true class GraphqlChannel < ActionCable::Channel::Base class QueryType < GraphQL::Schema::Object field :value, Integer, null: false def value 3 end end class PayloadType < GraphQL::Schema::Object field :value, Integer, null: false end class CounterIncremented < GraphQL::Schema::Subscription def self.reset_call_count @@call_count = 0 end reset_call_count field :new_value, Integer, null: false def update if object if object.value == "server-unsubscribe" unsubscribe elsif object.value == "server-unsubscribe-with-message" unsubscribe({ new_value: 9999 }) end end result = { new_value: @@call_count += 1 } puts " -> CounterIncremented#update: #{result}" result end end class SubscriptionType < GraphQL::Schema::Object field :payload, PayloadType, null: false do argument :id, ID end field :counter_incremented, subscription: CounterIncremented end # Wacky behavior around the number 4 # so we can confirm it's used by the UI module CustomSerializer def self.load(value) if value == "4x" ExamplePayload.new(400) else GraphQL::Subscriptions::Serialize.load(value) end end def self.dump(obj) if obj.is_a?(ExamplePayload) && obj.value == 4 "4x" else GraphQL::Subscriptions::Serialize.dump(obj) end end end class GraphQLSchema < GraphQL::Schema query(QueryType) subscription(SubscriptionType) use GraphQL::Subscriptions::ActionCableSubscriptions, serializer: CustomSerializer, broadcast: true, default_broadcastable: true end def subscribed @subscription_ids = [] end def execute(data) query = data["query"] variables = data["variables"] || {} operation_name = data["operationName"] context = { # Make sure the channel is in the context channel: self, } puts "[GraphQLSchema.execute] #{query} || #{variables}" result = GraphQLSchema.execute( query: query, context: context, variables: variables, operation_name: operation_name ) payload = { result: result.to_h, more: result.subscription?, } # Track the subscription here so we can remove it # on unsubscribe. if result.context[:subscription_id] @subscription_ids << result.context[:subscription_id] end puts " -> [transmit(#{result.context[:subscription_id]})] #{payload.inspect}" transmit(payload) end def make_trigger(data) field = data["field"] args = data["arguments"] value = data["value"] value = value && ExamplePayload.new(value) puts "[make_trigger] #{[field, args, value]}" GraphQLSchema.subscriptions.trigger(field, args, value) end def unsubscribed @subscription_ids.each { |sid| puts "[delete_subscription] #{sid}" GraphQLSchema.subscriptions.delete_subscription(sid) } end # This is to make sure that GlobalID is used to load and dump this object class ExamplePayload include GlobalID::Identification def initialize(value) @value = value end def self.find(value) self.new(value) end attr_reader :value alias :id :value end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/channels/application_cable/channel.rb
spec/dummy/app/channels/application_cable/channel.rb
# frozen_string_literal: true module ApplicationCable class Channel < ActionCable::Channel::Base end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/app/channels/application_cable/connection.rb
spec/dummy/app/channels/application_cable/connection.rb
# frozen_string_literal: true module ApplicationCable class Connection < ActionCable::Connection::Base end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/application_system_test_case.rb
spec/dummy/test/application_system_test_case.rb
# frozen_string_literal: true require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :selenium, using: :headless_chrome, screen_size: [1400, 1400] end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/test_helper.rb
spec/dummy/test/test_helper.rb
# frozen_string_literal: true require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help'
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/system/action_cable_subscription_test.rb
spec/dummy/test/system/action_cable_subscription_test.rb
# frozen_string_literal: true require "application_system_test_case" class ActionCableSubscriptionsTest < ApplicationSystemTestCase setup do ActionCable.server.config.logger = Logger.new(STDOUT) end # This test covers a lot of ground! test "it handles subscriptions" do # Load the page and let the subscriptions happen visit "/" # make sure they connect successfully assert_selector "#updates-1-connected" assert_selector "#updates-2-connected" # Trigger a few updates, make sure we get a client update: click_on("Trigger 1") click_on("Trigger 1") click_on("Trigger 1") assert_selector "#updates-1-3", text: "3" # Make sure there aren't any unexpected elements: refute_selector "#updates-1-4" refute_selector "#updates-2-1" # Now, trigger updates to a different stream # and make sure the previous stream is not affected click_on("Trigger 2") click_on("Trigger 2") assert_selector "#updates-2-1", text: "1" assert_selector "#updates-2-2", text: "2" refute_selector "#updates-2-3" refute_selector "#updates-1-4" # Now unsubscribe one, it should not receive updates but the other should click_on("Unsubscribe 1") click_on("Trigger 1") # This should not have changed refute_selector "#updates-1-4" click_on("Trigger 2") assert_selector "#updates-2-3", text: "3" refute_selector "#updates-1-4" # wacky behavior to make sure the custom serializer is used: click_on("Trigger 2") assert_selector "#updates-2-400", text: "400" end # Wrap an `assert_selector` call in a debugging check def debug_assert_selector(selector) if !page.has_css?(selector) puts "[debug_assert_selector(#{selector.inspect})] Failed to find #{selector.inspect} in:" puts page.html else puts "[debug_assert_selector(#{selector.inspect})] Found #{selector.inspect}" end assert_selector(selector) end # It seems like ActionCable's order of evaluation here is non-deterministic, # so detect which order to make the assertions. # (They still both have to pass, but we don't know exactly what order the evaluations went in.) def detect_update_values(possibility_1, possibility_2) if page.has_css?("#fingerprint-updates-1-update-1-value-#{possibility_1}") [possibility_1, possibility_2] else [possibility_2, possibility_1] end end test "it only re-runs queries once for subscriptions with matching fingerprints" do GraphqlChannel::CounterIncremented.reset_call_count visit "/" using_wait_time 10 do sleep 1 # Make 3 subscriptions to the same payload click_on("Subscribe with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-connected-1" click_on("Subscribe with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-connected-2" click_on("Subscribe with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-connected-3" # And two to the next payload click_on("Subscribe with fingerprint 2") debug_assert_selector "#fingerprint-updates-2-connected-1" click_on("Subscribe with fingerprint 2") debug_assert_selector "#fingerprint-updates-2-connected-2" # Now trigger. We expect a total of two updates: # - One is built & delivered to the first three subscribers # - Another is built & delivered to the next two click_on("Trigger with fingerprint 2") # The order here is random, I think depending on ActionCable's internal storage: fingerprint_1_value, fingerprint_2_value = detect_update_values(1, 2) # These all share the first value: debug_assert_selector "#fingerprint-updates-1-update-1-value-#{fingerprint_1_value}" debug_assert_selector "#fingerprint-updates-1-update-2-value-#{fingerprint_1_value}" debug_assert_selector "#fingerprint-updates-1-update-3-value-#{fingerprint_1_value}" # and these share the second value: debug_assert_selector "#fingerprint-updates-2-update-1-value-#{fingerprint_2_value}" debug_assert_selector "#fingerprint-updates-2-update-2-value-#{fingerprint_2_value}" click_on("Unsubscribe with fingerprint 2") click_on("Trigger with fingerprint 1") fingerprint_1_value_2, fingerprint_2_value_2 = detect_update_values(3, 4) # These get an update debug_assert_selector "#fingerprint-updates-1-update-1-value-#{fingerprint_1_value_2}" debug_assert_selector "#fingerprint-updates-1-update-2-value-#{fingerprint_1_value_2}" debug_assert_selector "#fingerprint-updates-1-update-3-value-#{fingerprint_1_value_2}" # But these are unsubscribed: refute_selector "#fingerprint-updates-2-update-1-value-#{fingerprint_2_value_2}" refute_selector "#fingerprint-updates-2-update-2-value-#{fingerprint_2_value_2}" click_on("Unsubscribe with fingerprint 1") # Make a new subscription and make sure it's updated: click_on("Subscribe with fingerprint 2") click_on("Trigger with fingerprint 2") debug_assert_selector "#fingerprint-updates-2-update-1-value-#{fingerprint_2_value_2}" # But this one was unsubscribed: refute_selector "#fingerprint-updates-1-update-1-value-#{fingerprint_1_value_2 + 1}" refute_selector "#fingerprint-updates-1-update-1-value-#{fingerprint_1_value_2 + 2}" end end test "it unsubscribes from the server" do GraphqlChannel::CounterIncremented.reset_call_count visit "/" using_wait_time 10 do sleep 1 # Establish the connection click_on("Subscribe with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-connected-1" # Trigger once click_on("Trigger with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-update-1-value-1" # Server unsubscribe click_on("Server-side unsubscribe with fingerprint 1") # Subsequent updates should fail click_on("Trigger with fingerprint 1") refute_selector "#fingerprint-updates-1-update-2-value-2" # The client has only 2 connections (from the initial 2) assert_text "Remaining ActionCable subscriptions: 2" end end test "it unsubscribes with a message" do GraphqlChannel::CounterIncremented.reset_call_count visit "/" using_wait_time 10 do sleep 1 # Establish the connection click_on("Subscribe with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-connected-1" # Trigger once click_on("Trigger with fingerprint 1") debug_assert_selector "#fingerprint-updates-1-update-1-value-1" # Server unsubscribe click_on("Unsubscribe with message with fingerprint 1") # Magic value from unsubscribe hook: debug_assert_selector "#fingerprint-updates-1-update-1-value-9999" # The client has only 2 connections (from the initial 2) assert_text "Remaining ActionCable subscriptions: 2" end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/application_controller_test.rb
spec/dummy/test/controllers/dashboard/application_controller_test.rb
# frozen_string_literal: true require "test_helper" class DashboardApplicationControllerTest < ActionDispatch::IntegrationTest def test_it_calls_on_load_hook assert_equal true, GraphQL::Dashboard::ApplicationController.hook_was_called? end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/statics_controller_test.rb
spec/dummy/test/controllers/dashboard/statics_controller_test.rb
# frozen_string_literal: true require "test_helper" class DashboardStaticsControllerTest < ActionDispatch::IntegrationTest def test_it_serves_assets get graphql_dashboard.static_path("dashboard.css") assert_includes response.body, "#header-icon {" assert_equal response.headers["Cache-Control"], "max-age=31556952, public" end def test_it_responds_404_for_others get graphql_dashboard.static_path("other.rb") assert_equal 404, response.status assert_raises ActionController::UrlGenerationError do graphql_dashboard.static_path("invalid~char.js") end get graphql_dashboard.static_path("invalid-char.js").sub("-char", "~char") assert_equal 404, response.status end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/landings_controller_test.rb
spec/dummy/test/controllers/dashboard/landings_controller_test.rb
# frozen_string_literal: true require "test_helper" class DashboardLandingsControllerTest < ActionDispatch::IntegrationTest def test_it_shows_a_landing_page get graphql_dashboard.root_path assert_includes response.body, "Welcome to the GraphQL-Ruby Dashboard" end def test_it_shows_version_and_schema_info get graphql_dashboard.root_path assert_includes response.body, "GraphQL-Ruby v#{GraphQL::VERSION}" assert_includes response.body, "<code>DummySchema</code>" get graphql_dashboard.root_path, params: { schema: "NotInstalledSchema" } assert_includes response.body, "<code>NotInstalledSchema</code>" end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/subscriptions/topics_controller_test.rb
spec/dummy/test/controllers/dashboard/subscriptions/topics_controller_test.rb
# frozen_string_literal: true require "test_helper" require "ostruct" # TODO use a real class in RedisBackend if defined?(GraphQL::Pro) class DashboardSubscriptionsTopicsControllerTest < ActionDispatch::IntegrationTest def test_it_checks_installed get graphql_dashboard.subscriptions_topics_path, params: { schema: GraphQL::Schema } assert_includes response.body, "GraphQL-Pro Subscriptions aren't installed on this schema yet." end def test_it_renders_empty_state_and_not_found_states get graphql_dashboard.subscriptions_topics_path assert_includes response.body, "There aren't any subscriptions right now." get graphql_dashboard.subscriptions_topic_path(":something:") assert_includes response.body, ":something:" assert_includes response.body, "Last triggered: none" assert_includes response.body, "0 Subscriptions" get graphql_dashboard.subscriptions_subscription_path("abcd-efg") assert_includes response.body, "abcd-efg" assert_includes response.body, "This subscription was not found or is no longer active." end def test_it_lists_topics_and_shows_detail DummySchema.subscriptions.clear _res1 = DummySchema.execute("subscription { message(channel: \"cats\") }") res2 = DummySchema.execute("subscription { message(channel: \"dogs\") }") DummySchema.subscriptions.trigger(:message, { channel: "dogs"}, "Woof!") get graphql_dashboard.subscriptions_topics_path assert_includes response.body, ":message:channel:cats" assert_includes response.body, ":message:channel:dogs" assert_includes response.body, Time.now.strftime("%Y-%m-%d %H:%M:%S") get graphql_dashboard.subscriptions_topic_path(":message:channel:dogs") assert_includes response.body, res2.context[:subscription_id] assert_includes response.body, Time.now.strftime("%Y-%m-%d %H:%M:%S") get graphql_dashboard.subscriptions_subscription_path(res2.context[:subscription_id]) assert_includes response.body, res2.context[:subscription_id] assert_includes response.body, CGI::escapeHTML('subscription { message(channel: "dogs") }') post graphql_dashboard.subscriptions_clear_all_path get graphql_dashboard.subscriptions_topics_path refute_includes response.body, ":message:" ensure DummySchema.subscriptions.clear end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/limiters/limiters_controller_test.rb
spec/dummy/test/controllers/dashboard/limiters/limiters_controller_test.rb
# frozen_string_literal: true require "test_helper" if defined?(GraphQL::Pro) class DashboardLimitersLimitersControllerTest < ActionDispatch::IntegrationTest def test_it_checks_installed get graphql_dashboard.limiters_limiter_path("runtime", { schema: "GraphQL::Schema" }) assert_includes response.body, CGI::escapeHTML("Rate limiters aren't installed on this schema yet.") refute_includes response.headers["Content-Security-Policy"], "nonce-" end def test_it_shows_limiters Redis.new(db: DummySchema::DB_NUMBER).flushdb 3.times do DummySchema.execute("{ sleep(seconds: 0.02) }", context: { limiter_key: "client-1" }).to_h end 4.times do DummySchema.execute("{ sleep(seconds: 0.110) }", context: { limiter_key: "client-2" }).to_h end get graphql_dashboard.limiters_limiter_path("runtime") assert_includes response.body, "<span class=\"data\">4</span>" assert_includes response.body, "<span class=\"data\">3</span>" assert_includes response.body, "Disable Soft Limiting" assert_includes response.headers["Content-Security-Policy"], "nonce-" patch graphql_dashboard.limiters_limiter_path("runtime") get graphql_dashboard.limiters_limiter_path("runtime") assert_includes response.body, "Enable Soft Limiting" get graphql_dashboard.limiters_limiter_path("active_operations") assert_includes response.body, "It looks like this limiter isn't installed yet." end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/operation_store/clients_controller_test.rb
spec/dummy/test/controllers/dashboard/operation_store/clients_controller_test.rb
# frozen_string_literal: true require "test_helper" if defined?(GraphQL::Pro) class DashboardOperationStoreClientsControllerTest < ActionDispatch::IntegrationTest def test_it_manages_clients assert_equal 0, DummySchema.operation_store.all_clients(page: 1, per_page: 1).total_count get graphql_dashboard.operation_store_clients_path assert_includes response.body, "0 Clients" assert_includes response.body, "To get started, create" get graphql_dashboard.new_operation_store_client_path assert_includes response.body, "New Client" post graphql_dashboard.operation_store_clients_path, params: { client: { name: "client-1", secret: "abcdefedcba" } } get graphql_dashboard.operation_store_clients_path assert_includes response.body, "1 Client" get graphql_dashboard.edit_operation_store_client_path(name: "client-1") assert_includes response.body, "abcdefedcba" patch graphql_dashboard.operation_store_client_path(name: "client-1"), params: { client: { secret: "123456789" } } get graphql_dashboard.edit_operation_store_client_path(name: "client-1") assert_includes response.body, "123456789" delete graphql_dashboard.operation_store_client_path(name: "client-1") assert_equal 0, DummySchema.operation_store.all_clients(page: 1, per_page: 1).total_count ensure DummySchema.operation_store.delete_client("client-1") end def test_it_paginates 5.times do |i| DummySchema.operation_store.upsert_client("client-#{i}", "abcdef") end get graphql_dashboard.operation_store_clients_path(per_page: 2) assert_includes response.body, "5 Clients" assert_includes response.body, "?page=2&amp;per_page=2" assert_includes response.body, "disabled>« prev</button>" get graphql_dashboard.operation_store_clients_path(per_page: 2, page: 2) assert_includes response.body, "?page=1&amp;per_page=2" assert_includes response.body, "?page=3&amp;per_page=2" get graphql_dashboard.operation_store_clients_path(per_page: 2, page: 3) assert_includes response.body, "disabled>next »</button>" assert_includes response.body, "?page=2&amp;per_page=2" ensure 5.times do |i| DummySchema.operation_store.delete_client("client-#{i}") end end def test_it_checks_installed get graphql_dashboard.new_operation_store_client_path, params: { schema: GraphQL::Schema } assert_includes response.body, "isn't installed for this schema yet" end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/operation_store/operations_controller_test.rb
spec/dummy/test/controllers/dashboard/operation_store/operations_controller_test.rb
# frozen_string_literal: true require "test_helper" if defined?(GraphQL::Pro) class DashboardOperationStoreOperationsControllerTest < ActionDispatch::IntegrationTest def teardown DummySchema.operation_store.delete_client("client-1") DummySchema.operation_store.delete_client("client-2") super end def test_it_lists_shows_and_archives_operations get graphql_dashboard.operation_store_operations_path assert_includes response.body, "Add your first stored operations with" get graphql_dashboard.operation_store_operations_path(client_name: "client-5000") assert_includes response.body, "Add your first stored operations with" get graphql_dashboard.archived_operation_store_operations_path assert_includes response.body, "Archived operations</a> will appear here." get graphql_dashboard.archived_operation_store_client_operations_path(client_name: "client-5000") assert_includes response.body, "Archived operations</a> will appear here." os = DummySchema.operation_store os.upsert_client("client-1", "abcdef") os.add(body: "query GetTypename { __typename }", operation_alias: "GetTypename", client_name: "client-1") os.add(body: "query GetAliasedTypename { t: __typename }", operation_alias: "get-aliased-typename", client_name: "client-1") os.upsert_client("client-2", "abcdef") os.add(body: "query GetTypename { __typename }", operation_alias: "GetTypename2", client_name: "client-2") get graphql_dashboard.operation_store_operations_path assert_includes response.body, "2 Active" assert_includes response.body, "GetTypename" assert_includes response.body, "GetAliasedTypename" get graphql_dashboard.operation_store_operations_path(sort_by: "name", order_dir: "asc", per_page: 1) refute_includes response.body, "GetTypename" assert_includes response.body, "GetAliasedTypename" get graphql_dashboard.operation_store_operations_path(sort_by: "name", order_dir: "desc", per_page: 1) assert_includes response.body, "GetTypename" refute_includes response.body, "GetAliasedTypename" get graphql_dashboard.operation_store_operations_path(client_name: "client-2") assert_includes response.body, "1 Active" assert_includes response.body, "GetTypename" refute_includes response.body, "GetAliasedTypename" get graphql_dashboard.operation_store_operation_path(digest: "4cd12cc333c91f78e8f781933ecc783d") assert_includes response.body, "GetAliasedTypename" assert_includes response.body, "client-1" assert_includes response.body, "Query.__typename" post graphql_dashboard.archive_operation_store_client_operations_path(client_name: "client-1", operation_aliases: ["get-aliased-typename"]) post graphql_dashboard.archive_operation_store_operations_path(digests: ["b161214b11847649e7f36cc50e1257a1"]) get graphql_dashboard.operation_store_operations_path assert_includes response.body, "0 Active" assert_includes response.body, "2 Archived" get graphql_dashboard.archived_operation_store_operations_path assert_includes response.body, "2 Archived" assert_includes response.body, "0 Active" get graphql_dashboard.operation_store_operations_path(client_name: "client-2") assert_includes response.body, "0 Active" assert_includes response.body, "1 Archived" end def test_it_checks_installed get graphql_dashboard.new_operation_store_client_path, params: { schema: GraphQL::Schema } assert_includes response.body, "isn't installed for this schema yet" end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/operation_store/index_entries_controller_test.rb
spec/dummy/test/controllers/dashboard/operation_store/index_entries_controller_test.rb
# frozen_string_literal: true require "test_helper" if defined?(GraphQL::Pro) class DashboardOperationStoreIndexEntriesControllerTest < ActionDispatch::IntegrationTest def test_it_shows_entries DummySchema.operation_store.upsert_client("client-1", "abcdef") DummySchema.operation_store.add(body: "query GetTypename { __type(name: \"Query\") { name @skip(if: true) } }", operation_alias: "GetTypename", client_name: "client-1") get graphql_dashboard.operation_store_index_entries_path assert_includes response.body, "Query.__type.name" assert_includes response.body, "7 entries" get graphql_dashboard.operation_store_index_entries_path(q: "Query") assert_includes response.body, "3 results" assert_includes response.body, ">Query</a>" assert_includes response.body, ">Query.__type</a>" assert_includes response.body, ">Query.__type.name</a>" get graphql_dashboard.operation_store_index_entries_path(q: "Query", per_page: 1, page: 2) assert_includes response.body, "3 results" refute_includes response.body, ">Query</a>" assert_includes response.body, ">Query.__type</a>" refute_includes response.body, ">Query.__type.name</a>" get graphql_dashboard.operation_store_index_entry_path(name: "Query.__type.name") assert_includes response.body, "GetTypename" ensure DummySchema.operation_store.delete_client("client-1") end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/controllers/dashboard/detailed_traces/traces_controller_test.rb
spec/dummy/test/controllers/dashboard/detailed_traces/traces_controller_test.rb
# frozen_string_literal: true require "test_helper" class DashboardTracesControllerTest < ActionDispatch::IntegrationTest def teardown DummySchema.detailed_trace.delete_all_traces end def test_it_renders_not_installed get graphql_dashboard.detailed_traces_traces_path, params: { schema: "NotInstalledSchema" } assert_includes response.body, CGI::escapeHTML("Detailed traces aren't installed yet") assert_includes response.body, "<code>NotInstalledSchema</code>" end def test_it_renders_blank_state get graphql_dashboard.detailed_traces_traces_path assert_includes response.body, "No traces saved yet." assert_includes response.body, "<code>DummySchema</code>" end def test_it_renders_trace_listing_with_pagination 20.times do |n| sleep 0.05 DummySchema.execute("query Query#{n} { str }", context: { profile: true }) end assert_equal 20, DummySchema.detailed_trace.traces.size get graphql_dashboard.detailed_traces_traces_path, params: { last: 10 } assert_includes response.body, "Query19" assert_includes response.body, "Query10" refute_includes response.body, "Query9" last_trace = DummySchema.detailed_trace.traces[9] last_ts = last_trace.begin_ms assert_includes response.body, "<td>#{Time.at(last_ts / 1000.0).strftime("%Y-%m-%d %H:%M:%S.%L")}</td>" assert_includes response.body, "<a class=\"btn btn-outline-primary\" href=\"/dash/detailed_traces/traces?before=#{last_ts}&amp;last=10\">Previous &gt;</a>" get graphql_dashboard.detailed_traces_traces_path, params: { last: 10, before: last_ts } assert_includes response.body, "Query9" assert_includes response.body, "Query0" refute_includes response.body, "Query10" very_last_trace = DummySchema.detailed_trace.traces.last very_last_ts = very_last_trace.begin_ms very_last_td = "<td>#{Time.at(very_last_ts / 1000.0).strftime("%Y-%m-%d %H:%M:%S.%L")}</td>" assert_includes response.body, very_last_td very_last_previous_link = "<a class=\"btn btn-outline-primary\" href=\"/dash/detailed_traces/traces?before=#{very_last_ts}&amp;last=10\">Previous &gt;</a>" assert_includes response.body, very_last_previous_link # Go beyond last trace: get graphql_dashboard.detailed_traces_traces_path, params: { last: 11, before: last_ts } assert_includes response.body, very_last_td refute_includes response.body, very_last_previous_link end def test_it_deletes_one_trace DummySchema.execute("{ str }", context: { profile: true }) assert_equal 1, DummySchema.detailed_trace.traces.size id = DummySchema.detailed_trace.traces.first.id delete graphql_dashboard.detailed_traces_trace_path(id) assert_equal 0, DummySchema.detailed_trace.traces.size end def test_it_deletes_all_traces DummySchema.execute("{ str }", context: { profile: true }) assert_equal 1, DummySchema.detailed_trace.traces.size delete graphql_dashboard.delete_all_detailed_traces_traces_path assert_equal 0, DummySchema.detailed_trace.traces.size end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/test/channels/graphql_channel_test.rb
spec/dummy/test/channels/graphql_channel_test.rb
# frozen_string_literal: true require "test_helper" class GraphqlChannelTest < ActionCable::Channel::TestCase module RealChannelStub def confirmed? subscription_confirmation_sent? end def real_streams streams end end def assert_has_real_stream(stream_name) assert subscription.real_streams.key?(stream_name), "Expected Stream #{stream_name.inspect} to be present in #{subscription.real_streams.keys}" end def setup @prev_server = ActionCable.server @server = TestServer.new(subscription_adapter: ActionCable::SubscriptionAdapter::Async) @server.config.allowed_request_origins = [ 'http://rubyonrails.com' ] ActionCable.instance_variable_set(:@server, @server) end def teardown ActionCable.instance_variable_set(:@server, @prev_server) end def wait_for_async wait_for_executor Concurrent.global_io_executor end def run_in_eventmachine yield wait_for_async end def wait_for_executor(executor) # do not wait forever, wait 2s timeout = 2 until executor.completed_task_count == executor.scheduled_task_count sleep 0.1 timeout -= 0.1 raise "Executor could not complete all tasks in 2 seconds" unless timeout > 0 end end class Connection < ActionCable::Connection::Base attr_reader :websocket def send_async(method, *args) send method, *args end public :handle_close end module InterceptTransmit def transmit(msg) intercepted_messages << JSON.parse(msg) super end def intercepted_messages @intercepted_messages ||= [] end end test "it subscribes and unsubscribes" do run_in_eventmachine do env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket", "HTTP_ORIGIN" => "http://rubyonrails.com" @connection = Connection.new(ActionCable.server, env).tap do |connection| connection.process assert_predicate connection.websocket, :possible? wait_for_async assert_predicate connection.websocket, :alive? connection.websocket.singleton_class.prepend(InterceptTransmit) end @connection.subscriptions.add({"identifier" => "{\"channel\": \"GraphqlChannel\"}"}) @subscription = @connection.subscriptions.instance_variable_get(:@subscriptions).values.first @subscription.singleton_class.prepend(RealChannelStub) assert subscription.confirmed? subscription.execute({ "query" => "subscription { payload(id: \"abc\") { value } }" }) wait_for_async sub_id = subscription.instance_variable_get(:@subscription_ids).first subscription_stream = "graphql-subscription:#{sub_id}" assert_has_real_stream subscription_stream topic_stream = "graphql-event::payload:id:abc" assert_has_real_stream topic_stream subscription.make_trigger({ "field" => "payload", "arguments" => { "id" => "abc"}, "value" => 19 }) wait_for_async @connection.handle_close wait_for_async expected_data = [ {"identifier"=>"{\"channel\": \"GraphqlChannel\"}", "type"=>"confirm_subscription"}, {"identifier"=>"{\"channel\": \"GraphqlChannel\"}", "message"=>{"result"=>{"data"=>{}}, "more"=>true}}, {"identifier"=>"{\"channel\": \"GraphqlChannel\"}", "message"=>{"result"=>{"data"=>{"payload"=>{"value"=>19}}}, "more"=>true}}, {"identifier"=>"{\"channel\": \"GraphqlChannel\"}", "message"=>{"more"=>false}}, ] assert_equal expected_data, @connection.websocket.intercepted_messages end end class TestServer include ActionCable::Server::Connections include ActionCable::Server::Broadcasting attr_reader :logger, :config, :mutex class FakeConfiguration < ActionCable::Server::Configuration attr_accessor :subscription_adapter, :log_tags, :filter_parameters def initialize(subscription_adapter:) @log_tags = [] @filter_parameters = [] @subscription_adapter = subscription_adapter end def pubsub_adapter @subscription_adapter end end def initialize(subscription_adapter: SuccessAdapter) @logger = ActiveSupport::TaggedLogging.new ActiveSupport::Logger.new(StringIO.new) @config = FakeConfiguration.new(subscription_adapter: subscription_adapter) @mutex = Monitor.new end def pubsub @pubsub ||= @config.subscription_adapter.new(self) end def event_loop @event_loop ||= ActionCable::Connection::StreamEventLoop.new.tap do |loop| loop.instance_variable_set(:@executor, Concurrent.global_io_executor) end end def worker_pool @worker_pool ||= ActionCable::Server::Worker.new(max_size: 5) end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/application.rb
spec/dummy/config/application.rb
# frozen_string_literal: true require_relative 'boot' require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "action_controller/railtie" require "action_view/railtie" require "action_cable/engine" require "sprockets/railtie" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Dummy class Application < Rails::Application # Don't generate system test files. config.generators.system_tests = nil end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/environment.rb
spec/dummy/config/environment.rb
# frozen_string_literal: true # Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false