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/introspection/input_value_type_spec.rb
spec/graphql/introspection/input_value_type_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Introspection::InputValueType do let(:query_string) {%| { __type(name: "DairyProductInput") { name description kind inputFields { name type { kind, name } defaultValue description } } } |} let(:result) { Dummy::Schema.execute(query_string) } it "exposes metadata about input objects, giving extra quotes for strings" do expected = { "data" => { "__type" => { "name"=>"DairyProductInput", "description"=>"Properties for finding a dairy product", "kind"=>"INPUT_OBJECT", "inputFields"=>[ {"name"=>"source", "type"=>{"kind"=>"NON_NULL", "name" => nil}, "defaultValue"=>nil, "description" => "Where it came from"}, {"name"=>"originDairy", "type"=>{"kind"=>"SCALAR", "name" => "String"}, "defaultValue"=>"\"Sugar Hollow Dairy\"", "description" => "Dairy which produced it"}, {"name"=>"fatContent", "type"=>{"kind"=>"SCALAR", "name" => "Float"}, "defaultValue"=>"0.3", "description" => "How much fat it has"}, {"name"=>"organic", "type"=>{"kind"=>"SCALAR", "name" => "Boolean"}, "defaultValue"=>"false", "description" => nil}, {"name"=>"order_by", "type"=>{"kind"=>"INPUT_OBJECT", "name"=>"ResourceOrderType"}, "defaultValue"=>"{direction: \"ASC\"}", "description" => nil}, ] } }} assert_equal(expected, result.to_h) end let(:cheese_type) { Dummy::Schema.execute(%| { __type(name: "Cheese") { fields { name args { name defaultValue } } } } |) } it "converts default values to GraphQL values" do field = cheese_type['data']['__type']['fields'].detect { |f| f['name'] == 'similarCheese' } arg = field['args'].detect { |a| a['name'] == 'nullableSource' } assert_equal('[COW]', arg['defaultValue']) end it "supports list of enum default values" do schema = GraphQL::Schema.from_definition(%| type Query { hello(enums: [MyEnum] = [A, B]): String } enum MyEnum { A B } |) result = schema.execute(%| { __type(name: "Query") { fields { args { defaultValue } } } } |) expected = { "data" => { "__type" => { "fields" => [{ "args" => [{ "defaultValue" => "[A, B]" }] }] } } } assert_equal expected, result end it "supports null default values" do schema = GraphQL::Schema.from_definition(%| type Query { hello(person: Person): String } input Person { firstName: String! lastName: String = null } |) result = schema.execute(%| { __type(name: "Person") { inputFields { name defaultValue } } } |) expected = { "data" => { "__type" => { "inputFields" => [ { "name" => "firstName", "defaultValue" => nil}, { "name" => "lastName", "defaultValue" => "null"} ] } } } assert_equal expected, result 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/introspection/entry_points_spec.rb
spec/graphql/introspection/entry_points_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Introspection::EntryPoints do describe "#__type" do let(:schema) do nested_invisible_type = Class.new(GraphQL::Schema::Object) do graphql_name 'NestedInvisible' field :foo, String, null: false end invisible_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Invisible' field :foo, String, null: false field :nested_invisible, nested_invisible_type, null: false def self.visible?(context) false end end visible_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Visible' field :foo, String, null: false end query_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Query' field :foo, String, null: false field :invisible, invisible_type, null: false field :visible, visible_type, null: false end Class.new(GraphQL::Schema) do query query_type use GraphQL::Schema::Warden if ADD_WARDEN end end let(:query_string) {%| query getType($name: String!) { __type(name: $name) { name } } |} it "returns reachable types" do result = schema.execute(query_string, variables: { name: 'Visible' }) type_name = result['data']['__type']['name'] assert_equal('Visible', type_name) end it "returns nil for unreachable types" do result = schema.execute(query_string, variables: { name: 'NestedInvisible' }) type_name = result['data']['__type'] assert_nil(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/introspection/schema_type_spec.rb
spec/graphql/introspection/schema_type_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Introspection::SchemaType do let(:schema) { Class.new(Dummy::Schema) { description("Cool schema") }} let(:query_string) {%| query getSchema { __schema { description types { name } queryType { fields { name }} mutationType { fields { name }} } } |} let(:result) { schema.execute(query_string) } it "exposes the schema" do expected = { "data" => { "__schema" => { "description" => "Cool schema", "types" => schema.types.values.sort_by(&:graphql_name).map { |t| t.graphql_name.nil? ? (p t; raise("no name for #{t}")) : {"name" => t.graphql_name} }, "queryType"=>{ "fields"=>[ {"name"=>"allAnimal"}, {"name"=>"allAnimalAsCow"}, {"name"=>"allDairy"}, {"name"=>"allEdible"}, {"name"=>"allEdibleAsMilk"}, {"name"=>"cheese"}, {"name"=>"cow"}, {"name"=>"dairy"}, {"name"=>"deepNonNull"}, {"name"=>"error"}, {"name"=>"exampleBeverage"}, {"name"=>"executionError"}, {"name"=>"executionErrorWithExtensions"}, {"name"=>"executionErrorWithOptions"}, {"name"=>"favoriteEdible"}, {"name"=>"fromSource"}, {"name"=>"hugeInteger"}, {"name"=>"maybeNull"}, {"name"=>"milk"}, {"name"=>"multipleErrorsOnNonNullableField"}, {"name"=>"multipleErrorsOnNonNullableListField"}, {"name"=>"root"}, {"name"=>"searchDairy"}, {"name"=>"tracingScalar"}, {"name"=>"valueWithExecutionError"}, ] }, "mutationType"=> { "fields"=>[ {"name"=>"pushValue"}, {"name"=>"replaceValues"}, ] }, } }} assert_equal(expected, result.to_h) end describe "when the schema has types that are only reachable through hidden types" do let(:schema) do nested_invisible_type = Class.new(GraphQL::Schema::Object) do graphql_name 'NestedInvisible' field :foo, String, null: false end invisible_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Invisible' field :foo, String, null: false field :nested_invisible, nested_invisible_type, null: false def self.visible?(context) false end end invisible_input_type = Class.new(GraphQL::Schema::InputObject) do graphql_name 'InvisibleInput' argument :foo, String, required: false def self.visible?(context) false end end visible_input_type = Class.new(GraphQL::Schema::InputObject) do graphql_name 'VisibleInput' argument :foo, String, required: false end visible_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Visible' field :foo, String, null: false end invisible_orphan_type = Class.new(GraphQL::Schema::Object) do graphql_name 'InvisibleOrphan' field :foo, String, null: false def self.visible?(context) false end end query_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Query' field :foo, String, null: false field :invisible, invisible_type, null: false field :visible, visible_type, null: false field :with_invisible_args, String, null: false do argument :invisible, invisible_input_type, required: false argument :visible, visible_input_type end end Class.new(GraphQL::Schema) do query query_type orphan_types invisible_orphan_type use GraphQL::Schema::Warden if ADD_WARDEN end end let(:query_string) {%| query getSchema { __schema { types { name } } } |} it "only returns reachable types" do expected_types = [ 'Boolean', 'Query', 'String', 'Visible', 'VisibleInput', '__Directive', '__DirectiveLocation', '__EnumValue', '__Field', '__InputValue', '__Schema', '__Type', '__TypeKind' ] types = result['data']['__schema']['types'].map { |type| type.fetch('name') } assert_equal(expected_types, types) end end describe "when the schema has hidden directives" do let(:schema) do invisible_directive = Class.new(GraphQL::Schema::Directive) do graphql_name 'invisibleDirective' locations(GraphQL::Schema::Directive::QUERY) argument(:val, Integer, "Initial integer value.", required: false) def self.visible?(context) false end end visible_directive = Class.new(GraphQL::Schema::Directive) do graphql_name 'visibleDirective' locations(GraphQL::Schema::Directive::QUERY) argument(:val, Integer, "Initial integer value.", required: false) def self.visible?(context) true end end query_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Query' field :foo, String, null: false end Class.new(GraphQL::Schema) do use GraphQL::Schema::Visibility query query_type directives invisible_directive, visible_directive end end let(:query_string) {%| query getSchema { __schema { directives { name } } } |} it "only returns visible directives" do expected_dirs = ['deprecated', 'include', 'skip', 'oneOf', 'specifiedBy', 'visibleDirective'] directives = result['data']['__schema']['directives'].map { |dir| dir.fetch('name') } assert_equal(expected_dirs.sort, directives.sort) 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/tracing/sentry_trace_spec.rb
spec/graphql/tracing/sentry_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::SentryTrace do module SentryTraceTest class Thing < GraphQL::Schema::Object field :str, String def str; "blah"; end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end field :thing, Thing def thing; :thing; end end class SchemaWithoutTransactionName < GraphQL::Schema query(Query) module OtherTrace def execute_query(query:) query.context[:other_trace_ran] = true super end end trace_with OtherTrace trace_with GraphQL::Tracing::SentryTrace end class SchemaWithTransactionName < GraphQL::Schema query(Query) trace_with(GraphQL::Tracing::SentryTrace, set_transaction_name: true) end end before do Sentry.clear_all end it "works with other trace modules" do res = SentryTraceTest::SchemaWithoutTransactionName.execute("{ int }") assert res.context[:other_trace_ran] end it "handles cases when Sentry has no current span" do Sentry.use_nil_span = true assert SentryTraceTest::SchemaWithoutTransactionName.execute("{ int }") ensure Sentry.use_nil_span = false end describe "When Sentry is not configured" do it "does not initialize any spans" do Sentry.stub(:initialized?, false) do SentryTraceTest::SchemaWithoutTransactionName.execute("{ int thing { str } }") assert_equal [], Sentry::SPAN_DATA assert_equal [], Sentry::SPAN_DESCRIPTIONS assert_equal [], Sentry::SPAN_OPS end end end describe "When Sentry.with_child_span / start_child returns nil" do it "does not initialize any spans" do Sentry.stub(:with_child_span, nil) do Sentry::DummySpan.stub(:start_child, nil) do SentryTraceTest::SchemaWithoutTransactionName.execute("{ int thing { str } }") assert_equal [], Sentry::SPAN_DATA assert_equal [], Sentry::SPAN_DESCRIPTIONS assert_equal [], Sentry::SPAN_OPS end end end end it "sets the expected spans" do SentryTraceTest::SchemaWithoutTransactionName.execute("{ int thing { str } }") expected_span_ops = [ "graphql.execute", "graphql.analyze", (USING_C_PARSER ? "graphql.lex" : nil), "graphql.parse", "graphql.validate", "graphql.authorized.Query", "graphql.Query.thing", "graphql.authorized.Thing", ].compact assert_equal expected_span_ops, Sentry::SPAN_OPS end it "sets span descriptions for an anonymous query" do SentryTraceTest::SchemaWithoutTransactionName.execute("{ int }") assert_equal ["query"], Sentry::SPAN_DESCRIPTIONS end it "sets span data for an anonymous query" do SentryTraceTest::SchemaWithoutTransactionName.execute("{ int }") expected_span_data = [ ["graphql.document", "{ int }"], ["graphql.operation.type", "query"] ].compact assert_equal expected_span_data.sort, Sentry::SPAN_DATA.sort end it "sets span descriptions for a named query" do SentryTraceTest::SchemaWithoutTransactionName.execute("query Ab { int }") assert_equal ["query Ab"], Sentry::SPAN_DESCRIPTIONS end it "sets span data for a named query" do SentryTraceTest::SchemaWithoutTransactionName.execute("query Ab { int }") expected_span_data = [ ["graphql.document", "query Ab { int }"], ["graphql.operation.name", "Ab"], ["graphql.operation.type", "query"] ].compact assert_equal expected_span_data.sort, Sentry::SPAN_DATA.sort end it "can leave the transaction name in place" do SentryTraceTest::SchemaWithoutTransactionName.execute "query X { int }" assert_equal [], Sentry::TRANSACTION_NAMES end it "can override the transaction name" do SentryTraceTest::SchemaWithTransactionName.execute "query X { int }" assert_equal ["GraphQL/query.X"], Sentry::TRANSACTION_NAMES end it "can override the transaction name per query" do # Override with `false` SentryTraceTest::SchemaWithTransactionName.execute "{ int }", context: { set_sentry_transaction_name: false } assert_equal [], Sentry::TRANSACTION_NAMES # Override with `true` SentryTraceTest::SchemaWithoutTransactionName.execute "{ int }", context: { set_sentry_transaction_name: true } assert_equal ["GraphQL/query.anonymous"], Sentry::TRANSACTION_NAMES end it "falls back to a :tracing_fallback_transaction_name when provided" do SentryTraceTest::SchemaWithTransactionName.execute("{ int }", context: { tracing_fallback_transaction_name: "Abcd" }) assert_equal ["GraphQL/query.Abcd"], Sentry::TRANSACTION_NAMES end it "does not use the :tracing_fallback_transaction_name if an operation name is present" do SentryTraceTest::SchemaWithTransactionName.execute( "query Ab { int }", context: { tracing_fallback_transaction_name: "Cd" } ) assert_equal ["GraphQL/query.Ab"], Sentry::TRANSACTION_NAMES end it "does not require a :tracing_fallback_transaction_name even if an operation name is not present" do SentryTraceTest::SchemaWithTransactionName.execute("{ int }") assert_equal ["GraphQL/query.anonymous"], Sentry::TRANSACTION_NAMES 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/tracing/new_relic_tracing_spec.rb
spec/graphql/tracing/new_relic_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::NewRelicTracing do module NewRelicTest class Thing < GraphQL::Schema::Object implements GraphQL::Types::Relay::Node end class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int 1 end end class SchemaWithoutTransactionName < GraphQL::Schema query(Query) use(GraphQL::Tracing::NewRelicTracing) orphan_types(Thing) def self.object_from_id(_id, _ctx) :thing end def self.resolve_type(_type, _obj, _ctx) Thing end end class SchemaWithTransactionName < GraphQL::Schema query(Query) use(GraphQL::Tracing::NewRelicTracing, set_transaction_name: true) end class SchemaWithScalarTrace < GraphQL::Schema query(Query) use(GraphQL::Tracing::NewRelicTracing, trace_scalars: true) end end before do NewRelic.clear_all end it "Actually uses the new-style trace under the hood" do assert NewRelicTest::SchemaWithoutTransactionName.trace_class_for(:default).ancestors.include?(GraphQL::Tracing::NewRelicTrace) end it "works with the built-in node field, even though it doesn't have an @owner" do res = NewRelicTest::SchemaWithoutTransactionName.execute '{ node(id: "1") { __typename } }' assert_equal "Thing", res["data"]["node"]["__typename"] end it "can leave the transaction name in place" do NewRelicTest::SchemaWithoutTransactionName.execute "query X { int }" assert_equal [], NewRelic::TRANSACTION_NAMES end it "can override the transaction name" do NewRelicTest::SchemaWithTransactionName.execute "query X { int }" assert_equal ["GraphQL/query.X"], NewRelic::TRANSACTION_NAMES end it "can override the transaction name per query" do # Override with `false` NewRelicTest::SchemaWithTransactionName.execute "{ int }", context: { set_new_relic_transaction_name: false } assert_equal [], NewRelic::TRANSACTION_NAMES # Override with `true` NewRelicTest::SchemaWithoutTransactionName.execute "{ int }", context: { set_new_relic_transaction_name: true } assert_equal ["GraphQL/query.anonymous"], NewRelic::TRANSACTION_NAMES end it "falls back to a :tracing_fallback_transaction_name when provided" do NewRelicTest::SchemaWithTransactionName.execute("{ int }", context: { tracing_fallback_transaction_name: "Abcd" }) assert_equal ["GraphQL/query.Abcd"], NewRelic::TRANSACTION_NAMES end it "does not use the :tracing_fallback_transaction_name if an operation name is present" do NewRelicTest::SchemaWithTransactionName.execute( "query Ab { int }", context: { tracing_fallback_transaction_name: "Cd" } ) assert_equal ["GraphQL/query.Ab"], NewRelic::TRANSACTION_NAMES end it "does not require a :tracing_fallback_transaction_name even if an operation name is not present" do NewRelicTest::SchemaWithTransactionName.execute("{ int }") assert_equal ["GraphQL/query.anonymous"], NewRelic::TRANSACTION_NAMES end it "traces scalars when trace_scalars is true" do NewRelicTest::SchemaWithScalarTrace.execute "query X { int }" assert_includes NewRelic::EXECUTION_SCOPES, "GraphQL/Query/int" 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/tracing/prometheus_trace_spec.rb
spec/graphql/tracing/prometheus_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::PrometheusTracing do module PrometheusTraceTest class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end end class Schema < GraphQL::Schema query Query end end describe "Observing" do it "sends JSON to Prometheus client" do client = Minitest::Mock.new send_json_called = false client.expect :send_json, true do |obj| send_json_called = true obj[:type] == 'graphql' && obj[:key] == :execute_field && obj[:platform_key] == 'graphql.Query.int' end PrometheusTraceTest::Schema.trace_with GraphQL::Tracing::PrometheusTrace, client: client, trace_scalars: true PrometheusTraceTest::Schema.execute "query X { int }" assert send_json_called, "send_json was called" 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/tracing/detailed_trace_spec.rb
spec/graphql/tracing/detailed_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::DetailedTrace do class SamplerSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :truthy, Boolean, fallback_value: true end query(Query) use GraphQL::Tracing::DetailedTrace, memory: true def self.detailed_trace?(query) if query.is_a?(GraphQL::Execution::Multiplex) query.queries.all? { |q| q.context[:profile] != false } else query.context[:profile] != false end end end before do SamplerSchema.detailed_trace.delete_all_traces end it "runs when the configured trace mode is set" do assert_equal 0, SamplerSchema.detailed_trace.traces.size res = SamplerSchema.execute("{ truthy }", context: { profile: false }) assert_equal true, res["data"]["truthy"] assert_equal 0, SamplerSchema.detailed_trace.traces.size SamplerSchema.execute("{ truthy }") assert_equal 1, SamplerSchema.detailed_trace.traces.size end it "calls through to storage for access methods" do SamplerSchema.execute("{ truthy }") id = SamplerSchema.detailed_trace.traces.first.id assert_kind_of GraphQL::Tracing::DetailedTrace::StoredTrace, SamplerSchema.detailed_trace.find_trace(id) SamplerSchema.detailed_trace.delete_trace(id) assert_equal 0, SamplerSchema.detailed_trace.traces.size SamplerSchema.execute("{ truthy }") assert_equal 1, SamplerSchema.detailed_trace.traces.size SamplerSchema.detailed_trace.delete_all_traces end it "raises when no storage is configured" do err = assert_raises ArgumentError do Class.new(GraphQL::Schema) do use GraphQL::Tracing::DetailedTrace end end assert_equal "Pass `redis: ...` to store traces in Redis for later review", err.message end it "calls detailed_profile? on a Multiplex" do assert_equal 0, SamplerSchema.detailed_trace.traces.size SamplerSchema.multiplex([ { query: "{ truthy }", context: { profile: false } }, { query: "{ truthy }", context: { profile: true } }, ]) assert_equal 0, SamplerSchema.detailed_trace.traces.size SamplerSchema.multiplex([ { query: "{ truthy }", context: { profile: true } }, { query: "{ truthy }", context: { profile: true } }, ]) assert_equal 1, SamplerSchema.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/graphql/tracing/legacy_trace_spec.rb
spec/graphql/tracing/legacy_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::LegacyTrace do it "calls tracers on a parent schema class" do custom_tracer = Module.new do def self.trace(key, data) if key == "execute_query" data[:query].context[:tracer_ran] = true end yield end end query_type = Class.new(GraphQL::Schema::Object) do graphql_name("Query") field :int, Integer def int 4 end end parent_schema = Class.new(GraphQL::Schema) do query(query_type) tracer(custom_tracer, silence_deprecation_warning: true) end child_schema = Class.new(parent_schema) res1 = parent_schema.execute("{ int }") assert_equal true, res1.context[:tracer_ran] res2 = child_schema.execute("{ int }") assert_equal true, res2.context[:tracer_ran] end it "Works with new trace modules in the parent class" do custom_tracer = Module.new do def self.trace(key, data) if key == "execute_query" data[:query].context[:tracer_ran] = true end yield end end custom_trace_module = Module.new do def execute_query(query:) query.context[:trace_module_ran] = true super end end query_type = Class.new(GraphQL::Schema::Object) do graphql_name("Query") field :int, Integer def int 4 end end parent_schema = Class.new(GraphQL::Schema) do query(query_type) trace_with(custom_trace_module) end child_schema = Class.new(parent_schema) do tracer(custom_tracer) end res1 = parent_schema.execute("{ int }") assert_equal true, res1.context[:trace_module_ran] assert_nil res1.context[:tracer_ran] res2 = child_schema.execute("{ int }") assert_equal true, res2.context[:trace_module_ran], "New Trace Ran" assert_equal true, res2.context[:tracer_ran], "Legacy Trace Ran" 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/tracing/notifications_trace_spec.rb
spec/graphql/tracing/notifications_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::NotificationsTrace do module NotificationsTraceTest class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end end class DummyEngine < GraphQL::Tracing::NotificationsTrace::Adapter class << self def dispatched_events @dispatched_events ||= [] end end def instrument(event, payload = nil) self.class.dispatched_events << [event, payload] yield end class Event < GraphQL::Tracing::NotificationsTrace::Adapter::Event def start; end def finish DummyEngine.dispatched_events << [@name, @payload] end end end module OtherTrace def execute_query(query:) query.context[:other_trace_ran] = true super end end class Schema < GraphQL::Schema query Query trace_with OtherTrace trace_with GraphQL::Tracing::NotificationsTrace, engine: DummyEngine end end before do NotificationsTraceTest::DummyEngine.dispatched_events.clear end describe "Observing" do it "dispatches the event to the notifications engine with a suffix" do NotificationsTraceTest::Schema.execute "query X { int }" dispatched_events = NotificationsTraceTest::DummyEngine.dispatched_events.to_h expected_event_keys = [ "execute.graphql", (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "validate.graphql", "analyze.graphql", "authorized.graphql", "execute_field.graphql" ].compact assert_equal expected_event_keys, dispatched_events.keys end it "works with other tracers" do res = NotificationsTraceTest::Schema.execute "query X { int }" assert res.context[:other_trace_ran] 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/tracing/scout_tracing_spec.rb
spec/graphql/tracing/scout_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::ScoutTracing do module ScoutApmTest class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int 1 end end class ScoutSchemaBase < GraphQL::Schema query(Query) end class SchemaWithoutTransactionName < ScoutSchemaBase use(GraphQL::Tracing::ScoutTracing) end class SchemaWithTransactionName < ScoutSchemaBase use(GraphQL::Tracing::ScoutTracing, set_transaction_name: true) end end before do ScoutApm.clear_all end it "can leave the transaction name in place" do ScoutApmTest::SchemaWithoutTransactionName.execute "query X { int }" assert_equal [], ScoutApm::TRANSACTION_NAMES end it "can override the transaction name" do ScoutApmTest::SchemaWithTransactionName.execute "query X { int }" assert_equal ["GraphQL/query.X"], ScoutApm::TRANSACTION_NAMES end it "can override the transaction name per query" do # Override with `false` ScoutApmTest::SchemaWithTransactionName.execute "{ int }", context: { set_scout_transaction_name: false } assert_equal [], ScoutApm::TRANSACTION_NAMES # Override with `true` ScoutApmTest::SchemaWithoutTransactionName.execute "{ int }", context: { set_scout_transaction_name: true } assert_equal ["GraphQL/query.anonymous"], ScoutApm::TRANSACTION_NAMES 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/tracing/scout_trace_spec.rb
spec/graphql/tracing/scout_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::ScoutTrace do module ScoutApmTraceTest class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int 1 end end class ScoutSchemaBase < GraphQL::Schema query(Query) end class SchemaWithoutTransactionName < ScoutSchemaBase trace_with GraphQL::Tracing::ScoutTrace end class SchemaWithTransactionName < ScoutSchemaBase trace_with GraphQL::Tracing::ScoutTrace, set_transaction_name: true, trace_authorized: false, trace_scalars: true end end before do ScoutApm.clear_all end it "can leave the transaction name in place" do ScoutApmTraceTest::SchemaWithoutTransactionName.execute "query X { int }" assert_equal [], ScoutApm::TRANSACTION_NAMES expected_events = [ "execute.graphql", "analyze.graphql", (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "validate.graphql", "Query.authorized.graphql" ].compact assert_equal expected_events, ScoutApm::EVENTS end it "can override the transaction name, skip authorized, and trace scalars" do ScoutApmTraceTest::SchemaWithTransactionName.execute "query X { int }" assert_equal ["GraphQL/query.X"], ScoutApm::TRANSACTION_NAMES expected_events = [ (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "execute.graphql", "analyze.graphql", "validate.graphql", "Query.int.graphql" ].compact assert_equal expected_events, ScoutApm::EVENTS end it "can override the transaction name per query" do # Override with `false` ScoutApmTraceTest::SchemaWithTransactionName.execute "{ int }", context: { set_scout_transaction_name: false } assert_equal [], ScoutApm::TRANSACTION_NAMES # Override with `true` ScoutApmTraceTest::SchemaWithoutTransactionName.execute "{ int }", context: { set_scout_transaction_name: true } assert_equal ["GraphQL/query.anonymous"], ScoutApm::TRANSACTION_NAMES 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/tracing/notifications_tracing_spec.rb
spec/graphql/tracing/notifications_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::NotificationsTracing do module NotificationsTracingTest class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end end class Schema < GraphQL::Schema query Query end end describe "Observing" do it "dispatches the event to the notifications engine with suffixed key" do dispatched_events = trigger_fake_notifications_tracer(NotificationsTracingTest::Schema) assert dispatched_events.length > 0 dispatched_events.each do |event, payload| assert event.end_with?(".graphql") assert payload.is_a?(Hash) end end end def trigger_fake_notifications_tracer(schema) dispatched_events = [] engine = Object.new engine.define_singleton_method(:instrument) do |event, payload, &blk| dispatched_events << [event, payload] blk.call if blk end tracer = GraphQL::Tracing::NotificationsTracing.new(engine) schema.tracer(tracer, silence_deprecation_warning: true) schema.execute "query X { int }" dispatched_events 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/tracing/statsd_tracing_spec.rb
spec/graphql/tracing/statsd_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::StatsdTracing do module MockStatsd class << self def time(key) self.timings << key yield end attr_reader :timings def clear @timings = [] end end end class StatsdTestSchema < GraphQL::Schema class Thing < GraphQL::Schema::Object field :str, String def str; "blah"; end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end field :thing, Thing def thing; :thing; end end query(Query) use GraphQL::Tracing::StatsdTracing, statsd: MockStatsd, legacy_tracing: true end before do MockStatsd.clear end it "gathers timings" do StatsdTestSchema.execute("query X { int thing { str } }") expected_timings = [ "graphql.execute_multiplex", "graphql.analyze_multiplex", (USING_C_PARSER ? "graphql.lex" : nil), "graphql.parse", "graphql.validate", "graphql.analyze_query", "graphql.execute_query", "graphql.authorized.Query", "graphql.Query.thing", "graphql.authorized.Thing", "graphql.execute_query_lazy" ].compact assert_equal expected_timings, MockStatsd.timings 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/tracing/statsd_trace_spec.rb
spec/graphql/tracing/statsd_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::StatsdTracing do module TraceMockStatsd class << self def time(key) self.timings << key yield end def timing(key, ms) self.timings << key end attr_reader :timings def clear @timings = [] end end end class StatsdTraceTestSchema < GraphQL::Schema class Thing < GraphQL::Schema::Object field :str, String def str; "blah"; end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end field :thing, Thing def thing; :thing; end end query(Query) trace_with GraphQL::Tracing::StatsdTrace, statsd: TraceMockStatsd end before do TraceMockStatsd.clear end it "gathers timings" do StatsdTraceTestSchema.execute("query X { int thing { str } }") expected_timings = [ "graphql.execute", (USING_C_PARSER ? "graphql.lex" : nil), "graphql.parse", "graphql.validate", "graphql.analyze", "graphql.authorized.Query", "graphql.Query.thing", "graphql.authorized.Thing", ].compact assert_equal expected_timings, TraceMockStatsd.timings 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/tracing/trace_spec.rb
spec/graphql/tracing/trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::Trace do it "has all its methods in the development cop" do trace_source = File.read("cop/development/trace_methods_cop.rb") superable_methods = GraphQL::Tracing::Trace.instance_methods(false).sort superable_methods_source = superable_methods.map { |m| " #{m.inspect},\n" }.join assert_includes trace_source, superable_methods_source 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/tracing/active_support_notifications_trace_spec.rb
spec/graphql/tracing/active_support_notifications_trace_spec.rb
# frozen_string_literal: true require "spec_helper" if testing_rails? describe GraphQL::Tracing::ActiveSupportNotificationsTrace do class AsnSchema < GraphQL::Schema class ThingSource < GraphQL::Dataloader::Source def fetch(ids) ids.map { |id| { name: "Thing #{id}" } } end end module Nameable include GraphQL::Schema::Interface field :name, String def self.resolve_type(...) Thing end end class Thing < GraphQL::Schema::Object implements Nameable end class Query < GraphQL::Schema::Object field :nameable, Nameable do argument :id, ID, loads: Thing, as: :thing end def nameable(thing:) thing end end query(Query) trace_with GraphQL::Tracing::ActiveSupportNotificationsTrace use GraphQL::Dataloader orphan_types(Thing) def self.object_from_id(id, ctx) ctx.dataloader.with(ThingSource).load(id) end def self.resolve_type(_abs, _obj, _ctx) Thing end end it "emits tracing info" do events = [] callback = lambda { |name, started, finished, unique_id, payload| events << [name, payload] } ActiveSupport::Notifications.subscribed(callback) do AsnSchema.execute("{ nameable(id: 1) { name } }") end expected_names = [ (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "validate.graphql", "analyze.graphql", "authorized.graphql", "dataloader_source.graphql", "execute_field.graphql", "resolve_type.graphql", "authorized.graphql", "execute_field.graphql", "execute.graphql" ].compact assert_equal expected_names, events.map(&:first) assert_equal [Hash], events.map(&:last).map(&:class).uniq 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/tracing/data_dog_tracing_spec.rb
spec/graphql/tracing/data_dog_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::DataDogTracing do module DataDogTest class Thing < GraphQL::Schema::Object field :str, String def str "blah" end end class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int 1 end field :thing, Thing def thing :thing end end class TestSchema < GraphQL::Schema query(Query) use(GraphQL::Tracing::DataDogTracing, legacy_tracing: true) end class CustomTracerTestSchema < GraphQL::Schema class CustomDataDogTracing < GraphQL::Tracing::DataDogTracing def prepare_span(trace_key, data, span) span.set_tag("custom:#{trace_key}", data.keys.join(",")) end end query(Query) use(CustomDataDogTracing) end end before do Datadog.clear_all end it "falls back to a :tracing_fallback_transaction_name when provided" do DataDogTest::TestSchema.execute("{ int }", context: { tracing_fallback_transaction_name: "Abcd" }) assert_equal ["Abcd"], Datadog::SPAN_RESOURCE_NAMES end it "does not use the :tracing_fallback_transaction_name if an operation name is present" do DataDogTest::TestSchema.execute( "query Ab { int }", context: { tracing_fallback_transaction_name: "Cd" } ) assert_equal ["Ab"], Datadog::SPAN_RESOURCE_NAMES end it "does not set resource if no value can be derived" do DataDogTest::TestSchema.execute("{ int }") assert_equal [], Datadog::SPAN_RESOURCE_NAMES end it "sets component and operation tags" do DataDogTest::TestSchema.execute("{ int }") assert_includes Datadog::SPAN_TAGS, ['component', 'graphql'] assert_includes Datadog::SPAN_TAGS, ['operation', 'execute_multiplex'] end it "sets custom tags tags" do DataDogTest::CustomTracerTestSchema.execute("{ thing { str } }") expected_custom_tags = [ (USING_C_PARSER ? ["custom:lex", "query_string"] : nil), ["custom:parse", "query_string"], ["custom:execute_multiplex", "multiplex"], ["custom:analyze_multiplex", "multiplex"], ["custom:validate", "validate,query"], ["custom:analyze_query", "query"], ["custom:execute_query", "query"], ["custom:authorized", "context,type,object,path"], ["custom:execute_field", "field,query,ast_node,arguments,object,owner,path"], ["custom:authorized", "context,type,object,path"], ["custom:execute_query_lazy", "multiplex,query"], ].compact actual_custom_tags = Datadog::SPAN_TAGS.reject { |t| t[0] == "operation" || t[0] == "component" || t[0].is_a?(Symbol) } assert_equal expected_custom_tags, actual_custom_tags 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/tracing/new_relic_trace_spec.rb
spec/graphql/tracing/new_relic_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::NewRelicTrace do module NewRelicTraceTest class EchoSource < GraphQL::Dataloader::Source def fetch(keys) keys end end class OtherSource < GraphQL::Dataloader::Source def fetch(keys) dataloader.with(EchoSource).load_all(keys) end end class Thing < GraphQL::Schema::Object implements GraphQL::Types::Relay::Node end module Nameable include GraphQL::Schema::Interface field :name, String def self.resolve_type(abs_type, ctx) ctx[:lazy] ? -> { Other } : Other end end class Other < GraphQL::Schema::Object implements Nameable def self.authorized?(obj, ctx) ctx[:lazy] ? -> { true } : true end field :name, String def name dataload(EchoSource, "name") end end class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int 1 end field :other, Other def other dataloader.with(OtherSource).load(:other) end field :nameable, Nameable, fallback_value: :nameable field :lazy_nameable, Nameable, fallback_value: -> { :nameable } end class SchemaWithoutTransactionName < GraphQL::Schema query(Query) trace_with(GraphQL::Tracing::NewRelicTrace) orphan_types(Thing) def self.object_from_id(_id, _ctx) :thing end def self.resolve_type(_type, _obj, ctx) Thing end end class SchemaWithTransactionName < GraphQL::Schema query(Query) trace_with(GraphQL::Tracing::NewRelicTrace, set_transaction_name: true) use GraphQL::Dataloader lazy_resolve(Proc, :call) end class SchemaWithScalarTrace < GraphQL::Schema query(Query) trace_with(GraphQL::Tracing::NewRelicTrace, trace_scalars: true) end class SchemaWithoutAuthorizedOrResolveType < GraphQL::Schema query(Query) trace_with(GraphQL::Tracing::NewRelicTrace, set_transaction_name: true, trace_authorized: false, trace_resolve_type: false, trace_scalars: true) use GraphQL::Dataloader end end before do NewRelic.clear_all end it "works with the built-in node field, even though it doesn't have an @owner" do res = NewRelicTraceTest::SchemaWithoutTransactionName.execute '{ node(id: "1") { __typename } }' assert_equal "Thing", res["data"]["node"]["__typename"] end it "can leave the transaction name in place" do NewRelicTraceTest::SchemaWithoutTransactionName.execute "query X { int }" assert_equal [], NewRelic::TRANSACTION_NAMES end it "can override the transaction name" do NewRelicTraceTest::SchemaWithTransactionName.execute "query X { int }" assert_equal ["GraphQL/query.X"], NewRelic::TRANSACTION_NAMES end it "can override the transaction name per query" do # Override with `false` NewRelicTraceTest::SchemaWithTransactionName.execute "{ int }", context: { set_new_relic_transaction_name: false } assert_equal [], NewRelic::TRANSACTION_NAMES # Override with `true` NewRelicTraceTest::SchemaWithoutTransactionName.execute "{ int }", context: { set_new_relic_transaction_name: true } assert_equal ["GraphQL/query.anonymous"], NewRelic::TRANSACTION_NAMES end it "falls back to a :tracing_fallback_transaction_name when provided" do NewRelicTraceTest::SchemaWithTransactionName.execute("{ int }", context: { tracing_fallback_transaction_name: "Abcd" }) assert_equal ["GraphQL/query.Abcd"], NewRelic::TRANSACTION_NAMES end it "does not use the :tracing_fallback_transaction_name if an operation name is present" do NewRelicTraceTest::SchemaWithTransactionName.execute( "query Ab { int }", context: { tracing_fallback_transaction_name: "Cd" } ) assert_equal ["GraphQL/query.Ab"], NewRelic::TRANSACTION_NAMES end it "does not require a :tracing_fallback_transaction_name even if an operation name is not present" do NewRelicTraceTest::SchemaWithTransactionName.execute("{ int }") assert_equal ["GraphQL/query.anonymous"], NewRelic::TRANSACTION_NAMES end it "traces scalars when trace_scalars is true" do NewRelicTraceTest::SchemaWithScalarTrace.execute "query X { int }" assert_includes NewRelic::EXECUTION_SCOPES, "GraphQL/Query/int" end it "handles fiber pauses" do NewRelicTraceTest::SchemaWithTransactionName.execute("{ other { name } }") expected_steps = [ (USING_C_PARSER ? "GraphQL/lex" : nil), "GraphQL/parse", "GraphQL/execute", "GraphQL/analyze", "GraphQL/validate", "FINISH GraphQL/analyze", "GraphQL/Authorized/Query", "FINISH GraphQL/Authorized/Query", "GraphQL/Query/other", "FINISH GraphQL/Query/other", # Here's the source run: "GraphQL/Source/NewRelicTraceTest::OtherSource", "FINISH GraphQL/Source/NewRelicTraceTest::OtherSource", # Nested source: "GraphQL/Source/NewRelicTraceTest::EchoSource", "FINISH GraphQL/Source/NewRelicTraceTest::EchoSource", "GraphQL/Source/NewRelicTraceTest::OtherSource", "FINISH GraphQL/Source/NewRelicTraceTest::OtherSource", # And back to the field: "GraphQL/Query/other", "FINISH GraphQL/Query/other", "GraphQL/Authorized/Other", "FINISH GraphQL/Authorized/Other", "GraphQL/Source/NewRelicTraceTest::EchoSource", "FINISH GraphQL/Source/NewRelicTraceTest::EchoSource", ].compact assert_equal expected_steps, NewRelic::EXECUTION_SCOPES end it "can skip authorized and resolve type and instrument scalars" do NewRelicTraceTest::SchemaWithoutAuthorizedOrResolveType.execute("{ nameable { name } }") expected_steps = [ (USING_C_PARSER ? "GraphQL/lex" : nil), "GraphQL/parse", "GraphQL/execute", "GraphQL/analyze", "GraphQL/validate", "FINISH GraphQL/analyze", # "GraphQL/Authorized/Query", # "FINISH GraphQL/Authorized/Query", "GraphQL/Query/nameable", "FINISH GraphQL/Query/nameable", # "GraphQL/ResolveType/Nameable", # "FINISH GraphQL/ResolveType/Nameable", # "GraphQL/Authorized/Other", # "FINISH GraphQL/Authorized/Other", "GraphQL/Other/name", "FINISH GraphQL/Other/name", "GraphQL/Source/NewRelicTraceTest::EchoSource", "FINISH GraphQL/Source/NewRelicTraceTest::EchoSource", "GraphQL/Other/name", "FINISH GraphQL/Other/name", ].compact assert_equal expected_steps, NewRelic::EXECUTION_SCOPES end it "can generate a transaction name without a selected operation" do res = NewRelicTraceTest::SchemaWithTransactionName.execute("query Q1 { other { name } } query Q2 { other { name } }") assert_equal ["An operation name is required"], res["errors"].map { |e| e["message"] } assert_equal ["GraphQL/query.anonymous"], NewRelic::TRANSACTION_NAMES end it "handles lazies" do NewRelicTraceTest::SchemaWithTransactionName.execute("{ lazyNameable { name } }", context: { lazy: true }) expected_steps = [ (USING_C_PARSER ? "GraphQL/lex" : nil), "GraphQL/parse", "GraphQL/execute", "GraphQL/analyze", "GraphQL/validate", "FINISH GraphQL/analyze", "GraphQL/Authorized/Query", "FINISH GraphQL/Authorized/Query", # Eager: "GraphQL/Query/lazyNameable", "FINISH GraphQL/Query/lazyNameable", # Lazy: "GraphQL/Query/lazyNameable", "FINISH GraphQL/Query/lazyNameable", # Eager/lazy: "GraphQL/ResolveType/Nameable", "FINISH GraphQL/ResolveType/Nameable", "GraphQL/ResolveType/Nameable", "FINISH GraphQL/ResolveType/Nameable", # Eager/lazy: "GraphQL/Authorized/Other", "FINISH GraphQL/Authorized/Other", "GraphQL/Authorized/Other", "FINISH GraphQL/Authorized/Other", "GraphQL/Source/NewRelicTraceTest::EchoSource", "FINISH GraphQL/Source/NewRelicTraceTest::EchoSource", ].compact assert_equal expected_steps, NewRelic::EXECUTION_SCOPES end describe "multiplex queries" do it "handles multiplex" do NewRelicTraceTest::SchemaWithTransactionName.multiplex([ { query: "query Q1 { int }", variables: {}, operation_name: "Q1" }, { query: "query Q2 { int }", variables: {}, operation_name: "Q2" } ]) assert_equal ["GraphQL/query.Q1"], NewRelic::TRANSACTION_NAMES end it "handles empty multiplex" do NewRelicTraceTest::SchemaWithTransactionName.multiplex([]) assert_equal [], NewRelic::TRANSACTION_NAMES 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/tracing/appsignal_trace_spec.rb
spec/graphql/tracing/appsignal_trace_spec.rb
# frozen_string_literal: true require "spec_helper" module Appsignal module_function def instrument(key, &block) instrumented << key yield end def instrumented @instrumented ||= [] end def current self end def start_event # pass end def finish_event(name, title, body) instrumented << name end Transaction = self end describe GraphQL::Tracing::AppsignalTrace do class IntBox def initialize(value) @value = value end attr_reader :value end module AppsignalTraceTest class Thing < GraphQL::Schema::Object field :str, String def str; "blah"; end end class Named < GraphQL::Schema::Union possible_types Thing def self.resolve_type(obj, ctx) Thing end end class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int IntBox.new(1) end field :thing, Thing def thing; :thing; end field :named, Named, resolver_method: :thing end class TestSchema < GraphQL::Schema query(Query) trace_with(GraphQL::Tracing::AppsignalTrace) lazy_resolve(IntBox, :value) end end before do Appsignal.instrumented.clear end it "traces events" do _res = AppsignalTraceTest::TestSchema.execute("{ int thing { str } named { ... on Thing { str } } }") expected_trace = [ "execute.graphql", (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "validate.graphql", "analyze.graphql", "Query.authorized.graphql", "Query.thing.graphql", "Thing.authorized.graphql", "Query.named.graphql", "Named.resolve_type.graphql", "Thing.authorized.graphql", ].compact assert_equal expected_trace, Appsignal.instrumented end describe "With Datadog Trace" do class AppsignalAndDatadogTestSchema < GraphQL::Schema query(AppsignalTraceTest::Query) trace_with(GraphQL::Tracing::DataDogTrace) trace_with(GraphQL::Tracing::AppsignalTrace) lazy_resolve(IntBox, :value) end class AppsignalAndDatadogReverseOrderTestSchema < GraphQL::Schema query(AppsignalTraceTest::Query) # Include these modules in different order than above: trace_with(GraphQL::Tracing::AppsignalTrace) trace_with(GraphQL::Tracing::DataDogTrace) lazy_resolve(IntBox, :value) end before do Datadog.clear_all end it "traces with both systems" do _res = AppsignalAndDatadogTestSchema.execute("{ int thing { str } named { ... on Thing { str } } }") expected_appsignal_trace = [ "execute.graphql", (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "validate.graphql", "analyze.graphql", "Query.authorized.graphql", "Query.thing.graphql", "Thing.authorized.graphql", "Query.named.graphql", "Named.resolve_type.graphql", "Thing.authorized.graphql", ].compact expected_datadog_trace = [ ["component", "graphql"], ["operation", "execute"], ["component", "graphql"], *(USING_C_PARSER ? [["operation", "lex"], ["component", "graphql"]] : []), ["operation", "parse"], ["selected_operation_name", nil], ["selected_operation_type", "query"], ["query_string", "{ int thing { str } named { ... on Thing { str } } }"], ["component", "graphql"], ["operation", "validate"] ] assert_equal expected_appsignal_trace, Appsignal.instrumented assert_equal expected_datadog_trace, Datadog::SPAN_TAGS end it "works when the modules are included in reverse order" do _res = AppsignalAndDatadogReverseOrderTestSchema.execute("{ int thing { str } named { ... on Thing { str } } }") expected_appsignal_trace = [ (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "execute.graphql", "validate.graphql", "analyze.graphql", "Query.authorized.graphql", "Query.thing.graphql", "Thing.authorized.graphql", "Query.named.graphql", "Named.resolve_type.graphql", "Thing.authorized.graphql", ].compact expected_datadog_trace = [ ["component", "graphql"], ["operation", "execute"], *(USING_C_PARSER ? [["component", "graphql"], ["operation", "lex"]] : []), ["component", "graphql"], ["operation", "parse"], ["selected_operation_name", nil], ["selected_operation_type", "query"], ["query_string", "{ int thing { str } named { ... on Thing { str } } }"], ["component", "graphql"], ["operation", "validate"] ] assert_equal expected_appsignal_trace, Appsignal.instrumented assert_equal expected_datadog_trace, Datadog::SPAN_TAGS 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/tracing/appoptics_tracing_spec.rb
spec/graphql/tracing/appoptics_tracing_spec.rb
# frozen_string_literal: true # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Tests for appoptics_apm tracing # # if any of these tests fail, please file an issue at # https://github.com/appoptics/appoptics-apm-ruby # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # require 'spec_helper' describe GraphQL::Tracing::AppOpticsTracing do module AppOpticsTest class Schema < GraphQL::Schema def self.id_from_object(_object = nil, _type = nil, _context = {}) SecureRandom.uuid end class Address < GraphQL::Schema::Object global_id_field :id field :street, String field :number, Integer end class Company < GraphQL::Schema::Object global_id_field :id field :name, String field :address, Schema::Address def address OpenStruct.new( id: AppOpticsTest::Schema.id_from_object, street: 'MyStreetName', number: 'MyStreetNumber' ) end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int; 1; end field :company, Company do argument :id, ID end def company(id:) OpenStruct.new( id: id, name: 'MyName') end end query Query use GraphQL::Tracing::AppOpticsTracing end end before do $appoptics_tracing_spans = [] $appoptics_tracing_kvs = [] $appoptics_tracing_name = nil AppOpticsAPM::Config[:graphql] = { :enabled => true, :remove_comments => true, :sanitize_query => true, :transaction_name => true } end it 'calls AppOpticsAPM::SDK.trace with names and kvs' do query = 'query Query { int }' AppOpticsTest::Schema.execute(query) assert_equal $appoptics_tracing_name, 'graphql.query.Query' refute $appoptics_tracing_spans.find { |name| name !~ /^graphql\./ } assert_equal $appoptics_tracing_kvs.compact.size, $appoptics_tracing_spans.compact.size assert_equal($appoptics_tracing_kvs[0][:Spec], 'graphql') assert_equal($appoptics_tracing_kvs[0][:InboundQuery], query) end it 'uses type + field keys' do query = <<-QL query { company(id: 1) # there is a comment here { id name address { street } } } # and another one here QL AppOpticsTest::Schema.execute(query) assert_equal $appoptics_tracing_name, 'graphql.query.company' refute $appoptics_tracing_spans.find { |name| name !~ /^graphql\./ } assert_equal $appoptics_tracing_kvs.compact.size, $appoptics_tracing_spans.compact.size assert_includes($appoptics_tracing_spans, 'graphql.Query.company') assert_includes($appoptics_tracing_spans, 'graphql.Company.address') end # case: appoptics_apm didn't get required it 'should not barf, when AppOpticsAPM is undefined' do prev_apm = AppOpticsAPM Object.send(:remove_const, :AppOpticsAPM) query = 'query Query { int }' begin AppOpticsTest::Schema.execute(query) rescue StandardError => e msg = e.message.split("\n").first flunk "failed: It raised '#{msg}' when AppOpticsAPM is undefined." end Object.send(:const_set, :AppOpticsAPM, prev_apm) end # case: appoptics may have encountered a compile or service key problem it 'should not barf, when appoptics is present but not loaded' do AppOpticsAPM.stub(:loaded, false) do query = 'query Query { int }' begin AppOpticsTest::Schema.execute(query) rescue StandardError => e msg = e.message.split("\n").first flunk "failed: It raised '#{msg}' when AppOpticsAPM is not loaded." end end end # case: using appoptics_apm < 4.12.0, without default graphql configs it 'creates traces by default when it cannot find configs for graphql' do AppOpticsAPM::Config.clear query = 'query Query { int }' AppOpticsTest::Schema.execute(query) refute $appoptics_tracing_spans.empty?, 'failed: no traces were created' end it 'should not create traces when disabled' do AppOpticsAPM::Config[:graphql][:enabled] = false query = 'query Query { int }' AppOpticsTest::Schema.execute(query) assert $appoptics_tracing_spans.empty?, 'failed: traces were created' 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/tracing/trace_modes_spec.rb
spec/graphql/tracing/trace_modes_spec.rb
# frozen_string_literal: true require "spec_helper" describe "Trace modes for schemas" do module TraceModesTest class ParentSchema < GraphQL::Schema module GlobalTrace def execute_query(query:) query.context[:global_trace] = true super end end module SpecialTrace def execute_query(query:) query.context[:special_trace] = true super end end module OptionsTrace def initialize(configured_option:, **_rest) @configured_option = configured_option super end def execute_query(query:) query.context[:configured_option] = @configured_option super end end class Query < GraphQL::Schema::Object field :greeting, String, fallback_value: "Howdy!" end query(Query) trace_with GlobalTrace, global_arg: 1 trace_with SpecialTrace, mode: :special trace_with OptionsTrace, mode: :options, configured_option: :was_configured end class ChildSchema < ParentSchema module ChildSpecialTrace def execute_query(query:) query.context[:child_special_trace] = true super end end trace_with(ChildSpecialTrace, mode: [:special, :extra_special]) end class GrandchildSchema < ChildSchema module GrandchildDefaultTrace def execute_query(query:) query.context[:grandchild_default] = true super end end trace_with GrandchildDefaultTrace end end it "traces are inherited from default modes" do res = TraceModesTest::ParentSchema.execute("{ greeting }") assert res.context[:global_trace] refute res.context[:grandchild_default] res = TraceModesTest::ChildSchema.execute("{ greeting }") assert res.context[:global_trace] refute res.context[:grandchild_default] res = TraceModesTest::GrandchildSchema.execute("{ greeting }") assert res.context[:global_trace] assert res.context[:grandchild_default] end it "uses the default trace class and trace options for unknown modes" do assert_nil TraceModesTest::ParentSchema.trace_class_for(:who_knows_what2) constructed_trace_class = TraceModesTest::ParentSchema.trace_class_for(:who_knows_what2, build: true) assert_equal TraceModesTest::ParentSchema.trace_class_for(:default), constructed_trace_class.superclass assert_equal({global_arg: 1}, TraceModesTest::ParentSchema.trace_options_for(:who_know_what3)) end it "uses the default trace mode when an unknown mode is given" do res = TraceModesTest::ParentSchema.execute("{ greeting }", context: { trace_mode: :who_knows_what }) assert res.context[:global_trace] end it "inherits special modes" do res = TraceModesTest::ParentSchema.execute("{ greeting }", context: { trace_mode: :special }) assert res.context[:global_trace] assert res.context[:special_trace] refute res.context[:child_special_trace] refute res.context[:grandchild_default] res = TraceModesTest::ChildSchema.execute("{ greeting }", context: { trace_mode: :special }) assert res.context[:global_trace] assert res.context[:special_trace] assert res.context[:child_special_trace] refute res.context[:grandchild_default] # This doesn't inherit `:special` configs from ParentSchema: res = TraceModesTest::ChildSchema.execute("{ greeting }", context: { trace_mode: :extra_special }) assert res.context[:global_trace] refute res.context[:special_trace] assert res.context[:child_special_trace] refute res.context[:grandchild_default] res = TraceModesTest::GrandchildSchema.execute("{ greeting }", context: { trace_mode: :special }) assert res.context[:global_trace] assert res.context[:special_trace] assert res.context[:child_special_trace] assert res.context[:grandchild_default] end it "Only requires and passes arguments for the modes that require them" do res = TraceModesTest::ParentSchema.execute("{ greeting }", context: { trace_mode: :options }) assert_equal :was_configured, res.context[:configured_option] end describe "inheriting from GraphQL::Schema" do it "gets CallLegacyTracers" do # Use a new base trace mode class to avoid polluting the base class # which already-initialized schemas have in their inheritance chain # (It causes `CallLegacyTracers` to end up in the chain twice otherwise) GraphQL::Schema.send(:remove_const, :DefaultTrace) GraphQL::Schema.own_trace_modes[:default] = GraphQL::Schema.build_trace_mode(:default) child_class = Class.new(GraphQL::Schema) # Initialize the trace class, make sure no legacy tracers are present at this point: refute_includes child_class.trace_class_for(:default).ancestors, GraphQL::Tracing::CallLegacyTracers tracer_class = Class.new # add a legacy tracer GraphQL::Schema.tracer(tracer_class, silence_deprecation_warning: true) # A newly created child class gets the right setup: new_child_class = Class.new(GraphQL::Schema) assert_includes new_child_class.trace_class_for(:default).ancestors, GraphQL::Tracing::CallLegacyTracers # But what about an already-created child class? assert_includes child_class.trace_class_for(:default).ancestors, GraphQL::Tracing::CallLegacyTracers # Reset GraphQL::Schema tracer state: GraphQL::Schema.send(:remove_const, :DefaultTrace) GraphQL::Schema.send(:own_tracers).delete(tracer_class) GraphQL::Schema.own_trace_modes[:default] = GraphQL::Schema.build_trace_mode(:default) refute_includes GraphQL::Schema.new_trace.class.ancestors, GraphQL::Tracing::CallLegacyTracers ensure # Since this modifies the base class, make sure it's undone for future test cases GraphQL::Schema.instance_variable_get(:@own_tracers).clear GraphQL::Schema.own_trace_modes.clear GraphQL::Schema.own_trace_modules.clear GraphQL::Schema.instance_variable_get(:@trace_options_for_mode).clear end end describe "inheriting from a custom default trace class" do class CustomBaseTraceParentSchema < GraphQL::Schema class CustomTrace < GraphQL::Tracing::Trace end trace_class CustomTrace end class CustomBaseTraceSubclassSchema < CustomBaseTraceParentSchema trace_with Module.new, mode: :special_with_base_class end class TraceWithWithOptionsSchema < GraphQL::Schema class CustomTrace < GraphQL::Tracing::Trace end module OptionsTrace def initialize(configured_option:, **_rest) @configured_option = configured_option super end end trace_class CustomTrace trace_with OptionsTrace, configured_option: :foo end it "uses the default trace class for default mode" do assert_equal CustomBaseTraceParentSchema::CustomTrace, CustomBaseTraceParentSchema.trace_class_for(:default) assert_equal CustomBaseTraceParentSchema::CustomTrace, CustomBaseTraceSubclassSchema.trace_class_for(:default).superclass assert_instance_of CustomBaseTraceParentSchema::CustomTrace, CustomBaseTraceParentSchema.new_trace assert_kind_of CustomBaseTraceParentSchema::CustomTrace, CustomBaseTraceSubclassSchema.new_trace end it "uses the default trace class for special modes" do assert_includes CustomBaseTraceSubclassSchema.trace_class_for(:special_with_base_class).ancestors, CustomBaseTraceParentSchema::CustomTrace assert_kind_of CustomBaseTraceParentSchema::CustomTrace, CustomBaseTraceSubclassSchema.new_trace(mode: :special_with_base_class) end it "custom options are retained when using `trace_with` when there is already default tracer configured with `trace_class`" do assert_equal({configured_option: :foo}, TraceWithWithOptionsSchema.trace_options_for(:default)) end end describe "custom default trace mode" do class CustomDefaultSchema < TraceModesTest::ParentSchema class CustomDefaultTrace < GraphQL::Tracing::Trace def execute_query(query:) query.context[:custom_default_used] = true super end end trace_mode :custom_default, CustomDefaultTrace default_trace_mode :custom_default end class ChildCustomDefaultSchema < CustomDefaultSchema end it "inherits configuration" do assert_equal :default, TraceModesTest::ParentSchema.default_trace_mode assert_equal :custom_default, CustomDefaultSchema.default_trace_mode assert_equal :custom_default, ChildCustomDefaultSchema.default_trace_mode end it "uses the specified default when none is given" do res = CustomDefaultSchema.execute("{ greeting }") assert res.context[:custom_default_used] refute res.context[:global_trace] res2 = ChildCustomDefaultSchema.execute("{ greeting }") assert res2.context[:custom_default_used] refute res2.context[:global_trace] end end describe "custom mode options and default options" do class ModeOptionsSchema < GraphQL::Schema module SomePlugin def self.use(schema) schema.trace_with(Trace, arg1: 1) end module Trace def initialize(arg1:, **kwargs) super(**kwargs) end end end module BaseTracer def initialize(arg3:, **kwargs) super(**kwargs) end end module ExtraTracer def initialize(arg2:, **kwargs) super(**kwargs) end end use SomePlugin trace_with(ExtraTracer, mode: :extra, arg2: true) trace_with(BaseTracer, arg3: true) end it "merges default options into custom mode options" do assert_equal [:arg1, :arg3], ModeOptionsSchema.trace_options_for(:default).keys.sort assert_equal [:arg1, :arg2, :arg3], ModeOptionsSchema.trace_options_for(:extra).keys.sort assert ModeOptionsSchema.new_trace(mode: :default) assert ModeOptionsSchema.new_trace(mode: :extra) end end module SomeTraceMod def execute_query(query) super end end CustomTraceClass = Class.new(GraphQL::Tracing::Trace) class BaseSchemaWithCustomTraceClass < GraphQL::Schema use(GraphQL::Batch) trace_class(CustomTraceClass) trace_with(SomeTraceMod) end ChildSchema = Class.new(BaseSchemaWithCustomTraceClass) describe "custom trace class supports trace module inheritance" do it "inherits parent trace modules" do assert_equal [GraphQL::Batch::SetupMultiplex::Trace, SomeTraceMod], ChildSchema.trace_modules_for(:default) assert ChildSchema.new_trace.instance_variable_defined?(:@executor_class) end end describe "when GraphQL::Schema gets a new default trace" do module NewDefaultTrace module ParentClassTrace def execute_query(query:) query[:parent_trace_ran] = true super end end module ChildClassTrace def execute_query(query:) query[:child_trace_ran] = true super end end class ParentSchema < GraphQL::Schema end class ChildSchema < ParentSchema trace_with(ChildClassTrace) end ParentSchema.trace_with(ParentClassTrace) end it "still uses custom traces on subclasses" do dummy_query = {} finished = false NewDefaultTrace::ChildSchema.new_trace.execute_query(query: dummy_query) { finished = true } assert dummy_query[:child_trace_ran] assert dummy_query[:parent_trace_ran] assert finished 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/tracing/platform_trace_spec.rb
spec/graphql/tracing/platform_trace_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./appsignal_trace_spec" require_relative "./statsd_trace_spec" describe GraphQL::Tracing::PlatformTrace do module CustomPlatformTrace include GraphQL::Tracing::PlatformTrace TRACE = [] { "lex" => "l", "parse" => "p", "validate" => "v", "analyze_query" => "aq", "analyze_multiplex" => "am", "execute_multiplex" => "em", "execute_query" => "eq", "execute_query_lazy" => "eql", }.each do |method_name, trace_key| define_method(method_name) do |**data, &block| TRACE << trace_key block.call end end def platform_authorized(platform_key) TRACE << platform_key yield end def platform_resolve_type(platform_key) TRACE << platform_key yield end def platform_execute_field(platform_key) TRACE << platform_key res = yield if res.is_a?(GraphQL::ExecutionError) TRACE << "returned error" end res end def platform_field_key(field) "#{field.owner.graphql_name[0]}.#{field.graphql_name[0]}" end def platform_authorized_key(type) "#{type.graphql_name}.authorized" end def platform_resolve_type_key(type) "#{type.graphql_name}.resolve_type" end end describe "calling a platform tracer" do let(:schema) { Class.new(Dummy::Schema) { trace_with(CustomPlatformTrace) } } before do CustomPlatformTrace::TRACE.clear end it "runs the introspection query (handles late-bound types)" do assert schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) end it "gets execution errors raised from field resolution" do scalar_schema = Class.new(Dummy::Schema) { trace_with(CustomPlatformTrace, trace_scalars: true) } scalar_schema.execute("{ executionError }") assert_includes CustomPlatformTrace::TRACE, "returned error" end it "calls the platform's own method with its own keys" do schema.execute(" { cheese(id: 1) { flavor } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.c", # notice that the flavor is skipped "Cheese.authorized", "eql", "Cheese.authorized", # This is the lazy part, calling the proc ].compact assert_equal expected_trace, CustomPlatformTrace::TRACE end it "traces during Query#result" do query_str = "{ cheese(id: 1) { flavor } }" expected_trace = [ # This is from the extra validation "v", "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.c", # notice that the flavor is skipped "Cheese.authorized", "eql", "Cheese.authorized", # This is the lazy part, calling the proc ].compact query = GraphQL::Query.new(schema, query_str) # First, validate schema.validate(query.query_string) # Then execute query.result assert_equal expected_trace, CustomPlatformTrace::TRACE end it "traces resolve_type and differentiates field calls on different types" do scalar_schema = Class.new(Dummy::Schema) { trace_with(CustomPlatformTrace, trace_scalars: true) } scalar_schema.execute(" { allEdible { __typename fatContent } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.a", "Edible.resolve_type", "Edible.resolve_type", "Edible.resolve_type", "Edible.resolve_type", "eql", "Edible.resolve_type", "Cheese.authorized", "Cheese.authorized", "DynamicFields.authorized", "D._", "C.f", "Edible.resolve_type", "Cheese.authorized", "Cheese.authorized", "DynamicFields.authorized", "D._", "C.f", "Edible.resolve_type", "Cheese.authorized", "Cheese.authorized", "DynamicFields.authorized", "D._", "C.f", "Edible.resolve_type", "Milk.authorized", "DynamicFields.authorized", "D._", "E.f", ].compact assert_equal expected_trace, CustomPlatformTrace::TRACE end end describe "by default, scalar fields are not traced" do let(:schema) { Class.new(Dummy::Schema) { trace_with(CustomPlatformTrace) } } before do CustomPlatformTrace::TRACE.clear end it "only traces traceTrue, not traceFalse or traceNil" do schema.execute(" { tracingScalar { traceNil traceFalse traceTrue } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.t", "TracingScalar.authorized", "T.t", "eql", ].compact assert_equal expected_trace, CustomPlatformTrace::TRACE end end describe "when scalar fields are traced by default, they are unless specified" do let(:schema) { Class.new(Dummy::Schema) do trace_with(CustomPlatformTrace, trace_scalars: true) end } before do CustomPlatformTrace::TRACE.clear end it "traces traceTrue and traceNil but not traceFalse" do schema.execute(" { tracingScalar { traceNil traceFalse traceTrue } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.t", "TracingScalar.authorized", "T.t", "T.t", "eql", ].compact assert_equal expected_trace, CustomPlatformTrace::TRACE end end describe "using subclasses altogether" do class KitchenSinkTraceSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :int, Int, fallback_value: 1 end query(Query) trace_with GraphQL::Tracing::DataDogTrace trace_with GraphQL::Tracing::SentryTrace trace_with GraphQL::Tracing::PrometheusTrace, client: Minitest::Mock.new trace_with GraphQL::Tracing::ScoutTrace trace_with GraphQL::Tracing::AppsignalTrace trace_with GraphQL::Tracing::NewRelicTrace trace_with GraphQL::Tracing::StatsdTrace, statsd: TraceMockStatsd end before do TraceMockStatsd.clear end it "doesn't crash" do res = KitchenSinkTraceSchema.execute("{ int }") assert_equal 1, res["data"]["int"] 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/tracing/perfetto_trace_spec.rb
spec/graphql/tracing/perfetto_trace_spec.rb
# frozen_string_literal: true require "spec_helper" require "open3" if testing_rails? describe GraphQL::Tracing::PerfettoTrace do include PerfettoSnapshot class PerfettoSchema < GraphQL::Schema class BaseObject < GraphQL::Schema::Object end class AverageReview < GraphQL::Dataloader::Source def fetch(books) averages = ::Book.joins(:reviews) .select("books.id, AVG(stars) as avg_review ") .group("books.id") books.map { |b| averages.find { |avg| avg.id == b.id }&.avg_review } end end class OtherBook < GraphQL::Dataloader::Source def fetch(books) author_ids = books.map(&:author_id).uniq book_ids = ::Book.select(:id).where(author_id: author_ids).where.not(id: books.map(&:id)).group(:author_id).maximum(:id) other_books = dataloader.with(GraphQL::Dataloader::ActiveRecordSource, ::Book).load_all(book_ids.values) books.map { |b| other_books.find { |b2| b.author_id == b2.author_id } } end end class Authorized < GraphQL::Dataloader::Source def fetch(objs) objs.map { true } end end class User < BaseObject field :username, String end class Review < BaseObject field :stars, Int field :user, User def self.authorized?(obj, ctx) ctx.dataloader.with(Authorized).load(obj) end def user dataload_record(::User, object.user_id) end end class Book < BaseObject field :title, String field :reviews, [Review] field :average_review, Float field :author, "PerfettoSchema::Author" field :other_book, Book def reviews object.reviews.limit(2) end def average_review dataload(AverageReview, object) end def author dataload_association(:author) end def other_book dataload(OtherBook, object) end end class Author < BaseObject field :name, String field :books, [Book] def books object.books.limit(2) end end class Thing < GraphQL::Schema::Union possible_types(Author, Book) end class Query < BaseObject field :authors, [Author] def authors ::Author.all end field :thing, Thing do argument :id, ID end def thing(id:) model_name, db_id = id.split("-") dataload_record(Object.const_get(model_name), db_id) end field :crash, Int def crash raise "Crash the query" end end query(Query) use GraphQL::Dataloader, fiber_limit: 7 trace_with GraphQL::Tracing::PerfettoTrace def self.resolve_type(type, obj, ctx) self.const_get(obj.class.name) end def self.detailed_trace?(q) true end end it "traces fields, dataloader, and activesupport notifications" do query_str = <<-GRAPHQL query GetStuff($thingId: ID!) { authors { name books { title reviews { stars user { username } } averageReview author { name } otherBook { title } } } t5: thing(id: $thingId) { ... on Book { title } ... on Author { name }} } GRAPHQL # warm up: PerfettoSchema.execute(query_str, variables: { thingId: "Book-#{::Book.first.id}" }) res = PerfettoSchema.execute(query_str, variables: { thingId: "Book-#{::Book.first.id}" }) 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-rails-#{Rails::VERSION::MAJOR}-#{Rails::VERSION::MINOR}.json") end it "provides an error when google-protobuf isn't available" do stderr_and_stdout, _status = Open3.capture2e(%|ruby -e 'require "bundler/inline"; gemfile(true) { source("https://rubygems.org"); gem("graphql", path: "./") }; class MySchema < GraphQL::Schema; trace_with(GraphQL::Tracing::PerfettoTrace); end;'|) assert_includes stderr_and_stdout, "GraphQL::Tracing::PerfettoTrace can't be used because the `google-protobuf` gem wasn't available. Add it to your project, then try again." end it "doesn't leave AS::N subscriptions behind" do refute ActiveSupport::Notifications.notifier.listening?("event.nonsense") _trace_instance = PerfettoSchema.new_trace refute ActiveSupport::Notifications.notifier.listening?("event.nonsense") assert_raises do PerfettoSchema.execute("{ crash }") end refute ActiveSupport::Notifications.notifier.listening?("event.nonsense") end it "doesn't create DebugAnnotations when `debug: false` or `detailed_trace_debug: false`" do res = PerfettoSchema.execute("{ authors { name } }") json = res.context.query.current_trace.write(file: nil, debug_json: true) assert_includes json, "debugAnnotations", "it includes them by default" res = PerfettoSchema.execute("{ authors { name } }", context: { detailed_trace_debug: false }) json = res.context.query.current_trace.write(file: nil, debug_json: true) assert_nil json["debugAnnotations"], "doesn't write debug annotations with detailed_trace_debug: false" # Ususally this would be `use DetailedTrace, debug: false` PerfettoSchema.detailed_trace = GraphQL::Tracing::DetailedTrace.new(storage: nil, trace_mode: nil, debug: false) res = PerfettoSchema.execute("{ authors { name } }") assert_equal 4, res["data"]["authors"].size json = res.context.query.current_trace.write(file: nil, debug_json: true) assert_nil json["debugAnnotations"], "doesn't write them when top-level setting is false " ensure PerfettoSchema.detailed_trace = nil 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/tracing/data_dog_trace_spec.rb
spec/graphql/tracing/data_dog_trace_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::DataDogTrace do module DataDogTraceTest class Box def initialize(value) @value = value end attr_reader :value end class Thing < GraphQL::Schema::Object field :str, String def str; Box.new("blah"); end end class Query < GraphQL::Schema::Object include GraphQL::Types::Relay::HasNodeField field :int, Integer, null: false def int 1 end field :thing, Thing def thing; :thing; end field :str, String def str dataloader.with(EchoSource).load("hello") end end class EchoSource < GraphQL::Dataloader::Source def fetch(strs) strs end end class TestSchema < GraphQL::Schema query(Query) use GraphQL::Dataloader trace_with(GraphQL::Tracing::DataDogTrace) lazy_resolve(Box, :value) end class CustomTracerTestSchema < GraphQL::Schema module CustomDataDogTracing include GraphQL::Tracing::DataDogTrace def prepare_span(trace_key, object, span) span.set_tag("custom:#{trace_key}", object.class.name) end end query(Query) trace_with(CustomDataDogTracing) lazy_resolve(Box, :value) end end before do Datadog.clear_all end it "falls back to a :tracing_fallback_transaction_name when provided" do DataDogTraceTest::TestSchema.execute("{ int }", context: { tracing_fallback_transaction_name: "Abcd" }) assert_equal ["Abcd"], Datadog::SPAN_RESOURCE_NAMES end it "does not use the :tracing_fallback_transaction_name if an operation name is present" do DataDogTraceTest::TestSchema.execute( "query Ab { int }", context: { tracing_fallback_transaction_name: "Cd" } ) assert_equal ["Ab"], Datadog::SPAN_RESOURCE_NAMES end it "does not set resource if no value can be derived" do DataDogTraceTest::TestSchema.execute("{ int }") assert_equal [], Datadog::SPAN_RESOURCE_NAMES end it "sets component and operation tags" do DataDogTraceTest::TestSchema.execute("{ int }") assert_includes Datadog::SPAN_TAGS, ['component', 'graphql'] assert_includes Datadog::SPAN_TAGS, ['operation', 'execute'] end it "works with dataloader" do DataDogTraceTest::TestSchema.execute("{ str }") expected_keys = [ "execute.graphql", (USING_C_PARSER ? "lex.graphql" : nil), "parse.graphql", "analyze.graphql", "validate.graphql", "Query.authorized.graphql", "DataDogTraceTest_EchoSource.fetch.graphql" ].compact assert_equal expected_keys, Datadog::TRACE_KEYS end it "sets custom tags" do DataDogTraceTest::CustomTracerTestSchema.execute("{ thing { str } }") expected_custom_tags = [ (USING_C_PARSER ? ["custom:lex", "String"] : nil), ["custom:parse", "String"], ["selected_operation_name", nil], ["selected_operation_type", "query"], ["query_string", "{ thing { str } }"], ["custom:execute", "GraphQL::Execution::Multiplex"], ["custom:validate", "GraphQL::Query"], ].compact actual_custom_tags = Datadog::SPAN_TAGS.reject { |t| t[0] == "operation" || t[0] == "component" || t[0].is_a?(Symbol) } assert_equal expected_custom_tags, actual_custom_tags 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/tracing/prometheus_tracing_spec.rb
spec/graphql/tracing/prometheus_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::PrometheusTracing do module PrometheusTracingTest class Query < GraphQL::Schema::Object field :int, Integer, null: false def int 1 end end class Schema < GraphQL::Schema query Query end end describe "Observing" do it "sends JSON to Prometheus client" do client = Minitest::Mock.new client.expect :send_json, true do |obj| obj[:type] == 'graphql' && obj[:key] == 'execute_field' && obj[:platform_key] == 'Query.int' end PrometheusTracingTest::Schema.use( GraphQL::Tracing::PrometheusTracing, client: client, trace_scalars: true, legacy_tracing: true, ) PrometheusTracingTest::Schema.execute "query X { int }" 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/tracing/appoptics_trace_spec.rb
spec/graphql/tracing/appoptics_trace_spec.rb
# frozen_string_literal: true # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Tests for appoptics_apm tracing # # if any of these tests fail, please file an issue at # https://github.com/appoptics/appoptics-apm-ruby # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # require 'spec_helper' describe GraphQL::Tracing::AppOpticsTrace do module AppOpticsTraceTest class Schema < GraphQL::Schema def self.id_from_object(_object = nil, _type = nil, _context = {}) SecureRandom.uuid end class Address < GraphQL::Schema::Object global_id_field :id field :street, String field :number, Integer end class Company < GraphQL::Schema::Object global_id_field :id field :name, String field :address, Schema::Address def address OpenStruct.new( id: AppOpticsTraceTest::Schema.id_from_object, street: 'MyStreetName', number: 'MyStreetNumber' ) end end class Query < GraphQL::Schema::Object field :int, Integer, null: false def int; 1; end field :company, Company do argument :id, ID end def company(id:) OpenStruct.new( id: id, name: 'MyName') end end query Query trace_with GraphQL::Tracing::AppOpticsTrace end end before do $appoptics_tracing_spans = [] $appoptics_tracing_kvs = [] $appoptics_tracing_name = nil AppOpticsAPM::Config[:graphql] = { :enabled => true, :remove_comments => true, :sanitize_query => true, :transaction_name => true } end it 'calls AppOpticsAPM::SDK.trace with names and kvs' do query = 'query Query { int }' AppOpticsTraceTest::Schema.execute(query) assert_equal $appoptics_tracing_name, 'graphql.query.Query' refute $appoptics_tracing_spans.find { |name| name !~ /^graphql\./ } assert_equal $appoptics_tracing_kvs.compact.size, $appoptics_tracing_spans.compact.size assert_equal($appoptics_tracing_kvs[0][:Spec], 'graphql') assert_equal($appoptics_tracing_kvs[0][:InboundQuery], query) end it 'uses type + field keys' do query = <<-QL query { company(id: 1) # there is a comment here { id name address { street } } } # and another one here QL AppOpticsTraceTest::Schema.execute(query) assert_equal $appoptics_tracing_name, 'graphql.query.company' refute $appoptics_tracing_spans.find { |name| name !~ /^graphql\./ } assert_equal $appoptics_tracing_kvs.compact.size, $appoptics_tracing_spans.compact.size assert_includes($appoptics_tracing_spans, 'graphql.Query.company') assert_includes($appoptics_tracing_spans, 'graphql.Company.address') end # case: appoptics_apm didn't get required it 'should not barf, when AppOpticsAPM is undefined' do prev_apm = AppOpticsAPM Object.send(:remove_const, :AppOpticsAPM) query = 'query Query { int }' begin AppOpticsTraceTest::Schema.execute(query) rescue StandardError => e msg = e.message.split("\n").first flunk "failed: It raised '#{msg}' when AppOpticsAPM is undefined." end Object.send(:const_set, :AppOpticsAPM, prev_apm) end # case: appoptics may have encountered a compile or service key problem it 'should not barf, when appoptics is present but not loaded' do AppOpticsAPM.stub(:loaded, false) do query = 'query Query { int }' begin AppOpticsTraceTest::Schema.execute(query) rescue StandardError => e msg = e.message.split("\n").first flunk "failed: It raised '#{msg}' when AppOpticsAPM is not loaded." end end end # case: using appoptics_apm < 4.12.0, without default graphql configs it 'creates traces by default when it cannot find configs for graphql' do AppOpticsAPM::Config.clear query = 'query Query { int }' AppOpticsTraceTest::Schema.execute(query) refute $appoptics_tracing_spans.empty?, 'failed: no traces were created' end it 'should not create traces when disabled' do AppOpticsAPM::Config[:graphql][:enabled] = false query = 'query Query { int }' AppOpticsTraceTest::Schema.execute(query) assert $appoptics_tracing_spans.empty?, 'failed: traces were created' 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/tracing/platform_tracing_spec.rb
spec/graphql/tracing/platform_tracing_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Tracing::PlatformTracing do class CustomPlatformTracer < GraphQL::Tracing::PlatformTracing TRACE = [] self.platform_keys = { "lex" => "l", "parse" => "p", "validate" => "v", "analyze_query" => "aq", "analyze_multiplex" => "am", "execute_multiplex" => "em", "execute_query" => "eq", "execute_query_lazy" => "eql", } def platform_field_key(type, field) "#{type.graphql_name[0]}.#{field.graphql_name[0]}" end def platform_authorized_key(type) "#{type.graphql_name}.authorized" end def platform_resolve_type_key(type) "#{type.graphql_name}.resolve_type" end def platform_trace(platform_key, key, data) TRACE << platform_key res = yield if res.is_a?(GraphQL::ExecutionError) TRACE << "returned error" end res end end describe "calling a platform tracer" do let(:schema) { Class.new(Dummy::Schema) { use(CustomPlatformTracer) } } before do CustomPlatformTracer::TRACE.clear end it "runs the introspection query (handles late-bound types)" do assert schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) end it "calls the platform's own method with its own keys" do schema.execute(" { cheese(id: 1) { flavor } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.c", # notice that the flavor is skipped "Cheese.authorized", "eql", "Cheese.authorized", # This is the lazy part, calling the proc ].compact assert_equal expected_trace, CustomPlatformTracer::TRACE end it "traces during Query#result" do query_str = "{ cheese(id: 1) { flavor } }" expected_trace = [ # This is from the extra validation "v", "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.c", # notice that the flavor is skipped "Cheese.authorized", "eql", "Cheese.authorized", # This is the lazy part, calling the proc ].compact query = GraphQL::Query.new(schema, query_str) # First, validate schema.validate(query.query_string) # Then execute query.result assert_equal expected_trace, CustomPlatformTracer::TRACE end it "gets execution errors raised from field resolution" do scalar_schema = Class.new(Dummy::Schema) { use(CustomPlatformTracer, trace_scalars: true) } scalar_schema.execute("{ executionError }") assert_includes CustomPlatformTracer::TRACE, "returned error" end it "traces resolve_type calls" do schema.execute(" { favoriteEdible { __typename } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.f", "Edible.resolve_type", "eql", "Edible.resolve_type", "Milk.authorized", "DynamicFields.authorized", ].compact assert_equal expected_trace, CustomPlatformTracer::TRACE end it "traces resolve_type and differentiates field calls on different types" do scalar_schema = Class.new(Dummy::Schema) { use(CustomPlatformTracer, trace_scalars: true) } scalar_schema.execute(" { allEdible { __typename fatContent } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.a", "Edible.resolve_type", "Edible.resolve_type", "Edible.resolve_type", "Edible.resolve_type", "eql", "Edible.resolve_type", "Cheese.authorized", "Cheese.authorized", "DynamicFields.authorized", "D._", "C.f", "Edible.resolve_type", "Cheese.authorized", "Cheese.authorized", "DynamicFields.authorized", "D._", "C.f", "Edible.resolve_type", "Cheese.authorized", "Cheese.authorized", "DynamicFields.authorized", "D._", "C.f", "Edible.resolve_type", "Milk.authorized", "DynamicFields.authorized", "D._", "E.f", ].compact assert_equal expected_trace, CustomPlatformTracer::TRACE end end describe "by default, scalar fields are not traced" do let(:schema) { Class.new(Dummy::Schema) { use(CustomPlatformTracer) } } before do CustomPlatformTracer::TRACE.clear end it "only traces traceTrue, not traceFalse or traceNil" do schema.execute(" { tracingScalar { traceNil traceFalse traceTrue } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.t", "TracingScalar.authorized", "T.t", "eql", ].compact assert_equal expected_trace, CustomPlatformTracer::TRACE end end describe "when scalar fields are traced by default, they are unless specified" do let(:schema) { Class.new(Dummy::Schema) do use(CustomPlatformTracer, trace_scalars: true) end } before do CustomPlatformTracer::TRACE.clear end it "traces traceTrue and traceNil but not traceFalse" do schema.execute(" { tracingScalar { traceNil traceFalse traceTrue } }") expected_trace = [ "em", "am", (USING_C_PARSER ? "l" : nil), "p", "v", "aq", "eq", "Query.authorized", "Q.t", "TracingScalar.authorized", "T.t", "T.t", "eql", ].compact assert_equal expected_trace, CustomPlatformTracer::TRACE 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/tracing/detailed_trace/memory_backend_spec.rb
spec/graphql/tracing/detailed_trace/memory_backend_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./backend_assertions" describe GraphQL::Tracing::DetailedTrace::MemoryBackend do include GraphQLTracingDetailedTraceBackendAssertions def new_backend(**kwargs) GraphQL::Tracing::DetailedTrace::MemoryBackend.new(**kwargs) 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/tracing/detailed_trace/backend_assertions.rb
spec/graphql/tracing/detailed_trace/backend_assertions.rb
# frozen_string_literal: true module GraphQLTracingDetailedTraceBackendAssertions def self.included(child_class) child_class.instance_eval do describe "BackendAssertions" do before do @backend = new_backend @backend.delete_all_traces end it "can save, retreive, list, and delete traces" do data = SecureRandom.bytes(1000) trace_id = @backend.save_trace( "GetStuff", 100.56, (Time.utc(2024, 01, 01, 04, 44, 33, 695000).to_f * 1000).round, data ) trace = @backend.find_trace(trace_id) assert_kind_of GraphQL::Tracing::DetailedTrace::StoredTrace, trace assert_equal trace_id, trace.id assert_equal "GetStuff", trace.operation_name assert_equal 100.56, trace.duration_ms assert_equal "2024-01-01 04:44:33.694", Time.at(trace.begin_ms / 1000.0).utc.strftime("%Y-%m-%d %H:%M:%S.%L") assert_equal data, trace.trace_data @backend.save_trace( "GetOtherStuff", 200.16, (Time.utc(2024, 01, 03, 04, 44, 33, 695000).to_f * 1000).round, data ) @backend.save_trace( "GetMoreOtherStuff", 200.16, (Time.utc(2024, 01, 03, 04, 44, 33, 795000).to_f * 1000).round, data ) assert_equal ["GetMoreOtherStuff", "GetOtherStuff", "GetStuff" ], @backend.traces(last: 20, before: nil).map(&:operation_name) assert_equal ["GetMoreOtherStuff"], @backend.traces(last: 1, before: nil).map(&:operation_name) assert_equal ["GetOtherStuff", "GetStuff"], @backend.traces(last: 2, before: Time.utc(2024, 01, 03, 04, 44, 33, 795000).to_f * 1000).map(&:operation_name) @backend.delete_trace(trace_id) assert_equal ["GetMoreOtherStuff", "GetOtherStuff"], @backend.traces(last: 20, before: nil).map(&:operation_name) @backend.delete_all_traces assert_equal [], @backend.traces(last: 20, before: nil) end it "returns nil for nonexistent IDs" do assert_nil @backend.find_trace(999_999_999) end it "implements a limit" do limit_backend = new_backend(limit: 10) 10.times do |n| limit_backend.save_trace( "Trace#{n}", 1.5, 5000 + n, "some-data" ) end all_traces = limit_backend.traces(last: nil, before: nil) assert_equal 10, all_traces.size assert_equal "Trace9", all_traces.first.operation_name assert_equal "Trace0", all_traces.last.operation_name 3.times do |n| limit_backend.save_trace( "Trace 2-#{n}", 1.5, 5020 + n, "some-data" ) end all_traces = limit_backend.traces(last: nil, before: nil) assert_equal 10, all_traces.size assert_equal "Trace 2-2", all_traces.first.operation_name assert_equal "Trace3", all_traces.last.operation_name 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/tracing/detailed_trace/redis_backend_spec.rb
spec/graphql/tracing/detailed_trace/redis_backend_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "./backend_assertions" if testing_redis? describe GraphQL::Tracing::DetailedTrace::RedisBackend do include GraphQLTracingDetailedTraceBackendAssertions def new_backend(**kwargs) GraphQL::Tracing::DetailedTrace::RedisBackend.new(redis: Redis.new, **kwargs) 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/static_validation/validator_spec.rb
spec/graphql/static_validation/validator_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::Validator do let(:validator) { GraphQL::StaticValidation::Validator.new(schema: Dummy::Schema) } let(:query) { GraphQL::Query.new(Dummy::Schema, query_string) } let(:validate) { true } let(:errors) { validator.validate(query, validate: validate)[:errors].map(&:to_h) } describe "tracing" do let(:query_string) { "{ t: __typename }"} let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, context: {tracers: [TestTracing]}) } it "emits a trace" do traces = TestTracing.with_trace do validator.validate(query) end if USING_C_PARSER assert_equal 3, traces.length else assert_equal 2, traces.length end validate_trace = traces.last assert_equal "validate", validate_trace[:key] assert_equal true, validate_trace[:validate] assert_instance_of GraphQL::Query, validate_trace[:query] assert_instance_of Hash, validate_trace[:result] end end describe "error format" do let(:query_string) { "{ cheese(id: $undefinedVar) { source } }" } let(:document) { GraphQL.parse(query_string, filename: "not_a_real.graphql") } let(:query) { GraphQL::Query.new(Dummy::Schema, nil, document: document) } it "includes message, locations, and fields keys" do expected_errors = [{ "message" => "Variable $undefinedVar is used by anonymous query but not declared", "locations" => [{"line" => 1, "column" => 14, "filename" => "not_a_real.graphql"}], "path" => ["query", "cheese", "id"], "extensions"=>{"code"=>"variableNotDefined", "variableName"=>"undefinedVar"} }] assert_equal expected_errors, errors end end describe "validation order" do let(:document) { GraphQL.parse(query_string)} describe "fields & arguments" do let(:query_string) { %| query getCheese($id: Int!) { cheese(id: $undefinedVar, bogusArg: true) { source, nonsenseField, id(nonsenseArg: 1) bogusField(bogusArg: true) } otherCheese: cheese(id: $id) { source, } } |} it "handles args on invalid fields" do # nonsenseField, nonsenseArg, bogusField, bogusArg, undefinedVar assert_equal(5, errors.length) end describe "when validate: false" do let(:validate) { false } it "skips validation" do assert_equal 0, errors.length end end end describe "infinite fragments" do let(:query_string) { %| query getCheese { cheese(id: 1) { ... cheeseFields } } fragment cheeseFields on Cheese { ... on Cheese { id, ... cheeseFields } } |} it "handles infinite fragment spreads" do assert_equal(1, errors.length) end describe "nested spreads" do let(:query_string) {%| { allEdible { ... on Cheese { ... cheeseFields } } } fragment cheeseFields on Cheese { similarCheese(source: COW) { similarCheese(source: COW) { ... cheeseFields } } } |} it "finds an error on the nested spread" do expected = [ { "message"=>"Fragment cheeseFields contains an infinite loop", "locations"=>[{"line"=>10, "column"=>9}], "path"=>["fragment cheeseFields"], "extensions"=>{"code"=>"infiniteLoop", "fragmentName"=>"cheeseFields"} } ] assert_equal(expected, errors) end end end describe "fragment spreads with no selections" do let(:query_string) {%| query SimpleQuery { cheese(id: 1) { # OK: ... { id } # NOT OK: ...cheeseFields } } |} it "marks an error" do assert_equal(1, errors.length) end end describe "fragments with no names" do let(:query_string) {%| fragment on Cheese { id flavor } |} it "marks an error" do assert_equal(1, errors.length) end end end describe "validation timeout" do module StubValidationTimeout def on_operation_definition(node, parent) raise Timeout::Error.new end end let(:rules) { [ StubValidationTimeout ] } let(:validator) { GraphQL::StaticValidation::Validator.new(schema: Dummy::Schema, rules: rules) } let(:query_string) { "{ t: __typename }"} let(:errors) { validator.validate(query, validate: validate, timeout: 0.1)[:errors].map(&:to_h) } it "aborts and return error" do expected_errors = [{ "message" => "Timeout on validation of query", "locations" => [], "extensions"=>{"code"=>"validationTimeout"} }] assert_equal expected_errors, errors end end describe "Custom ruleset" do let(:query_string) { " fragment Thing on Cheese { __typename similarCheese(source: COW) } " } let(:rules) { # This is from graphql-client, eg # https://github.com/github/graphql-client/blob/c86fc05d7eba2370452592bb93572caced4123af/lib/graphql/client.rb#L168 GraphQL::StaticValidation::ALL_RULES - [ GraphQL::StaticValidation::FragmentsAreUsed, GraphQL::StaticValidation::FieldsHaveAppropriateSelections ] } let(:validator) { GraphQL::StaticValidation::Validator.new(schema: Dummy::Schema, rules: rules) } it "runs the specified rules" do assert_equal 0, errors.size 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/static_validation/rules/no_definitions_are_present_spec.rb
spec/graphql/static_validation/rules/no_definitions_are_present_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::NoDefinitionsArePresent do include StaticValidationHelpers describe "when schema definitions are present in the query" do let(:query_string) { <<-GRAPHQL { cheese(id: 1) { flavor } } type Thing { stuff: Int } scalar Date GRAPHQL } it "adds an error" do assert_equal 1, errors.length err = errors[0] assert_equal "Query cannot contain schema definitions", err["message"] assert_equal [{"line"=>5, "column"=>7}, {"line"=>9, "column"=>7}], err["locations"] end end describe "when schema extensions are present in the query" do let(:query_string) { <<-GRAPHQL { cheese(id: 1) { flavor } } extend schema { subscription: Query } extend scalar TracingScalar @deprecated extend type Dairy @deprecated extend interface Edible @deprecated extend union Beverage @deprecated extend enum DairyAnimal @deprecated extend input ResourceOrderType @deprecated GRAPHQL } it "adds an error" do assert_equal 1, errors.length err = errors[0] assert_equal "Query cannot contain schema definitions", err["message"] assert_equal [{"line"=>5, "column"=>7}, {"line"=>9, "column"=>7}, {"line"=>10, "column"=>7}, {"line"=>11, "column"=>7}, {"line"=>12, "column"=>7}, {"line"=>13, "column"=>7}, {"line"=>14, "column"=>7}], err["locations"] 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/static_validation/rules/subscription_root_exists_and_single_selection_spec.rb
spec/graphql/static_validation/rules/subscription_root_exists_and_single_selection_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::SubscriptionRootExistsAndSingleSubscriptionSelection do include StaticValidationHelpers let(:query_string) {%| subscription { test } |} let(:schema) { Class.new(GraphQL::Schema) do query_root = Class.new(GraphQL::Schema::Object) do graphql_name "Query" end query query_root end } it "errors when a subscription is performed on a schema without a subscription root" do assert_equal(1, errors.length) missing_subscription_root_error = { "message"=>"Schema is not configured for subscriptions", "locations"=>[{"line"=>2, "column"=>5}], "path"=>["subscription"], "extensions"=>{"code"=>"missingSubscriptionConfiguration"} } assert_includes(errors, missing_subscription_root_error) end describe "when multiple subscription selections" do let(:query_string) { "subscription { subscription1 subscription2 }" } let(:schema) { Class.new(GraphQL::Schema) do subscription(Class.new(GraphQL::Schema::Object) do graphql_name "Subscription" field :subscription1, String field :subscription2, String end) end } it "returns an error" do expected_errs = [ { "message" => "A subscription operation may only have one selection", "locations" => [{"line" => 1, "column" => 1}], "path" => ["subscription"], "extensions" => {"code" => "notSingleSubscription"} } ] assert_equal(expected_errs, errors) 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/static_validation/rules/one_of_input_objects_are_valid_spec.rb
spec/graphql/static_validation/rules/one_of_input_objects_are_valid_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::OneOfInputObjectsAreValid do include StaticValidationHelpers let(:schema) { GraphQL::Schema.from_definition(%| type Query { oneOfArgField(oneOfArg: OneOfArgInput): String } input OneOfArgInput @oneOf { stringField: String intField: Int } |) } describe "with exactly one field" do let(:query_string) {%| { oneOfArgField(oneOfArg: { stringField: "abc" }) } |} it "finds no errors" do assert_equal [], errors end end describe "with exactly one non-nullable variable" do let(:query_string) {%| query ($string: String!) { oneOfArgField(oneOfArg: { stringField: $string }) } |} it "finds no errors" do assert_equal [], errors end end describe "with an invalid field type" do let(:query_string) {%| { oneOfArgField(oneOfArg: { stringField: 2 }) } |} it "finds errors" do expected = [ { "message" => "Argument 'stringField' on InputObject 'OneOfArgInput' has an invalid value (2). " \ "Expected type 'String'.", "locations" => [{ "line" => 3, "column" => 33 }], "path" => ["query", "oneOfArgField", "oneOfArg", "stringField"], "extensions" => { "code" => "argumentLiteralsIncompatible", "typeName" => "InputObject", "argumentName" => "stringField" } } ] assert_equal expected, errors end end describe "with exactly one null field" do let(:query_string) {%| { oneOfArgField(oneOfArg: { stringField: null }) } |} it "finds errors" do expected = [ { "message" => "Argument 'OneOfArgInput.stringField' must be non-null.", "locations" => [{ "line" => 3, "column" => 35 }], "path" => ["query", "oneOfArgField", "oneOfArg", "stringField"], "extensions" => { "code" => "invalidOneOfInputObject", "inputObjectType" => "OneOfArgInput" } } ] assert_equal expected, errors end end describe "with exactly one nullable variable" do let(:query_string) {%| query ($string: String) { oneOfArgField(oneOfArg: { stringField: $string }) } |} it "finds errors" do expected = [ { "message" => "Variable 'string' must be non-nullable to be used for OneOf Input Object 'OneOfArgInput'.", "locations"=>[{ "line" => 3, "column" => 33 }], "path" => ["query", "oneOfArgField", "oneOfArg", "stringField"], "extensions" => { "code" => "invalidOneOfInputObject", "inputObjectType" => "OneOfArgInput" } } ] assert_equal expected, errors end end describe "with more than one field" do let(:query_string) {%| { oneOfArgField(oneOfArg: { stringField: "abc", intField: 2 }) } |} it "finds errors" do expected = [ { "message" => "OneOf Input Object 'OneOfArgInput' must specify exactly one key.", "locations" => [{ "line" => 3, "column" => 33 }], "path" => ["query", "oneOfArgField", "oneOfArg"], "extensions" => { "code" => "invalidOneOfInputObject", "inputObjectType" => "OneOfArgInput" } } ] assert_equal expected, errors 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/static_validation/rules/required_input_object_attributes_are_present_spec.rb
spec/graphql/static_validation/rules/required_input_object_attributes_are_present_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::RequiredInputObjectAttributesArePresent do include StaticValidationHelpers let(:query_string) {%| query getCheese { stringCheese: cheese(id: "aasdlkfj") { ...cheeseFields } cheese(id: 1) { source @skip(if: "whatever") } yakSource: searchDairy(product: [{source: COW, fatContent: 1.1}]) { __typename } badSource: searchDairy(product: [{source: 1.1}]) { __typename } missingSource: searchDairy(product: [{fatContent: 1.1}]) { __typename } missingNestedRequiredInputObjectAttribute: searchDairy(product: [{fatContent: 1.2, order_by: {}}]) { __typename } errorAtIndexOne: searchDairy(product: [{source: COW, fatContent: 1.0}, {fatContent: 1.2, order_by: {}}]) { __typename } listCoerce: cheese(id: 1) { similarCheese(source: YAK) { __typename } } missingInputField: searchDairy(product: [{source: YAK, wacky: 1}]) { __typename } } fragment cheeseFields on Cheese { similarCheese(source: 4.5) { __typename } } |} describe "with error bubbling disabled" do missing_required_field_error = { "message"=>"Argument 'product' on Field 'missingSource' has an invalid value ([{fatContent: 1.1}]). Expected type '[DairyProductInput]'.", "locations"=>[{"line"=>7, "column"=>7}], "path"=>["query getCheese", "missingSource", "product"], "extensions"=>{ "code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"product", }, } missing_source_error = { "message"=>"Argument 'source' on InputObject 'DairyProductInput' is required. Expected type DairyAnimal!", "locations"=>[{"line"=>7, "column"=>44}], "path"=>["query getCheese", "missingSource", "product", 0, "source"], "extensions"=>{ "code"=>"missingRequiredInputObjectAttribute", "argumentName"=>"source", "argumentType"=>"DairyAnimal!", "inputObjectType"=>"DairyProductInput" } } missing_order_by_direction_error = { "message"=>"Argument 'direction' on InputObject 'ResourceOrderType' is required. Expected type String!", "locations"=>[{"line"=>8, "column"=>100}], "path"=>["query getCheese", "missingNestedRequiredInputObjectAttribute", "product", 0, "order_by", "direction"], "extensions"=>{ "code"=>"missingRequiredInputObjectAttribute", "argumentName"=>"direction", "argumentType"=>"String!", "inputObjectType"=>"ResourceOrderType" } } missing_order_by_direction_index_one_error = { "message"=>"Argument 'direction' on InputObject 'ResourceOrderType' is required. Expected type String!", "locations"=>[{"line"=>9, "column"=>106}], "path"=>["query getCheese", "errorAtIndexOne", "product", 1, "order_by", "direction"], "extensions"=>{ "code"=>"missingRequiredInputObjectAttribute", "argumentName"=>"direction", "argumentType"=>"String!", "inputObjectType"=>"ResourceOrderType" } } it "finds undefined or missing-required arguments to fields and directives" do assert_includes(errors, missing_source_error) assert_includes(errors, missing_order_by_direction_error) assert_includes(errors, missing_order_by_direction_index_one_error) refute_includes(errors, missing_required_field_error) end end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 10) assert_equal(error_messages, [ "Argument 'id' on Field 'stringCheese' has an invalid value (\"aasdlkfj\"). Expected type 'Int!'.", "Argument 'if' on Directive 'skip' has an invalid value (\"whatever\"). Expected type 'Boolean!'.", "Argument 'source' on InputObject 'DairyProductInput' has an invalid value (1.1). Expected type 'DairyAnimal!'.", "Argument 'source' on InputObject 'DairyProductInput' is required. Expected type DairyAnimal!", "Argument 'source' on InputObject 'DairyProductInput' is required. Expected type DairyAnimal!", "Argument 'direction' on InputObject 'ResourceOrderType' is required. Expected type String!", "Argument 'source' on InputObject 'DairyProductInput' is required. Expected type DairyAnimal!", "Argument 'direction' on InputObject 'ResourceOrderType' is required. Expected type String!", "InputObject 'DairyProductInput' doesn't accept argument 'wacky'", "Argument 'source' on Field 'similarCheese' has an invalid value (4.5). Expected type '[DairyAnimal!]!'." ]) end end describe("enabled") do let(:args) { { max_errors: 4 } } it "does limit the number of errors" do assert_equal(error_messages.length, 4) assert_equal(error_messages, [ "Argument 'id' on Field 'stringCheese' has an invalid value (\"aasdlkfj\"). Expected type 'Int!'.", "Argument 'if' on Directive 'skip' has an invalid value (\"whatever\"). Expected type 'Boolean!'.", "Argument 'source' on InputObject 'DairyProductInput' has an invalid value (1.1). Expected type 'DairyAnimal!'.", "Argument 'source' on InputObject 'DairyProductInput' is required. Expected type DairyAnimal!", ]) 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/static_validation/rules/required_arguments_are_present_spec.rb
spec/graphql/static_validation/rules/required_arguments_are_present_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::RequiredArgumentsArePresent do include StaticValidationHelpers let(:query_string) {" query getCheese { okCheese: cheese(id: 1) { ...cheeseFields } cheese { source } } fragment cheeseFields on Cheese { similarCheese { __typename } flavor @include(if: true) id @skip } "} it "finds undefined arguments to fields and directives" do assert_equal(3, errors.length) query_root_error = { "message"=>"Field 'cheese' is missing required arguments: id", "locations"=>[{"line"=>4, "column"=>7}], "path"=>["query getCheese", "cheese"], "extensions"=>{"code"=>"missingRequiredArguments", "className"=>"Field", "name"=>"cheese", "arguments"=>"id"} } assert_includes(errors, query_root_error) fragment_error = { "message"=>"Field 'similarCheese' is missing required arguments: source", "locations"=>[{"line"=>8, "column"=>7}], "path"=>["fragment cheeseFields", "similarCheese"], "extensions"=>{"code"=>"missingRequiredArguments", "className"=>"Field", "name"=>"similarCheese", "arguments"=>"source"} } assert_includes(errors, fragment_error) directive_error = { "message"=>"Directive 'skip' is missing required arguments: if", "locations"=>[{"line"=>10, "column"=>10}], "path"=>["fragment cheeseFields", "id"], "extensions"=>{"code"=>"missingRequiredArguments", "className"=>"Directive", "name"=>"skip", "arguments"=>"if"} } assert_includes(errors, directive_error) end describe "dynamic fields" do let(:query_string) {" query { __type { name } } "} it "finds undefined required arguments" do expected_errors = [ { "message"=>"Field '__type' is missing required arguments: name", "locations"=>[ {"line"=>3, "column"=>9} ], "path"=>["query", "__type"], "extensions"=>{ "code"=>"missingRequiredArguments", "className"=>"Field", "name"=>"__type", "arguments"=>"name" } } ] assert_equal(expected_errors, errors) end end describe "when a required arg is hidden" do class Query < GraphQL::Schema::Object field :int, Integer do argument :input, Integer do def visible?(*) false end end end def int(input: -1) input end end class HiddenArgSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN query(Query) end it "Doesn't require a hidden input" do res = HiddenArgSchema.execute("{ int }") assert_equal(-1, res["data"]["int"]) 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/static_validation/rules/fragments_are_used_spec.rb
spec/graphql/static_validation/rules/fragments_are_used_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentsAreUsed do include StaticValidationHelpers let(:query_string) {" query getCheese { name ...cheeseFields ...undefinedFields } fragment cheeseFields on Cheese { fatContent } fragment unusedFields on Cheese { is, not, used } "} it "adds errors for unused fragment definitions" do assert_includes(errors, { "message"=>"Fragment unusedFields was defined, but not used", "locations"=>[{"line"=>8, "column"=>5}], "path"=>["fragment unusedFields"], "extensions"=>{"code"=>"useAndDefineFragment", "fragmentName"=>"unusedFields"} }) end it "adds errors for undefined fragment spreads" do assert_includes(errors, { "message"=>"Fragment undefinedFields was used, but not defined", "locations"=>[{"line"=>5, "column"=>7}], "path"=>["query getCheese", "... undefinedFields"], "extensions"=>{"code"=>"useAndDefineFragment", "fragmentName"=>"undefinedFields"} }) end describe "invalid unused fragments" do let(:query_string) {" query getCheese { name } fragment Invalid on DoesNotExist { fatContent } "} it "handles them gracefully" do assert_includes(errors, { "message"=>"No such type DoesNotExist, so it can't be a fragment condition", "locations"=>[{"line"=>5, "column"=>7}], "path"=>["fragment Invalid"], "extensions"=>{"code"=>"undefinedType", "typeName"=>"DoesNotExist"} }) end end describe "with error limiting" do let(:query_string) {" query getCheese { ...cheeseFields ...undefinedFields } fragment cheeseFields on Cheese { fatContent } fragment unusedFields on Cheese { not_used } fragment yetMoreUnusedFields on Cheese { must_be_vegan } "} describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 6) assert_equal(error_messages,[ "Field 'not_used' doesn't exist on type 'Cheese'", "Field 'must_be_vegan' doesn't exist on type 'Cheese'", "Fragment cheeseFields on Cheese can't be spread inside Query", "Fragment undefinedFields was used, but not defined", "Fragment yetMoreUnusedFields was defined, but not used", "Fragment unusedFields was defined, but not used" ]) end end describe("enabled") do let(:args) { { max_errors: 5 } } it "does limit the number of errors" do assert_equal(error_messages.length, 5) assert_equal(error_messages, [ "Field 'not_used' doesn't exist on type 'Cheese'", "Field 'must_be_vegan' doesn't exist on type 'Cheese'", "Fragment cheeseFields on Cheese can't be spread inside Query", "Fragment undefinedFields was used, but not defined", "Fragment yetMoreUnusedFields was defined, but not used", ]) 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/static_validation/rules/unique_directives_per_location_spec.rb
spec/graphql/static_validation/rules/unique_directives_per_location_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::UniqueDirectivesPerLocation do include StaticValidationHelpers let(:schema) { GraphQL::Schema.from_definition(" type Query { type: Type } type Type { field: String } directive @A on FIELD directive @B on FIELD directive @C repeatable on FIELD ") } describe "query with no directives" do let(:query_string) {" { type { field } } "} it "passes rule" do assert_equal [], errors end end describe "query with repeatable directives" do let(:query_string) {" { type { field @C @C @C } } "} it "passes rule" do assert_equal [], errors end end describe "query with unique directives in different locations" do let(:query_string) {" { type @A { field @B } } "} it "passes rule" do assert_equal [], errors end end describe "query with unique directives in same locations" do let(:query_string) {" { type @A @B { field @A @B } } "} it "passes rule" do assert_equal [], errors end end describe "query with same directives in different locations" do let(:query_string) {" { type @A { field @A } } "} it "passes rule" do assert_equal [], errors end end describe "query with same directives in similar locations" do let(:query_string) {" { type { field @A field @A } } "} it "passes rule" do assert_equal [], errors end end describe "query with duplicate directives in one location" do let(:query_string) {" { type { field @A @A } } "} it "fails rule" do assert_includes errors, { "message" => 'The directive "A" can only be used once at this location.', "locations" => [{ "line" => 4, "column" => 17 }, { "line" => 4, "column" => 20 }], "path" => ["query", "type", "field"], "extensions" => {"code"=>"directiveNotUniqueForLocation", "directiveName"=>"A"} } end end describe "query with many duplicate directives in one location" do let(:query_string) {" { type { field @A @A @A } } "} it "fails rule" do assert_includes errors, { "message" => 'The directive "A" can only be used once at this location.', "locations" => [{ "line" => 4, "column" => 17 }, { "line" => 4, "column" => 20 }, { "line" => 4, "column" => 23 }], "path" => ["query", "type", "field"], "extensions" => {"code"=>"directiveNotUniqueForLocation", "directiveName"=>"A"} } end end describe "query with different duplicate directives in one location" do let(:query_string) {" { type { field @A @B @A @B } } "} it "fails rule" do assert_includes errors, { "message" => 'The directive "A" can only be used once at this location.', "locations" => [{ "line" => 4, "column" => 17 }, { "line" => 4, "column" => 23 }], "path" => ["query", "type", "field"], "extensions" => {"code"=>"directiveNotUniqueForLocation", "directiveName"=>"A"} } assert_includes errors, { "message" => 'The directive "B" can only be used once at this location.', "locations" => [{ "line" => 4, "column" => 20 }, { "line" => 4, "column" => 26 }], "path" => ["query", "type", "field"], "extensions" => {"code"=>"directiveNotUniqueForLocation", "directiveName"=>"B"} } end end describe "query with duplicate directives in many locations" do let(:query_string) {" { type @A @A { field @A @A } } "} it "fails rule" do assert_includes errors, { "message" => 'The directive "A" can only be used once at this location.', "locations" => [{ "line" => 3, "column" => 14 }, { "line" => 3, "column" => 17 }], "path" => ["query", "type"], "extensions" => {"code"=>"directiveNotUniqueForLocation", "directiveName"=>"A"} } assert_includes errors, { "message" => 'The directive "A" can only be used once at this location.', "locations" => [{ "line" => 4, "column" => 17 }, { "line" => 4, "column" => 20 }], "path" => ["query", "type", "field"], "extensions" => {"code"=>"directiveNotUniqueForLocation", "directiveName"=>"A"} } end end describe "with error limiting" do let(:query_string) {" { type @A @A { field @A @A } } "} describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 2) assert_equal(error_messages, [ "The directive \"A\" can only be used once at this location.", "The directive \"A\" can only be used once at this location." ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages.length, 1) assert_equal(error_messages, [ "The directive \"A\" can only be used once at this location." ]) 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/static_validation/rules/fields_will_merge_spec.rb
spec/graphql/static_validation/rules/fields_will_merge_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FieldsWillMerge do include StaticValidationHelpers let(:schema) { GraphQL::Schema.from_definition(%| type Query { dog: Dog cat: Cat pet: Pet toy: Toy animal: Animal } union Animal = Dog \| Cat type Mutation { registerPet(params: PetParams): Pet } enum PetCommand { SIT HEEL JUMP DOWN } enum ToySize { SMALL LARGE } enum PetSpecies { DOG CAT } input PetParams { name: String! species: PetSpecies! } interface Mammal { name(surname: Boolean = false): String! nickname: String } interface Pet { name(surname: Boolean = false): String! nickname: String! toys: [Toy!]! } interface Canine { barkVolume: Int! } interface Feline { meowVolume: Int! } type Dog implements Pet & Mammal & Canine { name(surname: Boolean = false): String! nickname: String! doesKnowCommand(dogCommand: PetCommand): Boolean! barkVolume: Int! toys: [Toy!]! } type Cat implements Pet & Mammal & Feline { name(surname: Boolean = false): String! nickname: String! doesKnowCommand(catCommand: PetCommand): Boolean! meowVolume: Int! toys: [Toy!]! } type Toy { name: String! size: ToySize! image(maxWidth: Int!): String! } |) } describe "unique fields" do let(:query_string) {%| { dog { name nickname } } |} it "passes rule" do assert_equal [], errors end end describe "identical fields" do let(:query_string) {%| { dog { name name } } |} it "passes rule" do assert_equal [], errors end end describe "identical fields with identical input objects" do let(:query_string) {%| mutation { registerPet(params: { name: "Fido", species: DOG }) { name } registerPet(params: { name: "Fido", species: DOG }) { __typename } } |} it "passes rule" do assert_equal [], errors end end describe "identical fields with identical args" do let(:query_string) {%| { dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: SIT) } } |} it "passes rule" do assert_equal [], errors end end describe "identical fields with identical values" do let(:query_string) {%| query($dogCommand: PetCommand) { dog { doesKnowCommand(dogCommand: $dogCommand) doesKnowCommand(dogCommand: $dogCommand) } } |} it "passes rule" do assert_equal [], errors end end describe "identical aliases and fields" do let(:query_string) {%| { dog { otherName: name otherName: name } } |} it "passes rule" do assert_equal [], errors end end describe "different args with different aliases" do let(:query_string) {%| { dog { knowsSit: doesKnowCommand(dogCommand: SIT) knowsDown: doesKnowCommand(dogCommand: DOWN) } } |} it "passes rule" do assert_equal [], errors end end describe "conflicting args value and var" do let(:query_string) {%| query ($dogCommand: PetCommand) { dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: $dogCommand) } } |} it "fails rule" do assert_equal [%q(Field 'doesKnowCommand' has an argument conflict: {dogCommand:"SIT"} or {dogCommand:"$dogCommand"}?)], error_messages end end describe "multiple conflicting args value and var" do let(:query_string) {%| query ($dogCommand: PetCommand) { dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: HEEL) doesKnowCommand(dogCommand: $dogCommand) } } |} it "fails rule" do message = %Q(Field 'doesKnowCommand' has an argument conflict: {dogCommand:"SIT"} or {dogCommand:"HEEL"} or {dogCommand:"$dogCommand"}?) assert_equal [message], error_messages end end describe "very large multiple conflicting args value and var" do let(:query_string) {%| query ($a: PetCommand, $b: PetCommand, $c: PetCommand, $d: PetCommand, $e: PetCommand, $f: PetCommand) { dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: HEEL) doesKnowCommand(dogCommand: JUMP) doesKnowCommand(dogCommand: DOWN) doesKnowCommand(dogCommand: $a) doesKnowCommand(dogCommand: $b) doesKnowCommand(dogCommand: $c) doesKnowCommand(dogCommand: $d) doesKnowCommand(dogCommand: $e) doesKnowCommand(dogCommand: $f) } } |} it "fails rule" do assert_equal 1, error_messages.size # instead of n**2 = 100 assert_match %r/SIT.*HEEL.*JUMP.*DOWN.*\$a.*\$b.*\$c.*\$d.*\$e.*\$f/, error_messages.first end end describe "conflicting args value and var" do let(:query_string) {%| query ($varOne: PetCommand, $varTwo: PetCommand) { dog { doesKnowCommand(dogCommand: $varOne) doesKnowCommand(dogCommand: $varTwo) } } |} it "fails rule" do assert_equal [%q(Field 'doesKnowCommand' has an argument conflict: {dogCommand:"$varOne"} or {dogCommand:"$varTwo"}?)], error_messages end end describe "different directives with different aliases" do let(:query_string) {%| { dog { nameIfTrue: name @include(if: true) nameIfFalse: name @include(if: false) } } |} it "passes rule" do assert_equal [], errors end end describe "different skip/include directives accepted" do let(:query_string) {%| { dog { name @include(if: true) name @include(if: false) } } |} it "passes rule" do assert_equal [], errors end end describe "same aliases with different field targets" do let(:query_string) {%| { dog { fido: name fido: nickname } } |} it "fails rule" do assert_equal ["Field 'fido' has a field conflict: name or nickname?"], error_messages end end describe "multiple aliases with different field targets" do let(:query_string) {%| { dog { fido: name fido: nickname fido: barkVolume } } |} it "fails rule" do assert_equal ["Field 'fido' has a field conflict: name or nickname or barkVolume?"], error_messages end end describe "alias masking direct field access" do let(:query_string) {%| { dog { name: nickname name } } |} it "fails rule" do assert_equal ["Field 'name' has a field conflict: nickname or name?"], error_messages end end describe "different args, second adds an argument" do let(:query_string) {%| { dog { doesKnowCommand doesKnowCommand(dogCommand: HEEL) } } |} it "fails rule" do assert_equal [%q(Field 'doesKnowCommand' has an argument conflict: {} or {dogCommand:"HEEL"}?)], error_messages end end describe "different args, second missing an argument" do let(:query_string) {%| { dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand } } |} it "fails rule" do assert_equal [%q(Field 'doesKnowCommand' has an argument conflict: {dogCommand:"SIT"} or {}?)], error_messages end end describe "conflicting args" do let(:query_string) {%| { dog { doesKnowCommand(dogCommand: SIT) doesKnowCommand(dogCommand: HEEL) } } |} it "fails rule" do assert_equal [%q(Field 'doesKnowCommand' has an argument conflict: {dogCommand:"SIT"} or {dogCommand:"HEEL"}?)], error_messages end end describe "conflicting arg values" do let(:query_string) {%| { toy { image(maxWidth: 10) image(maxWidth: 20) } } |} it "fails rule" do assert_equal [%q(Field 'image' has an argument conflict: {maxWidth:"10"} or {maxWidth:"20"}?)], error_messages end end describe "encounters conflict in fragments" do let(:query_string) {%| { pet { ...A ...B name } } fragment A on Dog { x: name } fragment B on Dog { x: nickname name: nickname } |} it "fails rule" do assert_equal [ "Field 'x' has a field conflict: name or nickname?", "Field 'name' has a field conflict: name or nickname?" ], error_messages end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages, [ "Field 'x' has a field conflict: name or nickname?", "Field 'name' has a field conflict: name or nickname?" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages, [ "Field 'x' has a field conflict: name or nickname?", ]) end end end end describe "deep conflict" do let(:query_string) {%| { dog { x: name } dog { x: nickname } } |} it "fails rule" do expected_errors = [ { "message"=>"Field 'x' has a field conflict: name or nickname?", "locations"=>[ {"line"=>4, "column"=>11}, {"line"=>8, "column"=>11} ], "path"=>[], "extensions"=>{"code"=>"fieldConflict", "fieldName"=>"x", "conflicts"=>"name or nickname"} } ] assert_equal expected_errors, errors end end describe "deep conflict with multiple issues" do let(:query_string) {%| { dog { x: name y: barkVolume } dog { x: nickname y: doesKnowCommand } } |} it "fails rule" do assert_equal [ "Field 'x' has a field conflict: name or nickname?", "Field 'y' has a field conflict: barkVolume or doesKnowCommand?", ], error_messages end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages, [ "Field 'x' has a field conflict: name or nickname?", "Field 'y' has a field conflict: barkVolume or doesKnowCommand?", ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages, [ "Field 'x' has a field conflict: name or nickname?", ]) end end end end describe "very deep conflict" do let(:query_string) {%| { dog { toys { x: name } } dog { toys { x: size } } } |} it "fails rule" do assert_equal [ "Field 'x' has a field conflict: name or size?", ], error_messages end end describe "same aliases allowed on non-overlapping fields" do let(:query_string) {%| { pet { ... on Dog { name } ... on Cat { name: nickname } } } |} it "passes rule" do assert_equal [], errors end end describe "nested spreads on the same type with a conflict" do let(:query_string) {%| { dog { name ...D } } fragment D on Dog { ...D2 } fragment D2 on Dog { name: __typename } |} it "finds a conflict" do assert_equal [ {"message"=>"Field 'name' has a field conflict: name or __typename?", "locations"=>[{"line"=>4, "column"=>11}, {"line"=>14, "column"=>9}], "path"=>[], "extensions"=> {"code"=>"fieldConflict", "fieldName"=>"name", "conflicts"=>"name or __typename"} } ], errors end end describe "same aliases not allowed on different interfaces" do let(:query_string) {%| { pet { ... on Pet { name } ... on Mammal { name: nickname } } } |} it "fails rule" do assert_equal [ "Field 'name' has a field conflict: name or nickname?", ], error_messages end end describe "same aliases on divergent abstract types" do let(:query_string) {%| { animal { ... on Feline { volume: meowVolume } ... on Canine { volume: barkVolume } } } |} it "passes rule" do assert_equal [], errors end end describe "same aliases allowed on different parent interfaces and different concrete types" do let(:query_string) {%| { pet { ... on Pet { ...X } ... on Mammal { ...Y } } } fragment X on Dog { name } fragment Y on Cat { name: nickname } |} it "passes rule" do assert_equal [], errors end end describe "allows different args where no conflict is possible" do let(:query_string) {%| { pet { ... on Dog { ...X } ... on Cat { ...Y } } } fragment X on Pet { name(surname: true) } fragment Y on Pet { name } |} it "passes rule" do assert_equal [], errors end describe "allows different args where no conflict is possible" do let(:query_string) {%| { pet { ... on Dog { ... on Pet { name } } ... on Cat { name(surname: true) } } } |} it "passes rule" do assert_equal [], errors end end describe "allows different args where no conflict is possible with uneven abstract scoping" do let(:query_string) {%| { pet { ... on Pet { ... on Dog { name } } ... on Cat { name(surname: true) } } } |} it "passes rule" do assert_equal [], errors end end end describe "allows different args where no conflict is possible deep" do let(:query_string) {%| { pet { ... on Dog { ...X } } pet { ... on Cat { ...Y } } } fragment X on Pet { name(surname: true) } fragment Y on Pet { name } |} it "passes rule" do assert_equal [], errors end end describe "arguments that are a list of enums, in fragments" do let(:schema) { GraphQL::Schema.from_definition <<-GRAPHQL type Query { field(categories: [Category!]): Int } enum Category { A B C } GRAPHQL } describe "When there's not a conflict" do let(:query_string) { " { field(categories: [A, B, C]) ...Q } fragment Q on Query { field(categories: [A, B, C]) } " } it "doesn't find errors" do assert_equal [], errors end end describe "When there is a conflict" do let(:query_string) { " { field(categories: [A, B]) ...Q } fragment Q on Query { field(categories: [A, B, C]) } " } it "adds an error" do expected_error = { "message"=>"Field 'field' has an argument conflict: {categories:\"[A, B]\"} or {categories:\"[A, B, C]\"}?", "locations"=>[{"line"=>3, "column"=>11}, {"line"=>7, "column"=>11}], "path"=>[], "extensions"=> { "code"=>"fieldConflict", "fieldName"=>"field", "conflicts"=>"{categories:\"[A, B]\"} or {categories:\"[A, B, C]\"}" } } assert_equal [expected_error], errors end end end describe "return types must be unambiguous" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { someBox: SomeBox connection: Connection } type Edge { id: ID name: String } interface SomeBox { deepBox: SomeBox unrelatedField: String } type StringBox implements SomeBox { scalar: String deepBox: StringBox unrelatedField: String listStringBox: [StringBox] stringBox: StringBox intBox: IntBox } type IntBox implements SomeBox { scalar: Int deepBox: IntBox unrelatedField: String listStringBox: [StringBox] stringBox: StringBox intBox: IntBox } interface NonNullStringBox1 { scalar: String! } type NonNullStringBox1Impl implements SomeBox & NonNullStringBox1 { scalar: String! unrelatedField: String deepBox: SomeBox } interface NonNullStringBox2 { scalar: String! } type NonNullStringBox2Impl implements SomeBox & NonNullStringBox2 { scalar: String! unrelatedField: String deepBox: SomeBox } type Connection { edges: [Edge] } |) } describe "compatible return shapes on different return types" do let(:query_string) {%| { someBox { ... on SomeBox { deepBox { unrelatedField } } ... on StringBox { deepBox { unrelatedField } } } } |} it "passes rule" do assert_equal [], errors end end describe "reports correctly when a non-exclusive follows an exclusive" do let(:query_string) {%| { someBox { ... on IntBox { deepBox { ...X } } } someBox { ... on StringBox { deepBox { ...Y } } } memoed: someBox { ... on IntBox { deepBox { ...X } } } memoed: someBox { ... on StringBox { deepBox { ...Y } } } other: someBox { ...X } other: someBox { ...Y } } fragment X on SomeBox { scalar: deepBox { unrelatedField } } fragment Y on SomeBox { scalar: unrelatedField } |} it "fails rule" do assert_includes error_messages, "Field 'scalar' has a field conflict: deepBox or unrelatedField?" end end end describe "conflicts exceeding the max_errors count" do signature = (1..20).map { |n| "$arg#{n}: PetCommand" }.join(', ') fields = (1..20).map { |n| "doesKnowCommand(dogCommand: $arg#{n})" }.join(" ") let(:args) do { max_errors: 10 } end let(:query_string) {%| query (#{signature}) { dog { #{fields} } } |} it "fails rule" do assert_equal 1, error_messages.size (1..11).each do |n| assert_match %r/\$arg#{n}/, error_messages.first end refute_match %r/\$arg12/, error_messages.first end end describe "Conflicting leaf typed fields" do let(:schema) { GraphQL::Schema.from_definition(<<-GRAPHQL) interface Thing { name: String } type Dog implements Thing { spots: Boolean } type Jaguar implements Thing { spots: Int } type Query { thing: Thing } GRAPHQL } let(:query_str) { <<-GRAPHQL { thing { ... on Dog { spots } ... on Jaguar { spots } } } GRAPHQL } it "warns by default" do res = nil stdout, _stderr = capture_io do res = schema.validate(query_str) end assert_equal [], res expected_warning = [ "GraphQL-Ruby encountered mismatched types in this query: `Boolean` (at 3:26) vs. `Int` (at 4:29).", "This will return an error in future GraphQL-Ruby versions, as per the GraphQL specification", "Learn about migrating here: https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#allow_legacy_invalid_return_type_conflicts-class_method" ].join("\n") assert_includes stdout, expected_warning end it "calls the handler when legacy is enabled" do legacy_schema = Class.new(schema) do allow_legacy_invalid_return_type_conflicts(true) def self.legacy_invalid_return_type_conflicts(query, t1, t2, node1, node2) raise "#{query.class} / #{t1.to_type_signature} / #{t2.to_type_signature} / #{node1.position} / #{node2.position}" end end err = assert_raises do legacy_schema.validate(query_str) end assert_equal "GraphQL::Query / Boolean / Int / [3, 26] / [4, 29]", err.message end it "adds an error when legacy is disabled" do future_schema = Class.new(schema) { allow_legacy_invalid_return_type_conflicts(false) } res = future_schema.validate(query_str) expected_error = { "message"=>"Field 'spots' has a return_type conflict: `Boolean` or `Int`?", "locations"=>[{"line"=>3, "column"=>26}, {"line"=>4, "column"=>29}], "path"=>[], "extensions"=> {"code"=>"fieldConflict", "fieldName"=>"spots", "conflicts"=>"`Boolean` or `Int`"} } assert_equal [expected_error], res.map(&:to_h) end it "inherits allow_legacy_invalid_empty_selections_on_union" do base_schema = Class.new(schema) { allow_legacy_invalid_return_type_conflicts(true) } ext_schema = Class.new(base_schema) assert ext_schema.allow_legacy_invalid_return_type_conflicts end end describe "conflicting list / non-list fields" do it "requires matching list/non-list structure" do schema = GraphQL::Schema.from_definition <<~GRAPHQL type Query { u: U } union U = A | B type A { f: [Int] } type B { f: Int } GRAPHQL schema.allow_legacy_invalid_return_type_conflicts(false) query_str = <<~GRAPHQL { u { ... on A { f } ... on B { f } } } GRAPHQL res = schema.validate(query_str) assert_equal ["Field 'f' has a return_type conflict: `[Int]` or `Int`?"], res.map(&:message) query_str = <<~GRAPHQL { u { ... on B { f } ... on A { f } } } GRAPHQL res = schema.validate(query_str) assert_equal ["Field 'f' has a return_type conflict: `Int` or `[Int]`?"], res.map(&:message) end end describe "duplicate aliases on a interface with inline fragment spread" do class DuplicateAliasesSchema < GraphQL::Schema module Node include GraphQL::Schema::Interface field :id, ID def self.resolve_type(obj, ctx) Repository end end class Repository < GraphQL::Schema::Object implements Node field :name, String field :id, ID end class Query < GraphQL::Schema::Object field :node, Node, fallback_value: { name: "graphql-ruby", id: "abcdef" } end query(Query) orphan_types(Repository) end it "returns an error" do query_str = 'query { node { ... on Repository { info: name info: id } } } ' res = DuplicateAliasesSchema.execute(query_str) assert_equal ["Field 'info' has a field conflict: name or id?"], 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/static_validation/rules/fragment_spreads_are_possible_spec.rb
spec/graphql/static_validation/rules/fragment_spreads_are_possible_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentSpreadsArePossible do include StaticValidationHelpers let(:query_string) {%| query getCheese { cheese(id: 1) { ... milkFields ... cheeseFields ... on Milk { fatContent } ... on AnimalProduct { source } ... on DairyProduct { ... on Cheese { fatContent } ... on Edible { fatContent } } } } fragment milkFields on Milk { fatContent } fragment cheeseFields on Cheese { fatContent ... milkFields } |} it "doesnt allow spreads where they'll never apply" do # TODO: more negative, abstract examples here, add stuff to the schema expected = [ { "message"=>"Fragment on Milk can't be spread inside Cheese", "locations"=>[{"line"=>6, "column"=>9}], "path"=>["query getCheese", "cheese", "... on Milk"], "extensions"=>{"code"=>"cannotSpreadFragment", "typeName"=>"Milk", "fragmentName"=>"unknown", "parentName"=>"Cheese"} }, { "message"=>"Fragment milkFields on Milk can't be spread inside Cheese", "locations"=>[{"line"=>4, "column"=>9}], "path"=>["query getCheese", "cheese", "... milkFields"], "extensions"=>{"code"=>"cannotSpreadFragment", "typeName"=>"Milk", "fragmentName"=>" milkFields", "parentName"=>"Cheese"} }, { "message"=>"Fragment milkFields on Milk can't be spread inside Cheese", "locations"=>[{"line"=>18, "column"=>7}], "path"=>["fragment cheeseFields", "... milkFields"], "extensions"=>{"code"=>"cannotSpreadFragment", "typeName"=>"Milk", "fragmentName"=>" milkFields", "parentName"=>"Cheese"} } ] assert_equal(expected, 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/static_validation/rules/variables_are_used_and_defined_spec.rb
spec/graphql/static_validation/rules/variables_are_used_and_defined_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::VariablesAreUsedAndDefined do include StaticValidationHelpers let(:query_string) {' query getCheese( $usedVar: Int!, $usedInnerVar: [DairyAnimal!]!, $usedInlineFragmentVar: Int!, $usedFragmentVar: Int!, $notUsedVar: Int!, ) { c1: cheese(id: $usedVar) { __typename } ... on Query { c2: cheese(id: $usedInlineFragmentVar) { similarCheese(source: $usedInnerVar) { __typename } } } c3: cheese(id: $undefinedVar) { __typename } ... outerCheeseFields } fragment outerCheeseFields on Query { ... innerCheeseFields } fragment innerCheeseFields on Query { c4: cheese(id: $undefinedFragmentVar) { __typename } c5: cheese(id: $usedFragmentVar) { __typename } } '} describe "variables which are used-but-not-defined or defined-but-not-used" do it "finds the variables" do expected = [ { "message"=>"Variable $notUsedVar is declared by getCheese but not used", "locations"=>[{"line"=>2, "column"=>5}], "path"=>["query getCheese"], "extensions"=>{"code"=>"variableNotUsed", "variableName"=>"notUsedVar"} }, { "message"=>"Variable $undefinedVar is used by getCheese but not declared", "locations"=>[{"line"=>19, "column"=>22}], "path"=>["query getCheese", "c3", "id"], "extensions"=>{"code"=>"variableNotDefined", "variableName"=>"undefinedVar"} }, { "message"=>"Variable $undefinedFragmentVar is used by innerCheeseFields but not declared", "locations"=>[{"line"=>29, "column"=>22}], "path"=>["fragment innerCheeseFields", "c4", "id"], "extensions"=>{"code"=>"variableNotDefined", "variableName"=>"undefinedFragmentVar"} }, ] assert_equal(expected, errors) end describe "with an anonymous query" do let(:query_string) do <<-GRAPHQL query($notUsedVar: Int!) { c1: cheese(id: $undeclared) { __typename } } GRAPHQL end it "shows 'anonymous query' in the message" do expected = [ { "message"=>"Variable $notUsedVar is declared by anonymous query but not used", "locations"=>[{"line"=>1, "column"=>9}], "path"=>["query"], "extensions"=>{"code"=>"variableNotUsed", "variableName"=>"notUsedVar"} }, { "message"=>"Variable $undeclared is used by anonymous query but not declared", "locations"=>[{"line"=>2, "column"=>26}], "path"=>["query", "c1", "id"], "extensions"=>{"code"=>"variableNotDefined", "variableName"=>"undeclared"} } ] assert_equal(expected, errors) end end end describe "usages in directives on fragment spreads" do let(:query_string) { <<-GRAPHQL query($f: Boolean!){ ...F @include(if: $f) } fragment F on Query { __typename } GRAPHQL } it "finds usages" do assert_equal([], errors) end end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 3) assert_equal(error_messages, [ "Variable $notUsedVar is declared by getCheese but not used", "Variable $undefinedVar is used by getCheese but not declared", "Variable $undefinedFragmentVar is used by innerCheeseFields but not declared" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages.length, 1) assert_equal(error_messages, [ "Variable $notUsedVar is declared by getCheese but not used" ]) 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/static_validation/rules/input_object_names_are_unique_spec.rb
spec/graphql/static_validation/rules/input_object_names_are_unique_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::InputObjectNamesAreUnique do include StaticValidationHelpers let(:query_string) {%| query getCheese { validInputObjectName: searchDairy(product: [{source: YAK}]) { __typename } duplicateInputObjectNames: searchDairy(product: [{source: YAK, source: YAK}]) { __typename } } |} describe "when queries contain duplicate input fields" do duplicate_input_field_error = { "message" => 'There can be only one input field named "source"', "locations"=>[{ "line" => 4, "column" => 57 }, { "line" => 4, "column" => 70 }], "path" => ["query getCheese", "duplicateInputObjectNames", "product", 0], "extensions" => { "code" => "inputFieldNotUnique", "name" => "source" } } it "returns errors in the response" do assert_includes(errors, duplicate_input_field_error) end end describe "with error limiting" do let(:query_string) {%| query getCheese { validInputObjectName: searchDairy(product: [{source: YAK}]) { __typename } duplicateInputObjectNames: searchDairy(product: [{source: YAK, source: YAK}]) { __typename } moreDuplicateInputObjectNames: searchDairy(product: [{fatContent: YAK, fatContent: YAK, source: COW}]) { __typename } } |} describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 3) assert_equal(error_messages, [ "There can be only one input field named \"source\"", "There can be only one input field named \"fatContent\"", "Argument 'fatContent' on InputObject 'DairyProductInput' has an invalid value (YAK). Expected type 'Float'." ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages.length, 1) assert_equal(error_messages, [ "There can be only one input field named \"source\"", ]) 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/static_validation/rules/fragments_are_on_composite_types_spec.rb
spec/graphql/static_validation/rules/fragments_are_on_composite_types_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentsAreOnCompositeTypes do include StaticValidationHelpers let(:query_string) {%| query getCheese { cheese(id: 1) { ... on Cheese { source ... on Boolean { something } } ... intFields ... on DairyProduct { ... on Cheese { flavor } } ... on DairyProductInput { something } } } fragment intFields on Int { something } |} it "requires Object/Union/Interface fragment types" do expected = [ { "message"=>"Invalid fragment on type Boolean (must be Union, Interface or Object)", "locations"=>[{"line"=>6, "column"=>11}], "path"=>["query getCheese", "cheese", "... on Cheese", "... on Boolean"], "extensions"=>{"code"=>"fragmentOnNonCompositeType", "typeName"=>"Boolean"} }, { "message"=>"Invalid fragment on type DairyProductInput (must be Union, Interface or Object)", "locations"=>[{"line"=>16, "column"=>9}], "path"=>["query getCheese", "cheese", "... on DairyProductInput"], "extensions"=>{"code"=>"fragmentOnNonCompositeType", "typeName"=>"DairyProductInput"} }, { "message"=>"Invalid fragment on type Int (must be Union, Interface or Object)", "locations"=>[{"line"=>22, "column"=>5}], "path"=>["fragment intFields"], "extensions"=>{"code"=>"fragmentOnNonCompositeType", "typeName"=>"Int"} }, ] assert_equal(expected, 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/static_validation/rules/directives_are_in_valid_locations_spec.rb
spec/graphql/static_validation/rules/directives_are_in_valid_locations_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::DirectivesAreInValidLocations do include StaticValidationHelpers describe "invalid directive locations" do let(:query_string) {" query getCheese @skip(if: true) { okCheese: cheese(id: 1) { id @skip(if: true), source ... on Cheese @skip(if: true) { flavor ... whatever } } } fragment whatever on Cheese @skip(if: true) { id } "} it "makes errors for them" do expected = [ { "message"=> "'@skip' can't be applied to queries (allowed: fields, fragment spreads, inline fragments)", "locations"=>[{"line"=>2, "column"=>23}], "path"=>["query getCheese"], "extensions"=>{"code"=>"directiveCannotBeApplied", "targetName"=>"queries", "name"=>"skip"} }, { "message"=>"'@skip' can't be applied to fragment definitions (allowed: fields, fragment spreads, inline fragments)", "locations"=>[{"line"=>13, "column"=>35}], "path"=>["fragment whatever"], "extensions"=>{"code"=>"directiveCannotBeApplied", "targetName"=>"fragment definitions", "name"=>"skip"} }, ] assert_equal(expected, errors) end end describe "valid directive locations" do let(:query_string) {" query getCheese($id: Int! @directiveForVariableDefinition) { cheese(id: $id) { id } } "} it "does not make errors for them" do expected = [] assert_equal(expected, errors) 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/static_validation/rules/argument_literals_are_compatible_spec.rb
spec/graphql/static_validation/rules/argument_literals_are_compatible_spec.rb
# frozen_string_literal: true require "spec_helper" require "uri" describe GraphQL::StaticValidation::ArgumentLiteralsAreCompatible do include StaticValidationHelpers let(:query_string) {%| query getCheese { stringCheese: cheese(id: "aasdlkfj") { ...cheeseFields } cheese(id: 1) { source @skip(if: "whatever") } yakSource: searchDairy(product: [{source: COW, fatContent: 1.1}]) { __typename } badSource: searchDairy(product: {source: 1.1}) { __typename } missingSource: searchDairy(product: [{fatContent: 1.1}]) { __typename } listCoerce: cheese(id: 1) { similarCheese(source: YAK) { __typename } } missingInputField: searchDairy(product: [{source: YAK, wacky: 1}]) { __typename } } fragment cheeseFields on Cheese { similarCheese(source: 4.5) { __typename } } |} it "finds undefined or missing-required arguments to fields and directives" do # `wacky` above is handled by ArgumentsAreDefined, missingSource is handled by RequiredInputObjectAttributesArePresent # so only 4 are tested below assert_equal(6, errors.length) query_root_error = { "message"=>"Argument 'id' on Field 'stringCheese' has an invalid value (\"aasdlkfj\"). Expected type 'Int!'.", "locations"=>[{"line"=>3, "column"=>7}], "path"=>["query getCheese", "stringCheese", "id"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"id"}, } assert_includes(errors, query_root_error) directive_error = { "message"=>"Argument 'if' on Directive 'skip' has an invalid value (\"whatever\"). Expected type 'Boolean!'.", "locations"=>[{"line"=>4, "column"=>30}], "path"=>["query getCheese", "cheese", "source", "if"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"Directive", "argumentName"=>"if"}, } assert_includes(errors, directive_error) input_object_field_error = { "message"=>"Argument 'source' on InputObject 'DairyProductInput' has an invalid value (1.1). Expected type 'DairyAnimal!'.", "locations"=>[{"line"=>6, "column"=>39}], "path"=>["query getCheese", "badSource", "product", 0, "source"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"InputObject", "argumentName"=>"source"}, } assert_includes(errors, input_object_field_error) fragment_error = { "message"=>"Argument 'source' on Field 'similarCheese' has an invalid value (4.5). Expected type '[DairyAnimal!]!'.", "locations"=>[{"line"=>13, "column"=>7}], "path"=>["fragment cheeseFields", "similarCheese", "source"], "extensions"=> {"code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"source"} } assert_includes(errors, fragment_error) end describe "using input objects for enums it adds an error" do let(:query_string) { <<-GRAPHQL { yakSource: searchDairy(product: [{source: {a: 1, b: 2}, fatContent: 1.1}]) { __typename } } GRAPHQL } it "works" do assert_equal 1, errors.length end end describe "using enums for scalar arguments it adds an error" do let(:query_string) { <<-GRAPHQL { cheese(id: I_AM_ENUM_VALUE) { source } } GRAPHQL } let(:enum_invalid_for_id_error) do { "message" => "Argument 'id' on Field 'cheese' has an invalid value (I_AM_ENUM_VALUE). Expected type 'Int!'.", "locations" => [{ "line" => 2, "column" => 9 }], "path"=> ["query", "cheese", "id"], "extensions"=> { "code" => "argumentLiteralsIncompatible", "typeName" => "Field", "argumentName" => "id" } } end it "works" do assert_includes(errors, enum_invalid_for_id_error) assert_equal 1, errors.length end end describe "null value" do describe "nullable arg" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(arg: Int): Int } |) } let(:query_string) {%| query { field(arg: null) } |} it "finds no errors" do assert_equal [], errors end end describe "non-nullable arg" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(arg: Int!): Int } |) } let(:query_string) {%| query { field(arg: null) } |} it "finds error" do assert_equal [{ "message"=>"Argument 'arg' on Field 'field' has an invalid value (null). Expected type 'Int!'.", "locations"=>[{"line"=>3, "column"=>11}], "path"=>["query", "field", "arg"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"arg"} }], errors end end describe "non-nullable array" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(arg: [Int!]): Int } |) } let(:query_string) {%| query { field(arg: [null]) } |} it "finds error" do assert_equal [{ "message"=>"Argument 'arg' on Field 'field' has an invalid value ([null]). Expected type '[Int!]'.", "locations"=>[{"line"=>3, "column"=>11}], "path"=>["query", "field", "arg"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"arg"} }], errors end end describe "array with nullable values" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(arg: [Int]): Int } |) } let(:query_string) {%| query { field(arg: [null]) } |} it "finds no errors" do assert_equal [], errors end end describe "input object" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(arg: Input): Int } input Input { a: Int b: Int! } |) } let(:query_string) {%| query { field(arg: {a: null, b: null}) } |} it "it finds errors" do assert_equal 1, errors.length refute_includes errors, { "message"=>"Argument 'arg' on Field 'field' has an invalid value ({a: null, b: null}). Expected type 'Input'.", "locations"=>[{"line"=>3, "column"=>11}], "path"=>["query", "field", "arg"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"arg"} } assert_includes errors, { "message"=>"Argument 'b' on InputObject 'Input' has an invalid value (null). Expected type 'Int!'.", "locations"=>[{"line"=>3, "column"=>22}], "path"=>["query", "field", "arg", "b"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"InputObject", "argumentName"=>"b"} } end end end describe "dynamic fields" do let(:query_string) {" query { __type(name: 1) { name } } "} it "finds invalid argument types" do assert_includes(errors, { "message"=>"Argument 'name' on Field '__type' has an invalid value (1). Expected type 'String!'.", "locations"=>[{"line"=>3, "column"=>9}], "path"=>["query", "__type", "name"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"Field", "argumentName"=>"name"} }) end end describe "error references argument" do let(:validator) { GraphQL::StaticValidation::Validator.new(schema: schema) } let(:query) { GraphQL::Query.new(schema, query_string) } let(:errors) { validator.validate(query)[:errors] } let(:query_string) {" query { cheese(id: true) { source } milk(id: 1) { source @skip(if: TRUE) } } "} it "works with field" do id_argument = schema.types['Query'].fields['cheese'].get_argument('id') error = errors.find { |error| error.argument_name == 'id' } assert_equal id_argument, error.argument assert_equal true, error.value end it "works with directive" do if_argument = schema.directives['skip'].get_argument('if') error = errors.find { |error| error.argument_name == 'if' } assert_equal if_argument, error.argument assert_instance_of GraphQL::Language::Nodes::Enum, error.value assert_equal "TRUE", error.value.name end end class CustomErrorMessagesSchema < GraphQL::Schema class TimeType < GraphQL::Schema::Scalar description "Time since epoch in seconds" def self.coerce_input(value, ctx) Time.at(Float(value)) rescue ArgumentError raise GraphQL::CoercionError, 'cannot coerce to Float' end def self.coerce_result(value, ctx) value.to_f end end class RangeType < GraphQL::Schema::InputObject argument :from, TimeType argument :to, TimeType end class EmailType < GraphQL::Schema::Scalar def self.coerce_input(value, ctx) if URI::MailTo::EMAIL_REGEXP.match(value) value else raise GraphQL::CoercionError.new("Invalid email address", extensions: { "code" => "invalid_email_address" }) end end def self.coerce_result(value, ctx) value.to_f end end class Query < GraphQL::Schema::Object description "The query root of this schema" field :time, TimeType do argument :value, TimeType, required: false argument :range, RangeType, required: false end def time(value: nil, range: nil) value end field :email, EmailType do argument :value, EmailType, required: false end def email(value:) value end end query(Query) end describe "custom error messages" do let(:schema) { CustomErrorMessagesSchema } let(:query_string) {%| query { time(value: "a") } |} describe "with a shallow coercion" do it "sets error message from a CoercionError if raised" do assert_equal 1, errors.length assert_includes errors, { "message"=> "cannot coerce to Float", "locations"=>[{"line"=>3, "column"=>9}], "path"=>["query", "time", "value"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"CoercionError"} } end end describe "with a deep coercion" do let(:query_string) {%| query { time(range: { from: "a", to: "b" }) } |} from_error = { "message"=>"cannot coerce to Float", "locations"=>[{"line"=>3, "column"=>23}], "path"=>["query", "time", "range", "from"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"CoercionError"}, } to_error = { "message"=>"cannot coerce to Float", "locations"=>[{"line"=>3, "column"=>23}], "path"=>["query", "time", "range", "to"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"CoercionError"}, } bubbling_error = { "message"=>"cannot coerce to Float", "locations"=>[{"line"=>3, "column"=>11}], "path"=>["query", "time", "range"], "extensions"=>{"code"=>"argumentLiteralsIncompatible", "typeName"=>"CoercionError"}, } describe "sets deep error message from a CoercionError if raised" do it "works" do assert_equal 2, errors.length assert_includes(errors, from_error) assert_includes(errors, to_error) refute_includes(errors, bubbling_error) end end end end describe "custom error extensions" do let(:schema) { CustomErrorMessagesSchema } let(:query_string) {%| query { email(value: "a") } |} describe "with a shallow coercion" do it "sets error extensions code from a CoercionError if raised" do assert_equal 1, errors.length assert_includes errors, { "message"=> "Invalid email address", "locations"=>[{"line"=>3, "column"=>9}], "path"=>["query", "email", "value"], "extensions"=>{"code"=>"invalid_email_address", "typeName"=>"CoercionError"} } 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/static_validation/rules/fields_have_appropriate_selections_spec.rb
spec/graphql/static_validation/rules/fields_have_appropriate_selections_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FieldsHaveAppropriateSelections do include StaticValidationHelpers let(:query_string) {" query getCheese { okCheese: cheese(id: 1) { fatContent, similarCheese(source: YAK) { source } } missingFieldsObject: cheese(id: 1) missingFieldsInterface: cheese(id: 1) { selfAsEdible } illegalSelectionCheese: cheese(id: 1) { id { something, ... someFields } } incorrectFragmentSpread: cheese(id: 1) { flavor { ... on String { __typename } } } } "} it "adds errors for selections on scalars" do assert_equal(4, errors.length) illegal_selection_error = { "message"=>"Selections can't be made on scalars (field 'id' returns Int but has selections [\"something\", \"someFields\"])", "locations"=>[{"line"=>6, "column"=>47}], "path"=>["query getCheese", "illegalSelectionCheese", "id"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"field 'id'", "typeName"=>"Int"} } assert_includes(errors, illegal_selection_error, "finds illegal selections on scalars") objects_selection_required_error = { "message"=>"Field must have selections (field 'cheese' returns Cheese but has no selections. Did you mean 'cheese { ... }'?)", "locations"=>[{"line"=>4, "column"=>7}], "path"=>["query getCheese", "missingFieldsObject"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"field 'cheese'", "typeName"=>"Cheese"} } assert_includes(errors, objects_selection_required_error, "finds objects without selections") interfaces_selection_required_error = { "message"=>"Field must have selections (field 'selfAsEdible' returns Edible but has no selections. Did you mean 'selfAsEdible { ... }'?)", "locations"=>[{"line"=>5, "column"=>47}], "path"=>["query getCheese", "missingFieldsInterface", "selfAsEdible"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"field 'selfAsEdible'", "typeName"=>"Edible"} } assert_includes(errors, interfaces_selection_required_error, "finds interfaces without selections") incorrect_fragment_error = { "message"=>"Selections can't be made on scalars (field 'flavor' returns String but has selections [\"... on String { ... }\"])", "locations"=>[{"line"=>7, "column"=>48}], "path"=>["query getCheese", "incorrectFragmentSpread", "flavor"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"field 'flavor'", "typeName"=>"String"} } assert_includes(errors, incorrect_fragment_error, "finds scalar fields with selections") end describe "anonymous operations" do let(:query_string) { "{ }" } it "requires selections" do assert_equal(1, errors.length) selections_required_error = { "message"=> "Field must have selections (anonymous query returns Query but has no selections. Did you mean ' { ... }'?)", "locations"=>[{"line"=>1, "column"=>1}], "path"=>["query"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"anonymous query", "typeName"=>"Query"} } assert_includes(errors, selections_required_error) end end describe "selections and inline fragments on scalars" do let(:query_string) {" { cheese(id: 1) { fatContent { name ... on User { id } ... F } } } fragment F on Cheese { id } "} it "returns an error" do expected_err = "Selections can't be made on scalars (field 'fatContent' returns Float but has selections [\"name\", \"... on User { ... }\", \"F\"])" assert_includes(errors.map { |e| e["message"] }, expected_err) end end describe "selections on unions" do let(:query_string) { "{ searchDairy }"} describe "When the schema has custom handling with type to return the message" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) def self.legacy_invalid_empty_selections_on_union_with_type(query, type) :return_validation_error end } } it "returns the default message" do expected_err = "Field must have selections (field 'searchDairy' returns DairyProduct but has no selections. Did you mean 'searchDairy { ... }'?)" assert_includes(errors.map { |e| e["message"] }, expected_err) end end describe "When the schema has custom handling to return the message" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) def self.legacy_invalid_empty_selections_on_union(query) :return_validation_error end } } it "returns the default message" do expected_err = "Field must have selections (field 'searchDairy' returns DairyProduct but has no selections. Did you mean 'searchDairy { ... }'?)" assert_includes(errors.map { |e| e["message"] }, expected_err) end end describe "When the schema has custom handling with type to return a custom message" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) def self.legacy_invalid_empty_selections_on_union_with_type(query, type) "Boo, hiss!" end } } it "returns the custom message" do expected_err = "Boo, hiss!" assert_includes(errors.map { |e| e["message"] }, expected_err) end end describe "When the schema has custom handling to return a custom message" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) def self.legacy_invalid_empty_selections_on_union(query) "Boo, hiss!" end } } it "returns the custom message" do expected_err = "Boo, hiss!" assert_includes(errors.map { |e| e["message"] }, expected_err) end end describe "When the schema has custom handling with type to allow the query" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) def self.legacy_invalid_empty_selections_on_union_with_type(query, type) nil end } } it "returns no errors" do assert_equal [], errors end end describe "When the schema has custom handling to allow the query" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) def self.legacy_invalid_empty_selections_on_union(query) nil end } } it "returns no errors" do assert_equal [], errors end end describe "When the schema has no setting" do it "allows it with a warning to query.logger" do expected_warning = "Unions require selections but searchDairy (DairyProduct) doesn't have any. This will fail with a validation error on a future GraphQL-Ruby version. More info: https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#allow_legacy_invalid_empty_selections_on_union-class_method" stdout, _stderr = capture_io do assert_equal [], errors end assert_includes stdout, expected_warning end end describe "When the schema has legacy mode disabled" do let(:schema) { Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(false) } } it "requires some" do expected_err = "Field must have selections (field 'searchDairy' returns DairyProduct but has no selections. Did you mean 'searchDairy { ... }'?)" assert_includes(errors.map { |e| e["message"] }, expected_err) end end describe "With inherited setting" do let(:schema) { Class.new(Class.new(Dummy::Schema) { allow_legacy_invalid_empty_selections_on_union(true) }) } it "has correct value" do assert schema.allow_legacy_invalid_empty_selections_on_union 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/static_validation/rules/variable_names_are_unique_spec.rb
spec/graphql/static_validation/rules/variable_names_are_unique_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::VariableNamesAreUnique do include StaticValidationHelpers let(:query_string) { <<-GRAPHQL query GetStuff($var1: Int!, $var2: Int!, $var1: Int!, $var2: Int!, $var3: Int!) { c1: cheese(id: $var1) { flavor } c2: cheese(id: $var2) { flavor } c3: cheese(id: $var3) { flavor } } GRAPHQL } it "finds duplicate variable names" do assert_equal 2, errors.size last_err = errors.last assert_equal 'There can only be one variable named "var2"', last_err["message"] assert_equal 2, last_err["locations"].size end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 2) assert_equal(error_messages, [ "There can only be one variable named \"var1\"", "There can only be one variable named \"var2\"" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages.length, 1) assert_equal(error_messages, [ "There can only be one variable named \"var1\"", ]) 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/static_validation/rules/directives_are_defined_spec.rb
spec/graphql/static_validation/rules/directives_are_defined_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::DirectivesAreDefined do include StaticValidationHelpers let(:query_string) {" query getCheese { okCheese: cheese(id: 1) { id @skip(if: true), source @nonsense(if: false) ... on Cheese { flavor @moreNonsense @moreNonsense } id2: id @sikp(if: true) } } "} describe "non-existent directives" do it "makes errors for them" do expected = [ { "message"=>"Directive @nonsense is not defined", "locations"=>[{"line"=>5, "column"=>16}], "path"=>["query getCheese", "okCheese", "source"], "extensions"=>{"code"=>"undefinedDirective", "directiveName"=>"nonsense"} }, { "message"=>"The directive \"moreNonsense\" can only be used once at this location.", "locations"=>[{"line"=>7, "column"=>18}, {"line"=>7, "column"=>32}], "path"=>["query getCheese", "okCheese", "... on Cheese", "flavor"], "extensions"=>{"code"=>"directiveNotUniqueForLocation", "directiveName"=>"moreNonsense"} }, { "message"=>"Directive @moreNonsense is not defined", "locations"=>[{"line"=>7, "column"=>18}, {"line"=>7, "column"=>32}], "path"=>["query getCheese", "okCheese", "... on Cheese", "flavor"], "extensions"=>{"code"=>"undefinedDirective", "directiveName"=>"moreNonsense"} }, { "message"=>"Directive @sikp is not defined (Did you mean `skip`?)", "locations"=>[{"line"=>9, "column"=>17}], "path"=>["query getCheese", "okCheese", "id2"], "extensions"=>{"code"=>"undefinedDirective", "directiveName"=>"sikp"} } ] assert_equal(expected, errors) 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/static_validation/rules/variable_usages_are_allowed_spec.rb
spec/graphql/static_validation/rules/variable_usages_are_allowed_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::VariableUsagesAreAllowed do include StaticValidationHelpers let(:query_string) {' query getCheese( $goodInt: Int = 1, $okInt: Int!, $badInt: Int, $badStr: String!, $goodAnimals: [DairyAnimal!]!, $badAnimals: [DairyAnimal]!, $deepAnimals: [[DairyAnimal!]!]!, $goodSource: DairyAnimal!, ) { goodCheese: cheese(id: $goodInt) { source } okCheese: cheese(id: $okInt) { source } badCheese: cheese(id: $badInt) { source } badStrCheese: cheese(id: $badStr) { source } cheese(id: 1) { similarCheese(source: $goodAnimals) { source } other: similarCheese(source: $badAnimals) { source } tooDeep: similarCheese(source: $deepAnimals) { source } nullableCheese(source: $goodAnimals) { source } deeplyNullableCheese(source: $deepAnimals) { source } } milk(id: 1) { flavors(limit: $okInt) } searchDairy(product: [{source: $goodSource}]) { ... on Cheese { id } } } '} it "finds variables used as arguments but don't match the argument's type" do assert_equal(4, errors.length) expected = [ { "message"=>"Nullability mismatch on variable $badInt and argument id (Int / Int!)", "locations"=>[{"line"=>14, "column"=>28}], "path"=>["query getCheese", "badCheese", "id"], "extensions"=>{"code"=>"variableMismatch", "variableName"=>"badInt", "typeName"=>"Int", "argumentName"=>"id", "errorMessage"=>"Nullability mismatch"} }, { "message"=>"Type mismatch on variable $badStr and argument id (String! / Int!)", "locations"=>[{"line"=>15, "column"=>28}], "path"=>["query getCheese", "badStrCheese", "id"], "extensions"=>{"code"=>"variableMismatch", "variableName"=>"badStr", "typeName"=>"String!", "argumentName"=>"id", "errorMessage"=>"Type mismatch"} }, { "message"=>"Nullability mismatch on variable $badAnimals and argument source ([DairyAnimal]! / [DairyAnimal!]!)", "locations"=>[{"line"=>18, "column"=>30}], "path"=>["query getCheese", "cheese", "other", "source"], "extensions"=>{"code"=>"variableMismatch", "variableName"=>"badAnimals", "typeName"=>"[DairyAnimal]!", "argumentName"=>"source", "errorMessage"=>"Nullability mismatch"} }, { "message"=>"List dimension mismatch on variable $deepAnimals and argument source ([[DairyAnimal!]!]! / [DairyAnimal!]!)", "locations"=>[{"line"=>19, "column"=>32}], "path"=>["query getCheese", "cheese", "tooDeep", "source"], "extensions"=>{"code"=>"variableMismatch", "variableName"=>"deepAnimals", "typeName"=>"[[DairyAnimal!]!]!", "argumentName"=>"source", "errorMessage"=>"List dimension mismatch"} } ] assert_equal(expected, errors) end describe "input objects that are out of place" do let(:query_string) { <<-GRAPHQL query getCheese($id: ID!) { cheese(id: {blah: $id} ) { __typename @nonsense(id: {blah: $id}) nonsense(id: {blah: {blah: $id}}) } } GRAPHQL } it "adds an error" do assert_equal 3, errors.length assert_equal "Argument 'id' on Field 'cheese' has an invalid value ({blah: $id}). Expected type 'Int!'.", errors[0]["message"] end end describe "list-type variables" do let(:schema) { GraphQL::Schema.from_definition <<-GRAPHQL input ImageSize { height: Int width: Int scale: Int } type Query { imageUrl(height: Int, width: Int, size: ImageSize, sizes: [ImageSize!]): String! sizedImageUrl(sizes: [ImageSize!]!): String! } GRAPHQL } describe "nullability mismatch" do let(:query_string) { <<-GRAPHQL # This variable _should_ be [ImageSize!] query ($sizes: [ImageSize]) { imageUrl(sizes: $sizes) } GRAPHQL } it "finds invalid inner definitions" do assert_equal 1, errors.size expected_message = "Nullability mismatch on variable $sizes and argument sizes ([ImageSize] / [ImageSize!])" assert_equal [expected_message], errors.map { |e| e["message"] } end end describe "list dimension mismatch" do let(:query_string) { <<-GRAPHQL query ($sizes: [ImageSize]) { imageUrl(sizes: [$sizes]) } GRAPHQL } it "finds invalid inner definitions" do assert_equal 1, errors.size expected_message = "List dimension mismatch on variable $sizes and argument sizes ([[ImageSize]]! / [ImageSize!])" assert_equal [expected_message], errors.map { |e| e["message"] } end end describe 'list is in the argument' do let(:query_string) { <<-GRAPHQL query ($size: ImageSize!) { imageUrl(sizes: [$size]) } GRAPHQL } it "is a valid query" do assert_equal 0, errors.size end describe "mixed with invalid literals" do let(:query_string) { <<-GRAPHQL query ($size: ImageSize!) { imageUrl(sizes: [$size, 1, true]) } GRAPHQL } it "is an invalid query" do assert_equal 1, errors.size end end describe "mixed with invalid variables" do let(:query_string) { <<-GRAPHQL query ($size: ImageSize!, $wrongSize: Boolean!) { imageUrl(sizes: [$size, $wrongSize]) } GRAPHQL } it "is an invalid query" do assert_equal 1, errors.size end end describe "mixed with valid literals and invalid variables" do let(:query_string) { <<-GRAPHQL query ($size: ImageSize!, $wrongSize: Boolean!) { imageUrl(sizes: [$size, {height: 100} $wrongSize]) } GRAPHQL } it "is an invalid query" do assert_equal 1, errors.size end end end describe 'argument contains a list with literal values' do let(:query_string) { <<-GRAPHQL query { imageUrl(sizes: [{height: 100, width: 100, scale: 1}]) } GRAPHQL } it "is a valid query" do assert_equal 0, errors.size end end describe 'argument contains a list with both literal and variable values' do let(:query_string) { <<-GRAPHQL query($size1: ImageSize!, $size2: ImageSize!) { imageUrl(sizes: [{height: 100, width: 100, scale: 1}, $size1, {height: 1920, width: 1080, scale: 2}, $size2]) } GRAPHQL } it "is a valid query" do assert_equal 0, errors.size end end describe "variable in non-null list" do let(:query_string) { <<-GRAPHQL # This should work query ($size: ImageSize!) { sizedImageUrl(sizes: [$size]) } GRAPHQL } it "is allowed" do assert_equal [], errors end end describe "nullability mismatch in non-null list" do let(:query_string) { <<-GRAPHQL query ($sizes: [ImageSize!]) { sizedImageUrl(sizes: $sizes) } GRAPHQL } it "gives the right error" do err = "Nullability mismatch on variable $sizes and argument sizes ([ImageSize!] / [ImageSize!]!)" assert_equal [err], errors.map { |e| e["message"]} end end end describe "for input properties" do class InputVariableSchema < GraphQL::Schema class Input < GraphQL::Schema::InputObject argument(:id, String) end class FooMutation < GraphQL::Schema::Mutation field(:foo, String) argument(:input, Input) def resolve(input:) { foo: input.id } end end class Mutation < GraphQL::Schema::Object field(:foo_mutation, mutation: FooMutation) end mutation(Mutation) end it "gives a proper error" do res1 = InputVariableSchema.execute("mutation($id: String) { fooMutation(input: { id: $id }) { foo } }") assert_equal ["Nullability mismatch on variable $id and argument id (String / String!)"], res1["errors"].map { |e| e["message"] } res2 = InputVariableSchema.execute("mutation($id: String!) { fooMutation(input: { id: $id }) { foo } }", variables: { id: "abc" }) refute res2.key?("errors") assert_equal "abc", res2["data"]["fooMutation"]["foo"] end end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 4) assert_equal(error_messages, [ "Nullability mismatch on variable $badInt and argument id (Int / Int!)", "Type mismatch on variable $badStr and argument id (String! / Int!)", "Nullability mismatch on variable $badAnimals and argument source ([DairyAnimal]! / [DairyAnimal!]!)", "List dimension mismatch on variable $deepAnimals and argument source ([[DairyAnimal!]!]! / [DairyAnimal!]!)" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages.length, 1) assert_equal(error_messages, [ "Nullability mismatch on variable $badInt and argument id (Int / Int!)" ]) end end end describe "non-null arguments with default values" do it "doesn't require a value in the query" do schema_graphql = <<~GRAPHQL type Query { songs(sort: SongSort! = {name: asc}): [Song!]! topSong(input: TopSongInput!): Song } type Song { name: String! } input SongSort { name: SortDirection } enum SortDirection { asc desc } input TopSongInput { thisYear: Boolean! = true } GRAPHQL schema = GraphQL::Schema.from_definition( schema_graphql, default_resolve: { "Query" => { "songs" => ->(obj, args, ctx) { sort = args[:sort] names = ["asc", nil].include?(sort[:name]) ? ["A", "B"] : ["B", "A"] names.map { |name| Struct.new(:name).new(name) } }, "topSong" => ->(obj, args, ctx) { args[:input][:this_year] ? OpenStruct.new(name: "Hey Ya!") : OpenStruct.new(name: "Here Comes the Sun") } } } ) result = schema.execute("query($sort: SongSort) { songs(sort: $sort) { name } }", variables: {}) expected_result = {"data" => {"songs" => [{"name" => "A"},{"name" => "B"}]}} assert_graphql_equal expected_result, result result = schema.execute("query($sort: SongSort) { songs(sort: $sort) { name } }", variables: { sort: { name: "desc" } }) expected_result = {"data" => {"songs" => [{"name" => "B"},{"name" => "A"}]}} assert_graphql_equal expected_result, result result = schema.execute("query($sort: SongSort) { songs(sort: $sort) { name } }", variables: { sort: nil }) expected_result = {"errors"=>[{"message"=>"`null` is not a valid input for `SongSort!`, please provide a value for this argument.", "locations"=>[{"line"=>1, "column"=>26}], "path"=>["songs"]}], "data" => nil} assert_graphql_equal expected_result, result result = schema.execute("{ topSong(input: {}) { name } }") assert_equal "Hey Ya!", result["data"]["topSong"]["name"] result = schema.execute("{ topSong(input: { thisYear: false }) { name } }") assert_equal "Here Comes the Sun", result["data"]["topSong"]["name"] result = schema.execute("{ topSong(input: { thisYear: null }) { name } }") assert_equal ["Argument 'thisYear' on InputObject 'TopSongInput' has an invalid value (null). Expected type 'Boolean!'."], result["errors"].map { |err| 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/static_validation/rules/mutation_root_exists_spec.rb
spec/graphql/static_validation/rules/mutation_root_exists_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::MutationRootExists do include StaticValidationHelpers let(:query_string) {%| mutation addBagel { introduceShip(input: {shipName: "Bagel"}) { clientMutationId shipEdge { node { name, id } } } } |} let(:schema) { Class.new(GraphQL::Schema) do query_root = Class.new(GraphQL::Schema::Object) do graphql_name "Query" end query query_root end } it "errors when a mutation is performed on a schema without a mutation root" do assert_equal(1, errors.length) missing_mutation_root_error = { "message"=>"Schema is not configured for mutations", "locations"=>[{"line"=>2, "column"=>5}], "path"=>["mutation addBagel"], "extensions"=>{"code"=>"missingMutationConfiguration"} } assert_includes(errors, missing_mutation_root_error) 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/static_validation/rules/argument_names_are_unique_spec.rb
spec/graphql/static_validation/rules/argument_names_are_unique_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::ArgumentNamesAreUnique do include StaticValidationHelpers describe "field arguments" do let(:query_string) { <<-GRAPHQL query GetStuff { c1: cheese(id: 1, id: 2) { flavor } c2: cheese(id: 2) { flavor } } GRAPHQL } it "finds duplicate names" do assert_equal 1, errors.size error = errors.first assert_equal 'There can be only one argument named "id"', error["message"] assert_equal [{ "line" => 2, "column" => 18}, { "line" => 2, "column" => 25 }], error["locations"] assert_equal ["query GetStuff", "c1"], error["path"] end end describe "directive arguments" do let(:query_string) { <<-GRAPHQL query GetStuff { c1: cheese(id: 1) @include(if: true, if: true) { flavor } c2: cheese(id: 2) @include(if: true) { flavor } } GRAPHQL } it "finds duplicate names" do assert_equal 1, errors.size error = errors.first assert_equal 'There can be only one argument named "if"', error["message"] assert_equal [{ "line" => 2, "column" => 34}, { "line" => 2, "column" => 44 }], error["locations"] assert_equal ["query GetStuff", "c1"], error["path"] end end describe "with error limiting" do let(:query_string) { <<-GRAPHQL query GetStuff { c1: cheese(id: 1, id: 2) @include(if: true, if: true) { flavor } c2: cheese(id: 3, id: 3) @include(if: true) { flavor } } GRAPHQL } describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages, [ "There can be only one argument named \"id\"", "There can be only one argument named \"if\"", "There can be only one argument named \"id\"" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages, [ "There can be only one argument named \"id\"" ]) 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/static_validation/rules/arguments_are_defined_spec.rb
spec/graphql/static_validation/rules/arguments_are_defined_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::ArgumentsAreDefined do include StaticValidationHelpers let(:query_string) {" query getCheese { okCheese: cheese(id: 1) { source } cheese(silly: false, id: 2) { source } searchDairy(product: [{wacky: 1}]) { ...cheeseFields } } fragment cheeseFields on Cheese { similarCheese(source: SHEEP, nonsense: 1) { __typename } id @skip(something: 3.4, if: false) } "} describe "finds undefined arguments to fields and directives" do it "works" do assert_equal(5, errors.length) extra_error = { "message"=>"Argument 'product' on Field 'searchDairy' has an invalid value. Expected type '[DairyProductInput]'.", "locations"=>[{"line"=>5, "column"=>7}], "path"=>["query getCheese", "searchDairy", "product"] } refute_includes(errors, extra_error) end end describe "dynamic fields" do let(:query_string) {" query { __type(somethingInvalid: 1, nme: \"something\") { name } } "} it "finds undefined arguments" do assert_includes(errors, { "message"=>"Field '__type' doesn't accept argument 'somethingInvalid'", "locations"=>[{"line"=>3, "column"=>16}], "path"=>["query", "__type", "somethingInvalid"], "extensions"=>{"code"=>"argumentNotAccepted", "name"=>"__type", "typeName"=>"Field", "argumentName"=>"somethingInvalid"} }) assert_includes(errors, { "message"=>"Field '__type' doesn't accept argument 'nme' (Did you mean `name`?)", "locations"=>[{"line"=>3, "column"=>37}], "path"=>["query", "__type", "nme"], "extensions"=>{"code"=>"argumentNotAccepted", "name"=>"__type", "typeName"=>"Field", "argumentName"=>"nme"} }) end end describe "error references argument's parent" do let(:validator) { GraphQL::StaticValidation::Validator.new(schema: schema) } let(:query) { GraphQL::Query.new(schema, query_string) } let(:errors) { validator.validate(query)[:errors] } let(:query_string) {" query { cheese(silly: true, id: 1) { source } milk(id: 1) { source @skip(something: 3.4, if: false) } } "} it "works with field" do query_cheese_field = schema.types['Query'].fields['cheese'] error = errors.find { |error| error.argument_name == 'silly' } assert_equal query_cheese_field, error.parent end it "works with directive" do skip_directive = schema.directives['skip'] error = errors.find { |error| error.argument_name == 'something' } assert_equal skip_directive, error.parent 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/static_validation/rules/fields_are_defined_on_type_spec.rb
spec/graphql/static_validation/rules/fields_are_defined_on_type_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FieldsAreDefinedOnType do include StaticValidationHelpers let(:query_string) { " query getCheese { notDefinedField { name } cheese(id: 1) { nonsenseField, flavor ...cheeseFields } fromSource(source: COW) { bogusField } } fragment cheeseFields on Cheese { fatContent, hogwashField } "} it "finds fields that are requested on types that don't have that field" do expected_errors = [ "Field 'notDefinedField' doesn't exist on type 'Query'", # from query root "Field 'nonsenseField' doesn't exist on type 'Cheese'", # from another field "Field 'bogusField' doesn't exist on type 'Cheese'", # from a list "Field 'hogwashField' doesn't exist on type 'Cheese'", # from a fragment ] assert_equal(expected_errors, error_messages) end describe "on objects" do let(:query_string) { "query getStuff { notDefinedField }"} it "finds invalid fields" do expected_errors = [ { "message"=>"Field 'notDefinedField' doesn't exist on type 'Query'", "locations"=>[{"line"=>1, "column"=>18}], "path"=>["query getStuff", "notDefinedField"], "extensions"=>{"code"=>"undefinedField", "typeName"=>"Query", "fieldName"=>"notDefinedField"} } ] assert_equal(expected_errors, errors) end end describe "on interfaces" do let(:query_string) { "query getStuff { favoriteEdible { amountThatILikeIt orgin } }"} it "finds invalid fields" do expected_errors = [ { "message"=>"Field 'amountThatILikeIt' doesn't exist on type 'Edible'", "locations"=>[{"line"=>1, "column"=>35}], "path"=>["query getStuff", "favoriteEdible", "amountThatILikeIt"], "extensions"=>{"code"=>"undefinedField", "typeName"=>"Edible", "fieldName"=>"amountThatILikeIt"} }, { "message"=>"Field 'orgin' doesn't exist on type 'Edible' (Did you mean `origin`?)", "locations"=>[{"line"=>1, "column"=>53}], "path"=>["query getStuff", "favoriteEdible", "orgin"], "extensions"=>{"code"=>"undefinedField", "typeName"=>"Edible", "fieldName"=>"orgin"} } ] assert_equal(expected_errors, errors) end end describe "on unions" do let(:query_string) { " query notOnUnion { favoriteEdible { ...dpFields ...dpIndirectFields } } fragment dpFields on DairyProduct { source } fragment dpIndirectFields on DairyProduct { ... on Cheese { source } } "} it "doesnt allow selections on unions" do expected_errors = [ { "message"=>"Selections can't be made directly on unions (see selections on DairyProduct)", "locations"=>[ {"line"=>3, "column"=>7} ], "path"=>["fragment dpFields", "source"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"DairyProduct"} } ] assert_equal(expected_errors, errors) end end describe "__typename" do describe "on existing unions" do let(:query_string) { " query { favoriteEdible { ...dpFields } } fragment dpFields on DairyProduct { __typename } "} it "is allowed" do assert_equal([], errors) end end describe "on existing objects" do let(:query_string) { " query { cheese(id: 1) { __typename } } "} it "is allowed" do assert_equal([], errors) end end end describe "__schema" do describe "on query root" do let(:query_string) { " query { __schema { queryType { name } } } "} it "is allowed" do assert_equal([], errors) end end describe "on non-query root" do let(:query_string) { " query { cheese(id: 1) { __schema { queryType { name } } } } "} it "is not allowed" do expected_errors = [ { "message"=>"Field '__schema' doesn't exist on type 'Cheese'", "locations"=>[ {"line"=>2, "column"=>33} ], "path"=>["query", "cheese", "__schema"], "extensions"=>{"code"=>"undefinedField", "typeName"=>"Cheese", "fieldName"=>"__schema"} } ] assert_equal(expected_errors, errors) end end end describe "__type" do describe "on query root" do let(:query_string) { %| query { __type(name: "Cheese") { name } } |} it "is allowed" do assert_equal([], errors) end end describe "on non-query root" do let(:query_string) { %| query { cheese(id: 1) { __type(name: "Cheese") { name } } } |} it "is not allowed" do expected_errors = [ { "message"=>"Field '__type' doesn't exist on type 'Cheese'", "locations"=>[ {"line"=>2, "column"=>33} ], "path"=>["query", "cheese", "__type"], "extensions"=>{"code"=>"undefinedField", "typeName"=>"Cheese", "fieldName"=>"__type"} } ] assert_equal(expected_errors, errors) 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/static_validation/rules/fragments_are_named_spec.rb
spec/graphql/static_validation/rules/fragments_are_named_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentTypesExist do include StaticValidationHelpers let(:query_string) {" fragment on Cheese { id flavor } "} it "finds non-existent types on fragments" do assert_equal(1, errors.length) fragment_def_error = { "message"=>"Fragment definition has no name", "locations"=>[{"line"=>2, "column"=>5}], "path"=>["fragment "], "extensions"=>{"code"=>"anonymousFragment"} } assert_includes(errors, fragment_def_error, "on fragment definitions") 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/static_validation/rules/variables_are_input_types_spec.rb
spec/graphql/static_validation/rules/variables_are_input_types_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::VariablesAreInputTypes do include StaticValidationHelpers let(:query_string) {' query getCheese( $id: Int = 1, $str: [String!], $interface: AnimalProduct!, $object: Milk = 1, $objects: [Cheese]!, $unknownType: Nonsense, $misspelled: Bolean, ) { cheese(id: $id) { source } __type(name: $str) { name } } '} it "finds variables whose types are invalid" do assert_includes(errors, { "message"=>"AnimalProduct isn't a valid input type (on $interface)", "locations"=>[{"line"=>5, "column"=>7}], "path"=>["query getCheese"], "extensions"=> {"code"=>"variableRequiresValidType", "typeName"=>"AnimalProduct", "variableName"=>"interface"} }) assert_includes(errors, { "message"=>"Milk isn't a valid input type (on $object)", "locations"=>[{"line"=>6, "column"=>7}], "path"=>["query getCheese"], "extensions"=>{"code"=>"variableRequiresValidType", "typeName"=>"Milk", "variableName"=>"object"} }) assert_includes(errors, { "message"=>"Cheese isn't a valid input type (on $objects)", "locations"=>[{"line"=>7, "column"=>7}], "path"=>["query getCheese"], "extensions"=>{"code"=>"variableRequiresValidType", "typeName"=>"Cheese", "variableName"=>"objects"} }) assert_includes(errors, { "message"=>"Nonsense isn't a defined input type (on $unknownType)", "locations"=>[{"line"=>8, "column"=>7}], "path"=>["query getCheese"], "extensions"=>{"code"=>"variableRequiresValidType", "typeName"=>"Nonsense", "variableName"=>"unknownType"} }) assert_includes(errors, { "message"=>"Bolean isn't a defined input type (on $misspelled) (Did you mean `Boolean`?)", "locations"=>[{"line"=>9, "column"=>7}], "path"=>["query getCheese"], "extensions"=>{"code"=>"variableRequiresValidType", "typeName"=>"Bolean", "variableName"=>"misspelled"} }) end describe "typos" do it "returns a client error" do res = schema.execute <<-GRAPHQL query GetCheese($id: IDX) { cheese(id: $id) { flavor } } GRAPHQL assert_equal false, res.key?("data") assert_equal 1, res["errors"].length assert_equal "IDX isn't a defined input type (on $id) (Did you mean `ID`?)", res["errors"][0]["message"] end it "returns a client error when there are directives" do res = schema.execute <<-GRAPHQL query GetCheese($msg: IDX) { cheese(id: $id) @skip(if: true) { flavor } } GRAPHQL assert_equal false, res.key?("data") assert_equal 3, res["errors"].length assert_equal "IDX isn't a defined input type (on $msg) (Did you mean `ID`?)", res["errors"][0]["message"] assert_equal "Variable $msg is declared by GetCheese but not used", res["errors"][1]["message"] assert_equal "Variable $id is used by GetCheese but not declared", res["errors"][2]["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/static_validation/rules/operation_names_are_valid_spec.rb
spec/graphql/static_validation/rules/operation_names_are_valid_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::OperationNamesAreValid do include StaticValidationHelpers describe "when there are multiple operations" do let(:query_string) { <<-GRAPHQL query getCheese { cheese(id: 1) { flavor } } { cheese(id: 2) { flavor } } { cheese(id: 3) { flavor } } GRAPHQL } it "must have operation names" do assert_equal 1, errors.length requires_name_error = { "message"=>"Operation name is required when multiple operations are present", "locations"=>[{"line"=>5, "column"=>5}, {"line"=>9, "column"=>5}], "path"=>[], "extensions"=>{"code"=>"uniquelyNamedOperations"} } assert_includes(errors, requires_name_error) end end describe "when there are only unnamed operations" do let(:query_string) { <<-GRAPHQL { cheese(id: 2) { flavor } } { cheese(id: 3) { flavor } } GRAPHQL } it "requires names" do assert_equal 1, errors.length requires_name_error = { "message"=>"Operation name is required when multiple operations are present", "locations"=>[{"line"=>1, "column"=>5}, {"line"=>5, "column"=>5}], "path"=>[], "extensions"=>{"code"=>"uniquelyNamedOperations"} } assert_includes(errors, requires_name_error) end end describe "when multiple operations have names" do let(:query_string) { <<-GRAPHQL query getCheese { cheese(id: 1) { flavor } } query getCheese { cheese(id: 2) { flavor } } GRAPHQL } it "must be unique" do assert_equal 1, errors.length name_uniqueness_error = { "message"=>'Operation name "getCheese" must be unique', "locations"=>[{"line"=>1, "column"=>5}, {"line"=>5, "column"=>5}], "path"=>[], "extensions"=>{"code"=>"uniquelyNamedOperations", "operationName"=>"getCheese"} } assert_includes(errors, name_uniqueness_error) end end describe "with error limiting" do let(:query_string) { <<-GRAPHQL query getCheese { cheese(id: 1) { flavor } } query getCheese { cheese(id: 2) { flavor } } query getCheeses{ searchDairy(product: [{ source: COW }]) { __typename } } query getCheeses{ searchDairy(product: [{ source: COW }]) { __typename } } GRAPHQL } describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages.length, 2) assert_equal(error_messages, [ "Operation name \"getCheese\" must be unique", "Operation name \"getCheeses\" must be unique" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages.length, 1) assert_equal(error_messages, [ "Operation name \"getCheese\" must be unique", ]) 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/static_validation/rules/fragments_are_finite_spec.rb
spec/graphql/static_validation/rules/fragments_are_finite_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentsAreFinite do include StaticValidationHelpers let(:query_string) {%| query getCheese { cheese(id: 1) { ... idField ... sourceField similarCheese(source: SHEEP) { ... flavorField } } } fragment sourceField on Cheese { source, ... flavorField ... idField } fragment flavorField on Cheese { flavor, similarCheese(source: SHEEP) { ... on Cheese { ... sourceField } } } fragment idField on Cheese { id } |} it "doesnt allow infinite loops" do expected = [ { "message"=>"Fragment sourceField contains an infinite loop", "locations"=>[{"line"=>12, "column"=>5}], "path"=>["fragment sourceField"], "extensions"=>{"code"=>"infiniteLoop", "fragmentName"=>"sourceField"} }, { "message"=>"Fragment flavorField contains an infinite loop", "locations"=>[{"line"=>17, "column"=>5}], "path"=>["fragment flavorField"], "extensions"=>{"code"=>"infiniteLoop", "fragmentName"=>"flavorField"} } ] assert_equal(expected, errors) end describe "undefined spreads inside fragments" do let(:query_string) {%| { cheese(id: 1) { ... frag1 } } fragment frag1 on Cheese { id, ...frag2 } |} it "doesn't blow up" do assert_equal("Fragment frag2 was used, but not defined", errors.first["message"]) end end describe "a duplicate fragment name with a loop" do let(:query_string) {%| { cheese(id: 1) { ... frag1 } } fragment frag1 on Cheese { id } fragment frag1 on Cheese { ...frag1 } |} it "detects the uniqueness problem" do assert_equal 1, errors.length assert_equal("Fragment name \"frag1\" must be unique", errors[0]["message"]) end end describe "a duplicate operation name with a loop" do let(:query_string) {%| fragment frag1 on Cheese { ...frag1 } query frag1 { cheese(id: 1) { ... frag1 } } |} it "detects the loop" do assert_equal 1, errors.length assert_equal("Fragment frag1 contains an infinite loop", errors[0]["message"]) end end describe "several duplicate operation names with a loop" do let(:query_string) {%| query frag1 { cheese(id: 1) { id } } fragment frag1 on Cheese { ...frag1 } query frag1 { cheese(id: 1) { ... frag1 } } |} it "detects the loop" do assert_equal 2, errors.length assert_equal("Fragment frag1 contains an infinite loop", errors[0]["message"]) assert_equal("Operation name \"frag1\" must be unique", errors[1]["message"]) end describe "with error limiting" do describe("disabled") do let(:args) { { max_errors: nil } } it "does not limit the number of errors" do assert_equal(error_messages, [ "Fragment frag1 contains an infinite loop", "Operation name \"frag1\" must be unique" ]) end end describe("enabled") do let(:args) { { max_errors: 1 } } it "does limit the number of errors" do assert_equal(error_messages, [ "Fragment frag1 contains an infinite loop", ]) 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/static_validation/rules/variable_default_values_are_correctly_typed_spec.rb
spec/graphql/static_validation/rules/variable_default_values_are_correctly_typed_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::VariableDefaultValuesAreCorrectlyTyped do include StaticValidationHelpers let(:query_string) {%| query getCheese( $id: Int = 1, $str: String!, $badInt: Int = "abc", $input: DairyProductInput = {source: YAK, fatContent: 1}, $badInput: DairyProductInput = {source: YAK, fatContent: true}, $nonNull: Int! = 1, ) { cheese1: cheese(id: $id) { source } cheese2: cheese(id: $badInt) { source } cheese3: cheese(id: $nonNull) { source } search1: searchDairy(product: [$input]) { __typename } search2: searchDairy(product: [$badInput]) { __typename } __type(name: $str) { name } } |} it "finds default values that don't match their types" do expected = [ { "message"=>"Could not coerce value \"abc\" to Int", "locations"=>[{"line"=>5, "column"=>7}], "path"=>["query getCheese"], "extensions"=>{"code"=>"defaultValueInvalidType", "variableName"=>"badInt", "typeName"=>"Int"} }, { "message"=>"Could not coerce value true to Float", "locations"=>[{"line"=>7, "column"=>7}], "path"=>["query getCheese"], "extensions"=>{"code"=>"defaultValueInvalidType", "variableName"=>"badInput", "typeName"=>"DairyProductInput"} }, ] assert_equal(expected, errors) end it "returns a client error when the type isn't found" do res = schema.execute <<-GRAPHQL query GetCheese($msg: IDX = 1) { cheese(id: $msg) @skip(if: true) { flavor } } GRAPHQL assert_equal false, res.key?("data") assert_equal 1, res["errors"].length assert_equal "IDX isn't a defined input type (on $msg) (Did you mean `ID`?)", res["errors"][0]["message"] end describe "null default values" do describe "variables with valid default null values" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(a: Int, b: String, c: ComplexInput): Int } input ComplexInput { requiredField: Boolean! intField: Int } |) } let(:query_string) {%| query getCheese( $a: Int = null, $b: String = null, $c: ComplexInput = { requiredField: true, intField: null } ) { field(a: $a, b: $b, c: $c) } |} it "finds no errors" do assert_equal [], errors end end describe "variables with invalid default null values" do let(:schema) { GraphQL::Schema.from_definition(%| type Query { field(a: Int!, b: String!, c: ComplexInput): Int } input ComplexInput { requiredField: Boolean! intField: Int } |) } let(:query_string) {%| query getCheese( $a: Int! = null, $b: String! = null, $c: ComplexInput = { requiredField: null, intField: null } ) { field(a: $a, b: $b, c: $c) } |} it "finds errors" do expected = [ { "message"=>"Default value for $a doesn't match type Int!", "locations"=>[{"line"=>3, "column"=>11}], "path"=>["query getCheese"], "extensions"=> {"code"=>"defaultValueInvalidType", "variableName"=>"a", "typeName"=>"Int!"} }, { "message"=>"Default value for $b doesn't match type String!", "locations"=>[{"line"=>4, "column"=>11}], "path"=>["query getCheese"], "extensions"=>{"code"=>"defaultValueInvalidType", "variableName"=>"b", "typeName"=>"String!"} }, { "message"=>"Default value for $c doesn't match type ComplexInput", "locations"=>[{"line"=>5, "column"=>11}], "path"=>["query getCheese"], "extensions"=>{"code"=>"defaultValueInvalidType", "variableName"=>"c", "typeName"=>"ComplexInput"} } ] assert_equal expected, errors end end end describe "custom error messages" do class CustomErrorMessagesSchema2 < GraphQL::Schema class TimeType < GraphQL::Schema::Scalar description "Time since epoch in seconds" def self.coerce_input(value, ctx) Time.at(Float(value)) rescue ArgumentError raise GraphQL::CoercionError, 'cannot coerce to Float' end def self.coerce_result(value, ctx) value.to_f end end class Query < GraphQL::Schema::Object description "The query root of this schema" field :time, TimeType do argument :value, TimeType, required: false end def time(value: nil, range: nil) value end end query(Query) end let(:schema) { CustomErrorMessagesSchema2 } let(:query_string) {%| query( $value: Time = "a" ) { time(value: $value) } |} it "sets error message from a CoercionError if raised" do assert_equal 1, errors.length assert_includes errors, { "message"=> "cannot coerce to Float", "locations"=>[{"line"=>3, "column"=>9}], "path"=>["query"], "extensions"=>{"code"=>"defaultValueInvalidType", "variableName"=>"value", "typeName"=>"Time"} } 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/static_validation/rules/fragment_types_exist_spec.rb
spec/graphql/static_validation/rules/fragment_types_exist_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentTypesExist do include StaticValidationHelpers let(:query_string) {" query getCheese { cheese(id: 1) { ... on Cheese { source } ... on Nothing { whatever } ... somethingFields ... cheeseFields ...cf2 } } fragment somethingFields on Something { something } fragment cheeseFields on Cheese { fatContent } fragment cf2 on Chese { fatContent } "} it "finds non-existent types on fragments" do assert_equal(3, errors.length) inline_fragment_error = { "message"=>"No such type Something, so it can't be a fragment condition", "locations"=>[{"line"=>12, "column"=>5}], "path"=>["fragment somethingFields"], "extensions"=>{"code"=>"undefinedType", "typeName"=>"Something"} } assert_includes(errors, inline_fragment_error, "on inline fragments") fragment_def_error = { "message"=>"No such type Nothing, so it can't be a fragment condition", "locations"=>[{"line"=>5, "column"=>9}], "path"=>["query getCheese", "cheese", "... on Nothing"], "extensions"=>{"code"=>"undefinedType", "typeName"=>"Nothing"} } assert_includes(errors, fragment_def_error, "on fragment definitions") fragment_def_error = { "message"=>"No such type Chese, so it can't be a fragment condition (Did you mean `Cheese`?)", "locations"=>[{"line"=>18, "column"=>5}], "path"=>["fragment cf2"], "extensions"=>{"code"=>"undefinedType", "typeName"=>"Chese"} } assert_includes(errors, fragment_def_error, "on fragment definitions") 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/static_validation/rules/fragment_names_are_unique_spec.rb
spec/graphql/static_validation/rules/fragment_names_are_unique_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::StaticValidation::FragmentNamesAreUnique do include StaticValidationHelpers let(:query_string) {" query { cheese(id: 1) { ... frag1 } } fragment frag1 on Cheese { id } fragment frag1 on Cheese { id } "} it "requires unique fragment names" do assert_equal(1, errors.length) fragment_def_error = { "message"=>"Fragment name \"frag1\" must be unique", "locations"=>[{"line"=>8, "column"=>5}, {"line"=>9, "column"=>5}], "path"=>[], "extensions"=>{"code"=>"fragmentNotUnique", "fragmentName"=>"frag1"} } assert_includes(errors, fragment_def_error) end describe "when used in a spread" do let(:query_string) {" query { cheese(id: 1) { ... frag1 } } fragment frag1 on Cheese { ...frag2 } fragment frag1 on Cheese { ...frag2 } fragment frag2 on Cheese { id } "} it "finds the error" do assert_equal(1, errors.length) fragment_def_error = { "message"=>"Fragment name \"frag1\" must be unique", "locations"=>[{"line"=>8, "column"=>7}, {"line"=>9, "column"=>7}], "path"=>[], "extensions"=>{"code"=>"fragmentNotUnique", "fragmentName"=>"frag1"} } assert_includes(errors, fragment_def_error) end end describe "when used at second level" do let(:query_string) {" query { cheese(id: 1) { ... frag1 } } fragment frag1 on Cheese { ...frag2 } fragment frag2 on Cheese { id } fragment frag2 on Cheese { id } "} it "finds the error" do assert_equal(1, errors.length) fragment_def_error = { "message"=>"Fragment name \"frag2\" must be unique", "locations"=>[{"line"=>9, "column"=>7}, {"line"=>10, "column"=>7}], "path"=>[], "extensions"=>{"code"=>"fragmentNotUnique", "fragmentName"=>"frag2"} } assert_includes(errors, fragment_def_error) 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/execution/lookahead_spec.rb
spec/graphql/execution/lookahead_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Execution::Lookahead do module LookaheadTest DATA = [ OpenStruct.new(name: "Cardinal", is_waterfowl: false, similar_species_names: ["Scarlet Tanager"], genus: OpenStruct.new(latin_name: "Piranga")), OpenStruct.new(name: "Scarlet Tanager", is_waterfowl: false, similar_species_names: ["Cardinal"], genus: OpenStruct.new(latin_name: "Cardinalis")), OpenStruct.new(name: "Great Egret", is_waterfowl: false, similar_species_names: ["Great Blue Heron"], genus: OpenStruct.new(latin_name: "Ardea")), OpenStruct.new(name: "Great Blue Heron", is_waterfowl: true, similar_species_names: ["Great Egret"], genus: OpenStruct.new(latin_name: "Ardea")), ] def DATA.find_by_name(name) DATA.find { |b| b.name == name } end module Node include GraphQL::Schema::Interface field :id, ID, null: false end class BirdGenus < GraphQL::Schema::Object implements Node field :name, String, null: false field :latin_name, String, null: false field :id, ID, null: false, method: :latin_name end class BirdSpecies < GraphQL::Schema::Object implements Node field :name, String, null: false field :id, ID, null: false, method: :name field :is_waterfowl, Boolean, null: false field :similar_species, [BirdSpecies], null: false def similar_species object.similar_species_names.map { |n| DATA.find_by_name(n) } end field :genus, BirdGenus, null: false, extras: [:lookahead] def genus(lookahead:) if lookahead.selects?(:latin_name) context[:lookahead_latin_name] += 1 end object.genus end end class PlantSpecies < GraphQL::Schema::Object implements Node field :name, String, null: false field :id, ID, null: false, method: :name field :is_edible, Boolean, null: false end class Species < GraphQL::Schema::Union possible_types BirdSpecies, PlantSpecies end class Query < GraphQL::Schema::Object field :find_bird_species, BirdSpecies do argument :by_name, String end def find_bird_species(by_name:) DATA.find_by_name(by_name) end field :node, Node do argument :id, ID end def node(id:) if (node = DATA.find_by_name(id)) node else DATA.map { |d| d.genus }.select { |g| g.name == id } end end field :species, Species do argument :id, ID end def species(id:) DATA.find_by_name(id) end end module LookaheadInstrumenter def execute_query(query:) query.context[:root_lookahead_selections] = query.lookahead.selections super end end class Schema < GraphQL::Schema query(Query) trace_with LookaheadInstrumenter end class AlwaysVisibleSchema < Schema use GraphQL::Schema::AlwaysVisible end end describe "looking ahead" do let(:document) { GraphQL.parse <<-GRAPHQL query($name: String!){ findBirdSpecies(byName: $name) { name similarSpecies { likesWater: isWaterfowl } } t: __typename } GRAPHQL } let(:schema) { LookaheadTest::Schema } let(:query) { GraphQL::Query.new(schema, document: document, variables: { name: "Cardinal" }) } it "has a good test setup" do res = query.result assert_equal [false], res["data"]["findBirdSpecies"]["similarSpecies"].map { |s| s["likesWater"] } end it "can detect fields on objects with symbol or string" do lookahead = query.lookahead.selection("findBirdSpecies") assert_equal true, lookahead.selects?("similarSpecies") assert_equal true, lookahead.selects?(:similar_species) assert_equal false, lookahead.selects?("isWaterfowl") assert_equal false, lookahead.selects?(:is_waterfowl) end it "detects by name, not by alias" do assert_equal true, query.lookahead.selects?("__typename") end it "uses null lookahead when no operation is selected" do query = GraphQL::Query.new(schema, document: document, variables: { name: "Cardinal" }, operation_name: "Invalid") assert_selection_is_null query.lookahead end describe "with a NullWarden" do let(:schema) { LookaheadTest::AlwaysVisibleSchema } it "works" do lookahead = query.lookahead.selection("findBirdSpecies") assert_equal true, lookahead.selects?("similarSpecies") assert_equal true, lookahead.selects?(:similar_species) assert_equal false, lookahead.selects?("isWaterfowl") assert_equal false, lookahead.selects?(:is_waterfowl) end end describe "on unions" do let(:document) { GraphQL.parse <<-GRAPHQL { species(id: "Cardinal") { ... on BirdSpecies { name isWaterfowl } ... on PlantSpecies { name isEdible } } } GRAPHQL } it "works" do lookahead = query.lookahead.selection(:species) assert lookahead.selects?(:name) assert_equal [:name, :is_waterfowl, :name, :is_edible], lookahead.selections.map(&:name) end it "works with different selected types" do lookahead = query.lookahead.selection(:species) # Both have `name` assert lookahead.selects?(:name, selected_type: LookaheadTest::BirdSpecies) assert lookahead.selects?(:name, selected_type: LookaheadTest::PlantSpecies) # Only birds have `isWaterfowl` assert lookahead.selects?(:is_waterfowl, selected_type: LookaheadTest::BirdSpecies) refute lookahead.selects?(:is_waterfowl, selected_type: LookaheadTest::PlantSpecies) # Only plants have `isEdible` refute lookahead.selects?(:is_edible, selected_type: LookaheadTest::BirdSpecies) assert lookahead.selects?(:is_edible, selected_type: LookaheadTest::PlantSpecies) end end describe "fields on interfaces" do let(:document) { GraphQL.parse <<-GRAPHQL query { node(id: "Cardinal") { id ... on BirdSpecies { name } ...Other } } fragment Other on BirdGenus { latinName } GRAPHQL } it "finds fields on object types and interface types" do node_lookahead = query.lookahead.selection("node") assert_equal [:id, :name, :latin_name], node_lookahead.selections.map(&:name) end end describe "inspect" do it "works for root lookaheads" do assert_includes query.lookahead.inspect, "#<GraphQL::Execution::Lookahead @root_type=" end it "works for field lookaheads" do assert_includes query.lookahead.selection(:find_bird_species).inspect, "#<GraphQL::Execution::Lookahead @field=" end end describe "constraints by arguments" do let(:lookahead) do query.lookahead end it "is true without constraints" do assert_equal true, lookahead.selects?("findBirdSpecies") end it "is true when all given constraints are satisfied" do assert_equal true, lookahead.selects?(:find_bird_species, arguments: { by_name: "Cardinal" }) assert_equal true, lookahead.selects?("findBirdSpecies", arguments: { "byName" => "Cardinal" }) end it "is true when no constraints are given" do assert_equal true, lookahead.selects?(:find_bird_species, arguments: {}) assert_equal true, lookahead.selects?("__typename", arguments: {}) end it "is false when some given constraints aren't satisfied" do assert_equal false, lookahead.selects?(:find_bird_species, arguments: { by_name: "Chickadee" }) assert_equal false, lookahead.selects?(:find_bird_species, arguments: { by_name: "Cardinal", other: "Nonsense" }) end describe "with literal values" do let(:document) { GraphQL.parse <<-GRAPHQL { findBirdSpecies(byName: "Great Blue Heron") { isWaterfowl } } GRAPHQL } it "works" do assert_equal true, lookahead.selects?(:find_bird_species, arguments: { by_name: "Great Blue Heron" }) end end end it "can do a chained lookahead" do next_lookahead = query.lookahead.selection(:find_bird_species, arguments: { by_name: "Cardinal" }) assert_equal true, next_lookahead.selected? nested_selection = next_lookahead.selection(:similar_species).selection(:is_waterfowl, arguments: {}) assert_equal true, nested_selection.selected? assert_equal false, next_lookahead.selection(:similar_species).selection(:name).selected? end it "can detect fields on lists with symbol or string" do assert_equal true, query.lookahead.selection(:find_bird_species).selection(:similar_species).selection(:is_waterfowl).selected? assert_equal true, query.lookahead.selection("findBirdSpecies").selection("similarSpecies").selection("isWaterfowl").selected? end describe "merging branches and fragments" do let(:document) { GraphQL.parse <<-GRAPHQL { findBirdSpecies(name: "Cardinal") { similarSpecies { __typename } } ...F ... { findBirdSpecies(name: "Cardinal") { similarSpecies { isWaterfowl } } } } fragment F on Query { findBirdSpecies(name: "Cardinal") { similarSpecies { name } } } GRAPHQL } it "finds selections using merging" do merged_lookahead = query.lookahead.selection(:find_bird_species).selection(:similar_species) assert merged_lookahead.selects?(:__typename) assert merged_lookahead.selects?(:is_waterfowl) assert merged_lookahead.selects?(:name) end end end describe "in queries" do it "can be an extra" do query_str = <<-GRAPHQL { cardinal: findBirdSpecies(byName: "Cardinal") { genus { __typename } } scarletTanager: findBirdSpecies(byName: "Scarlet Tanager") { genus { latinName } } greatBlueHeron: findBirdSpecies(byName: "Great Blue Heron") { genus { latinName } } } GRAPHQL context = {lookahead_latin_name: 0} res = LookaheadTest::Schema.execute(query_str, context: context) refute res.key?("errors") assert_equal 2, context[:lookahead_latin_name] assert_equal [:find_bird_species], context[:root_lookahead_selections].map(&:name).uniq assert_equal( [{ by_name: "Cardinal" }, { by_name: "Scarlet Tanager" }, { by_name: "Great Blue Heron" }], context[:root_lookahead_selections].map(&:arguments) ) end it "works for invalid queries" do context = {lookahead_latin_name: 0} res = LookaheadTest::Schema.execute("{ doesNotExist }", context: context) assert res.key?("errors") assert_equal 0, context[:lookahead_latin_name] end describe "When there is an argument error" do class NestedArgumentErrorSchema < GraphQL::Schema class Data < GraphQL::Schema::Object field :echo, String do argument :input, String end def echo(input:) input end end class Query < GraphQL::Schema::Object field :data, Data, extras: [:lookahead] def data(lookahead:) context[:args_class] = lookahead.selection(:echo).arguments.class {} end end query(Query) end it "uses empty arguments" do query_str = "query getEcho($input: String = null) { data { echo(input: $input) } }" res = NestedArgumentErrorSchema.execute(query_str, variables: {}) assert_equal ["`null` is not a valid input for `String!`, please provide a value for this argument."], res["errors"].map { |err| err["message"] } assert_equal Hash, res.context[:args_class] good_res = NestedArgumentErrorSchema.execute("{ data { echo(input: \"Hello\") } }") assert_equal "Hello", good_res["data"]["data"]["echo"] assert_equal Hash, good_res.context[:args_class] end end end describe '#selections' do let(:document) { GraphQL.parse <<-GRAPHQL query { findBirdSpecies(byName: "Laughing Gull") { name similarSpecies { likesWater: isWaterfowl } } } GRAPHQL } def query(doc = document) GraphQL::Query.new(LookaheadTest::Schema, document: doc) end it "provides a list of all selections" do ast_node = document.definitions.first.selections.first field = LookaheadTest::Query.fields["findBirdSpecies"] lookahead = GraphQL::Execution::Lookahead.new(query: query, ast_nodes: [ast_node], field: field) assert_equal [:name, :similar_species], lookahead.selections.map(&:name) end it "filters outs selections which do not match arguments" do ast_node = document.definitions.first lookahead = GraphQL::Execution::Lookahead.new(query: query, ast_nodes: [ast_node], root_type: LookaheadTest::Query) arguments = { by_name: "Cardinal" } assert_equal lookahead.selections(arguments: arguments).map(&:name), [] end it "includes selections which match arguments" do ast_node = document.definitions.first lookahead = GraphQL::Execution::Lookahead.new(query: query, ast_nodes: [ast_node], root_type: LookaheadTest::Query) arguments = { by_name: "Laughing Gull" } assert_equal lookahead.selections(arguments: arguments).map(&:name), [:find_bird_species] end it 'handles duplicate selections across fragments' do doc = GraphQL.parse <<-GRAPHQL query { ... on Query { ...MoreFields } } fragment MoreFields on Query { findBirdSpecies(byName: "Laughing Gull") { name } findBirdSpecies(byName: "Laughing Gull") { ...EvenMoreFields } } fragment EvenMoreFields on BirdSpecies { similarSpecies { likesWater: isWaterfowl } } GRAPHQL lookahead = query(doc).lookahead root_selections = lookahead.selections assert_equal [:find_bird_species], root_selections.map(&:name), "Selections are merged" assert_equal 2, root_selections.first.ast_nodes.size, "It represents both nodes" assert_equal [:name, :similar_species], root_selections.first.selections.map(&:name), "Subselections are merged" end it "avoids merging selections for same field name on distinct types" do query = GraphQL::Query.new(LookaheadTest::Schema, <<-GRAPHQL) query { node(id: "Cardinal") { ... on BirdSpecies { name } ... on BirdGenus { name } id } } GRAPHQL node_lookahead = query.lookahead.selection("node") assert_equal( [[LookaheadTest::Node, :id], [LookaheadTest::BirdSpecies, :name], [LookaheadTest::BirdGenus, :name]], node_lookahead.selections.map { |s| [s.owner_type, s.name] } ) end it "works for missing selections" do ast_node = document.definitions.first.selections.first field = LookaheadTest::Query.fields["findBirdSpecies"] lookahead = GraphQL::Execution::Lookahead.new(query: query, ast_nodes: [ast_node], field: field) null_lookahead = lookahead.selection(:genus) # This is an implementation detail, but I want to make sure the test is set up right assert_instance_of GraphQL::Execution::Lookahead::NullLookahead, null_lookahead assert_equal [], null_lookahead.selections end it "excludes fields skipped by directives" do document = GraphQL.parse <<-GRAPHQL query($skipName: Boolean!, $includeGenus: Boolean!){ findBirdSpecies(byName: "Cardinal") { id name @skip(if: $skipName) genus @include(if: $includeGenus) } } GRAPHQL query = GraphQL::Query.new(LookaheadTest::Schema, document: document, variables: { skipName: false, includeGenus: true }) lookahead = query.lookahead.selection("findBirdSpecies") assert_equal [:id, :name, :genus], lookahead.selections.map(&:name) assert_equal true, lookahead.selects?(:name) query = GraphQL::Query.new(LookaheadTest::Schema, document: document, variables: { skipName: true, includeGenus: false }) lookahead = query.lookahead.selection("findBirdSpecies") assert_equal [:id], lookahead.selections.map(&:name) assert_equal false, lookahead.selects?(:name) end end def assert_selection_exists(selection) assert GraphQL::Execution::Lookahead::NULL_LOOKAHEAD != selection end def assert_selection_is_null(selection) assert_equal GraphQL::Execution::Lookahead::NULL_LOOKAHEAD, selection end describe "#selection" do let(:document) { GraphQL.parse <<-GRAPHQL query { findBirdSpecies(byName: "Laughing Gull") { name similarSpecies { likesWater: isWaterfowl } } } GRAPHQL } def query(doc = document) GraphQL::Query.new(LookaheadTest::Schema, document: doc) end it "returns selection by field name" do ast_node = document.definitions.first.selections.first field = LookaheadTest::Query.fields["findBirdSpecies"] lookahead = GraphQL::Execution::Lookahead.new(query: query, ast_nodes: [ast_node], field: field) assert_selection_exists lookahead.selection("similarSpecies") end describe "when same field is selected twice" do let(:document) { GraphQL.parse <<-GRAPHQL query { gull: findBirdSpecies(byName: "Laughing Gull") { name } tanager: findBirdSpecies(byName: "Scarlet Tanager") { name } } GRAPHQL } let(:graphql_query) do GraphQL::Query.new(LookaheadTest::Schema, document: document) end it "returns lookahead with two ast_nodes" do assert_equal 2, graphql_query.lookahead.selection("findBirdSpecies").ast_nodes.length end end describe "when query has alias" do let(:document) { GraphQL.parse <<-GRAPHQL query { findBirdSpecies(byName: "Laughing Gull") { name similar: similarSpecies { likesWater: isWaterfowl } } } GRAPHQL } let(:graphql_query) do GraphQL::Query.new(LookaheadTest::Schema, document: document) end let(:species_lookahead) do graphql_query.lookahead.selection("findBirdSpecies") end it "returns selection when field name is passed" do assert_selection_exists species_lookahead.selection("similarSpecies") end it "returns null when alias name is passed" do assert_selection_is_null species_lookahead.selection("similar") end describe "when alias has arguments" do let(:document) { GraphQL.parse <<-GRAPHQL query { gull: findBirdSpecies(byName: "Laughing Gull") { name } } GRAPHQL } it "returns selection when field name is passed" do assert_selection_exists graphql_query.lookahead.selection("findBirdSpecies") end it "returns null when alias name is passed" do assert_selection_is_null graphql_query.lookahead.selection("gull") end describe "when same field is selected twice" do let(:document) { GraphQL.parse <<-GRAPHQL query { gull: findBirdSpecies(byName: "Laughing Gull") { name } tanager: findBirdSpecies(byName: "Scarlet Tanager") { name } } GRAPHQL } it "returns null when alias name is passed" do assert_selection_is_null graphql_query.lookahead.selection("gull") assert_selection_is_null graphql_query.lookahead.selection("tanager") end end end end end describe "#alias_selection" do let(:document) { GraphQL.parse <<-GRAPHQL query { findBirdSpecies(byName: "Laughing Gull") { name similar: similarSpecies { likesWater: isWaterfowl } } } GRAPHQL } def query(doc = document) GraphQL::Query.new(LookaheadTest::Schema, document: doc) end let(:graphql_query) do GraphQL::Query.new(LookaheadTest::Schema, document: document) end let(:species_lookahead) do graphql_query.lookahead.selection("findBirdSpecies") end describe "when alias name is passed" do it "returns selection" do assert_selection_exists species_lookahead.alias_selection("similar") end it "returns true from selects_alias?" do assert true, species_lookahead.selects_alias?("similar") end describe "when the aliased field is deeply nested" do it "not finds the deeply-nested alias" do assert_equal [:name, :similar_species], species_lookahead.selections.map(&:name) assert_equal false, species_lookahead.selects_alias?("likesWater") end end end describe "when the same field is executed with the same arguments but different aliases" do let(:document) { GraphQL.parse <<-GRAPHQL query { egret: findBirdSpecies(byName: "Great Egret") { isWaterfowl } otherEgret: findBirdSpecies(byName: "Great Egret") { name } findBirdSpecies(byName: "Great Egret") { __typename } } GRAPHQL } it "distinguishes between the aliased fields" do lookahead = query.lookahead assert_equal [:is_waterfowl], lookahead.alias_selection("egret").selections.map(&:name) assert_equal [:name], lookahead.alias_selection("otherEgret").selections.map(&:name) assert_equal [], lookahead.alias_selection("findBirdSpecies").selections.map(&:name) end it "filters aliased fields by arguments" do lookahead = query.lookahead # No `arguments:` performs no filtering assert_equal [:is_waterfowl], lookahead.alias_selection("egret").selections.map(&:name) # Matching arguments filters to the expected field: assert_equal [:is_waterfowl], lookahead.alias_selection("egret", arguments: {by_name: "Great Egret"}).selections.map(&:name) # Empty `arguments:` matches nothing: assert_equal [], lookahead.alias_selection("egret", arguments: {}).selections.map(&:name) # Mismatching `arguments:` filters to nothing: assert_equal [], lookahead.alias_selection("egret", arguments: {by_name: "Macaw"}).selections.map(&:name) end end describe "when field name is passed" do it "returns null_lookahead" do assert_selection_is_null species_lookahead.alias_selection("similarSpecies") end it "returns false from selects_alias?" do assert_equal false, species_lookahead.selects_alias?("similarSpecies") end end describe "when alias is inside fragment" do let(:document) { GraphQL.parse <<-GRAPHQL fragment BirdSpeciesFragment on BirdSpecies { name similar: similarSpecies { likesWater: isWaterfowl } } query { findBirdSpecies(byName: "Laughing Gull") { ...BirdSpeciesFragment } } GRAPHQL } it "returns selection" do assert_selection_exists species_lookahead.alias_selection("similar") end it "returns true from selects_alias?" do assert true, species_lookahead.selects_alias?("similar") end describe "when fragment name is wrong" do let(:document) { GraphQL.parse <<-GRAPHQL query { findBirdSpecies(byName: "Laughing Gull") { ...WrongFragment } } GRAPHQL } it "raises error" do assert_raises(RuntimeError) { species_lookahead.selects_alias?("similar") } end end end describe "when alias is inside inline fragment" do let(:document) { GraphQL.parse <<-GRAPHQL query { findBirdSpecies(byName: "Laughing Gull") { ...on BirdSpecies { name similar: similarSpecies { likesWater: isWaterfowl } } } } GRAPHQL } it "returns selection" do assert_selection_exists species_lookahead.alias_selection("similar") end it "returns true from selects_alias?" do assert true, species_lookahead.selects_alias?("similar") end end describe "when alias has arguments" do let(:document) { GraphQL.parse <<-GRAPHQL query { gull: findBirdSpecies(byName: "Laughing Gull") { name } } GRAPHQL } it "returns selection" do assert_selection_exists graphql_query.lookahead.alias_selection("gull") end it "returns true from selects_alias?" do assert true, graphql_query.lookahead.selects_alias?("gull") end describe "when same field is selected twice" do let(:document) { GraphQL.parse <<-GRAPHQL query { gull: findBirdSpecies(byName: "Laughing Gull") { name } tanager: findBirdSpecies(byName: "Scarlet Tanager") { name } } GRAPHQL } it "returns selection when alias name is passed" do graphql_query.lookahead.alias_selection("gull", arguments: { by_name: "Laughing Gull" }).tap do |selection| assert_selection_exists selection assert_equal({ by_name: "Laughing Gull" }, selection.arguments) assert_equal 1, selection.ast_nodes.length end graphql_query.lookahead.alias_selection("tanager", arguments: { by_name: "Scarlet Tanager" }).tap do |selection| assert_selection_exists selection assert_equal({ by_name: "Scarlet Tanager" }, selection.arguments) assert_equal 1, selection.ast_nodes.length 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/execution/breadth_runtime_spec.rb
spec/graphql/execution/breadth_runtime_spec.rb
# frozen_string_literal: true require "spec_helper" describe "GraphQL::Execution::Interpreter for breadth-first execution" do # A breadth-first interpreter uses the following runtime interface: # - evaluate_selection(result_key, ast_nodes, selections_result) # - exit_with_inner_result? class SimpleBreadthRuntime < GraphQL::Execution::Interpreter::Runtime class BreadthObject < GraphQL::Execution::Interpreter::Runtime::GraphQLResultHash attr_accessor :breadth_index attr_accessor :results_by_key def collect_result(result_name, result_value) results_by_key[result_name][breadth_index] = result_value true end end def initialize(query:) query.multiplex = GraphQL::Execution::Multiplex.new( schema: query.schema, queries: [query], context: query.context, max_complexity: nil, ) super(query: query) @breadth_results_by_key = {} end def run(&block) query.current_trace.execute_multiplex(multiplex: query.multiplex) do query.current_trace.execute_query(query: query, &block) end ensure delete_all_interpreter_context end def evaluate_breadth_selection(objects, parent_type, node) result_key = node.alias || node.name @breadth_results_by_key[result_key] = Array.new(objects.size) objects.each_with_index do |object, index| app_value = parent_type.wrap(object, query.context) breadth_object = BreadthObject.new(nil, parent_type, app_value, nil, false, node.selections, false, node, nil, nil) breadth_object.ordered_result_keys = [] breadth_object.breadth_index = index breadth_object.results_by_key = @breadth_results_by_key state = get_current_runtime_state state.current_result_name = nil state.current_result = breadth_object @dataloader.append_job { evaluate_selection(result_key, node, breadth_object) } end @dataloader.run @breadth_results_by_key[result_key] end end class PassthroughLoader < GraphQL::Batch::Loader def perform(objects) objects.each { |obj| fulfill(obj, obj) } end end class SimpleHashBatchLoader < GraphQL::Batch::Loader def initialize(key) super() @key = key end def perform(objects) objects.each { |obj| fulfill(obj, obj.fetch(@key)) } end end class UpcaseExtension < GraphQL::Schema::FieldExtension def after_resolve(value:, **rest) value&.upcase end end class RangeInput < GraphQL::Schema::InputObject argument :min, Int argument :max, Int def prepare min..max end end class BreadthBaseField < GraphQL::Schema::Field def authorized?(obj, args, ctx) if !ctx[:field_auth].nil? ctx[:field_auth] elsif !ctx[:lazy_field_auth].nil? PassthroughLoader.load(ctx[:lazy_field_auth]) elsif !ctx[:field_auth_with_error].nil? raise GraphQL::ExecutionError, "Not authorized" unless ctx[:field_auth_with_error] else true end end end class BreadthBaseObject < GraphQL::Schema::Object field_class BreadthBaseField end class BreadthTestQuery < BreadthBaseObject field :foo, String def foo object[:foo] end field :lazy_foo, String def lazy_foo SimpleHashBatchLoader.for(:foo).load(object) end field :maybe_lazy_foo, String def maybe_lazy_foo if object[:foo] == "beep" SimpleHashBatchLoader.for(:foo).load(object) else object[:foo] end end field :nested_lazy_foo, String def nested_lazy_foo PassthroughLoader .load(object) .then { |obj| SimpleHashBatchLoader.for(:foo).load(obj) } .then { |str| str } end field :upcase_foo, String, extensions: [UpcaseExtension] def upcase_foo object[:foo] end field :lazy_upcase_foo, String, extensions: [UpcaseExtension] def lazy_upcase_foo SimpleHashBatchLoader.for(:foo).load(object) end field :go_boom, String def go_boom raise GraphQL::ExecutionError, "boom" end field :args, String do |f| f.argument :a, String f.argument :b, String end def args(a:, b:) "#{a}#{b}" end field :valid_args, String do |f| f.argument :a, String, validates: { length: { is: 1 } } end def valid_args(a:) a end field :range, String do |f| f.argument :input, RangeInput end def range(input:) "#{input.min}-#{input.max}" end field :extras, String, extras: [:lookahead] def extras(lookahead:) lookahead.field.name end # uses default resolver... field :fizz, String end class BreadthTestSchema < GraphQL::Schema use(GraphQL::Batch) query BreadthTestQuery end SCHEMA_FROM_DEF = GraphQL::Schema.from_definition( %|type Query { a: String }|, default_resolve: { "Query" => { "a" => ->(obj, _args, _ctx) { obj["a"] } }, }, ) OBJECTS = [{ foo: "fizz" }, { foo: "buzz" }, { foo: "beep" }, { foo: "boom" }].freeze EXPECTED_RESULTS = ["fizz", "buzz", "beep", "boom"].freeze def test_maps_sync_results result = map_breadth_objects(OBJECTS, "{ foo }") assert_equal EXPECTED_RESULTS, result end def test_maps_lazy_results result = map_breadth_objects(OBJECTS, "{ lazyFoo }") assert_equal EXPECTED_RESULTS, result end def test_maps_sometimes_lazy_results result = map_breadth_objects(OBJECTS, "{ maybeLazyFoo }") assert_equal EXPECTED_RESULTS, result end def test_maps_nested_lazy_results result = map_breadth_objects(OBJECTS, "{ nestedLazyFoo }") assert_equal EXPECTED_RESULTS, result end def test_maps_field_extension_results result = map_breadth_objects(OBJECTS, "{ upcaseFoo }") assert_equal ["FIZZ", "BUZZ", "BEEP", "BOOM"], result end def test_maps_lazy_field_extension_results result = map_breadth_objects(OBJECTS, "{ lazyUpcaseFoo }") assert_equal ["FIZZ", "BUZZ", "BEEP", "BOOM"], result end def test_maps_fields_with_authorization context = { field_auth: false } result = map_breadth_objects(OBJECTS, "{ foo }", context: context) assert_equal [nil, nil, nil, nil], result end def test_maps_fields_with_lazy_authorization context = { lazy_field_auth: false } result = map_breadth_objects(OBJECTS, "{ foo }", context: context) assert result.all? { |r| r.is_a?(GraphQL::UnauthorizedFieldError) } end def test_maps_fields_with_authorization_errors context = { field_auth_with_error: false } result = map_breadth_objects(OBJECTS, "{ foo }", context: context) assert result.all? { |r| r.is_a?(GraphQL::ExecutionError) } end def test_maps_field_errors result = map_breadth_objects(OBJECTS, "{ goBoom }") assert result.all? { |r| r.is_a?(GraphQL::ExecutionError) } assert_equal ["boom", "boom", "boom", "boom"], result.map(&:message) end def test_maps_basic_arguments doc = %|{ args(a:"fizz", b:"buzz") }| result = map_breadth_objects([{}], doc) assert_equal ["fizzbuzz"], result end def test_maps_basic_arguments_with_variables doc = %|query($b: String) { args(a:"fizz", b: $b) }| result = map_breadth_objects([{}], doc, variables: { b: "buzz" }) assert_equal ["fizzbuzz"], result end def test_maps_invalidated_arguments doc = %|query { validArgs(a: "boo") }| result = map_breadth_objects([{}], doc) assert result.first.is_a?(GraphQL::ExecutionError) assert_equal "a is the wrong length (should be 1)", result.first.message end def test_maps_prepared_input_object doc = %|{ range(input: { min: 1, max: 2 }) }| result = map_breadth_objects([{}], doc) assert_equal ["1-2"], result end def test_maps_prepared_input_object_with_variables doc = %|query($b: Int) { range(input: { min: 1, max: $b }) }| result = map_breadth_objects([{}], doc, variables: { b: 2 }) assert_equal ["1-2"], result end def test_maps_extras_arguments result = map_breadth_objects([{}], "{ extras }") assert_equal ["extras"], result end def test_uses_default_resolver_for_hash_keys result = map_breadth_objects([{ fizz: "buzz" }], "{ fizz }") assert_equal ["buzz"], result end def test_uses_default_resolver_for_method_calls entity = Struct.new(:fizz) result = map_breadth_objects([entity.new("buzz")], "{ fizz }") assert_equal ["buzz"], result end def test_maps_schemas_from_definition objects = [{ "a" => "1" }, { "a" => "2" }] result = map_breadth_objects(objects, "{ a }", schema: SCHEMA_FROM_DEF) assert_equal ["1", "2"], result end def test_maps_results_with_multiple_nodes result = map_breadth_objects(OBJECTS, "{ foo foo }") assert_equal EXPECTED_RESULTS, result end private def map_breadth_objects(objects, doc, schema: BreadthTestSchema, variables: {}, context: {}) query = GraphQL::Query.new( schema, document: GraphQL.parse(doc), variables: variables, context: context, ) node = query.document.definitions.first.selections.first runtime = SimpleBreadthRuntime.new(query: query) runtime.run { runtime.evaluate_breadth_selection(objects, schema.query, node) } 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/execution/multiplex_spec.rb
spec/graphql/execution/multiplex_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Execution::Multiplex do def multiplex(*a, **kw) LazyHelpers::LazySchema.multiplex(*a, **kw) end let(:q1) { <<-GRAPHQL query Q1 { nestedSum(value: 3) { value nestedSum(value: 7) { value } } } GRAPHQL } let(:q2) { <<-GRAPHQL query Q2 { nestedSum(value: 2) { value nestedSum(value: 11) { value } } } GRAPHQL } let(:q3) { <<-GRAPHQL query Q3 { listSum(values: [1,2]) { nestedSum(value: 3) { value } } } GRAPHQL } let(:queries) { [{query: q1}, {query: q2}, {query: q3}] } describe "multiple queries in the same lazy context" do it "runs multiple queries in the same lazy context" do expected_data = [ {"data"=>{"nestedSum"=>{"value"=>14, "nestedSum"=>{"value"=>46}}}}, {"data"=>{"nestedSum"=>{"value"=>14, "nestedSum"=>{"value"=>46}}}}, {"data"=>{"listSum"=>[{"nestedSum"=>{"value"=>14}}, {"nestedSum"=>{"value"=>14}}]}}, ] res = multiplex(queries) assert_graphql_equal expected_data, res end it "returns responses in the same order as their respective requests" do queries = 2000.times.map do |index| case index % 3 when 0 {query: q1} when 1 {query: q2} when 2 {query: q3} end end responses = multiplex(queries) responses.each.with_index do |response, index| case index % 3 when 0 assert_equal "Q1", response.query.operation_name when 1 assert_equal "Q2", response.query.operation_name when 2 assert_equal "Q3", response.query.operation_name end end end end describe "when some have validation errors or runtime errors" do let(:q1) { " { success: nullableNestedSum(value: 1) { value } }" } let(:q2) { " { runtimeError: nullableNestedSum(value: 13) { value } }" } let(:q3) { "{ invalidNestedNull: nullableNestedSum(value: 1) { value nullableNestedSum(value: 2) { nestedSum(value: 13) { value } # This field will never get executed ns2: nestedSum(value: 13) { value } } } }" } let(:q4) { " { validationError: nullableNestedSum(value: true) }"} it "returns a mix of errors and values" do expected_res = [ { "data"=>{"success"=>{"value"=>2}} }, { "errors"=>[{ "message"=>"13 is unlucky", "locations"=>[{"line"=>1, "column"=>4}], "path"=>["runtimeError"] }], "data"=>{"runtimeError"=>nil}, }, { "errors"=>[{ "message"=>"Cannot return null for non-nullable field LazySum.nestedSum", "path"=>["invalidNestedNull", "nullableNestedSum", "nestedSum"], "locations"=>[{"line"=>5, "column"=>11}], }], "data"=>{"invalidNestedNull"=>{"value" => 2,"nullableNestedSum" => nil}}, }, { "errors" => [{ "message"=>"Field must have selections (field 'nullableNestedSum' returns LazySum but has no selections. Did you mean 'nullableNestedSum { ... }'?)", "locations"=>[{"line"=>1, "column"=>4}], "path"=>["query", "validationError"], "extensions"=>{"code"=>"selectionMismatch", "nodeName"=>"field 'nullableNestedSum'", "typeName"=>"LazySum"} }] }, ] res = multiplex([ {query: q1}, {query: q2}, {query: q3}, {query: q4}, ]) assert_graphql_equal expected_res, res.map(&:to_h) end end describe "context shared by a multiplex run" do it "is provided as context:" do checks = [] multiplex(queries, context: { instrumentation_checks: checks }) assert_equal ["before multiplex 1", "before multiplex 2", "after multiplex 2", "after multiplex 1"], checks end end describe "instrumenting a multiplex run" do it "runs query instrumentation for each query and multiplex-level instrumentation" do checks = [] queries_with_context = queries.map { |q| q.merge(context: { instrumentation_checks: checks }) } multiplex(queries_with_context, context: { instrumentation_checks: checks }) assert_equal [ "before multiplex 1", "before multiplex 2", "before Q1", "before Q2", "before Q3", "after Q3", "after Q2", "after Q1", "after multiplex 2", "after multiplex 1", ], checks end end describe "max_complexity" do it "can successfully calculate complexity" do message = "Query has complexity of 11, which exceeds max complexity of 10" results = multiplex(queries, max_complexity: 10) results.each do |res| assert_equal message, res["errors"][0]["message"] end end end describe "execute_query when errors are raised" do module InspectQueryInstrumentation def execute_multiplex(multiplex:) super ensure InspectQueryInstrumentation.last_json = multiplex.queries.first.result.to_json end class << self attr_accessor :last_json end end class InspectSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :raise_execution_error, String def raise_execution_error raise GraphQL::ExecutionError, "Whoops" end field :raise_error, String def raise_error raise GraphQL::Error, "Crash" end field :raise_syntax_error, String def raise_syntax_error raise SyntaxError end field :raise_exception, String def raise_exception raise Exception end end query(Query) trace_with(InspectQueryInstrumentation) end unhandled_err_json = '{}' it "can access the query results" do InspectSchema.execute("{ raiseExecutionError }") handled_err_json = '{"errors":[{"message":"Whoops","locations":[{"line":1,"column":3}],"path":["raiseExecutionError"]}],"data":{"raiseExecutionError":null}}' assert_equal handled_err_json, InspectQueryInstrumentation.last_json assert_raises(GraphQL::Error) do InspectSchema.execute("{ raiseError }") end assert_equal unhandled_err_json, InspectQueryInstrumentation.last_json end it "can access the query results when the error is not a StandardError" do assert_raises(SyntaxError) do InspectSchema.execute("{ raiseSyntaxError }") end assert_equal unhandled_err_json, InspectQueryInstrumentation.last_json assert_raises(Exception) do InspectSchema.execute("{ raiseException }") end assert_equal unhandled_err_json, InspectQueryInstrumentation.last_json end end describe "context[:trace]" do class MultiplexTraceSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :int, Integer def int; 1; end end class Trace < GraphQL::Tracing::Trace def execute_multiplex(multiplex:) @execute_multiplex_count ||= 0 @execute_multiplex_count += 1 super end def execute_query(query:) @execute_query_count ||= 0 @execute_query_count += 1 super end attr_reader :execute_multiplex_count, :execute_query_count end query(Query) end it "uses it instead of making a new trace" do query_str = "{ int }" trace_instance = MultiplexTraceSchema::Trace.new res = MultiplexTraceSchema.multiplex([{query: query_str}, {query: query_str}], context: { trace: trace_instance }) assert_equal [1, 1], res.map { |r| r["data"]["int"]} assert_equal 1, trace_instance.execute_multiplex_count assert_equal 2, trace_instance.execute_query_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/execution/instrumentation_spec.rb
spec/graphql/execution/instrumentation_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Schema do describe "instrumentation teardown bug" do # This instrumenter records that it ran, # or raises an error if instructed to do so class InstrumenterError < StandardError attr_reader :key def initialize(key) @key = key super() end end module LogInstrumenter def self.generate(context_key_sym) hook_method = :"#{context_key_sym}_run_hook" mod = Module.new mod.define_method(:execute_query) do |query:, &block| public_send(hook_method, query, "begin") result = nil begin result = super(query: query, &block) ensure public_send(hook_method, query, "end") end result end mod.define_method(:execute_multiplex) do |multiplex:, &block| public_send(hook_method, multiplex, "begin") result = nil begin result = super(multiplex: multiplex, &block) ensure public_send(hook_method, multiplex, "end") end result end mod.define_method(hook_method) do |unit_of_work, event_name| log_key = :"#{context_key_sym}_did_#{event_name}" error_key = :"#{context_key_sym}_should_raise_#{event_name}" unit_of_work.context[log_key] = true if unit_of_work.context[error_key] raise InstrumenterError.new(log_key) end end mod end end module ExecutionErrorTrace def execute_query(query:) if query.context[:raise_execution_error] raise GraphQL::ExecutionError, "Raised from trace execute_query" end super end end # This is how you might add queries from a persisted query backend module QueryStringTrace def execute_multiplex(multiplex:) multiplex.queries.each do |query| if query.context[:extra_query_string] && query.query_string.nil? query.query_string = query.context[:extra_query_string] end end super end end let(:query_type) { Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :int, Integer do argument :value, Integer, required: false end def int(value:) value end end } let(:schema) { spec = self Class.new(GraphQL::Schema) do query(spec.query_type) trace_with(LogInstrumenter.generate(:second_instrumenter)) trace_with(LogInstrumenter.generate(:first_instrumenter)) trace_with(ExecutionErrorTrace) trace_with(QueryStringTrace) end } describe "query instrumenters" do it "before_query of the 2nd instrumenter does not run but after_query does" do context = {second_instrumenter_should_raise_begin: true} assert_raises InstrumenterError do schema.execute(" { int(value: 2) } ", context: context) end assert context[:first_instrumenter_did_begin] assert context[:first_instrumenter_did_end] assert context[:second_instrumenter_did_begin] refute context[:second_instrumenter_did_end] end it "runs after_query even if a previous after_query raised an error" do context = {second_instrumenter_should_raise_end: true} err = assert_raises InstrumenterError do schema.execute(" { int(value: 2) } ", context: context) end # The error came from the second instrumenter: assert_equal :second_instrumenter_did_end, err.key # But the first instrumenter still got a chance to teardown assert context[:first_instrumenter_did_begin] assert context[:first_instrumenter_did_end] assert context[:second_instrumenter_did_begin] assert context[:second_instrumenter_did_end] end it "rescues execution errors from execute_query" do context = {raise_execution_error: true} res = schema.execute(" { int(value: 2) } ", context: context) assert_equal({ "data" => nil, "errors" => [ { "message" => "Raised from trace execute_query" }, ] }, res.to_h) end it "can assign a query string there" do context = { extra_query_string: "{ __typename }"} res = schema.execute(nil, context: context) assert_equal "Query", res["data"]["__typename"] end end describe "within a multiplex" do let(:multiplex_schema) { Class.new(schema) { trace_with(LogInstrumenter.generate(:second_instrumenter)) trace_with(LogInstrumenter.generate(:first_instrumenter)) } } it "only runs after_multiplex if before_multiplex finished" do multiplex_ctx = {second_instrumenter_should_raise_begin: true} query_1_ctx = {} query_2_ctx = {} assert_raises InstrumenterError do multiplex_schema.multiplex( [ {query: "{int(value: 1)}", context: query_1_ctx}, {query: "{int(value: 2)}", context: query_2_ctx}, ], context: multiplex_ctx ) end assert multiplex_ctx[:first_instrumenter_did_begin] assert multiplex_ctx[:first_instrumenter_did_end] assert multiplex_ctx[:second_instrumenter_did_begin] refute multiplex_ctx[:second_instrumenter_did_end] # No query instrumentation was run at all expected_ctx_size = GraphQL::Schema.use_visibility_profile? ? 1 : 0 assert_equal expected_ctx_size, query_1_ctx.size assert_equal expected_ctx_size, query_2_ctx.size end it "does full and partial query runs" do multiplex_ctx = {} query_1_ctx = {} query_2_ctx = {second_instrumenter_should_raise_begin: true} assert_raises InstrumenterError do multiplex_schema.multiplex( [ { query: " { int(value: 2) } ", context: query_1_ctx }, { query: " { int(value: 2) } ", context: query_2_ctx }, ], context: multiplex_ctx ) end # multiplex got a full run assert multiplex_ctx[:first_instrumenter_did_begin] assert multiplex_ctx[:first_instrumenter_did_end] assert multiplex_ctx[:second_instrumenter_did_begin] assert multiplex_ctx[:second_instrumenter_did_end] # query 1 got a full run assert query_1_ctx[:first_instrumenter_did_begin] assert query_1_ctx[:first_instrumenter_did_end] assert query_1_ctx[:second_instrumenter_did_begin] assert query_1_ctx[:second_instrumenter_did_end] # query 2 got a partial run assert query_2_ctx[:first_instrumenter_did_begin] assert query_2_ctx[:first_instrumenter_did_end] assert query_2_ctx[:second_instrumenter_did_begin] refute query_2_ctx[:second_instrumenter_did_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/execution/interpreter_spec.rb
spec/graphql/execution/interpreter_spec.rb
# frozen_string_literal: true require "spec_helper" require_relative "../subscriptions_spec" describe GraphQL::Execution::Interpreter do module InterpreterTest class Box def initialize(value: nil, &block) @value = value @block = block end def value if @block @value = @block.call @block = nil end @value end end class Expansion < GraphQL::Schema::Object field :sym, String, null: false field :lazy_sym, String, null: false field :name, String, null: false field :cards, ["InterpreterTest::Card"], null: false def self.authorized?(expansion, ctx) if expansion.sym == "NOPE" false else true end end def cards Query::CARDS.select { |c| c.expansion_sym == @object.sym } end def lazy_sym Box.new(value: object.sym) end field :always_cached_value, Integer, null: false def always_cached_value raise "should never be called" end end class Card < GraphQL::Schema::Object field :name, String, null: false field :colors, "[InterpreterTest::Color]", null: false field :expansion, Expansion, null: false def expansion Query::EXPANSIONS.find { |e| e.sym == @object.expansion_sym } end field :parent_class_name, String, null: false, extras: [:parent] def parent_class_name(parent:) parent.class.name end end class Color < GraphQL::Schema::Enum value "WHITE" value "BLUE" value "BLACK" value "RED" value "GREEN" end class Entity < GraphQL::Schema::Union possible_types Card, Expansion def self.resolve_type(obj, ctx) obj.sym ? Expansion : Card end end class FieldCounter < GraphQL::Schema::Object implements GraphQL::Types::Relay::Node field :field_counter, FieldCounter, null: false def field_counter; self.class.generate_tag(context); end field :calls, Integer, null: false do argument :expected, Integer end def calls(expected:) c = context[:calls] += 1 if c != expected raise "Expected #{expected} calls but had #{c} so far" else c end end field :runtime_info, String, null: false do argument :a, Integer, required: false argument :b, Integer, required: false end def runtime_info(a: nil, b: nil) inspect_context end field :lazy_runtime_info, String, null: false do argument :a, Integer, required: false argument :b, Integer, required: false end def lazy_runtime_info(a: nil, b: nil) Box.new { inspect_context } end def self.generate_tag(context) context[:field_counters_count] ||= 0 current_count = context[:field_counters_count] += 1 "field_counter_#{current_count}" end private def inspect_context "<#{interpreter_context_for(:current_object).object.inspect}> #{interpreter_context_for(:current_path)} -> #{interpreter_context_for(:current_field).path}(#{interpreter_context_for(:current_arguments).size})" end def interpreter_context_for(key) # Make sure it's set in query context and interpreter namespace. base_ctx_value = context[key] interpreter_ctx_value = context.namespace(:interpreter)[key] if base_ctx_value != interpreter_ctx_value raise "Context mismatch for #{key} -> #{base_ctx_value} / interpreter: #{interpreter_ctx_value}" else base_ctx_value end end end class Query < GraphQL::Schema::Object # Try a root-level authorized hook that returns a lazy value def self.authorized?(obj, ctx) Box.new(value: true) end field :card, Card do argument :name, String end def card(name:) Box.new(value: CARDS.find { |c| c.name == name }) end field :expansion, Expansion do argument :sym, String end def expansion(sym:) EXPANSIONS.find { |e| e.sym == sym } end field :expansion_raw, Expansion, null: false def expansion_raw raw_value(sym: "RAW", name: "Raw expansion", always_cached_value: 42) end field :expansion_mixed, [Expansion], null: false def expansion_mixed expansions + [expansion_raw] end field :expansions, [Expansion], null: false def expansions EXPANSIONS end class ExpansionData < OpenStruct end CARDS = [ OpenStruct.new(name: "Dark Confidant", colors: ["BLACK"], expansion_sym: "RAV"), ] EXPANSIONS = [ ExpansionData.new(name: "Ravnica, City of Guilds", sym: "RAV"), # This data has an error, for testing null propagation ExpansionData.new(name: nil, sym: "XYZ"), # This is not allowed by .authorized?, ExpansionData.new(name: nil, sym: "NOPE"), ] field :find, [Entity], null: false do argument :id, [ID] end def find(id:) id.map do |ent_id| Query::EXPANSIONS.find { |e| e.sym == ent_id } || Query::CARDS.find { |c| c.name == ent_id } end end field :find_many, [Entity, null: true], null: false do argument :ids, [ID] end def find_many(ids:) find(id: ids).map { |e| Box.new(value: e) } end field :field_counter, FieldCounter, null: false def field_counter; FieldCounter.generate_tag(context) ; end include GraphQL::Types::Relay::HasNodeField include GraphQL::Types::Relay::HasNodesField class NestedQueryResult < GraphQL::Schema::Object field :result, String field :current_path, [String] end field :nested_query, NestedQueryResult do argument :query, String end def nested_query(query:) result = context.schema.multiplex([{query: query}], context: { allow_pending_thread_state: true }).first { result: JSON.dump(result), current_path: context[:current_path], } end end class Counter < GraphQL::Schema::Object field :value, Integer, null: false def value counter.value end field :lazy_value, Integer, null: false def lazy_value Box.new { counter.value } end field :incremented_value, Integer, hash_key: :incremented_value field :increment, Counter, null: false def increment v = counter.value += 1 { counter: counter, incremented_value: v, } end private def counter if object.is_a?(Hash) && object.key?(:counter) object[:counter] else object end end end class Mutation < GraphQL::Schema::Object field :increment_counter, Counter, null: false def increment_counter counter = context[:counter] v = counter.value += 1 { counter: counter, incremented_value: v } end end class Schema < GraphQL::Schema query(Query) mutation(Mutation) lazy_resolve(Box, :value) use GraphQL::Schema::AlwaysVisible def self.object_from_id(id, ctx) OpenStruct.new(id: id) end def self.id_from_object(obj, type, ctx) obj.id end def self.resolve_type(type, obj, ctx) FieldCounter end class EnsureArgsAreObject def self.trace(event, data) case event when "execute_field", "execute_field_lazy" args = data[:query].context[:current_arguments] if !args.is_a?(GraphQL::Execution::Interpreter::Arguments) raise "Expected arguments object, got #{args.class}: #{args.inspect}" end end yield end end tracer EnsureArgsAreObject module EnsureThreadCleanedUp def execute_multiplex(multiplex:) res = super runtime_info = Fiber[:__graphql_runtime_info] if !runtime_info.nil? && runtime_info != {} if !multiplex.context[:allow_pending_thread_state] # `nestedQuery` can allow this raise "Query did not clean up runtime state, found: #{runtime_info.inspect}" end end res end end trace_with(EnsureThreadCleanedUp) end end it "runs a query" do query_string = <<-GRAPHQL query($expansion: String!, $id1: ID!, $id2: ID!){ card(name: "Dark Confidant") { colors expansion { ... { name } cards { name } } } expansion(sym: $expansion) { ... ExpansionFields } find(id: [$id1, $id2]) { __typename ... on Card { name } ... on Expansion { sym } } } fragment ExpansionFields on Expansion { cards { name } } GRAPHQL vars = {expansion: "RAV", id1: "Dark Confidant", id2: "RAV"} result = InterpreterTest::Schema.execute(query_string, variables: vars) assert_equal ["BLACK"], result["data"]["card"]["colors"] assert_equal "Ravnica, City of Guilds", result["data"]["card"]["expansion"]["name"] assert_equal [{"name" => "Dark Confidant"}], result["data"]["card"]["expansion"]["cards"] assert_equal [{"name" => "Dark Confidant"}], result["data"]["expansion"]["cards"] expected_abstract_list = [ {"__typename" => "Card", "name" => "Dark Confidant"}, {"__typename" => "Expansion", "sym" => "RAV"}, ] assert_equal expected_abstract_list, result["data"]["find"] assert_nil Fiber[:__graphql_runtime_info] end it "runs a nested query and maintains proper state" do query_str = "query($queryStr: String!) { nestedQuery(query: $queryStr) { result currentPath } }" result = InterpreterTest::Schema.execute(query_str, variables: { queryStr: "{ __typename }" }) assert_equal '{"data":{"__typename":"Query"}}', result["data"]["nestedQuery"]["result"] assert_equal ["nestedQuery"], result["data"]["nestedQuery"]["currentPath"] assert_nil Fiber[:__graphql_runtime_info] end it "runs mutation roots atomically and sequentially" do query_str = <<-GRAPHQL mutation { i1: incrementCounter { value lazyValue i2: increment { value incrementedValue lazyValue } i3: increment { value incrementedValue lazyValue } } i4: incrementCounter { value incrementedValue lazyValue } i5: incrementCounter { value incrementedValue lazyValue } } GRAPHQL result = InterpreterTest::Schema.execute(query_str, context: { counter: OpenStruct.new(value: 0) }) expected_data = { "i1" => { "value" => 1, # All of these get `3` as lazy value. They're resolved together, # since they aren't _root_ mutation fields. "lazyValue" => 3, "i2" => { "value" => 2, "incrementedValue" => 2, "lazyValue" => 3 }, "i3" => { "value" => 3, "incrementedValue" => 3, "lazyValue" => 3 }, }, "i4" => { "value" => 4, "incrementedValue" => 4, "lazyValue" => 4}, "i5" => { "value" => 5, "incrementedValue" => 5, "lazyValue" => 5}, } assert_graphql_equal expected_data, result["data"] end it "runs skip and include" do query_str = <<-GRAPHQL query($truthy: Boolean!, $falsey: Boolean!){ exp1: expansion(sym: "RAV") @skip(if: true) { name } exp2: expansion(sym: "RAV") @skip(if: false) { name } exp3: expansion(sym: "RAV") @include(if: true) { name } exp4: expansion(sym: "RAV") @include(if: false) { name } exp5: expansion(sym: "RAV") @include(if: $truthy) { name } exp6: expansion(sym: "RAV") @include(if: $falsey) { name } } GRAPHQL vars = {truthy: true, falsey: false} result = InterpreterTest::Schema.execute(query_str, variables: vars) expected_data = { "exp2" => {"name" => "Ravnica, City of Guilds"}, "exp3" => {"name" => "Ravnica, City of Guilds"}, "exp5" => {"name" => "Ravnica, City of Guilds"}, } assert_graphql_equal expected_data, result["data"] assert_nil Fiber[:__graphql_runtime_info] end describe "runtime info in context" do it "is available" do res = InterpreterTest::Schema.execute <<-GRAPHQL { fieldCounter { runtimeInfo(a: 1, b: 2) fieldCounter { runtimeInfo lazyRuntimeInfo(a: 1) } } } GRAPHQL assert_equal '<"field_counter_1"> ["fieldCounter", "runtimeInfo"] -> FieldCounter.runtimeInfo(2)', res["data"]["fieldCounter"]["runtimeInfo"] # These are both `field_counter_2`, but one is lazy assert_equal '<"field_counter_2"> ["fieldCounter", "fieldCounter", "runtimeInfo"] -> FieldCounter.runtimeInfo(0)', res["data"]["fieldCounter"]["fieldCounter"]["runtimeInfo"] assert_equal '<"field_counter_2"> ["fieldCounter", "fieldCounter", "lazyRuntimeInfo"] -> FieldCounter.lazyRuntimeInfo(1)', res["data"]["fieldCounter"]["fieldCounter"]["lazyRuntimeInfo"] end end describe "null propagation" do it "propagates nulls" do query_str = <<-GRAPHQL { expansion(sym: "XYZ") { name sym lazySym } } GRAPHQL res = InterpreterTest::Schema.execute(query_str) # Although the expansion was found, its name of `nil` # propagated to here assert_nil res["data"].fetch("expansion") assert_equal ["Cannot return null for non-nullable field Expansion.name"], res["errors"].map { |e| e["message"] } assert_nil Fiber[:__graphql_runtime_info] end it "places errors ahead of data in the response" do query_str = <<-GRAPHQL { expansion(sym: "XYZ") { name } } GRAPHQL res = InterpreterTest::Schema.execute(query_str) assert_equal ["errors", "data"], res.keys end it "propagates nulls in lists" do query_str = <<-GRAPHQL { expansions { name sym lazySym } } GRAPHQL res = InterpreterTest::Schema.execute(query_str) # A null in one of the list items removed the whole list assert_nil(res["data"]) end it "works with unions that fail .authorized?" do res = InterpreterTest::Schema.execute <<-GRAPHQL { find(id: "NOPE") { ... on Expansion { sym } } } GRAPHQL assert_equal ["Cannot return null for non-nullable element of type 'Entity!' for Query.find"], res["errors"].map { |e| e["message"] } end it "works with lists of unions" do res = InterpreterTest::Schema.execute <<-GRAPHQL { findMany(ids: ["RAV", "NOPE", "BOGUS"]) { ... on Expansion { sym } } } GRAPHQL assert_equal 3, res["data"]["findMany"].size assert_equal "RAV", res["data"]["findMany"][0]["sym"] assert_nil res["data"]["findMany"][1] assert_nil res["data"]["findMany"][2] assert_equal false, res.key?("errors") assert_equal Hash, res["data"].class assert_equal Array, res["data"]["findMany"].class end end describe "duplicated fields" do it "doesn't run them multiple times" do query_str = <<-GRAPHQL { fieldCounter { calls(expected: 1) # This should not be called since it matches the above calls(expected: 1) fieldCounter { calls(expected: 2) } ...ExtraFields } } fragment ExtraFields on FieldCounter { fieldCounter { # This should not be called since it matches the inline field: calls(expected: 2) # This _should_ be called c3: calls(expected: 3) } } GRAPHQL # It will raise an error if it doesn't match the expectation res = InterpreterTest::Schema.execute(query_str, context: { calls: 0 }) assert_equal 3, res["data"]["fieldCounter"]["fieldCounter"]["c3"] end end describe "backwards compatibility" do it "handles a legacy nodes field" do res = InterpreterTest::Schema.execute('{ node(id: "abc") { id } }') assert_equal "abc", res["data"]["node"]["id"] res = InterpreterTest::Schema.execute('{ nodes(ids: ["abc", "xyz"]) { id } }') assert_equal ["abc", "xyz"], res["data"]["nodes"].map { |n| n["id"] } end end describe "returning raw values" do it "returns raw value" do query_str = <<-GRAPHQL { expansionRaw { name sym alwaysCachedValue } } GRAPHQL res = InterpreterTest::Schema.execute(query_str) assert_equal({ sym: "RAW", name: "Raw expansion", always_cached_value: 42 }, res["data"]["expansionRaw"]) end end describe "returning raw values and resolved fields" do it "returns raw value" do query_str = <<-GRAPHQL { expansionRaw { name sym alwaysCachedValue } } GRAPHQL res = InterpreterTest::Schema.execute(query_str) assert_equal({ sym: "RAW", name: "Raw expansion", always_cached_value: 42 }, res["data"]["expansionRaw"]) end end describe "Lazy skips" do class LazySkipSchema < GraphQL::Schema class Query < GraphQL::Schema::Object def self.authorized?(obj, ctx) -> { true } end field :skip, String def skip context.skip end field :lazy_skip, String def lazy_skip -> { context.skip } end field :mixed_skips, [String] def mixed_skips [ "a", context.skip, "c", -> { context.skip }, "e", ] end end class NothingSubscription < GraphQL::Schema::Subscription field :nothing, String def authorized?(*) -> { true } end def update { nothing: object } end end class Subscription < GraphQL::Schema::Object field :nothing, subscription: NothingSubscription end query Query subscription Subscription use InMemoryBackend::Subscriptions, extra: nil lazy_resolve Proc, :call end it "skips properly" do res = LazySkipSchema.execute("{ skip }") assert_equal({}, res["data"]) refute res.key?("errors") res = LazySkipSchema.execute("{ mixedSkips }") assert_equal({ "mixedSkips" => ["a", "c", "e"] }, res["data"]) refute res.key?("errors") res = LazySkipSchema.execute("{ lazySkip }") assert_equal({}, res["data"]) refute res.key?("errors") res = LazySkipSchema.execute("subscription { nothing { nothing } }") assert_equal({}, res["data"]) refute res.key?("errors") # Make sure an update works properly LazySkipSchema.subscriptions.trigger(:nothing, {}, :nothing_at_all) _key, updates = LazySkipSchema.subscriptions.deliveries.first assert_equal "nothing_at_all", updates[0]["data"]["nothing"]["nothing"] end end describe "GraphQL::ExecutionErrors from connection fields" do module ConnectionErrorTest class BaseField < GraphQL::Schema::Field def authorized?(obj, args, ctx) ctx[:authorized_calls] ||= 0 ctx[:authorized_calls] += 1 raise GraphQL::ExecutionError, "#{name} is not authorized" end end class BaseConnection < GraphQL::Types::Relay::BaseConnection node_nullable(false) edge_nullable(false) edges_nullable(false) end class BaseEdge < GraphQL::Types::Relay::BaseEdge node_nullable(false) end class Thing < GraphQL::Schema::Object field_class BaseField connection_type_class BaseConnection edge_type_class BaseEdge field :title, String, null: false field :body, String, null: false end class Query < GraphQL::Schema::Object field :things, Thing.connection_type, null: false def things [{title: "a"}, {title: "b"}, {title: "c"}] end field :thing, Thing, null: false def thing { title: "a", body: "b", } end end class Schema < GraphQL::Schema query Query end end it "returns only 1 error and stops resolving fields after that" do res = ConnectionErrorTest::Schema.execute("{ things { nodes { title } } }") assert_equal 1, res["errors"].size assert_equal 1, res.context[:authorized_calls] res = ConnectionErrorTest::Schema.execute("{ things { edges { node { title } } } }") assert_equal 1, res["errors"].size assert_equal 1, res.context[:authorized_calls] res = ConnectionErrorTest::Schema.execute("{ thing { title body } }") assert_equal 1, res["errors"].size assert_equal 1, res.context[:authorized_calls] end end describe "GraphQL::ExecutionErrors from non-null list fields" do module ListErrorTest class BaseField < GraphQL::Schema::Field def authorized?(*) raise GraphQL::ExecutionError, "#{name} is not authorized" end end class Thing < GraphQL::Schema::Object field_class BaseField field :title, String, null: false end class Query < GraphQL::Schema::Object field :things, [Thing], null: false def things [{title: "a"}, {title: "b"}, {title: "c"}] end end class Schema < GraphQL::Schema query Query end end it "returns only 1 error" do res = ListErrorTest::Schema.execute("{ things { title } }") assert_equal 1, res["errors"].size end end describe "Invalid null from raised execution error doesn't halt parent fields" do class RaisedErrorSchema < GraphQL::Schema module Iface include GraphQL::Schema::Interface field :bar, String, null: false end class Txn < GraphQL::Schema::Object field :fails, String, null: false def fails raise GraphQL::ExecutionError, "boom" end end class Concrete < GraphQL::Schema::Object implements Iface field :txn, Txn def txn {} end field :msg, String def msg "THIS SHOULD SHOW UP" end end class Query < GraphQL::Schema::Object field :iface, Iface def iface {} end end query(Query) orphan_types([Concrete]) def self.resolve_type(type, obj, ctx) Concrete end end it "resolves fields on the parent object" do querystring = """ { iface { ... on Concrete { txn { fails } msg } } } """ result = RaisedErrorSchema.execute(querystring) expected_result = { "errors" => [ { "message"=>"boom", "locations"=>[{"line"=>6, "column"=>15}], "path"=>["iface", "txn", "fails"] }, ], "data" => { "iface" => { "txn" => nil, "msg" => "THIS SHOULD SHOW UP" }, }, } assert_graphql_equal expected_result, result.to_h end end it "supports extras: [:parent]" do query_str = <<-GRAPHQL { card(name: "Dark Confidant") { parentClassName } expansion(sym: "RAV") { cards { parentClassName } } } GRAPHQL res = InterpreterTest::Schema.execute(query_str, context: { calls: 0 }) assert_equal "NilClass", res["data"]["card"].fetch("parentClassName") assert_equal "InterpreterTest::Query::ExpansionData", res["data"]["expansion"]["cards"].first["parentClassName"] end describe "fragment used twice in different ways" do class FragmentBugSchema < GraphQL::Schema class ProductVariant < GraphQL::Schema::Object field :product, "FragmentBugSchema::Product" end class Product < GraphQL::Schema::Object field :id, ID field :variants, [ProductVariant] def variants [{ product: { id: "1" } }] end end class Query < GraphQL::Schema::Object field :variant, ProductVariant def variant { product: { id: "1" } } end end query(Query) end it "executes successfully" do query_str = <<-GRAPHQL { variant { ...variantFields ... on ProductVariant { product { variants { ...variantFields } } } } } fragment variantFields on ProductVariant { product { id } } GRAPHQL res = FragmentBugSchema.execute(query_str).to_h expected_result = { "variant" => { "product" => { "id" => "1", "variants" => [ { "product" => { "id" => "1" } } ] } } } assert_equal(expected_result, res["data"]) end end describe "multiplex queries" do it "runs multiplex queries" do result = InterpreterTest::Schema.multiplex([ { query: "query Card($name: String!) { card(name: $name) { colors } }", variables: { name: "Dark Confidant" }, operation_name: "Card" }, { query: "query Expansion($expansion: String!) { expansion(sym: $expansion) { cards { name } } }", variables: { expansion: "RAV" }, operation_name: "Expansion" } ]) assert_equal ["BLACK"], result[0]["data"]["card"]["colors"] assert_equal [{"name" => "Dark Confidant"}], result[1]["data"]["expansion"]["cards"] assert_nil Fiber[:__graphql_runtime_info] 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/execution/errors_spec.rb
spec/graphql/execution/errors_spec.rb
# frozen_string_literal: true require "spec_helper" describe "GraphQL::Execution::Errors" do class ParentErrorsTestSchema < GraphQL::Schema class ErrorD < RuntimeError; end rescue_from(ErrorD) do |err, obj, args, ctx, field| raise GraphQL::ExecutionError, "ErrorD on #{obj.inspect} at #{field ? "#{field.path}(#{args})" : "boot"}" end end class ErrorsTestSchema < ParentErrorsTestSchema ErrorD = ParentErrorsTestSchema::ErrorD class ErrorA < RuntimeError; end class ErrorB < RuntimeError; end class ErrorC < RuntimeError attr_reader :value def initialize(value:) @value = value super end end class ErrorASubclass < ErrorA; end class ErrorBChildClass < ErrorB; end class ErrorBGrandchildClass < ErrorBChildClass; end rescue_from(ErrorA) do |err, obj, args, ctx, field| ctx[:errors] << "#{err.message} (#{field.owner.name}.#{field.graphql_name}, #{obj.inspect}, #{args.inspect})" nil end rescue_from(ErrorBChildClass) do |*| "Handled ErrorBChildClass" end # Trying to assert that _specificity_ takes priority # over sequence, but the stability of that assertion # depends on the underlying implementation. rescue_from(ErrorBGrandchildClass) do |*| "Handled ErrorBGrandchildClass" end rescue_from(ErrorB) do |*| raise GraphQL::ExecutionError, "boom!" end rescue_from(ErrorC) do |err, *| err.value end class ErrorList < Array def each raise ErrorB end end class Thing < GraphQL::Schema::Object def self.authorized?(obj, ctx) if ctx[:authorized] == false raise ErrorD end true end field :string, String, null: false def string "a string" end end class ValuesInput < GraphQL::Schema::InputObject argument :value, Int, loads: Thing def self.object_from_id(type, value, ctx) if value == 1 :thing else raise ErrorD end end end class PickyString < GraphQL::Schema::Scalar def self.coerce_input(value, ctx) if value == "picky" value else raise ErrorB, "The string wasn't \"picky\"" end end end class Query < GraphQL::Schema::Object field :f1, Int do argument :a1, Int, required: false end def f1(a1: nil) raise ErrorA, "f1 broke" end field :f2, Int def f2 -> { raise ErrorA, "f2 broke" } end field :f3, Int def f3 raise ErrorB end field :f4, Int, null: false def f4 raise ErrorC.new(value: 20) end field :f5, Int def f5 raise ErrorASubclass, "raised subclass" end field :f6, Int def f6 -> { raise ErrorB } end field :f7, String def f7 raise ErrorBGrandchildClass end field :f8, String do argument :input, PickyString end def f8(input:) input end field :f9, String do argument :thing_id, ID, loads: Thing end def f9(thing:) thing[:id] end field :thing, Thing def thing :thing end field :input_field, Int do argument :values, ValuesInput end field :non_nullable_array, [String], null: false def non_nullable_array [nil] end field :error_in_each, [Int] def error_in_each ErrorList.new end end query(Query) lazy_resolve(Proc, :call) def self.object_from_id(id, ctx) if id == "boom" raise ErrorB end { thing: true, id: id } end def self.resolve_type(type, obj, ctx) Thing end end class ErrorsTestSchemaWithoutInterpreter < GraphQL::Schema class Query < GraphQL::Schema::Object field :non_nullable_array, [String], null: false def non_nullable_array [nil] end end query(Query) end describe "rescue_from handling" do it "can replace values with `nil`" do ctx = { errors: [] } res = ErrorsTestSchema.execute "{ f1(a1: 1) }", context: ctx, root_value: :abc assert_equal({ "data" => { "f1" => nil } }, res) assert_equal ["f1 broke (ErrorsTestSchema::Query.f1, :abc, #{{a1: 1}.inspect})"], ctx[:errors] end it "rescues errors from lazy code" do ctx = { errors: [] } res = ErrorsTestSchema.execute("{ f2 }", context: ctx) assert_equal({ "data" => { "f2" => nil } }, res) assert_equal ["f2 broke (ErrorsTestSchema::Query.f2, nil, {})"], ctx[:errors] end it "picks the most specific handler and uses the return value from it" do res = ErrorsTestSchema.execute("{ f7 }") assert_equal({ "data" => { "f7" => "Handled ErrorBGrandchildClass" } }, res) end it "rescues errors from lazy code with handlers that re-raise" do res = ErrorsTestSchema.execute("{ f6 }") expected_error = { "message"=>"boom!", "locations"=>[{"line"=>1, "column"=>3}], "path"=>["f6"] } assert_equal({ "data" => { "f6" => nil }, "errors" => [expected_error] }, res) end it "can raise new errors" do res = ErrorsTestSchema.execute("{ f3 }") expected_error = { "message"=>"boom!", "locations"=>[{"line"=>1, "column"=>3}], "path"=>["f3"] } assert_equal({ "data" => { "f3" => nil }, "errors" => [expected_error] }, res) end it "can replace values with non-nil" do res = ErrorsTestSchema.execute("{ f4 }") assert_equal({ "data" => { "f4" => 20 } }, res) end it "rescues subclasses" do context = { errors: [] } res = ErrorsTestSchema.execute("{ f5 }", context: context) assert_equal({ "data" => { "f5" => nil } }, res) assert_equal ["raised subclass (ErrorsTestSchema::Query.f5, nil, {})"], context[:errors] end describe "errors raised when coercing inputs" do it "rescues them" do res1 = ErrorsTestSchema.execute("{ f8(input: \"picky\") }") assert_equal "picky", res1["data"]["f8"] res2 = ErrorsTestSchema.execute("{ f8(input: \"blah\") }") assert_equal ["errors"], res2.keys assert_equal ["boom!"], res2["errors"].map { |e| e["message"] } res3 = ErrorsTestSchema.execute("query($v: PickyString!) { f8(input: $v) }", variables: { v: "blah" }) assert_equal ["errors"], res3.keys assert_equal ["Variable $v of type PickyString! was provided invalid value"], res3["errors"].map { |e| e["message"] } assert_equal [["boom!"]], res3["errors"].map { |e| e["extensions"]["problems"].map { |pr| pr["explanation"] } } end end describe "errors raised when loading objects from ID" do it "rescues them" do res1 = ErrorsTestSchema.execute("{ f9(thingId: \"abc\") }") assert_equal "abc", res1["data"]["f9"] res2 = ErrorsTestSchema.execute("{ f9(thingId: \"boom\") }") assert_equal ["boom!"], res2["errors"].map { |e| e["message"] } end end describe "errors raised in authorized hooks" do it "rescues them" do context = { authorized: false } res = ErrorsTestSchema.execute(" { thing { string } } ", context: context) assert_equal ["ErrorD on nil at Query.thing({})"], res["errors"].map { |e| e["message"] } end end describe "errors raised in input_object loads" do it "rescues them from literal values" do context = { authorized: false } res = ErrorsTestSchema.execute(" { inputField(values: { value: 2 }) } ", root_value: :root, context: context) # It would be better to have the arguments here, but since this error was raised during _creation_ of keywords, # so the runtime arguments aren't available now. assert_equal ["ErrorD on :root at Query.inputField()"], res["errors"].map { |e| e["message"] } end it "rescues them from variable values" do context = { authorized: false } res = ErrorsTestSchema.execute( "query($values: ValuesInput!) { inputField(values: $values) } ", variables: { values: { "value" => 2 } }, context: context, ) assert_equal ["ErrorD on nil at Query.inputField()"], res["errors"].map { |e| e["message"] } end end describe "errors raised in non_nullable_array loads" do it "outputs the appropriate error message when using non-interpreter schema" do res = ErrorsTestSchemaWithoutInterpreter.execute("{ nonNullableArray }") expected_error = { "message" => "Cannot return null for non-nullable element of type 'String!' for Query.nonNullableArray", "path" => ["nonNullableArray", 0], "locations" => [{ "line" => 1, "column" => 3 }] } assert_equal({ "data" => nil, "errors" => [expected_error] }, res) end it "outputs the appropriate error message when using interpreter schema" do res = ErrorsTestSchema.execute("{ nonNullableArray }") expected_error = { "message" => "Cannot return null for non-nullable element of type 'String!' for Query.nonNullableArray", "path" => ["nonNullableArray", 0], "locations" => [{ "line" => 1, "column" => 3 }] } assert_equal({ "data" => nil, "errors" => [expected_error] }, res) end end describe "when .each on a list type raises an error" do it "rescues it properly" do res = ErrorsTestSchema.execute("{ __typename errorInEach }") expected_error = { "message" => "boom!", "locations"=>[{"line"=>1, "column"=>14}], "path"=>["errorInEach"] } assert_equal({ "data" => { "__typename" => "Query", "errorInEach" => nil }, "errors" => [expected_error] }, res) 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/execution/lazy_spec.rb
spec/graphql/execution/lazy_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Execution::Lazy do include LazyHelpers describe "resolving" do it "calls value handlers" do res = run_query('{ int(value: 2, plus: 1) }') assert_equal 3, res["data"]["int"] end it "Works with Query.new" do query_str = '{ int(value: 2, plus: 1) }' query = GraphQL::Query.new(LazyHelpers::LazySchema, query_str) res = query.result assert_equal 3, res["data"]["int"] end it "can do nested lazy values" do res = run_query %| { a: nestedSum(value: 3) { value nestedSum(value: 7) { value nestedSum(value: 1) { value nestedSum(value: -50) { value } } } } b: nestedSum(value: 2) { value nestedSum(value: 11) { value nestedSum(value: 2) { value nestedSum(value: -50) { value } } } } c: listSum(values: [1,2]) { nestedSum(value: 3) { value } } } | expected_data = { "a"=>{"value"=>14, "nestedSum"=>{ "value"=>46, "nestedSum"=>{ "value"=>95, "nestedSum"=>{"value"=>90} } }}, "b"=>{"value"=>14, "nestedSum"=>{ "value"=>46, "nestedSum"=>{ "value"=>95, "nestedSum"=>{"value"=>90} } }}, "c"=>[ {"nestedSum"=>{"value"=>14}}, {"nestedSum"=>{"value"=>14}} ], } assert_graphql_equal expected_data, res["data"] end [ [1, 2, LazyHelpers::MAGIC_NUMBER_WITH_LAZY_AUTHORIZED_HOOK], [2, LazyHelpers::MAGIC_NUMBER_WITH_LAZY_AUTHORIZED_HOOK, 1], [LazyHelpers::MAGIC_NUMBER_WITH_LAZY_AUTHORIZED_HOOK, 1, 2], ].each do |ordered_values| it "resolves each field at one depth before proceeding to the next depth (using #{ordered_values})" do res = run_query <<-GRAPHQL, variables: { values: ordered_values } query($values: [Int!]!) { listSum(values: $values) { nestedSum(value: 3) { value } } } GRAPHQL # Even though magic number `44`'s `.authorized?` hook returns a lazy value, # these fields should be resolved together and return the same value. assert_equal 56, res["data"]["listSum"][0]["nestedSum"]["value"] assert_equal 56, res["data"]["listSum"][1]["nestedSum"]["value"] assert_equal 56, res["data"]["listSum"][2]["nestedSum"]["value"] end end it "Handles fields that return nil and batches lazy resultion across depths when possible" do values = [ LazyHelpers::MAGIC_NUMBER_THAT_RETURNS_NIL, LazyHelpers::MAGIC_NUMBER_WITH_LAZY_AUTHORIZED_HOOK, 1, 2, ] res = run_query <<-GRAPHQL, variables: { values: values } query($values: [Int!]!) { listSum(values: $values) { nullableNestedSum(value: 3) { value } } } GRAPHQL values = res["data"]["listSum"].map { |s| s && s["nullableNestedSum"]["value"] } assert_equal [nil, 56, 56, 56], values end it "propagates nulls to the root" do res = run_query %| { nestedSum(value: 1) { value nestedSum(value: 2) { nestedSum(value: 13) { value } } } }| assert_nil(res["data"]) assert_equal 1, res["errors"].length end it "propagates partial nulls" do res = run_query %| { nullableNestedSum(value: 1) { value nullableNestedSum(value: 2) { ns: nestedSum(value: 13) { value } } } }| expected_data = { "nullableNestedSum" => { "value" => 1, "nullableNestedSum" => nil, } } assert_equal(expected_data, res["data"]) assert_equal 1, res["errors"].length end it "handles raised errors" do res = run_query %| { a: nullableNestedSum(value: 1) { value } b: nullableNestedSum(value: 13) { value } c: nullableNestedSum(value: 2) { value } }| expected_data = { "a" => { "value" => 3 }, "b" => nil, "c" => { "value" => 3 }, } assert_graphql_equal expected_data, res["data"] expected_errors = [{ "message"=>"13 is unlucky", "locations"=>[{"line"=>4, "column"=>9}], "path"=>["b"], }] assert_equal expected_errors, res["errors"] end it "resolves mutation fields right away" do res = run_query %| { a: nestedSum(value: 2) { value } b: nestedSum(value: 4) { value } c: nestedSum(value: 6) { value } }| assert_equal [12, 12, 12], res["data"].values.map { |d| d["value"] } res = run_query %| mutation { a: nestedSum(value: 2) { value } b: nestedSum(value: 4) { value } c: nestedSum(value: 6) { value } } | assert_equal [2, 4, 6], res["data"].values.map { |d| d["value"] } end end describe "Schema#sync_lazy(object)" do it "Passes objects to that hook at runtime" do res = run_query <<-GRAPHQL { a: nullableNestedSum(value: 1001) { value } b: nullableNestedSum(value: 1013) { value } c: nullableNestedSum(value: 1002) { value } } GRAPHQL # This odd, non-adding behavior is hacked into `#sync_lazy` assert_equal 101, res["data"]["a"]["value"] assert_equal 113, res["data"]["b"]["value"] assert_equal 102, res["data"]["c"]["value"] end end describe "LazyMethodMap" do class SubWrapper < LazyHelpers::Wrapper; end let(:map) { GraphQL::Execution::Lazy::LazyMethodMap.new } it "finds methods for classes and subclasses" do map.set(LazyHelpers::Wrapper, :item) map.set(LazyHelpers::SumAll, :value) b = LazyHelpers::Wrapper.new(1) sub_b = LazyHelpers::Wrapper.new(2) s = LazyHelpers::SumAll.new(3) assert_equal(:item, map.get(b)) assert_equal(:item, map.get(sub_b)) assert_equal(:value, map.get(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/execution/lazy/lazy_method_map_spec.rb
spec/graphql/execution/lazy/lazy_method_map_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Execution::Lazy::LazyMethodMap do def self.test_lazy_method_map it "handles multithreaded access" do a = Class.new b = Class.new(a) c = Class.new(b) lazy_method_map.set(a, :a) threads = 1000.times.map do |i| Thread.new { d = Class.new(c) assert_equal :a, lazy_method_map.get(d.new) } end threads.map(&:join) end it "dups" do a = Class.new b = Class.new(a) c = Class.new(b) lazy_method_map.set(a, :a) lazy_method_map.get(b.new) lazy_method_map.get(c.new) dup_map = lazy_method_map.dup assert_equal 3, dup_map.instance_variable_get(:@storage).size assert_equal :a, dup_map.get(a.new) assert_equal :a, dup_map.get(b.new) assert_equal :a, dup_map.get(c.new) end end describe "with a plain hash" do let(:lazy_method_map) { GraphQL::Execution::Lazy::LazyMethodMap.new(use_concurrent: false) } test_lazy_method_map it "has a Ruby Hash inside" do storage = lazy_method_map .instance_variable_get(:@storage) .instance_variable_get(:@storage) assert_instance_of Hash, storage end end describe "with a Concurrent::Map" do let(:lazy_method_map) { GraphQL::Execution::Lazy::LazyMethodMap.new(use_concurrent: true) } test_lazy_method_map it "has a Concurrent::Map inside" do storage = lazy_method_map.instance_variable_get(:@storage) assert_instance_of Concurrent::Map, storage 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/execution/interpreter/arguments_spec.rb
spec/graphql/execution/interpreter/arguments_spec.rb
# frozen_string_literal: true require "spec_helper" describe "GraphQL::Execution::Interpreter::Arguments" do class InterpreterArgsTestSchema < GraphQL::Schema class SearchParams < GraphQL::Schema::InputObject argument :query, String, required: false end class Query < GraphQL::Schema::Object field :search, [String], null: false do argument :params, SearchParams, required: false argument :limit, Int end end query(Query) end def arguments(query_str) query = GraphQL::Query.new(InterpreterArgsTestSchema, query_str) ast_node = query.document.definitions.first.selections.first query_type = query.get_type("Query") field = query.get_field(query_type, "search") query.arguments_for(ast_node, field) end it "provides .dig" do query_str = <<-GRAPHQL { search(limit: 10, params: { query: "abcde" } ) } GRAPHQL args = arguments(query_str) assert_equal 10, args.dig(:limit) assert_equal "abcde", args.dig(:params, :query) assert_nil args.dig(:nothing) assert_nil args.dig(:params, :nothing) assert_nil args.dig(:nothing, :nothing, :nothing) end it "is frozen, and so are its constituent hashes" do query_str = <<-GRAPHQL { search(limit: 10, params: { query: "abcde" } ) } GRAPHQL args = arguments(query_str) assert args.frozen? assert args.argument_values.frozen? assert args.keyword_arguments.frozen? 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/analysis/max_query_complexity_spec.rb
spec/graphql/analysis/max_query_complexity_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Analysis::MaxQueryComplexity do let(:schema) { Class.new(Dummy::Schema) } let(:query_string) {%| { a: cheese(id: 1) { id } b: cheese(id: 1) { id } c: cheese(id: 1) { id } d: cheese(id: 1) { id } e: cheese(id: 1) { id } } |} let(:query) { GraphQL::Query.new(schema, query_string, variables: {}, max_complexity: max_complexity) } let(:result) { GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::MaxQueryComplexity]).first } describe "when a query goes over max complexity" do let(:max_complexity) { 9 } it "returns an error" do assert_equal GraphQL::AnalysisError, result.class assert_equal "Query has complexity of 10, which exceeds max complexity of 9", result.message end end describe "when there is no max complexity" do let(:max_complexity) { nil } it "doesn't error" do assert_nil result end end describe "when the query is less than the max complexity" do let(:max_complexity) { 99 } it "doesn't error" do assert_nil result end end describe "when max_complexity is decreased at query-level" do before do schema.max_complexity(100) end let(:max_complexity) { 7 } it "is applied" do assert_equal GraphQL::AnalysisError, result.class assert_equal "Query has complexity of 10, which exceeds max complexity of 7", result.message end end describe "when max_complexity is increased at query-level" do before do schema.max_complexity(1) end let(:max_complexity) { 10 } it "doesn't error" do assert_nil result end end describe "when max_complexity is nil at query-level" do let(:max_complexity) { nil } before do schema.max_complexity(1) end it "is applied" do assert_nil result end end describe "when used with the max_depth plugin" do let(:schema) do Class.new(GraphQL::Schema) do query Dummy::DairyAppQuery max_depth 3 max_complexity 1 end end let(:query_string) {%| { a: cheese(id: 1) { ...cheeseFields } b: cheese(id: 1) { ...cheeseFields } c: cheese(id: 1) { ...cheeseFields } d: cheese(id: 1) { ...cheeseFields } e: cheese(id: 1) { ...cheeseFields } } fragment cheeseFields on Cheese { id } |} let(:result) { schema.execute(query_string) } it "returns a complexity error" do assert_equal "Query has complexity of 10, which exceeds max complexity of 1", result["errors"].first["message"] end end describe "count_introspection_fields: false" do let(:schema) { Class.new(Dummy::Schema) { max_complexity(5) } } let(:skip_introspection_schema) { Class.new(Dummy::Schema) do max_complexity 5, count_introspection_fields: false end } it "skips introspection fields when configured" do query_string = "{ c1: cheese(id: 1) { id __typename } c2: cheese(id: 2) { id __typename } }" res = schema.execute(query_string) expected_msg = "Query has complexity of 6, which exceeds max complexity of 5" assert_equal [expected_msg], res["errors"].map { |e| e["message"]} res2 = skip_introspection_schema.execute(query_string) assert_equal 2, res2["data"].size refute res2.key?("errors") end end describe "across a multiplex" do before do schema.analysis_engine = GraphQL::Analysis::AST end let(:queries) { 5.times.map { |n| GraphQL::Query.new(schema, "{ cheese(id: #{n}) { id } }", variables: {}) } } let(:max_complexity) { 9 } let(:multiplex) { GraphQL::Execution::Multiplex.new(schema: schema, queries: queries, context: {}, max_complexity: max_complexity) } let(:analyze_multiplex) { GraphQL::Analysis.analyze_multiplex(multiplex, [GraphQL::Analysis::MaxQueryComplexity]) } it "returns errors for all queries" do analyze_multiplex err_msg = "Query has complexity of 10, which exceeds max complexity of 9" queries.each do |query| assert_equal err_msg, query.analysis_errors[0].message end end describe "with a local override" do let(:max_complexity) { 10 } it "uses the override" do analyze_multiplex queries.each do |query| assert query.analysis_errors.empty? end end end end describe "when an argument is unauthorized by type" do class AuthorizedTypeSchema < GraphQL::Schema class Thing < GraphQL::Schema::Object def self.authorized?(obj, ctx) !!ctx[:authorized] && super end field :name, String end class Query < GraphQL::Schema::Object field :things, Thing.connection_type do argument :thing_id, ID, loads: Thing end def things(thing:) [thing] end end query(Query) def self.resolve_type(abs_type, object, ctx) Thing end def self.object_from_id(id, ctx) if id == "13" raise GraphQL::ExecutionError, "No Thing ##{id}" else { name: "Loaded thing #{id}" } end end def self.unauthorized_object(err) raise GraphQL::ExecutionError, "Unauthorized Object: #{err.object[:name].inspect}" end default_max_page_size 30 max_complexity 10 end it "when the arg is unauthorized, returns an authorization error, not a complexity error" do query_str = "{ things(thingId: \"123\", first: 1) { nodes { name } } }" res = AuthorizedTypeSchema.execute(query_str, context: { authorized: true }) assert_equal "Loaded thing 123", res["data"]["things"]["nodes"].first["name"] res2 = AuthorizedTypeSchema.execute(query_str) assert_equal ["Unauthorized Object: \"Loaded thing 123\""], res2["errors"].map { |e| e["message"] } end it "returns the right error when the loaded object raises an error" do query_str = "{ things(thingId: \"13\", first: 1) { nodes { name } } }" res = AuthorizedTypeSchema.execute(query_str, context: { authorized: true }) assert_equal ["No Thing #13"], 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/analysis/query_complexity_spec.rb
spec/graphql/analysis/query_complexity_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Analysis::QueryComplexity do let(:schema) { Class.new(Dummy::Schema) { complexity_cost_calculation_mode(:future) } } let(:reduce_result) { GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::QueryComplexity]) } let(:reduce_multiplex_result) { GraphQL::Analysis.analyze_multiplex(multiplex, [GraphQL::Analysis::QueryComplexity]) } let(:variables) { {} } let(:query_context) { {} } let(:query) { GraphQL::Query.new(schema, query_string, context: query_context, variables: variables) } let(:multiplex) { GraphQL::Execution::Multiplex.new( schema: schema, queries: [query.dup, query.dup], context: {}, max_complexity: 10 ) } describe "simple queries" do let(:query_string) {%| query cheeses { # complexity of 3 cheese1: cheese(id: 1) { id flavor __typename } # complexity of 4 cheese2: cheese(id: 2) { similarCheese(source: SHEEP) { ... on Cheese { similarCheese(source: SHEEP) { id } } } } } |} it "sums the complexity" do complexities = reduce_result.first assert_equal 8, complexities end end describe "with skip/include" do let(:query_string) {%| query cheeses($skip: Boolean = false, $include: Boolean = true) { fields: cheese(id: 1) { flavor origin @skip(if: $skip) source @include(if: $include) } inlineFragments: cheese(id: 1) { ...on Cheese { flavor } ...on Cheese @skip(if: $skip) { origin } ...on Cheese @include(if: $include) { source } } fragmentSpreads: cheese(id: 1) { ...Flavorful ...Original @skip(if: $skip) ...Sourced @include(if: $include) } } fragment Flavorful on Cheese { flavor } fragment Original on Cheese { origin } fragment Sourced on Cheese { source } |} it "sums up all included complexities" do assert_equal 12, reduce_result.first end describe "when skipped by directives" do let(:variables) { { "skip" => true, "include" => false } } it "doesn't include skipped fields and fragments" do assert_equal 6, reduce_result.first end end end describe "query with fragments" do let(:query_string) {%| { # complexity of 3 cheese1: cheese(id: 1) { id flavor } # complexity of 7 cheese2: cheese(id: 2) { ... cheeseFields1 ... cheeseFields2 } } fragment cheeseFields1 on Cheese { similarCow: similarCheese(source: COW) { id ... cheeseFields2 } } fragment cheeseFields2 on Cheese { similarSheep: similarCheese(source: SHEEP) { id } } |} it "counts all fragment usages, not the definitions" do complexity = reduce_result.first assert_equal 10, complexity end describe "mutually exclusive types" do let(:query_string) {%| { favoriteEdible { # 1 for everybody fatContent # 1 for everybody ... on Edible { origin } # 1 for honey, aspartame ... on Sweetener { sweetness } # 2 for milk ... milkFields # 1 for cheese ... cheeseFields # 1 for honey ... honeyFields # 1 for milk + cheese ... dairyProductFields } } fragment milkFields on Milk { id source } fragment cheeseFields on Cheese { source } fragment honeyFields on Honey { flowerType } fragment dairyProductFields on DairyProduct { ... on Cheese { flavor } ... on Milk { flavors } } |} it "gets the max among options" do complexity = reduce_result.first assert_equal 6, complexity end end describe "when there are no selections on any object types" do let(:query_string) {%| { # 1 for everybody favoriteEdible { # 1 for everybody fatContent # 1 for everybody ... on Edible { origin } # 1 for honey, aspartame ... on Sweetener { sweetness } } } |} it "gets the max among interface types" do complexity = reduce_result.first assert_equal 4, complexity end end describe "redundant fields" do let(:query_string) {%| { favoriteEdible { fatContent # this is executed separately and counts separately: aliasedFatContent: fatContent ... on Edible { fatContent } ... edibleFields } } fragment edibleFields on Edible { fatContent } |} it "only counts them once" do complexity = reduce_result.first assert_equal 3, complexity end end describe "redundant fields not within a fragment" do let(:query_string) {%| { cheese { id } cheese { id } } |} it "only counts them once" do complexity = reduce_result.first assert_equal 2, complexity end end end describe "relay types" do let(:schema) { Class.new(StarWars::Schema) { complexity_cost_calculation_mode(:future) } } let(:query) { GraphQL::Query.new(schema, query_string) } let(:query_string) {%| { rebels { ships(first: 1) { edges { node { id } } nodes { id } pageInfo { hasNextPage } } } } |} it "gets the complexity" do complexity = reduce_result.first expected_complexity = 1 + # rebels 1 + # ships 1 + # edges 1 + # nodes 1 + 1 + # pageInfo, hasNextPage 1 + 1 + 1 # node, id, id assert_equal expected_complexity, complexity end describe "first/last" do let(:query_string) {%| { rebels { s1: ships(first: 5) { edges { node { id } } pageInfo { hasNextPage } } s2: ships(last: 3) { nodes { id } } } } |} it "uses first/last for calculating complexity" do complexity = reduce_result.first expected_complexity = ( 1 + # rebels (1 + 1 + (5 * 2) + 2) + # s1 (1 + 1 + (3 * 1) + 0) # s2 ) assert_equal expected_complexity, complexity end end describe "Field-level max_page_size" do let(:query_string) {%| { rebels { ships { nodes { id } } } } |} it "uses field max_page_size" do complexity = reduce_result.first assert_equal 1 + 1 + 1 + (1000 * 1), complexity end end describe "Schema-level default_max_page_size" do let(:query_string) {%| { rebels { bases { nodes { id } totalCount } } } |} it "uses schema default_max_page_size" do complexity = reduce_result.first assert_equal 1 + 1 + 1 + (3 * 1) + 1, complexity end end describe "Field-level default_page_size" do let(:query_string) {%| { rebels { shipsWithDefaultPageSize { nodes { id } } } } |} it "uses field default_page_size" do complexity = reduce_result.first assert_equal 1 + 1 + 1 + (500 * 1), complexity end end describe "Schema-level default_page_size" do let(:schema) { Class.new(StarWars::SchemaWithDefaultPageSize) { complexity_cost_calculation_mode(:future) } } let(:query) { GraphQL::Query.new(schema, query_string) } let(:query_string) {%| { rebels { bases { nodes { id } totalCount } } } |} it "uses schema default_page_size" do complexity = reduce_result.first assert_equal 1 + 1 + 1 + (2 * 1) + 1, complexity end end end describe "calculation complexity for a multiplex" do let(:query_string) {%| query cheeses { cheese(id: 1) { id flavor source } } |} it "sums complexity for both queries" do complexity = reduce_multiplex_result.first assert_equal 8, complexity end describe "abstract type" do let(:query_string) {%| query Edible { allEdible { origin fatContent } } |} it "sums complexity for both queries" do complexity = reduce_multiplex_result.first assert_equal 6, complexity end end end describe "custom complexities" do class CustomComplexitySchema < GraphQL::Schema module ComplexityInterface include GraphQL::Schema::Interface field :value, Int end class SingleComplexity < GraphQL::Schema::Object field :value, Int, complexity: 0.1 field :complexity, SingleComplexity do argument :int_value, Int, required: false complexity(->(ctx, args, child_complexity) { args[:int_value] + child_complexity }) end implements ComplexityInterface end class DoubleComplexity < GraphQL::Schema::Object field :value, Int, complexity: 4 implements ComplexityInterface end class Query < GraphQL::Schema::Object field :complexity, SingleComplexity do argument :int_value, Int, required: false, prepare: ->(val, ctx) { if ctx[:raise_prepare_error] raise GraphQL::ExecutionError, "Boom" else val end } complexity ->(ctx, args, child_complexity) { args[:int_value] + child_complexity } end def complexity(int_value:) { value: int_value } end field :inner_complexity, ComplexityInterface do argument :value, Int, required: false end end query(Query) orphan_types(DoubleComplexity) complexity_cost_calculation_mode(:future) module CustomIntrospection class DynamicFields < GraphQL::Introspection::DynamicFields field :__typename, String, complexity: 100 end class EntryPoints < GraphQL::Introspection::EntryPoints class CustomIntrospectionField < GraphQL::Schema::Field def calculate_complexity(query:, nodes:, child_complexity:) child_complexity + 0.6 end end field_class CustomIntrospectionField field :__schema, GraphQL::Schema::LateBoundType.new("__Schema") end end introspection(CustomIntrospection) end let(:query) { GraphQL::Query.new(complexity_schema, query_string, context: query_context) } let(:complexity_schema) { CustomComplexitySchema } let(:query_string) {%| { a: complexity(intValue: 3) { value } b: complexity(intValue: 6) { value complexity(intValue: 1) { value } } } |} it "sums the complexity" do complexity = reduce_result.first # 10 from `complexity`, `0.3` from `value` assert_equal 10.3, complexity end describe "introspection" do let(:query_string) { "{ __typename __schema { queryType } }"} it "does custom complexity for introspection" do complexity = reduce_result.first # 100 + 1 + 0.6 assert_equal 101.6, complexity end end describe "same field on multiple types" do let(:query_string) {%| { innerComplexity(intValue: 2) { ... on SingleComplexity { value } ... on DoubleComplexity { value } } } |} it "picks them max for those fields" do complexity = reduce_result.first # 1 for innerComplexity + 4 for DoubleComplexity.value assert_equal 5, complexity end end describe "when prepare raises an error" do let(:query_string) { "{ complexity(intValue: 3) { value } }"} let(:query_context) { { raise_prepare_error: true } } it "handles it nicely" do result = query.result assert_equal ["Boom"], result["errors"].map { |e| e["message"] } complexity = reduce_result.first assert_equal 0.1, complexity end end end describe "custom complexities by complexity_for(...)" do class CustomComplexityByMethodSchema < GraphQL::Schema module ComplexityInterface include GraphQL::Schema::Interface field :value, Int end class SingleComplexity < GraphQL::Schema::Object field :value, Int, complexity: 0.1 field :complexity, SingleComplexity do argument :int_value, Int, required: false def complexity_for(query:, child_complexity:, lookahead:) lookahead.arguments[:int_value] + child_complexity end end implements ComplexityInterface end class ComplexityFourField < GraphQL::Schema::Field def complexity_for(query:, lookahead:, child_complexity:) 4 end end class DoubleComplexity < GraphQL::Schema::Object field_class ComplexityFourField field :value, Int implements ComplexityInterface end class Thing < GraphQL::Schema::Object field :name, String end class CustomThingConnection < GraphQL::Types::Relay::BaseConnection edge_type Thing.edge_type field :something_special, String, complexity: 3 end class Query < GraphQL::Schema::Object field :complexity, SingleComplexity do argument :int_value, Int, required: false def complexity_for(query:, child_complexity:, lookahead:) lookahead.arguments[:int_value] + child_complexity end end field :inner_complexity, ComplexityInterface do argument :value, Int, required: false end field :things, Thing.connection_type, max_page_size: 100 do argument :count, Int, validates: { numericality: { less_than: 50 } } end def things(count:) count.times.map {|t| {name: t.to_s}} end class ThingsCustom < GraphQL::Schema::Resolver type CustomThingConnection, null: false complexity 100 def resolve 5.times { |t| { name: "Thing #{t}" } } end end field :things_custom, resolver: ThingsCustom end query(Query) orphan_types(DoubleComplexity) complexity_cost_calculation_mode(:future) end let(:query) { GraphQL::Query.new(complexity_schema, query_string) } let(:complexity_schema) { CustomComplexityByMethodSchema } let(:query_string) {%| { a: complexity(intValue: 3) { value } b: complexity(intValue: 6) { value complexity(intValue: 1) { value } } } |} it "inherits complexity_cost_calculation_mode" do schema = Class.new(CustomComplexityByMethodSchema) assert_equal CustomComplexityByMethodSchema.complexity_cost_calculation_mode, schema.complexity_cost_calculation_mode end it "sums the complexity" do complexity = reduce_result.first # 10 from `complexity`, `0.3` from `value` assert_equal 10.3, complexity end describe "same field on multiple types" do let(:query_string) {%| { innerComplexity(value: 2) { ... on SingleComplexity { value } ... on DoubleComplexity { value } } } |} it "picks them max for those fields" do complexity = reduce_result.first # 1 for innerComplexity + 4 for DoubleComplexity.value assert_equal 5, complexity end end describe "when the query fails validation" do let(:query_string) {%| { things(count: 200, first: 5) { nodes { name } } } |} it "handles the error" do res = GraphQL::Query.new(complexity_schema, query_string).result assert_equal ["count must be less than 50"], res["errors"].map { |e| e["message"] } assert_equal [], reduce_result, "It doesn't finish calculation" end end describe "when connection fields have custom complexity" do let(:query_string) { "{ thingsCustom(first: 2) { somethingSpecial nodes { name } } }"} it "uses the custom configured value" do complexity = reduce_result.first assert_equal 106, complexity end end end describe "field_complexity hook" do class CustomComplexityAnalyzer < GraphQL::Analysis::QueryComplexity def initialize(query) super @field_complexities_by_query = {} end def result super @field_complexities_by_query[@query] end private def field_complexity(scoped_type_complexity, max_complexity:, child_complexity:) @field_complexities_by_query[scoped_type_complexity.query] ||= {} @field_complexities_by_query[scoped_type_complexity.query][scoped_type_complexity.response_path] = { max_complexity: max_complexity, child_complexity: child_complexity, } end end let(:reduce_result) { GraphQL::Analysis.analyze_query(query, [CustomComplexityAnalyzer]) } let(:query_string) {%| { cheese { id } cheese { id flavor } } |} it "gets called for each field with complexity data" do field_complexities = reduce_result.first assert_equal({ ['cheese', 'id'] => { max_complexity: 1, child_complexity: 0 }, ['cheese', 'flavor'] => { max_complexity: 1, child_complexity: 0 }, ['cheese'] => { max_complexity: 3, child_complexity: 2 }, }, field_complexities) end end describe "maximum of possible scopes regardless of selection order" do class MaxOfPossibleScopes < GraphQL::Schema class Cheese < GraphQL::Schema::Object field :kind, String end module Producer include GraphQL::Schema::Interface field :cheese, Cheese, complexity: 5 field :name, String, complexity: 5 end class Farm < GraphQL::Schema::Object implements Producer field :cheese, Cheese, complexity: 10 field :name, String, complexity: 10 end class Entity < GraphQL::Schema::Union possible_types Farm end class Query < GraphQL::Schema::Object field :entity, Entity, fallback_value: nil end def self.resolve_type Farm end def self.cost(query_string_or_query) query = if query_string_or_query.is_a?(String) GraphQL::Query.new(self, query_string_or_query) else query_string_or_query end GraphQL::Analysis::AST.analyze_query( query, [GraphQL::Analysis::AST::QueryComplexity], ).first end query(Query) end describe "in :future mode" do let(:schema) { Class.new(MaxOfPossibleScopes) { complexity_cost_calculation_mode(:future) }} it "uses maximum of merged composite fields, regardless of selection order" do a = schema.cost(%| { entity { ...on Producer { cheese { kind } } ...on Farm { cheese { kind } } } } |) b = schema.cost(%| { entity { ...on Farm { cheese { kind } } ...on Producer { cheese { kind } } } } |) assert_equal 0, a - b end it "uses maximum of merged leaf fields, regardless of selection order" do a = schema.cost(%| { entity { ...on Producer { name } ...on Farm { name } } } |) b = schema.cost(%| { entity { ...on Farm { name } ...on Producer { name } } } |) assert_equal 0, a - b end end describe "in :legacy mode" do let(:schema) { Class.new(MaxOfPossibleScopes) { complexity_cost_calculation_mode(:legacy) }} it "uses the last of merged composite fields" do a = schema.cost(%| { entity { ...on Producer { cheese { kind } } ...on Farm { cheese { kind } } } } |) b = schema.cost(%| { entity { ...on Farm { cheese { kind } } ...on Producer { cheese { kind } } } } |) assert_equal 5, a - b end it "uses the last-occurring leaf field" do a = schema.cost(%| { entity { ...on Producer { name } ...on Farm { name } } } |) b = schema.cost(%| { entity { ...on Farm { name } ...on Producer { name } } } |) assert_equal 5, a - b end end describe "In dynamic mode with :compare" do let(:schema) { Class.new(MaxOfPossibleScopes) do def self.complexity_cost_calculation_mode_for(context) :compare end def self.legacy_complexity_cost_calculation_mismatch(query, future_cpx, legacy_cpx) query.context.response_extensions["complexity_warning"] = { "current" => legacy_cpx, "future" => future_cpx } 1003 end end } it "calls the handler and uses the returned value" do query = GraphQL::Query.new(schema, %| { entity { ...on Producer { cheese { kind } } ...on Farm { cheese { kind } } } } |) a = schema.cost(query) assert_equal 12, a refute query.result.to_h.key?("extensions") queryb = GraphQL::Query.new(schema, %| { entity { ...on Farm { cheese { kind } } ...on Producer { cheese { kind } } } } |) b = schema.cost(queryb) assert_equal 1003, b assert_equal({"complexity_warning" => {"current" => 7, "future" => 12}}, queryb.result.to_h["extensions"]) end it "calls the custom handler when leaf fields don't match" do a = schema.cost(%| { entity { ...on Producer { name } ...on Farm { name } } } |) assert_equal 11, a b = schema.cost(%| { entity { ...on Farm { name } ...on Producer { name } } } |) assert_equal 1003, b end end describe "without a mode setting" do it "warns, and invalid mismatched scope types will still compute without error" do cost = nil stdout, _stderr = capture_io do cost = MaxOfPossibleScopes.cost(%| { entity { ...on Farm { cheese { kind } } ...on Producer { cheese: name } } } |) end assert_equal 12, cost assert_includes stdout, "GraphQL-Ruby's complexity cost system is getting some \"breaking fixes\" in a future version. See the migration notes at https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#complexity_cost_calculation_mode_for-class_method To opt into the future behavior, configure your schema (MaxOfPossibleScopes) with: complexity_cost_calculation_mode(:future) # or `:legacy`, `:compare`" end it "uses legacy mode" do cost = nil assert_nil MaxOfPossibleScopes.complexity_cost_calculation_mode stdout, _stderr = capture_io do cost = MaxOfPossibleScopes.cost(%| { entity { ...on Farm { name } ...on Producer { name } } } |) end puts stdout assert_equal 6, cost assert_includes stdout, "GraphQL-Ruby's complexity cost system is getting some \"breaking fixes\" in a future version. See the migration notes at https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#complexity_cost_calculation_mode_for-class_method To opt into the future behavior, configure your schema (MaxOfPossibleScopes) with: complexity_cost_calculation_mode(:future) # or `:legacy`, `:compare`" 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/analysis/max_query_depth_spec.rb
spec/graphql/analysis/max_query_depth_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Analysis::MaxQueryDepth do let(:schema) { schema = Class.new(Dummy::Schema) schema.analysis_engine = GraphQL::Analysis::AST schema } let(:query_string) { " { cheese(id: 1) { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { id } } } } } } } "} let(:max_depth) { nil } let(:query) { # Don't override `schema.max_depth` with `nil` options = max_depth ? { max_depth: max_depth } : {} GraphQL::Query.new( schema, query_string, variables: {}, **options ) } let(:result) { GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::MaxQueryDepth]).first } let(:multiplex) { GraphQL::Execution::Multiplex.new( schema: schema, queries: [query.dup, query.dup], context: {}, max_complexity: nil ) } let(:multiplex_result) { GraphQL::Analysis.analyze_multiplex(multiplex, [GraphQL::Analysis::MaxQueryDepth]).first } describe "when the query is deeper than max depth" do let(:max_depth) { 5 } it "adds an error message for a too-deep query" do assert_equal "Query has depth of 7, which exceeds max depth of 5", result.message end end describe "when a multiplex queries is deeper than max depth" do before do schema.max_depth = 5 end it "adds an error message for a too-deep query on from multiplex analyzer" do assert_equal "Query has depth of 7, which exceeds max depth of 5", multiplex_result.message end end describe "when the query specifies a different max_depth" do let(:max_depth) { 100 } it "obeys that max_depth" do assert_nil result end end describe "When the query is not deeper than max_depth" do before do schema.max_depth = 100 end it "doesn't add an error" do assert_nil result end end describe "when the max depth isn't set" do before do schema.max_depth = nil end it "doesn't add an error message" do assert_nil result end end describe "when a fragment exceeds max depth" do before do schema.max_depth = 4 end let(:query_string) { " { cheese(id: 1) { ...moreFields } } fragment moreFields on Cheese { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { ...evenMoreFields } } } } fragment evenMoreFields on Cheese { similarCheese(source: SHEEP) { similarCheese(source: SHEEP) { id } } } "} it "adds an error message for a too-deep query" do assert_equal "Query has depth of 7, which exceeds max depth of 4", result.message end end describe "when the query would cause a stack error" do let(:query_string) { str = "query { cheese(id: 1) { ".dup n = 10_000 n.times { str << "similarCheese(source: SHEEP) { " } str << "id " n.times { str << "} " } str << "} }" str } it "returns an error" do assert_equal ["This query is too large to execute."], query.result["errors"].map { |err| err["message"] } # Make sure `Schema.execute` works too execute_result = schema.execute(query_string) assert_equal ["This query is too large to execute."], execute_result["errors"].map { |err| err["message"] } end end it "counts introspection fields by default, but can be set to skip" do schema.max_depth = 3 query_str = <<-GRAPHQL { __type(name: \"Abc\") { fields { type { ofType { name } } } } } GRAPHQL result = schema.execute(query_str) assert_equal ["Query has depth of 5, which exceeds max depth of 3"], result["errors"].map { |e| e["message"] } schema.max_depth(3, count_introspection_fields: false) result = schema.execute(query_str) assert_equal({ "__type" => nil }, result["data"]) 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/analysis/field_usage_spec.rb
spec/graphql/analysis/field_usage_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Analysis::FieldUsage do let(:result) { GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::FieldUsage]).first } let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables) } let(:variables) { {} } describe "query with deprecated fields" do let(:query_string) {%| query { cheese(id: 1) { id fatContent } } |} it "keeps track of used fields" do assert_equal ['Cheese.id', 'Cheese.fatContent', 'Query.cheese'], result[:used_fields] end it "keeps track of deprecated fields" do assert_equal ['Cheese.fatContent'], result[:used_deprecated_fields] end end describe "query with deprecated fields used more than once" do let(:query_string) {%| query { cheese1: cheese(id: 1) { id fatContent } cheese2: cheese(id: 2) { id fatContent } } |} it "omits duplicate usage of a field" do assert_equal ['Cheese.id', 'Cheese.fatContent', 'Query.cheese'], result[:used_fields] end it "omits duplicate usage of a deprecated field" do assert_equal ['Cheese.fatContent'], result[:used_deprecated_fields] end end describe "query with deprecated fields in a fragment" do let(:query_string) {%| query { cheese(id: 1) { id ...CheeseSelections } } fragment CheeseSelections on Cheese { fatContent } |} it "keeps track of fields used in the fragment" do assert_equal ['Cheese.id', 'Cheese.fatContent', 'Query.cheese'], result[:used_fields] end it "keeps track of deprecated fields used in the fragment" do assert_equal ['Cheese.fatContent'], result[:used_deprecated_fields] end end describe "query with deprecated fields in an inline fragment" do let(:query_string) {%| query { cheese(id: 1) { id ... on Cheese { fatContent } } } |} it "keeps track of fields used in the fragment" do assert_equal ['Cheese.id', 'Cheese.fatContent', 'Query.cheese'], result[:used_fields] end it "keeps track of deprecated fields used in the fragment" do assert_equal ['Cheese.fatContent'], result[:used_deprecated_fields] end end describe "query with deprecated arguments" do let(:query_string) {%| query { fromSource(oldSource: "deprecated") { id } } |} it "keeps track of deprecated arguments" do assert_equal ['Query.fromSource.oldSource'], result[:used_deprecated_arguments] end end describe "query with deprecated arguments used more than once" do let(:query_string) {%| query { fromSource(oldSource: "deprecated1") { id } fromSource(oldSource: "deprecated2") { id } } |} it "omits duplicate usage of a deprecated argument" do assert_equal ['Query.fromSource.oldSource'], result[:used_deprecated_arguments] end end describe "query with deprecated arguments nested in an array argument" do let(:query_string) {%| query { searchDairy(product: [{ oldSource: "deprecated" }]) { __typename } } |} it "keeps track of nested deprecated arguments" do assert_equal ['DairyProductInput.oldSource'], result[:used_deprecated_arguments] end end describe "query with deprecated enum argument" do let(:query_string) {%| query { fromSource(source: YAK) { id } } |} it "keeps track of deprecated arguments" do assert_equal ['DairyAnimal.YAK'], result[:used_deprecated_enum_values] end describe "tracks non-null/list enums" do let(:query_string) {%| query { cheese(id: 1) { similarCheese(source: [YAK]) { id } } } |} it "keeps track of deprecated arguments" do assert_equal ['DairyAnimal.YAK'], result[:used_deprecated_enum_values] end end end describe "query with an array argument sent as null" do let(:query_string) {%| query { searchDairy(product: null) { __typename } } |} it "tolerates null for array argument" do result end end describe "query with an input object sent in as null" do let(:query_string) {%| query { cheese(id: 1) { id dairyProduct(input: null) { __typename } } } |} it "tolerates null for object argument" do result end end describe "query with deprecated arguments nested in an argument" do let(:query_string) {%| query { searchDairy(singleProduct: { oldSource: "deprecated" }) { __typename } } |} it "keeps track of nested deprecated arguments" do assert_equal ['DairyProductInput.oldSource'], result[:used_deprecated_arguments] end end describe "query with arguments nested in a deprecated argument" do let(:query_string) {%| query { searchDairy(oldProduct: [{ source: "sheep" }]) { __typename } } |} it "keeps track of top-level deprecated arguments" do assert_equal ['Query.searchDairy.oldProduct'], result[:used_deprecated_arguments] end end describe "query with scalar arguments nested in a deprecated argument" do let(:query_string) {%| query { searchDairy(productIds: ["123"]) { __typename } } |} it "keeps track of top-level deprecated arguments" do assert_equal ['Query.searchDairy.productIds'], result[:used_deprecated_arguments] end end describe "mutation with deprecated argument" do let(:query_string) {%| mutation { pushValue(deprecatedTestInput: { oldSource: "deprecated" }) } |} it "keeps track of nested deprecated arguments" do assert_equal ['DairyProductInput.oldSource'], result[:used_deprecated_arguments] end end describe "mutation with deprecated arguments with prepared values" do let(:query_string) {%| mutation { pushValue(preparedTestInput: { deprecatedDate: "2020-10-10" }) } |} it "keeps track of nested deprecated arguments" do assert_equal ['PreparedDateInput.deprecatedDate'], result[:used_deprecated_arguments] end end describe "when an argument prepare raises a GraphQL::ExecutionError" do class ArgumentErrorFieldUsageSchema < GraphQL::Schema class FieldUsage < GraphQL::Analysis::FieldUsage def result values = super query.context[:field_usage] = values nil end end class Query < GraphQL::Schema::Object field :f, Int do argument :i, Int, prepare: ->(*) { raise GraphQL::ExecutionError.new("boom!") } end end query(Query) query_analyzer(FieldUsage) end it "skips analysis of those arguments" do res = ArgumentErrorFieldUsageSchema.execute("{ f(i: 1) }") assert_equal ["boom!"], res["errors"].map { |e| e["message"] } assert_equal({used_fields: ["Query.f"], used_deprecated_arguments: [], used_deprecated_fields: [], used_deprecated_enum_values: []}, res.context[:field_usage]) 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/analysis/query_depth_spec.rb
spec/graphql/analysis/query_depth_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Analysis::QueryDepth do let(:result) { GraphQL::Analysis.analyze_query(query, [GraphQL::Analysis::QueryDepth]) } let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables) } let(:variables) { {} } describe "multiple operations" do let(:query_string) {%| query Cheese1 { cheese1: cheese(id: 1) { id flavor } } query Cheese2 { cheese(id: 2) { similarCheese(source: SHEEP) { ... on Cheese { similarCheese(source: SHEEP) { id } } } } } |} let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables, operation_name: "Cheese1") } it "analyzes the selected operation only" do depth = result.first assert_equal 2, depth end end describe "simple queries" do let(:query_string) {%| query cheeses($isIncluded: Boolean = true){ # depth of 2 cheese1: cheese(id: 1) { id flavor } # depth of 4 cheese2: cheese(id: 2) @include(if: $isIncluded) { similarCheese(source: SHEEP) { ... on Cheese { similarCheese(source: SHEEP) { id } } } } } |} it "finds the max depth" do depth = result.first assert_equal 4, depth end describe "with directives" do let(:variables) { { "isIncluded" => false } } it "doesn't count skipped fields" do assert_equal 2, result.first end end end describe "query with fragments" do let(:query_string) {%| { # depth of 2 cheese1: cheese(id: 1) { id flavor } # depth of 4 cheese2: cheese(id: 2) { ... cheeseFields1 } } fragment cheeseFields1 on Cheese { similarCheese(source: COW) { id ... cheeseFields2 } } fragment cheeseFields2 on Cheese { similarCheese(source: SHEEP) { id } } |} it "finds the max depth" do assert_equal 4, result.first 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/types/id_spec.rb
spec/graphql/types/id_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::ID do let(:result) { Dummy::Schema.execute(query_string)} describe "coercion for int inputs" do let(:query_string) { %|query getMilk { cow: milk(id: 1) { id } }| } it "coerces IDs from ints and serializes as strings" do expected = {"data" => {"cow" => {"id" => "1"}}} assert_equal(expected, result) end end describe "coercion for string inputs" do let(:query_string) { %|query getMilk { cow: milk(id: "1") { id } }| } it "coerces IDs from strings and serializes as strings" do expected = {"data" => {"cow" => {"id" => "1"}}} assert_equal(expected, result) end end describe "coercion for float" do let(:query_string) { %|query getMilk { cow: milk(id: 1.0) { id } }| } it "results in an error" do assert_nil result["data"] assert_equal 1, result["errors"].length end end describe "coercion for enum values" do let(:query_string) { %|query getMilk { milk(id: dairy_rocks) { id } }|} it "results in an error" do assert_nil result["data"] assert_equal 1, result["errors"].length 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/types/big_int_spec.rb
spec/graphql/types/big_int_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::BigInt do it "encodes big and small integers as strings" do big_integer_1 = 99**99 expected_str_1 = "369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899" assert_equal expected_str_1, GraphQL::Types::BigInt.coerce_result(big_integer_1, nil) assert_equal big_integer_1, GraphQL::Types::BigInt.coerce_input(expected_str_1, nil) big_integer_2 = -(88**88) expected_str_2 = "-1301592834942972055182648307417315364538725075960067827915311484722452340966317215805106820959190833309704934346517741237438752456673499160125624414995891111204155079786496" assert_equal expected_str_2, GraphQL::Types::BigInt.coerce_result(big_integer_2, nil) assert_equal big_integer_2, GraphQL::Types::BigInt.coerce_input(expected_str_2, nil) assert_equal "31", GraphQL::Types::BigInt.coerce_result(31, nil) assert_equal(-17, GraphQL::Types::BigInt.coerce_input("-17", nil)) end it "returns `nil` for invalid inputs" do assert_nil GraphQL::Types::BigInt.coerce_input("xyz", nil) assert_nil GraphQL::Types::BigInt.coerce_input("2.2", nil) end it 'returns `nil` for nil' do assert_nil GraphQL::Types::BigInt.coerce_input(nil, nil) end it 'parses integers with base 10' do number_string = "01000" assert_equal 1000, GraphQL::Types::BigInt.coerce_input(number_string, 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/graphql/types/string_spec.rb
spec/graphql/types/string_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::String do let(:string_type) { GraphQL::Types::String } it "is a default scalar" do assert_equal(true, string_type.default_scalar?) end describe "coerce_result" do let(:utf_8_str) { "foobar" } let(:ascii_str) { "foobar".encode(Encoding::ASCII_8BIT) } let(:binary_str) { "\0\0\0foo\255\255\255".dup.force_encoding("BINARY") } describe "encoding" do subject { string_type.coerce_isolated_result(string) } describe "when result is encoded as UTF-8" do let(:string) { utf_8_str } it "returns the string" do assert_equal subject, string end end describe "when the result is not UTF-8 but can be transcoded" do let(:string) { ascii_str } it "returns the string transcoded to UTF-8" do assert_equal subject, string.encode(Encoding::UTF_8) end end describe "when the result is not UTF-8 and cannot be transcoded" do let(:string) { binary_str } it "raises GraphQL::StringEncodingError" do err = assert_raises(GraphQL::StringEncodingError) { subject } assert_equal "String \"\\x00\\x00\\x00foo\\xAD\\xAD\\xAD\" was encoded as ASCII-8BIT. GraphQL requires an encoding compatible with UTF-8.", err.message assert_equal string, err.string end end describe "In queries" do let(:schema) { query_type = Class.new(GraphQL::Schema::Object) do graphql_name "Query" field :bad_string, String def bad_string "\0\0\0foo\255\255\255".dup.force_encoding("BINARY") end end Class.new(GraphQL::Schema) do query(query_type) end } it "includes location in the error message" do err = assert_raises GraphQL::StringEncodingError do schema.execute("{ badString }") end expected_err = "String \"\\x00\\x00\\x00foo\\xAD\\xAD\\xAD\" was encoded as ASCII-8BIT @ badString (Query.badString). GraphQL requires an encoding compatible with UTF-8." assert_equal expected_err, err.message end end end describe "when the schema defines a custom handler" do let(:schema) { Class.new(GraphQL::Schema) do def self.type_error(err, ctx) ctx.errors << err "🌾" end end } let(:context) { OpenStruct.new(schema: schema, errors: []) } it "calls the handler" do assert_equal "🌾", string_type.coerce_result(binary_str, context) err = context.errors.last assert_instance_of GraphQL::StringEncodingError, err end end end describe "coerce_input" do it "accepts strings" do assert_equal "str", string_type.coerce_isolated_input("str") end it "doesn't accept other types" do assert_nil string_type.coerce_isolated_input(100) assert_nil string_type.coerce_isolated_input(true) assert_nil string_type.coerce_isolated_input(0.999) end end describe "unicode escapes" do class UnicodeEscapeSchema < GraphQL::Schema class QueryType < GraphQL::Schema::Object field :get_string, String do argument :string, String end def get_string(string:) string end end query(QueryType) end it "parses escapes properly in single-quoted strings" do query_str = File.read("./spec/fixtures/unicode_escapes/query1.graphql") res = UnicodeEscapeSchema.execute(query_str) assert_equal "d", res["data"]["example1"] assert_equal "\\u0064", res["data"]["example2"] assert_equal "\\u006", res["data"]["example4"] error_query_str = query_str.gsub(" # ", " ") res2 = UnicodeEscapeSchema.execute(error_query_str) expected_err = if USING_C_PARSER "syntax error, unexpected invalid token (\"\\\"\") at [4, 31]" else "Expected string or block string, but it was malformed" end assert_equal [expected_err], res2["errors"].map { |err| err["message"] } end it "parses escapes properly in triple-quoted strings" do query_str = File.read("./spec/fixtures/unicode_escapes/query2.graphql") res = UnicodeEscapeSchema.execute(query_str) # No replacing in block strings: assert_equal "\\a", res["data"]["example1"] assert_equal "\\u006", res["data"]["example2"] assert_equal "\\n", res["data"]["example3"] assert_equal "\\u0064", res["data"]["example4"] 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/types/int_spec.rb
spec/graphql/types/int_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Int do describe "coerce_input" do it "accepts ints within the bounds" do assert_equal(-(2**31), GraphQL::Types::Int.coerce_isolated_input(-(2**31))) assert_equal 1, GraphQL::Types::Int.coerce_isolated_input(1) assert_equal (2**31)-1, GraphQL::Types::Int.coerce_isolated_input((2**31)-1) end it "rejects other types and ints outside the bounds" do assert_nil GraphQL::Types::Int.coerce_isolated_input("55") assert_nil GraphQL::Types::Int.coerce_isolated_input(true) assert_nil GraphQL::Types::Int.coerce_isolated_input(6.1) assert_nil GraphQL::Types::Int.coerce_isolated_input(2**31) assert_nil GraphQL::Types::Int.coerce_isolated_input(-(2**31 + 1)) end describe "handling boundaries" do let(:context) { GraphQL::Query.new(Dummy::Schema, "{ __typename }").context } it "accepts result values in bounds" do assert_equal 0, GraphQL::Types::Int.coerce_result(0, context) assert_equal (2**31) - 1, GraphQL::Types::Int.coerce_result((2**31) - 1, context) assert_equal(-(2**31), GraphQL::Types::Int.coerce_result(-(2**31), context)) end it "replaces values, if configured to do so" do assert_equal Dummy::Schema::MAGIC_INT_COERCE_VALUE, GraphQL::Types::Int.coerce_result(99**99, context) end it "raises on values out of bounds" do err_ctx = GraphQL::Query.new(Dummy::Schema, "{ __typename }").context assert_raises(GraphQL::IntegerEncodingError) { GraphQL::Types::Int.coerce_result(2**31, err_ctx) } err = assert_raises(GraphQL::IntegerEncodingError) { GraphQL::Types::Int.coerce_result(-(2**31 + 1), err_ctx) } assert_equal "Integer out of bounds: -2147483649. Consider using ID or GraphQL::Types::BigInt instead.", err.message err = assert_raises GraphQL::IntegerEncodingError do Dummy::Schema.execute("{ hugeInteger }") end expected_err = "Integer out of bounds: 2147483648 @ hugeInteger (Query.hugeInteger). Consider using ID or GraphQL::Types::BigInt instead." assert_equal expected_err, err.message 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/types/float_spec.rb
spec/graphql/types/float_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Float do let(:enum) { GraphQL::Language::Nodes::Enum.new(name: 'MILK') } describe "coerce_input" do it "accepts ints and floats" do assert_equal 1.0, GraphQL::Types::Float.coerce_isolated_input(1) assert_equal 6.1, GraphQL::Types::Float.coerce_isolated_input(6.1) end it "rejects other types" do assert_nil GraphQL::Types::Float.coerce_isolated_input("55") assert_nil GraphQL::Types::Float.coerce_isolated_input(true) assert_nil GraphQL::Types::Float.coerce_isolated_input(enum) 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/types/iso_8601_date_spec.rb
spec/graphql/types/iso_8601_date_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::ISO8601Date do module DateTest class DateObject < GraphQL::Schema::Object field :year, Integer, null: false field :month, Integer, null: false field :day, Integer, null: false field :iso8601, GraphQL::Types::ISO8601Date, null: false, method: :itself end class Query < GraphQL::Schema::Object field :parse_date, DateObject do argument :date, GraphQL::Types::ISO8601Date end field :parse_date_optional, DateObject do argument :date, GraphQL::Types::ISO8601Date, required: false end field :parse_date_time, DateObject do argument :date, GraphQL::Types::ISO8601Date end field :parse_date_string, DateObject do argument :date, GraphQL::Types::ISO8601Date end field :parse_date_time_string, DateObject do argument :date, GraphQL::Types::ISO8601Date end field :serialize_date_default_argument, DateObject do argument( :date, GraphQL::Types::ISO8601Date, required: false, default_value: Date.today ) end field :serialize_date_time_default_argument, DateObject do argument( :date, GraphQL::Types::ISO8601Date, required: false, default_value: DateTime.now ) end field :serialize_time_default_argument, DateObject do argument( :date, GraphQL::Types::ISO8601Date, required: false, default_value: Time.now ) end field :serialize_string_default_argument, DateObject do argument( :date, GraphQL::Types::ISO8601Date, required: false, default_value: '1951-09-23' ) end def parse_date(date:) # Resolve a Date object Date.parse(date.iso8601) end def parse_date_optional(date:) return unless date Date.parse(date.iso8601) end def parse_date_time(date:) # Resolve a DateTime object DateTime.parse(date.iso8601) end def parse_date_string(date:) # Resolve a Date string Date.parse(date.iso8601).iso8601 end def parse_date_time_string(date:) # Resolve a DateTime string DateTime.parse(date.iso8601).iso8601 end def serialize_date_default_argument(date:) date end def serialize_date_time_default_argument(date:) date end def serialize_time_default_argument(date:) date end def serialize_string_default_argument(date:) date end end class Schema < GraphQL::Schema query(Query) def self.type_error(err, ctx) if ctx[:raise_type_error] raise GraphQL::ExecutionError, "A type error was raised: #{err}" else super end end end end describe "as an input" do def parse_date(date_str, context: {}) query_str = <<-GRAPHQL query($date: ISO8601Date!){ parseDate(date: $date) { year month day } } GRAPHQL full_res = DateTest::Schema.execute(query_str, context: context, variables: { date: date_str }) full_res["errors"] || full_res["data"]["parseDate"] end it "parses valid dates" do res = parse_date("2018-06-07") expected_res = { "year" => 2018, "month" => 6, "day" => 7, } assert_equal(expected_res, res) end it "adds an error for invalid dates" do expected_errors = ["Variable $date of type ISO8601Date! was provided invalid value"] assert_equal expected_errors, parse_date("2018-26-07").map { |e| e["message"] } assert_equal expected_errors, parse_date("xyz").map { |e| e["message"] } assert_equal expected_errors, parse_date(nil).map { |e| e["message"] } assert_equal expected_errors, parse_date([1, 2, 3]).map { |e| e["message"] } assert_equal "A type error was raised: Date cannot be parsed: blah. \nDate must be able to be parsed as a Ruby Date object.", parse_date("blah", context: { raise_type_error: true })[0]["extensions"]["problems"][0]["explanation"].strip assert_equal "Could not coerce value \"blah\" to ISO8601Date", parse_date("blah", context: { raise_type_error: false })[0]["extensions"]["problems"][0]["explanation"] end it "handles array inputs gracefully" do query_str = <<-GRAPHQL { parseDate(date: ["A", "B", "C"]) { year } } GRAPHQL res = DateTest::Schema.execute(query_str) expected_message = "Argument 'date' on Field 'parseDate' has an invalid value ([\"A\", \"B\", \"C\"]). Expected type 'ISO8601Date!'." assert_equal expected_message, res["errors"].first["message"] end it "handles null gracefully" do query_str = <<-GRAPHQL { parseDateOptional(date: null) { year } } GRAPHQL res = DateTest::Schema.execute(query_str) expected_res = { "parseDateOptional" => nil } assert_equal(expected_res, res["data"]) assert_nil(res["errors"]) res = DateTest::Schema.execute(query_str, context: { raise_type_error: true }) expected_res = { "parseDateOptional" => nil } assert_equal(expected_res, res["data"]) assert_nil(res["errors"]) end end describe "as an argument default value" do it 'serializes a Date object as an ISO8601 Date string' do query_str = <<-GRAPHQL query { serializeDateDefaultArgument { iso8601 } } GRAPHQL full_res = DateTest::Schema.execute(query_str) date_str = Date.today.iso8601 assert_equal date_str, full_res["data"]["serializeDateDefaultArgument"]["iso8601"] end it 'serializes a DateTime object as an ISO8601 Date string' do query_str = <<-GRAPHQL query { serializeDateTimeDefaultArgument { iso8601 } } GRAPHQL full_res = DateTest::Schema.execute(query_str) date_str = DateTime.now.to_date.iso8601 assert_equal date_str, full_res["data"]["serializeDateTimeDefaultArgument"]["iso8601"] end it 'serializes a Time object as an ISO8601 Date string' do query_str = <<-GRAPHQL query { serializeTimeDefaultArgument { iso8601 } } GRAPHQL full_res = DateTest::Schema.execute(query_str) date_str = Time.new.to_date.iso8601 assert_equal date_str, full_res["data"]["serializeTimeDefaultArgument"]["iso8601"] end it 'serializes a string object as an ISO8601 Date string' do query_str = <<-GRAPHQL query { serializeStringDefaultArgument { iso8601 } } GRAPHQL full_res = DateTest::Schema.execute(query_str) date_str = '1951-09-23' assert_equal date_str, full_res["data"]["serializeStringDefaultArgument"]["iso8601"] end end describe "as an output" do let(:date_str) { "2010-02-02" } let(:query_str) do <<-GRAPHQL query($date: ISO8601Date!){ parseDate(date: $date) { iso8601 } parseDateTime(date: $date) { iso8601 } parseDateString(date: $date) { iso8601 } parseDateTimeString(date: $date) { iso8601 } } GRAPHQL end let(:full_res) { DateTest::Schema.execute(query_str, variables: { date: date_str }) } it 'serializes a Date object as an ISO8601 Date string' do assert_equal date_str, full_res["data"]["parseDate"]["iso8601"] end it 'serializes a DateTime object as an ISO8601 Date string' do assert_equal date_str, full_res["data"]["parseDateTime"]["iso8601"] end it 'serializes a Date string as an ISO8601 Date string' do assert_equal date_str, full_res["data"]["parseDateString"]["iso8601"] end it 'serializes a DateTime string as an ISO8601 Date string' do assert_equal date_str, full_res["data"]["parseDateTimeString"]["iso8601"] end end describe "structure" do it "is in introspection" do introspection_res = DateTest::Schema.execute <<-GRAPHQL { __type(name: "ISO8601Date") { name kind } } GRAPHQL expected_res = { "name" => "ISO8601Date", "kind" => "SCALAR"} assert_graphql_equal expected_res, introspection_res["data"]["__type"] 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/types/boolean_spec.rb
spec/graphql/types/boolean_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Boolean do describe "coerce_input" do def coerce_input(input) GraphQL::Types::Boolean.coerce_isolated_input(input) end it "accepts true and false" do assert_equal true, coerce_input(true) assert_equal false, coerce_input(false) end it "rejects other types" do assert_nil coerce_input("true") assert_nil coerce_input(5.5) assert_nil coerce_input(nil) 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/types/iso_8601_date_time_spec.rb
spec/graphql/types/iso_8601_date_time_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::ISO8601DateTime do module DateTimeTest class DateTimeObject < GraphQL::Schema::Object field :year, Integer, null: false field :month, Integer, null: false field :day, Integer, null: false field :hour, Integer, null: false field :minute, Integer, method: :min, null: false field :second, Integer, method: :sec, null: false field :zone, String field :utc_offset, Integer, null: false field :iso8601, GraphQL::Types::ISO8601DateTime, null: false, method: :itself end class Query < GraphQL::Schema::Object field :parse_date, DateTimeObject do argument :date, GraphQL::Types::ISO8601DateTime end field :parse_date_time, DateTimeObject do argument :date, GraphQL::Types::ISO8601DateTime end field :parse_date_string, DateTimeObject do argument :date, GraphQL::Types::ISO8601DateTime end field :parse_date_time_string, DateTimeObject do argument :date, GraphQL::Types::ISO8601DateTime end field :invalid_date, DateTimeObject, null: false def parse_date(date:) # Resolve a Date object Date.parse(date.iso8601) end def parse_date_time(date:) # Resolve a Time object Time.parse(date.iso8601(3)) end def parse_date_string(date:) # Resolve a Date string Date.parse(date.iso8601).iso8601 end def parse_date_time_string(date:) # Resolve a DateTime string DateTime.parse(date.iso8601).iso8601 end def invalid_date 'abc' end end class Schema < GraphQL::Schema query(Query) end end describe "as an input" do def parse_date(date_str) query_str = <<-GRAPHQL query($date: ISO8601DateTime!){ parseDateTime(date: $date) { year month day hour minute second zone utcOffset } } GRAPHQL full_res = DateTimeTest::Schema.execute(query_str, variables: { date: date_str }) full_res["errors"] || full_res["data"]["parseDateTime"] end it "parses valid dates" do res = parse_date("2018-06-07T09:31:42-07:00") expected_res = { "year" => 2018, "month" => 6, "day" => 7, "hour" => 9, "minute" => 31, "second" => 42, "zone" => nil, "utcOffset" => -25200, } assert_equal(expected_res, res) end it "parses valid dates with a timezone" do res = parse_date("2018-06-07T09:31:42Z") expected_res = { "year" => 2018, "month" => 6, "day" => 7, "hour" => 9, "minute" => 31, "second" => 42, "zone" => "UTC", "utcOffset" => 0, } assert_equal(expected_res, res) end it "parses dates without times" do res = parse_date("2018-06-07") # It uses the system default timezone when none is given system_default_tz = Date.iso8601("2018-06-07").to_time.zone system_default_offset = Date.iso8601("2018-06-07").to_time.utc_offset expected_res = { "year" => 2018, "month" => 6, "day" => 7, "hour" => 0, "minute" => 0, "second" => 0, "zone" => system_default_tz, "utcOffset" => system_default_offset, } assert_equal(expected_res, res) end it "parses dates without times or dashes" do res = parse_date("20180827") # It uses the system default timezone when none is given system_default_tz = Date.iso8601("2018-08-27").to_time.zone system_default_offset = Date.iso8601("2018-08-27").to_time.utc_offset expected_res = { "year" => 2018, "month" => 8, "day" => 27, "hour" => 0, "minute" => 0, "second" => 0, "zone" => system_default_tz, "utcOffset" => system_default_offset, } assert_equal(expected_res, res) end it "rejects partial times" do expected_errors = ["Variable $date of type ISO8601DateTime! was provided invalid value"] assert_equal expected_errors, parse_date("2018-06-07T12:12").map { |e| e["message"] } assert_equal expected_errors, parse_date("2018-06-07T12").map { |e| e["message"] } end it "adds an error for invalid dates" do expected_errors = ["Variable $date of type ISO8601DateTime! was provided invalid value"] assert_equal expected_errors, parse_date("2018-99-07T99:31:42Z").map { |e| e["message"] } assert_equal expected_errors, parse_date("xyz").map { |e| e["message"] } assert_equal expected_errors, parse_date(nil).map { |e| e["message"] } assert_equal expected_errors, parse_date([1,2,3]).map { |e| e["message"] } end it "handles array inputs gracefully" do query_str = <<-GRAPHQL { parseDateTime(date: ["A", "B", "C"]) { year } } GRAPHQL res = DateTimeTest::Schema.execute(query_str) expected_message = "Argument 'date' on Field 'parseDateTime' has an invalid value ([\"A\", \"B\", \"C\"]). Expected type 'ISO8601DateTime!'." assert_equal expected_message, res["errors"].first["message"] end end describe "as an output" do let(:date_str) { "2010-02-02T22:30:30-06:00" } let(:date_str_midnight) { Time.parse(Date.parse(date_str).iso8601).iso8601 } let(:query_str) do <<-GRAPHQL query($date: ISO8601DateTime!){ parseDate(date: $date) { iso8601 } parseDateTime(date: $date) { iso8601 } parseDateString(date: $date) { iso8601 } parseDateTimeString(date: $date) { iso8601 } } GRAPHQL end let(:full_res) { DateTimeTest::Schema.execute(query_str, variables: { date: date_str }) } it 'serializes a Date object as an ISO8601 DateTime string' do assert_equal date_str_midnight, full_res["data"]["parseDate"]["iso8601"] end it 'serializes a DateTime object as an ISO8601 DateTime string' do assert_equal date_str, full_res["data"]["parseDateTime"]["iso8601"] end it 'serializes a Date string as an ISO8601 DateTime string' do assert_equal date_str_midnight, full_res["data"]["parseDateString"]["iso8601"] end it 'serializes a DateTime string as an ISO8601 DateTime string' do assert_equal date_str, full_res["data"]["parseDateTimeString"]["iso8601"] end describe "with time_precision = 3 (i.e. 'with milliseconds')" do before do @tp = GraphQL::Types::ISO8601DateTime.time_precision GraphQL::Types::ISO8601DateTime.time_precision = 3 end after do GraphQL::Types::ISO8601DateTime.time_precision = @tp end it "returns a string" do query_str = <<-GRAPHQL query($date: ISO8601DateTime!){ parseDateTime(date: $date) { iso8601 } } GRAPHQL date_str = "2010-02-02T22:30:30.123-06:00" full_res = DateTimeTest::Schema.execute(query_str, variables: { date: date_str }) assert_equal date_str, full_res["data"]["parseDateTime"]["iso8601"] end end describe "with Date value" do it "raises an error" do query_str = <<-GRAPHQL query { invalidDate { iso8601 } } GRAPHQL err = assert_raises(GraphQL::Error) do DateTimeTest::Schema.execute(query_str) end assert_equal err.message, 'An incompatible object (String) was given to GraphQL::Types::ISO8601DateTime. Make sure that only Times, Dates, DateTimes, and well-formatted Strings are used with this type. (no time information in "abc")' end end end describe "structure" do it "is in introspection" do introspection_res = DateTimeTest::Schema.execute <<-GRAPHQL { __type(name: "ISO8601DateTime") { name kind } } GRAPHQL expected_res = { "name" => "ISO8601DateTime", "kind" => "SCALAR"} assert_graphql_equal expected_res, introspection_res["data"]["__type"] 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/types/relay/has_node_field_spec.rb
spec/graphql/types/relay/has_node_field_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Relay::HasNodeField do it "populates .owner when it's included" do query = Class.new(GraphQL::Schema::Object) do graphql_name "Query" include GraphQL::Types::Relay::HasNodeField include GraphQL::Types::Relay::HasNodesField end node_field = query.fields["node"] assert_equal query, node_field.owner assert_equal query, node_field.owner_type nodes_field = query.fields["nodes"] assert_equal query, nodes_field.owner assert_equal query, nodes_field.owner_type 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/types/relay/base_connection_spec.rb
spec/graphql/types/relay/base_connection_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Relay::BaseConnection do module NonNullAbleNodeDummy class Node < GraphQL::Schema::Object field :some_field, String end class NodeEdgeType < GraphQL::Types::Relay::BaseEdge node_type(Node, null: false) end class NonNullableNodeEdgeConnectionType < GraphQL::Types::Relay::BaseConnection edge_type(NodeEdgeType, node_nullable: false, edges_nullable: false, edge_nullable: false) end class NonNullableEdgeClassOverrideConnectionType < GraphQL::Types::Relay::BaseConnection edges_nullable(false) edge_nullable(false) node_nullable(false) end class Query < GraphQL::Schema::Object field :connection, NonNullableNodeEdgeConnectionType, null: false end class NoNodesFieldClassOverrideConnectionType < GraphQL::Types::Relay::BaseConnection has_nodes_field(false) end class Schema < GraphQL::Schema query Query end end it "node_nullable option is works" do res = NonNullAbleNodeDummy::Schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) edge_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "NonNullableNodeEdgeConnection" } nodes_field = edge_type["fields"].find { |f| f["name"] == "nodes" } assert_equal "NON_NULL",nodes_field["type"]["kind"] assert_equal "NON_NULL",nodes_field["type"]["ofType"]["ofType"]["kind"] end it "edges_nullable option is works" do res = NonNullAbleNodeDummy::Schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) connection_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "NonNullableNodeEdgeConnection" } edges_field = connection_type["fields"].find { |f| f["name"] == "edges" } assert_equal "NON_NULL",edges_field["type"]["kind"] end it "supports class-level edges_nullable config" do assert_equal false, NonNullAbleNodeDummy::NonNullableEdgeClassOverrideConnectionType.edges_nullable assert_equal false, NonNullAbleNodeDummy::NonNullableEdgeClassOverrideConnectionType.edge_nullable assert_equal false, NonNullAbleNodeDummy::NonNullableEdgeClassOverrideConnectionType.node_nullable end it "edge_nullable option is works" do res = NonNullAbleNodeDummy::Schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) connection_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "NonNullableNodeEdgeConnection" } edges_field = connection_type["fields"].find { |f| f["name"] == "edges" } assert_equal "NON_NULL",edges_field["type"]["ofType"]["ofType"]["kind"] end it "never treats nodes like a connection" do type = Class.new(GraphQL::Schema::Object) do graphql_name "MissedConnection" field :id, "ID", null: false end refute type.connection_type.fields["nodes"].connection? refute type.connection_type.fields["edges"].type.unwrap.fields["node"].connection? end it "supports class-level nodes_field config" do assert_equal false, NonNullAbleNodeDummy::NoNodesFieldClassOverrideConnectionType.has_nodes_field end it "Supports extra kwargs for edges and nodes" do connection = Class.new(GraphQL::Types::Relay::BaseConnection) do edge_type(GraphQL::Schema::Object.edge_type, field_options: { deprecation_reason: "passing extra args" }) end edges_field = connection.fields["edges"] assert_equal "passing extra args", edges_field.deprecation_reason nodes_field = connection.fields["nodes"] assert_equal "passing extra args", nodes_field.deprecation_reason end describe "visibility" do class BaseConnectionImplementsInterfaceSchema < GraphQL::Schema module CountableConnection include GraphQL::Schema::Interface field :total_count, Integer, null: false end class BaseConnection < GraphQL::Types::Relay::BaseConnection implements CountableConnection end class Thing < GraphQL::Schema::Object connection_type_class(BaseConnection) field :name, String end class Query < GraphQL::Schema::Object field :things, Thing.connection_type end query(Query) end it "is visible when there's no node type" do defn = BaseConnectionImplementsInterfaceSchema.to_definition assert_includes defn, "type ThingConnection implements CountableConnection" refute_includes defn, "type BaseConnection" 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/types/relay/node_behaviors_spec.rb
spec/graphql/types/relay/node_behaviors_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Relay::NodeBehaviors do class NodeBehaviorsSchema < GraphQL::Schema class Thing < GraphQL::Schema::Object implements GraphQL::Types::Relay::Node end class Query < GraphQL::Schema::Object field :thing, Thing def thing {} end end query(Query) def self.id_from_object(obj, type, context) context[:id_from_object_type] = type "blah" end end it "adds an `id` field that calls `schema.id_from_object` with the type class" do res = NodeBehaviorsSchema.execute("{ thing { id } }") assert_equal "blah", res["data"]["thing"]["id"] assert_equal NodeBehaviorsSchema::Thing, res.context[:id_from_object_type] 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/types/relay/base_edge_spec.rb
spec/graphql/types/relay/base_edge_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Types::Relay::BaseEdge do module NonNullableDummy class NonNullableNode < GraphQL::Schema::Object field :some_field, String end class NonNullableNodeEdgeType < GraphQL::Types::Relay::BaseEdge node_type(NonNullableNode, null: false) end class NonNullableNodeClassOverrideEdgeType < GraphQL::Types::Relay::BaseEdge node_nullable(false) end class NonNullableNodeEdgeConnectionType < GraphQL::Types::Relay::BaseConnection edge_type(NonNullableNodeEdgeType, nodes_field: false) end class Query < GraphQL::Schema::Object field :connection, NonNullableNodeEdgeConnectionType, null: false end class Schema < GraphQL::Schema query Query end end it "runs the introspection query and the result contains a edge field that has non-nullable node" do res = NonNullableDummy::Schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY) assert res edge_type = res["data"]["__schema"]["types"].find { |t| t["name"] == "NonNullableNodeEdge" } node_field = edge_type["fields"].find { |f| f["name"] == "node" } assert_equal "NON_NULL", node_field["type"]["kind"] assert_equal "NonNullableNode", node_field["type"]["ofType"]["name"] end it "supports class-level node_nullable config" do assert_equal false, NonNullableDummy::NonNullableNodeClassOverrideEdgeType.node_nullable end it "Supports extra kwargs for node field" do extension = Class.new(GraphQL::Schema::FieldExtension) connection = Class.new(GraphQL::Types::Relay::BaseEdge) do node_type(GraphQL::Schema::Object, field_options: { extensions: [extension] }) end field = connection.fields["node"] assert_equal 1, field.extensions.size assert_instance_of extension, field.extensions.first end it "is a default relay type" do edge_type = NonNullableDummy::Schema.get_type("NonNullableNodeEdge") assert_equal true, edge_type.default_relay? assert_equal true, GraphQL::Types::Relay::BaseEdge.default_relay? 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/pagination/connections_spec.rb
spec/graphql/pagination/connections_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Pagination::Connections do ITEMS = ConnectionAssertions::NAMES.map { |n| { name: n } } class ArrayConnectionWithTotalCount < GraphQL::Pagination::ArrayConnection def total_count items.size end end let(:base_schema) { ConnectionAssertions.build_schema( connection_class: GraphQL::Pagination::ArrayConnection, total_count_connection_class: ArrayConnectionWithTotalCount, get_items: -> { ITEMS } ) } # These wouldn't _work_, I just need to test `.wrap` class SetConnection < GraphQL::Pagination::ArrayConnection; end class HashConnection < GraphQL::Pagination::ArrayConnection; end class OtherArrayConnection < GraphQL::Pagination::ArrayConnection; end let(:schema) do other_base_schema = Class.new(base_schema) do connections.add(Set, SetConnection) end Class.new(other_base_schema) do connections.add(Hash, HashConnection) connections.add(Array, OtherArrayConnection) end end it "returns connections by class, using inherited mappings and local overrides" do field_defn = OpenStruct.new(has_max_page_size?: true, max_page_size: 10, has_default_page_size?: true, default_page_size: 5, type: GraphQL::Types::Relay::BaseConnection) set_wrapper = schema.connections.wrap(field_defn, nil, Set.new([1,2,3]), {}, nil) assert_instance_of SetConnection, set_wrapper hash_wrapper = schema.connections.wrap(field_defn, nil, {1 => :a, 2 => :b}, {}, nil) assert_instance_of HashConnection, hash_wrapper array_wrapper = schema.connections.wrap(field_defn, nil, [1,2,3], {}, nil) assert_instance_of OtherArrayConnection, array_wrapper raw_value = schema.connections.wrap(field_defn, nil, GraphQL::Execution::Interpreter::RawValue.new([1,2,3]), {}, nil) assert_instance_of GraphQL::Execution::Interpreter::RawValue, raw_value end it "uses cached wrappers" do field_defn = OpenStruct.new(max_page_size: 10) dummy_ctx = Class.new do def namespace(some_key) if some_key == :connections { all_wrappers: {} } else raise ArgumentError, "unsupported key: #{some_key.inspect}" end end end assert_raises GraphQL::Pagination::Connections::ImplementationMissingError do schema.connections.wrap(field_defn, nil, Set.new([1,2,3]), {}, dummy_ctx.new) end end # Simulate a schema with a `*Connection` type that _isn't_ # supposed to be a connection. Help debug, see https://github.com/rmosolgo/graphql-ruby/issues/2588 class ConnectionErrorTestSchema < GraphQL::Schema class BadThing def name self.no_such_method # raise a NoMethodError end def inspect "<BadThing!>" end end class ThingConnection < GraphQL::Schema::Object field :name, String, null: false end class Query < GraphQL::Schema::Object field :things, [ThingConnection], null: false def things [{name: "thing1"}, {name: "thing2"}] end field :things2, [ThingConnection], null: false, connection: false def things2 [ BadThing.new ] end end query(Query) end it "raises a helpful error when it fails to implement a connection" do err = assert_raises GraphQL::Execution::Interpreter::ListResultFailedError do pp ConnectionErrorTestSchema.execute("{ things { name } }") end assert_includes err.message, "Failed to build a GraphQL list result for field `Query.things` at path `things`." assert_includes err.message, "(GraphQL::Pagination::ArrayConnection) to implement `.each` to satisfy the GraphQL return type `[ThingConnection!]!`" assert_includes err.message, "This field was treated as a Relay-style connection; add `connection: false` to the `field(...)` to disable this behavior." end it "lets unrelated NoMethodErrors bubble up" do err = assert_raises NoMethodError do ConnectionErrorTestSchema.execute("{ things2 { name } }") end expected_message = if RUBY_VERSION >= "3.4" "undefined method 'no_such_method' for an instance of ConnectionErrorTestSchema::BadThing" elsif RUBY_VERSION >= "3.3" "undefined method `no_such_method' for an instance of ConnectionErrorTestSchema::BadThing" else "undefined method `no_such_method' for <BadThing!>" end assert_includes err.message, expected_message end it "uses a field's `max_page_size: nil` configuration" do user_type = Class.new(GraphQL::Schema::Object) do graphql_name 'User' field :name, String, null: false end query_type = Class.new(GraphQL::Schema::Object) do graphql_name 'Query' field :users, user_type.connection_type, max_page_size: nil def users [{ name: 'Yoda' }, { name: 'Anakin' }, { name: 'Obi Wan' }] end end schema = Class.new(GraphQL::Schema) do # This value should be overridden by `max_page_size: nil` in the field definition above default_max_page_size 2 query(query_type) end res = schema.execute(<<-GRAPHQL).to_h { users { nodes { name } } } GRAPHQL assert_equal ["Yoda", "Anakin", "Obi Wan"], res['data']['users']['nodes'].map { |node| node['name'] } end class SingleNewConnectionSchema < GraphQL::Schema class Query < GraphQL::Schema::Object field :strings, GraphQL::Types::String.connection_type, null: false def strings GraphQL::Pagination::ArrayConnection.new(["a", "b", "c"]) end end query(Query) end it "works when new connections are not installed" do res = SingleNewConnectionSchema.execute("{ strings(first: 2) { edges { node } } }") assert_equal ["a", "b"], res["data"]["strings"]["edges"].map { |e| e["node"] } 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/pagination/array_connection_spec.rb
spec/graphql/pagination/array_connection_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Pagination::ArrayConnection do ARRAY_ITEMS = ConnectionAssertions::NAMES.map { |n| { name: n } } class ArrayTestConnectionWithTotalCount < GraphQL::Pagination::ArrayConnection def total_count items.size end end let(:schema) { ConnectionAssertions.build_schema( connection_class: GraphQL::Pagination::ArrayConnection, total_count_connection_class: ArrayTestConnectionWithTotalCount, get_items: -> { ARRAY_ITEMS } ) } include ConnectionAssertions end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/pagination/connection_spec.rb
spec/graphql/pagination/connection_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Pagination::Connection do describe "was_authorized_by_scope_ites?" do it "doesn't raise an error for missing runtime state and it updates it if context is assigned later" do context = GraphQL::Query.new(GraphQL::Schema, "{ __typename }").context conn = GraphQL::Pagination::Connection.new([], context: context) assert_nil conn.was_authorized_by_scope_items? conn.context = context assert_nil conn.was_authorized_by_scope_items? Fiber[:__graphql_runtime_info] = { context.query => OpenStruct.new(was_authorized_by_scope_items: true) } conn.context = context assert_equal true, conn.was_authorized_by_scope_items? ensure Fiber[:__graphql_runtime_info] = nil 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/pagination/mongoid_relation_connection_spec.rb
spec/graphql/pagination/mongoid_relation_connection_spec.rb
# frozen_string_literal: true require "spec_helper" if testing_mongoid? describe GraphQL::Pagination::MongoidRelationConnection do class Food include Mongoid::Document field :name, type: String end before do # Populate the DB Food.collection.drop ConnectionAssertions::NAMES.each { |n| Food.create(name: n) } end class MongoidRelationConnectionWithTotalCount < GraphQL::Pagination::MongoidRelationConnection def total_count items.count end end let(:schema) { ConnectionAssertions.build_schema( connection_class: GraphQL::Pagination::MongoidRelationConnection, total_count_connection_class: MongoidRelationConnectionWithTotalCount, get_items: -> { Food.all } ) } include ConnectionAssertions 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/pagination/sequel_dataset_connection_spec.rb
spec/graphql/pagination/sequel_dataset_connection_spec.rb
# frozen_string_literal: true require "spec_helper" if testing_rails? describe GraphQL::Pagination::SequelDatasetConnection do class SequelFood < Sequel::Model(:foods) end before do if SequelFood.empty? # Can overlap with ActiveRecordRelationConnection test ConnectionAssertions::NAMES.each { |n| SequelFood.create(name: n) } end end class SequelDatasetConnectionWithTotalCount < GraphQL::Pagination::SequelDatasetConnection def total_count items.count end end let(:schema) { ConnectionAssertions.build_schema( connection_class: GraphQL::Pagination::SequelDatasetConnection, total_count_connection_class: SequelDatasetConnectionWithTotalCount, get_items: -> { SequelFood.dataset } ) } include ConnectionAssertions 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/pagination/active_record_relation_connection_spec.rb
spec/graphql/pagination/active_record_relation_connection_spec.rb
# frozen_string_literal: true require "spec_helper" if testing_rails? describe GraphQL::Pagination::ActiveRecordRelationConnection do class RelationConnectionWithTotalCount < GraphQL::Pagination::ActiveRecordRelationConnection def total_count if items.respond_to?(:unscope) items.unscope(:order).count(:all) else # rails 3 items.count end end end let(:schema) { ConnectionAssertions.build_schema( connection_class: GraphQL::Pagination::ActiveRecordRelationConnection, total_count_connection_class: RelationConnectionWithTotalCount, get_items: -> { if Food.respond_to?(:scoped) Food.scoped.limit(limit) # Rails 3-friendly version of .all else Food.all.limit(limit) end } ) } let(:limit) { nil } include ConnectionAssertions before do if Food.count == 0 # Backwards-compat version of `.none?` ConnectionAssertions::NAMES.each { |n| Food.create!(name: n) } end end it "maintains an application-provided offset" do results = schema.execute("{ offsetItems(first: 3) { nodes { name } pageInfo { endCursor } } }") assert_equal ["Cucumber", "Dill", "Eggplant"], results["data"]["offsetItems"]["nodes"].map { |n| n["name"] } end_cursor = results["data"]["offsetItems"]["pageInfo"]["endCursor"] results = schema.execute("{ offsetItems(first: 3, after: #{end_cursor.inspect}) { nodes { name } } }") assert_equal ["Fennel", "Ginger", "Horseradish"], results["data"]["offsetItems"]["nodes"].map { |n| n["name"] } results = schema.execute("{ offsetItems(last: 2, before: #{end_cursor.inspect}) { nodes { name } } }") assert_equal ["Cucumber", "Dill"], results["data"]["offsetItems"]["nodes"].map { |n| n["name"] } end describe 'with application-provided limit, which is smaller than the max_page_size' do let(:limit) { 1 } it "maintains an application-provided limit" do results = schema.execute("{ limitedItems { nodes { name } } }") assert_equal ["Avocado"], results["data"]["limitedItems"]["nodes"].map { |n| n["name"] } end end describe 'with application-provided limit, which is larger than the max_page_size' do let(:limit) { 3 } it "applies a field-level max-page-size configuration" do results = schema.execute("{ limitedItems { nodes { name } } }") assert_equal ["Avocado", "Beet"], results["data"]["limitedItems"]["nodes"].map { |n| n["name"] } end end it "doesn't run pageInfo queries when not necessary" do results = nil log = with_active_record_log do results = schema.execute("{ items(first: 3) { __typename } }") end assert_equal "ItemConnection", results["data"]["items"]["__typename"] assert_equal "", log, "No queries are executed when no data is requested" log = with_active_record_log do results = schema.execute("{ items(first: 3) { pageInfo { hasNextPage hasPreviousPage } } }") end assert_equal true, results["data"]["items"]["pageInfo"]["hasNextPage"] assert_equal false, results["data"]["items"]["pageInfo"]["hasPreviousPage"] assert_equal 1, log.split("\n").size, "It runs only one query" assert_equal 1, log.squeeze.scan("SELECT 1 AS").size, "It's an exist query (#{log.inspect})" log = with_active_record_log do results = schema.execute("{ items(last: 3) { pageInfo { hasNextPage hasPreviousPage } } }") end assert_equal true, results["data"]["items"]["pageInfo"]["hasPreviousPage"] assert_equal false, results["data"]["items"]["pageInfo"]["hasNextPage"] assert_equal 1, log.split("\n").size, "It runs only one query" assert_equal 1, log.scan("COUNT(").size, "It's a count query" log = with_active_record_log do results = schema.execute("{ items(first: 3) { nodes { __typename } } }") end assert_equal ["Item", "Item", "Item"], results["data"]["items"]["nodes"].map { |i| i["__typename"] } assert_equal 1, log.split("\n").size, "It runs only one query" log = with_active_record_log do results = schema.execute("{ items(first: 11, maxPageSizeOverride: 11) { nodes { __typename } pageInfo { hasNextPage } } }") end assert_equal ["Item"] * 10, results["data"]["items"]["nodes"].map { |i| i["__typename"] } assert_equal 1, log.split("\n").size, "It runs only one query when less than total count is requested" assert_equal 0, log.scan("COUNT(").size, "It runs no count query" log = with_active_record_log do results = schema.execute("{ items(first: 3) { nodes { __typename } pageInfo { hasNextPage } } }") end # This currently runs one query to load the nodes, then another one to count _just beyond_ the nodes. # A better implementation would load `first + 1` nodes and use that to set `has_next_page`. assert_equal ["Item", "Item", "Item"], results["data"]["items"]["nodes"].map { |i| i["__typename"] } assert_equal 2, log.split("\n").size, "It runs two queries -- TODO this could be better" end describe "already-loaded ActiveRecord relations" do ALREADY_LOADED_QUERY_STRING = " query($first: Int, $after: String, $last: Int, $before: String) { preloadedItems(first: $first, after: $after, last: $last, before: $before) { pageInfo { hasPreviousPage hasNextPage endCursor } nodes { __typename } } } " it "only runs one query for already-loaded unbounded queries" do results = nil log = with_active_record_log do results = schema.execute(ALREADY_LOADED_QUERY_STRING) end # The default_page_size of 4 is applied to the results assert_equal 4, results["data"]["preloadedItems"]["nodes"].size assert_equal 1, log.split("\n").size, "It runs only one query" decolorized_log = log.gsub(/\e\[([;\d]+)?m/, '').chomp assert_operator decolorized_log, :end_with?, 'SELECT "foods".* FROM "foods"', "it's an unbounded select from the resolver" end it "only runs one query for already-loaded `last:...` queries" do results = nil log = with_active_record_log do results = schema.execute(ALREADY_LOADED_QUERY_STRING, variables: { last: 1 }) end assert_equal 1, results["data"]["preloadedItems"]["nodes"].size assert_equal 1, log.split("\n").size, "It runs only one query" decolorized_log = log.gsub(/\e\[([;\d]+)?m/, '').chomp assert_operator decolorized_log, :end_with?, 'SELECT "foods".* FROM "foods"', "it's an unbounded select from the resolver" end it "only runs one query for already-loaded `first:... / after:` queries" do results = nil log = with_active_record_log do results = schema.execute(ALREADY_LOADED_QUERY_STRING, variables: { first: 1 }) end assert_equal 1, results["data"]["preloadedItems"]["nodes"].size assert_equal 1, log.split("\n").size, "It runs only one query" decolorized_log = log.gsub(/\e\[([;\d]+)?m/, '').chomp assert_operator decolorized_log, :end_with?, 'SELECT "foods".* FROM "foods"', "it's an unbounded select from the resolver" cursor = results["data"]["preloadedItems"]["pageInfo"]["endCursor"] log = with_active_record_log do results = schema.execute(ALREADY_LOADED_QUERY_STRING, variables: { first: 1, after: cursor }) end assert_equal 1, results["data"]["preloadedItems"]["nodes"].size assert_equal 1, log.split("\n").size, "It runs only one query" decolorized_log = log.gsub(/\e\[([;\d]+)?m/, '').chomp assert_operator decolorized_log, :end_with?, 'SELECT "foods".* FROM "foods"', "it's an unbounded select from the resolver" assert_equal "[\"2\"]+nonce", results["data"]["preloadedItems"]["pageInfo"]["endCursor"], "it makes the right cursor" end let(:schema) { ConnectionAssertions.build_schema( connection_class: GraphQL::Pagination::ActiveRecordRelationConnection, total_count_connection_class: RelationConnectionWithTotalCount, get_items: -> { relation = if Food.respond_to?(:scoped) Food.scoped # Rails 3-friendly version of .all else Food.all end relation.load relation } ) } include ConnectionAssertions 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/testing/helpers_spec.rb
spec/graphql/testing/helpers_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Testing::Helpers do class AssertionsSchema < GraphQL::Schema use GraphQL::Schema::Warden if ADD_WARDEN class BillSource < GraphQL::Dataloader::Source def fetch(students) students.map { |s| { amount: 1_000_001 } } end end class TuitionBill < GraphQL::Schema::Object def self.visible?(ctx) ctx[:current_user]&.admin? end field :amount_in_cents, Int, hash_key: :amount end class Transcript < GraphQL::Schema::Object def self.authorized?(object, context) (current_user = context[:current_user]) && (admin_for = current_user[:admin_for]) && (admin_for.include?(object && object[:name])) end field :gpa, Float end class Student < GraphQL::Schema::Object def self.authorized?(object, context) context.errors.empty? end field :name, String, extras: [:ast_node] do argument :full_name, Boolean, required: false argument :prefix, String, required: false, default_value: "Mc", prepare: ->(val, ctx) { -> { val.capitalize } } end def name(full_name: nil, prefix: nil, ast_node:) name = object[:name] if full_name "#{name} #{ast_node.alias ? "\"#{ast_node.alias}\" " : ""}#{prefix}#{name}" else name end end field :latest_bill, TuitionBill def latest_bill dataloader.with(BillSource).load(object) end field :is_admin_for, Boolean def is_admin_for (list = context[:admin_for]) && list.include?(object[:name]) end field :transcript, Transcript, resolver_method: :object class Upcase < GraphQL::Schema::FieldExtension def after_resolve(value:, **rest) value.upcase end end field :upcased_name, String, extensions: [Upcase], hash_key: :name field :ssn, String do def authorized?(obj, args, ctx) ctx[:current_user]&.admin? end end field :current_field, String def current_field context[:current_field].path end end class AuthorizedObject < GraphQL::Schema::Object def self.authorized?(object, context) context.dataloader.with(BillSource).load(object)[:amount] > 5 end field :id, ID end class Query < GraphQL::Schema::Object field :students, [Student] field :student, Student do argument :student_id, ID, loads: Student end def student(student:) student end field :lookahead_selections, String, extras: [:lookahead] def lookahead_selections(lookahead:) lookahead.selections.to_s end field :authorized_object, AuthorizedObject end query(Query) use GraphQL::Dataloader lazy_resolve Proc, :call use GraphQL::Schema::Visibility, profiles: { public: { public: true } }, dynamic: true def self.unauthorized_object(err) raise err end def self.unauthorized_field(err) raise err end def self.object_from_id(id, ctx) if id == "s1" -> do { name: "Student1", type: Student } end else raise ArgumentError, "No data for id: #{id.inspect}" end end def self.resolve_type(abs_t, obj, ctx) obj.fetch(:type) end end include GraphQL::Testing::Helpers let(:admin_context) { { current_user: OpenStruct.new(admin?: true) } } describe "top-level helpers" do describe "run_graphql_field" do it "resolves fields" do assert_equal "Blah", run_graphql_field(AssertionsSchema, "Student.name", { name: "Blah" }) assert_equal "Blah McBlah", run_graphql_field(AssertionsSchema, "Student.name", { name: "Blah" }, arguments: { "fullName" => true }) assert_equal "Blah McBlah", run_graphql_field(AssertionsSchema, "Student.name", { name: "Blah" }, arguments: { full_name: true }) assert_equal({ amount: 1_000_001 }, run_graphql_field(AssertionsSchema, "Student.latestBill", :student, context: admin_context)) end it "loads arguments with lazy_resolve" do student = run_graphql_field(AssertionsSchema, "Query.student", nil, arguments: { "studentId" => "s1" }) expected_student = { name: "Student1", type: AssertionsSchema::Student } assert_equal(expected_student, student) student2 = run_graphql_field(AssertionsSchema, "Query.student", nil, arguments: { student: "s1" }) assert_equal(expected_student, student2) end it "works with resolution context" do with_resolution_context(AssertionsSchema, object: { name: "Foo" }, type: "Student", context: { admin_for: ["Foo"] }) do |rc| rc.run_graphql_field("name") rc.run_graphql_field("isAdminFor") assert_equal "Student.currentField", rc.run_graphql_field("currentField") end end it "works with a visibility_profile" do student2 = run_graphql_field(AssertionsSchema, "Query.student", nil, visibility_profile: :public, arguments: { student: "s1" }) expected_student = { name: "Student1", type: AssertionsSchema::Student } assert_equal(expected_student, student2) with_resolution_context(AssertionsSchema, object: {}, type: "Query", context: {}, visibility_profile: :public) do |rc| assert_equal :public, rc.visibility_profile end end it "raises an error when the type is hidden" do assert_equal 1_000_000, run_graphql_field(AssertionsSchema, "TuitionBill.amountInCents", { amount: 1_000_000 }, context: admin_context) err = assert_raises(GraphQL::Testing::Helpers::TypeNotVisibleError) do run_graphql_field(AssertionsSchema, "TuitionBill.amountInCents", { amount: 1_000_000 }) end expected_message = "`TuitionBill` should be `visible?` this field resolution and `context`, but it was not" assert_equal expected_message, err.message end it "raises an error when the type isn't authorized" do err = assert_raises GraphQL::UnauthorizedError do run_graphql_field(AssertionsSchema, "Student.transcript.gpa", { gpa: 3.1 }) end assert_equal "An instance of Hash failed Transcript's authorization check", err.message assert_equal 3.1, run_graphql_field(AssertionsSchema, "Student.transcript.gpa", { gpa: 3.1, name: "Jim" }, context: { current_user: OpenStruct.new(admin_for: ["Jim"])}) end it "works with field extensions" do assert_equal "BILL", run_graphql_field(AssertionsSchema, "Student.upcasedName", { name: "Bill" }) end it "works with extras: [:ast_node]" do assert_equal "Billy \"theKid\" McBilly", run_graphql_field(AssertionsSchema, "Student.name", { name: "Billy" }, arguments: { full_name: true }, ast_node: GraphQL::Language::Nodes::Field.new(name: "name", field_alias: "theKid")) end it "works with extras: [:lookahead]" do assert_equal "[]", run_graphql_field(AssertionsSchema, "Query.lookaheadSelections", :something) dummy_lookahead = OpenStruct.new(selections: ["one", "two"]) assert_equal "[\"one\", \"two\"]", run_graphql_field(AssertionsSchema, "Query.lookaheadSelections", :something, lookahead: dummy_lookahead) end it "prepares arguments" do assert_equal "Blah De Blah", run_graphql_field(AssertionsSchema, "Student.name", { name: "Blah" }, arguments: { full_name: true, prefix: "de " }) end it "handles unauthorized field errors" do assert_equal "123-45-6789", run_graphql_field(AssertionsSchema, "Student.ssn", { ssn: "123-45-6789"}, context: admin_context) err = assert_raises GraphQL::UnauthorizedFieldError do run_graphql_field(AssertionsSchema, "Student.ssn", {}) end assert_equal "An instance of Hash failed AssertionsSchema::Student's authorization check on field ssn", err.message end it "works when .authorized? calls dataloader" do assert_equal "100", run_graphql_field(AssertionsSchema, "AuthorizedObject.id", { id: "100" }) end it "raises when the type doesn't exist" do err = assert_raises GraphQL::Testing::Helpers::TypeNotDefinedError do run_graphql_field(AssertionsSchema, "Nothing.nothing", :nothing) end assert_equal "No type named `Nothing` is defined; choose another type name or define this type.", err.message end it "raises when the field doesn't exist" do err = assert_raises GraphQL::Testing::Helpers::FieldNotDefinedError do run_graphql_field(AssertionsSchema, "Student.nonsense", :student) end assert_equal "`Student` has no field named `nonsense`; pick another name or define this field.", err.message end end end describe "schema-level helpers" do include GraphQL::Testing::Helpers.for(AssertionsSchema) it "resolves fields" do assert_equal 5, run_graphql_field("TuitionBill.amountInCents", { amount: 5 }, context: admin_context) end it "works with resolution context" do with_resolution_context(object: { name: "Foo" }, type: "Student", context: { admin_for: ["Bar"] }) do |rc| assert_equal "Foo", rc.run_graphql_field("name") assert_equal false, rc.run_graphql_field("isAdminFor") 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/cop/field_type_in_block_spec.rb
spec/graphql/cop/field_type_in_block_spec.rb
# frozen_string_literal: true require 'spec_helper' describe "GraphQL::Cop::FieldTypeInBlock" do include RubocopTestHelpers it "finds and autocorrects field corrections with inline types" do result = run_rubocop_on("spec/fixtures/cop/field_type.rb") assert_equal 3, rubocop_errors(result) assert_includes result, <<-RUBY field :current_account, Types::Account, null: false, description: "The account of the current viewer" ^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY field :find_account, Types::Account do ^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY field(:all_accounts, [Types::Account, null: false]) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUBY assert_rubocop_autocorrects_all("spec/fixtures/cop/field_type.rb") end it "works on small classes" do result = run_rubocop_on("spec/fixtures/cop/small_field_type.rb") assert_equal 1, rubocop_errors(result) end it "works with array types" do result = run_rubocop_on("spec/fixtures/cop/field_type_array.rb") assert_equal 1, rubocop_errors(result) assert_includes result, <<-RUBY field :bar, [Thing], null: false do ^^^^^^^ RUBY assert_rubocop_autocorrects_all("spec/fixtures/cop/field_type_array.rb") end it "Works with interfaces" do result = run_rubocop_on("spec/fixtures/cop/field_type_interface.rb") assert_equal 1, rubocop_errors(result) assert_includes result, <<-RUBY field :thing, Thing ^^^^^ RUBY assert_rubocop_autocorrects_all("spec/fixtures/cop/field_type_interface.rb") 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/cop/default_null_true_spec.rb
spec/graphql/cop/default_null_true_spec.rb
# frozen_string_literal: true require 'spec_helper' describe "GraphQL::Cop::DefaultNullTrue" do include RubocopTestHelpers it "finds and autocorrects `null: true` field configurations" do result = run_rubocop_on("spec/fixtures/cop/null_true.rb") assert_equal 3, rubocop_errors(result) assert_includes result, <<-RUBY field :name, String, null: true ^^^^^^^^^^ RUBY assert_includes result, <<-RUBY null: true, ^^^^^^^^^^ RUBY assert_includes result, <<-RUBY field :described, [String, null: true], null: true, description: "Something" ^^^^^^^^^^ RUBY assert_rubocop_autocorrects_all("spec/fixtures/cop/null_true.rb") 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/cop/default_required_true_spec.rb
spec/graphql/cop/default_required_true_spec.rb
# frozen_string_literal: true require 'spec_helper' describe "GraphQL::Cop::DefaultRequiredTrue" do include RubocopTestHelpers it "finds and autocorrects `required: true` argument configurations" do result = run_rubocop_on("spec/fixtures/cop/required_true.rb") assert_equal 4, rubocop_errors(result) assert_includes result, <<-RUBY argument :id_1, ID, required: true ^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY required: true, ^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY argument :id_3, ID, other_config: { something: false, required: true }, required: true, description: \"Something\" ^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY f.argument(:id_1, ID, required: true) ^^^^^^^^^^^^^^ RUBY assert_rubocop_autocorrects_all("spec/fixtures/cop/required_true.rb") 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/cop/root_types_in_block_spec.rb
spec/graphql/cop/root_types_in_block_spec.rb
# frozen_string_literal: true require 'spec_helper' describe "GraphQL::Cop::RootTypesInBlock" do include RubocopTestHelpers it "finds and autocorrects field corrections with inline types" do result = run_rubocop_on("spec/fixtures/cop/root_types.rb") assert_equal 3, rubocop_errors(result) assert_includes result, <<-RUBY query Types::Query ^^^^^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY mutation Types::Mutation ^^^^^^^^^^^^^^^^^^^^^^^^ RUBY assert_includes result, <<-RUBY subscription Types::Subscription ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RUBY assert_rubocop_autocorrects_all("spec/fixtures/cop/root_types.rb") 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/definition_slice_spec.rb
spec/graphql/language/definition_slice_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::DefinitionSlice do let(:document) { GraphQL.parse(query_string) } describe "anonymous query with no dependencies" do let(:query_string) {%| { version } |} it "is already the smallest slice" do assert_equal document.to_query_string, document.slice_definition(nil).to_query_string end end describe "anonymous mutation with no dependencies" do let(:query_string) {%| mutation { ping { message } } |} it "is already the smallest slice" do assert_equal document.to_query_string, document.slice_definition(nil).to_query_string end end describe "anonymous fragment with no dependencies" do let(:query_string) {%| fragment on User { name } |} it "is already the smallest slice" do assert_equal document.to_query_string, document.slice_definition(nil).to_query_string end end describe "named query with no dependencies" do let(:query_string) {%| query getVersion { version } |} it "is already the smallest slice" do assert_equal document.to_query_string, document.slice_definition("getVersion").to_query_string end end describe "named fragment with no dependencies" do let(:query_string) {%| fragment profileFields on User { firstName lastName } |} it "is already the smallest slice" do assert_equal document.to_query_string, document.slice_definition("profileFields").to_query_string end end describe "document with multiple queries but no subdependencies" do let(:query_string) {%| query getVersion { version } query getTime { time } |} it "returns just the query definition" do assert_equal GraphQL::Language::Nodes::Document.new(definitions: [document.definitions[0]]).to_query_string, document.slice_definition("getVersion").to_query_string assert_equal GraphQL::Language::Nodes::Document.new(definitions: [document.definitions[1]]).to_query_string, document.slice_definition("getTime").to_query_string end end describe "document with multiple fragments but no subdependencies" do let(:query_string) {%| fragment profileFields on User { firstName lastName } fragment avatarFields on User { avatarURL(size: 80) } |} it "returns just the fragment definition" do assert_equal GraphQL::Language::Nodes::Document.new(definitions: [document.definitions[0]]).to_query_string, document.slice_definition("profileFields").to_query_string assert_equal GraphQL::Language::Nodes::Document.new(definitions: [document.definitions[1]]).to_query_string, document.slice_definition("avatarFields").to_query_string end end describe "query with missing spread" do let(:query_string) {%| query getUser { viewer { ...profileFields } } |} it "is ignored" do assert_equal document.to_query_string, document.slice_definition("getUser").to_query_string end end describe "query and fragment subdependency" do let(:query_string) {%| query getUser { viewer { ...profileFields } } fragment profileFields on User { firstName lastName } |} it "returns query and fragment dependency" do assert_equal document.to_query_string, document.slice_definition("getUser").to_query_string end end describe "query and fragment nested subdependencies" do let(:query_string) {%| query getUser { viewer { ...viewerInfo } } fragment viewerInfo on User { ...profileFields } fragment profileFields on User { firstName lastName ...avatarFields } fragment avatarFields on User { avatarURL(size: 80) } |} it "returns query and all fragment dependencies" do assert_equal document.to_query_string, document.slice_definition("getUser").to_query_string end end describe "fragment subdependency referenced multiple times" do let(:query_string) {%| query getUser { viewer { ...viewerInfo ...moreViewerInfo } } fragment viewerInfo on User { ...profileFields } fragment moreViewerInfo on User { ...profileFields } fragment profileFields on User { firstName lastName } |} it "is only returned once" do assert_equal document.to_query_string, document.slice_definition("getUser").to_query_string end end describe "query and unused fragment" do let(:query_string) {%| query getUser { viewer { id } } fragment profileFields on User { firstName lastName } |} it "returns just the query definition" do assert_equal GraphQL::Language::Nodes::Document.new(definitions: [document.definitions[0]]).to_query_string, document.slice_definition("getUser").to_query_string 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/visitor_spec.rb
spec/graphql/language/visitor_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::Visitor do let(:document) { GraphQL.parse(" query cheese { cheese(id: 1) { flavor, source, producers(first: 3) { name } ... cheeseFields } } fragment cheeseFields on Cheese { flavor } ")} module CountWhileVisiting attr_reader :counts def initialize(document) @counts = {fields_entered: 0, arguments_entered: 0, arguments_left: 0, argument_names: []} super end def on_field(node, parent) counts[:fields_entered] += 1 super(node, parent) end def on_argument(node, parent) counts[:argument_names] << node.name counts[:arguments_entered] += 1 super ensure counts[:arguments_left] += 1 end def on_document(node, parent) counts[:finished] = true super end end class VisitorSpecVisitor < GraphQL::Language::Visitor include CountWhileVisiting end class VisitorSpecStaticVisitor < GraphQL::Language::StaticVisitor include CountWhileVisiting end let(:visitor) { VisitorSpecVisitor.new(document) } let(:counts) { visitor.counts } it "visitor calls hooks during a depth-first tree traversal" do visitor.visit assert_equal(6, counts[:fields_entered]) assert_equal(2, counts[:arguments_entered]) assert_equal(2, counts[:arguments_left]) assert_equal(["id", "first"], counts[:argument_names]) assert(counts[:finished]) static_visitor = VisitorSpecStaticVisitor.new(document) static_visitor.visit static_counts = static_visitor.counts assert_equal(6, static_counts[:fields_entered]) assert_equal(2, static_counts[:arguments_entered]) assert_equal(2, static_counts[:arguments_left]) assert_equal(["id", "first"], static_counts[:argument_names]) assert(static_counts[:finished]) end class SkippingVisitor < VisitorSpecVisitor def on_document(_n, _p); end end describe "Visitor::SKIP" do let(:visitor) { SkippingVisitor.new(document) } it "visitor skips the rest of the node" do visitor.visit assert_equal(0, counts[:fields_entered]) end end describe "AST modification" do class ModificationTestVisitor < GraphQL::Language::Visitor def on_field(node, parent) if node.name == "c" new_node = node.merge(name: "renamedC") super(new_node, parent) elsif node.name == "addFields" new_node = node.merge_selection(name: "addedChild") super(new_node, parent) elsif node.name == "anotherAddition" new_node = node .merge_argument(name: "addedArgument", value: 1) .merge_directive(name: "doStuff") super(new_node, parent) else super end end def on_argument(node, parent) # https://github.com/rmosolgo/graphql-ruby/issues/2148 # Parent could become a random value, double check that it's a node # to actually fail the test raise RuntimeError, "Parent isn't a Node!" unless parent.class < GraphQL::Language::Nodes::AbstractNode if node.name == "deleteMe" super(DELETE_NODE, parent) elsif node.name.include?("nope") [1] else super end end def on_variable_identifier(node, parent) if node.name == "firstName" node = node.merge(name: "lastName") end super(node, parent) end def on_input_object(node, parent) if node.arguments.map(&:name).sort == ["delete", "me"] super(DELETE_NODE, parent) else super end end def on_directive(node, parent) if node.name == "doStuff" new_node = node.merge_argument(name: "addedArgument2", value: 2) super(new_node, parent) else super end end def on_inline_fragment(node, parent) if node.selections.map(&:name) == ["renameFragmentField", "spread"] _field, spread = node.selections new_node = node.merge(selections: [GraphQL::Language::Nodes::Field.new(name: "renamed"), spread]) super(new_node, parent) else super(node, parent) end end def on_fragment_spread(node, parent) if node.name == "spread" new_node = node.merge(name: "renamedSpread") super(new_node, parent) else super(node, parent) end end def on_object_type_definition(node, parent) if node.name == "Rename" new_node = node.merge(name: "WasRenamed") super(new_node, parent) else super(node, parent) end end def on_field_definition(node, parent) if node.name == "renameThis" new_node = node.merge(name: "wasRenamed") super(new_node, parent) else super end end def on_input_value_definition(node, parent) if node.name == "renameThisArg" new_node = node.merge(name: "argWasRenamed") super(new_node, parent) else super end end def on_variable_definition(node, parent) if node.type.name == 'A' new_type = GraphQL::Language::Nodes::TypeName.new(name: 'RenamedA') super(node.merge(type: new_type), parent) elsif node.name == "firstName" super(node.merge(name: "lastName"), parent) else super end end def on_directive_definition(node, parent) if node.name == "deleteMe" super(DELETE_NODE, parent) else super end end end def get_result(query_str) document = GraphQL.parse(query_str) visitor = ModificationTestVisitor.new(document) visitor.visit return document, visitor.result end it "can modify variable names" do query = <<-GRAPHQL.chop query($firstName: String) { a(b: $firstName) } GRAPHQL expected_result = <<-GRAPHQL.chop query($lastName: String) { a(b: $lastName) } GRAPHQL document, new_document = get_result(query) assert_equal expected_result, new_document.to_query_string, "the result has changes" assert_equal query, document.to_query_string, "the original is unchanged" end it "returns a new AST with modifications applied" do query = <<-GRAPHQL.chop query($a: A, $b: B) { a(a1: 1) { b(b2: 2) { c(c3: 3) } } d(d4: 4) } GRAPHQL document, new_document = get_result(query) refute_equal document, new_document expected_result = <<-GRAPHQL.chop query($a: RenamedA, $b: B) { a(a1: 1) { b(b2: 2) { renamedC(c3: 3) } } d(d4: 4) } GRAPHQL assert_equal expected_result, new_document.to_query_string, "the result has changes" assert_equal query, document.to_query_string, "the original is unchanged" # This is testing the implementation: nodes which aren't affected by modification # should be shared between the two trees orig_c3_argument = document.definitions.first.selections.first.selections.first.selections.first.arguments.first copy_c3_argument = new_document.definitions.first.selections.first.selections.first.selections.first.arguments.first assert_equal "c3", orig_c3_argument.name assert orig_c3_argument.equal?(copy_c3_argument), "Child nodes are persisted" orig_d_field = document.definitions.first.selections[1] copy_d_field = new_document.definitions.first.selections[1] assert_equal "d", orig_d_field.name assert orig_d_field.equal?(copy_d_field), "Sibling nodes are persisted" orig_b_field = document.definitions.first.selections.first.selections.first copy_b_field = new_document.definitions.first.selections.first.selections.first assert_equal "b", orig_b_field.name refute orig_b_field.equal?(copy_b_field), "Parents with modified children are copied" end it "deletes nodes with DELETE_NODE" do before_query = <<-GRAPHQL.chop query { f1 { f2(deleteMe: 1) { f3(c1: {deleteMe: {c2: 2}}) f4(c2: [{keepMe: 1}, {deleteMe: 2}, {keepMe: 3}]) } } } GRAPHQL after_query = <<-GRAPHQL.chop query { f1 { f2 { f3(c1: {}) f4(c2: [{keepMe: 1}, {}, {keepMe: 3}]) } } } GRAPHQL document, new_document = get_result(before_query) assert_equal before_query, document.to_query_string assert_equal after_query, new_document.to_query_string end it "Deletes from lists" do before_query = <<-GRAPHQL.chop query { f1(arg1: [{a: 1}, {delete: 1, me: 2}, {b: 2}]) } GRAPHQL after_query = <<-GRAPHQL.chop query { f1(arg1: [{a: 1}, {b: 2}]) } GRAPHQL document, new_document = get_result(before_query) assert_equal before_query, document.to_query_string assert_equal after_query, new_document.to_query_string end it "can add children" do before_query = <<-GRAPHQL.chop query { addFields anotherAddition } GRAPHQL after_query = <<-GRAPHQL.chop query { addFields { addedChild } anotherAddition(addedArgument: 1) @doStuff(addedArgument2: 2) } GRAPHQL document, new_document = get_result(before_query) assert_equal before_query, document.to_query_string assert_equal after_query, new_document.to_query_string end it "ignore non-Nodes::AbstractNode return values" do query = <<-GRAPHQL.chop query { doesntDoAnything(stillNothing: {nope: 1, alsoNope: 2, stillNope: 3}) } GRAPHQL document, new_document = get_result(query) assert_equal query, document.to_query_string assert_equal query, new_document.to_query_string end it "can modify inline fragments" do before_query = <<-GRAPHQL.chop query { ... on Query { renameFragmentField ...spread } } GRAPHQL after_query = <<-GRAPHQL.chop query { ... on Query { renamed ...renamedSpread } } GRAPHQL document, new_document = get_result(before_query) assert_equal before_query, document.to_query_string assert_equal after_query, new_document.to_query_string end it "works with SDL" do before_query = <<-GRAPHQL.chop directive @deleteMe on FIELD directive @keepMe on FIELD type Rename @doStuff { f: Int renameThis: String f2(renameThisArg: Boolean): Boolean } GRAPHQL after_query = <<-GRAPHQL.chop directive @keepMe on FIELD type WasRenamed @doStuff(addedArgument2: 2) { f: Int wasRenamed: String f2(argWasRenamed: Boolean): Boolean } GRAPHQL document, new_document = get_result(before_query) assert_equal before_query, document.to_query_string assert_equal after_query, new_document.to_query_string 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/block_string_spec.rb
spec/graphql/language/block_string_spec.rb
# frozen_string_literal: true require "spec_helper" describe GraphQL::Language::BlockString do describe "trimming whitespace" do def trim_whitespace(str) GraphQL::Language::BlockString.trim_whitespace(str) end it "matches the examples in graphql-js" do # these are taken from: # https://github.com/graphql/graphql-js/blob/36ec0e9d34666362ff0e2b2b18edeb98e3c9abee/src/language/__tests__/blockStringValue-test.js#L12 # A set of [before, after] pairs: examples = [ [ # Removes common whitespace: " Hello, World! Yours, GraphQL. ", "Hello,\n World!\n\nYours,\n GraphQL." ], [ # Removes leading and trailing newlines: " Hello, World! Yours, GraphQL. ", "Hello,\n World!\n\nYours,\n GraphQL." ], [ # Removes blank lines (with whitespace _and_ newlines:) "\n \n Hello, World! Yours, GraphQL. \n \n", "Hello,\n World!\n\nYours,\n GraphQL." ], [ # Retains indentation from the first line " Hello,\n World!\n\n Yours,\n GraphQL.", " Hello,\n World!\n\nYours,\n GraphQL.", ], [ # Doesn't alter trailing spaces "\n \n Hello, \n World! \n\n Yours, \n GraphQL. ", "Hello, \n World! \n\nYours, \n GraphQL. ", ], [ # Doesn't crash when the string is only a newline "\n", "" ], [ # Removes long blank lines " \n \n Hello, World! Yours, GraphQL. \n \n", "Hello,\n World!\n\nYours,\n GraphQL." ] ] examples.each_with_index do |(before, after), idx| transformed_str = trim_whitespace(before) assert_equal(after, transformed_str, "Example ##{idx + 1}") end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false