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/support/datadog.rb | spec/support/datadog.rb | # frozen_string_literal: true
# A stub for the Datadog agent, so we can make assertions about how it is used
if defined?(Datadog)
raise "Expected Datadog to be undefined, so that we could define a stub for it."
end
module Datadog
SPAN_RESOURCE_NAMES = []
SPAN_TAGS = []
TRACE_KEYS = []
def self.tracer
DummyTracer.new
end
def self.clear_all
SPAN_RESOURCE_NAMES.clear
SPAN_TAGS.clear
TRACE_KEYS.clear
end
class DummyTracer
def trace(platform_key, *args)
TRACE_KEYS << platform_key
yield DummySpan.new
end
end
class DummySpan
def resource=(resource_name)
SPAN_RESOURCE_NAMES << resource_name
end
def set_tag(key, value)
SPAN_TAGS << [key, value]
end
def finish
end
end
module Tracing
def self.trace(platform_key, *args)
TRACE_KEYS << platform_key
if block_given?
yield DummySpan.new
else
DummySpan.new
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/support/minimum_input_object.rb | spec/support/minimum_input_object.rb | # frozen_string_literal: true
# This is the minimum required interface for an input object
class MinimumInputObject
include Enumerable
def initialize(values)
@values = values
end
def each(&block)
@values.each(&block)
end
def [](key)
@values[key]
end
def key?(key)
@values.key?(key)
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/lazy_helpers.rb | spec/support/lazy_helpers.rb | # frozen_string_literal: true
module LazyHelpers
MAGIC_NUMBER_WITH_LAZY_AUTHORIZED_HOOK = 44
MAGIC_NUMBER_THAT_RETURNS_NIL = 0
MAGIC_NUMBER_THAT_RAISES_ERROR = 13
class Wrapper
def initialize(item = nil, &block)
if block
@block = block
else
@item = item
end
end
def item
if @block
@item = @block.call()
@block = nil
end
@item
end
end
class SumAll
attr_reader :own_value
attr_writer :value
def initialize(own_value)
@own_value = own_value
all << self
end
def value
@value ||= begin
total_value = all.map(&:own_value).reduce(&:+)
all.each { |v| v.value = total_value}
all.clear
total_value
end
@value
end
def all
self.class.all
end
def self.all
@all ||= []
end
end
class LazySum < GraphQL::Schema::Object
field :value, Integer
def value
if object == MAGIC_NUMBER_THAT_RAISES_ERROR
nil
else
object
end
end
def self.authorized?(obj, ctx)
if obj == MAGIC_NUMBER_WITH_LAZY_AUTHORIZED_HOOK
Wrapper.new { true }
else
true
end
end
field :nested_sum, LazySum, null: false do
argument :value, Integer
end
def nested_sum(value:)
if value == MAGIC_NUMBER_THAT_RAISES_ERROR
Wrapper.new(nil)
else
SumAll.new(@object + value)
end
end
field :nullable_nested_sum, LazySum do
argument :value, Integer
end
alias :nullable_nested_sum :nested_sum
end
class LazyQuery < GraphQL::Schema::Object
field :int, Integer, null: false do
argument :value, Integer
argument :plus, Integer, required: false, default_value: 0
end
def int(value:, plus:)
Wrapper.new(value + plus)
end
field :nested_sum, LazySum, null: false do
argument :value, Integer
end
def nested_sum(value:)
SumAll.new(value)
end
field :nullable_nested_sum, LazySum do
argument :value, Integer
end
def nullable_nested_sum(value:)
if value == MAGIC_NUMBER_THAT_RAISES_ERROR
Wrapper.new { raise GraphQL::ExecutionError.new("#{MAGIC_NUMBER_THAT_RAISES_ERROR} is unlucky") }
elsif value == MAGIC_NUMBER_THAT_RETURNS_NIL
nil
else
SumAll.new(value)
end
end
field :list_sum, [LazySum, null: true] do
argument :values, [Integer]
end
def list_sum(values:)
values.map { |v| v == MAGIC_NUMBER_THAT_RETURNS_NIL ? nil : v }
end
end
module SumAllInstrumentation
def execute_query(query:)
add_check(query, "before #{query.selected_operation.name}")
super
end
def execute_query_lazy(query:, multiplex:)
result = super
multiplex.queries.reverse_each do |q|
add_check(q, "after #{q.selected_operation.name}")
end
result
end
def execute_multiplex(multiplex:)
add_check(multiplex, "before multiplex 1")
# TODO not threadsafe
# This should use multiplex-level context
SumAll.all.clear
result = super
add_check(multiplex, "after multiplex 1")
result
end
private
def add_check(object, text)
checks = object.context[:instrumentation_checks]
if checks
checks << text
end
end
end
module SumAllInstrumentation2
def execute_multiplex(multiplex:)
add_check(multiplex, "before multiplex 2")
result = super
add_check(multiplex, "after multiplex 2")
result
end
private
def add_check(object, text)
checks = object.context[:instrumentation_checks]
if checks
checks << text
end
end
end
class LazySchema < GraphQL::Schema
query(LazyQuery)
mutation(LazyQuery)
lazy_resolve(Wrapper, :item)
lazy_resolve(SumAll, :value)
trace_with(SumAllInstrumentation2)
trace_with(SumAllInstrumentation)
def self.sync_lazy(lazy)
if lazy.is_a?(SumAll) && lazy.own_value > 1000
lazy.value # clear the previous set
lazy.own_value - 900
else
super
end
end
end
def run_query(query_str, **rest)
LazySchema.execute(query_str, **rest)
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/new_relic.rb | spec/support/new_relic.rb | # frozen_string_literal: true
# A stub for the NewRelic agent, so we can make assertions about how it is used
if defined?(NewRelic)
raise "Expected NewRelic to be undefined, so that we could define a stub for it."
end
module NewRelic
TRANSACTION_NAMES = []
EXECUTION_SCOPES = []
# Reset state between tests
def self.clear_all
TRANSACTION_NAMES.clear
EXECUTION_SCOPES.clear
end
module Agent
def self.set_transaction_name(name)
TRANSACTION_NAMES << name
end
module Tracer
def self.start_transaction_or_segment(partial_name:, category:)
EXECUTION_SCOPES << partial_name
Finisher.new(partial_name)
end
class Finisher
def initialize(name)
@partial_name = name
end
def finish
EXECUTION_SCOPES << "FINISH #{@partial_name}"
nil
end
end
end
module MethodTracerHelpers
def self.trace_execution_scoped(trace_name)
EXECUTION_SCOPES << trace_name
yield
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/support/static_validation_helpers.rb | spec/support/static_validation_helpers.rb | # frozen_string_literal: true
# This module assumes you have `let(:query_string)` in your spec.
# It provides `errors` which are the validation errors for that string,
# as validated against `Dummy::Schema`.
# You can override `schema` to provide another schema
# @example testing static validation
# include StaticValidationHelpers
# let(:query_string) { " ... " }
# it "validates" do
# assert_equal(errors, [ ... ])
# assert_equal(error_messages, [ ... ])
# end
module StaticValidationHelpers
def errors
@errors ||= begin
target_schema = schema
validator = GraphQL::StaticValidation::Validator.new(schema: target_schema)
query = GraphQL::Query.new(target_schema, query_string)
validator.validate(query, **args)[:errors].map(&:to_h)
end
end
def error_messages
errors.map { |e| e["message"] }
end
def schema
Dummy::Schema
end
def args
{}
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/jazz.rb | spec/support/jazz.rb | # frozen_string_literal: true
# Here's the "application"
module Jazz
module Models
Instrument = Struct.new(:name, :family)
Ensemble = Struct.new(:name)
Musician = Struct.new(:name, :favorite_key)
Key = Struct.new(:root, :sharp, :flat) do
def self.from_notation(key_str)
key, sharp_or_flat = key_str.split("")
sharp = sharp_or_flat == "♯"
flat = sharp_or_flat == "♭"
Models::Key.new(key, sharp, flat)
end
def to_notation
"#{root}#{sharp ? "♯" : ""}#{flat ? "♭" : ""}"
end
end
def self.reset
@data = {
"Instrument" => [
Models::Instrument.new("Banjo", :str),
Models::Instrument.new("Flute", "WOODWIND"),
Models::Instrument.new("Trumpet", "BRASS"),
Models::Instrument.new("Piano", "KEYS"),
Models::Instrument.new("Organ", "KEYS"),
Models::Instrument.new("Drum Kit", "PERCUSSION"),
],
"Ensemble" => [
Models::Ensemble.new("Bela Fleck and the Flecktones"),
Models::Ensemble.new("Robert Glasper Experiment"),
Models::Ensemble.new("Spinal Tap"),
],
"Musician" => [
Models::Musician.new("Herbie Hancock", Models::Key.from_notation("B♭")),
],
}
end
def self.data
@data || reset
end
end
class BaseArgument < GraphQL::Schema::Argument
def initialize(*args, custom: nil, **kwargs)
@custom = custom
super(*args, **kwargs)
end
end
# A custom field class that supports the `upcase:` option
class BaseField < GraphQL::Schema::Field
argument_class BaseArgument
attr_reader :upcase
def initialize(*args, **options, &block)
@upcase = options.delete(:upcase)
super(*args, **options, &block)
end
def resolve_field(*)
result = super
if @upcase && result
result.upcase
else
result
end
end
def resolve(*)
result = super
if @upcase && result
result.upcase
else
result
end
end
end
class BaseObject < GraphQL::Schema::Object
# Use this overridden field class
field_class BaseField
class << self
def config(key, value)
configs[key] = value
end
def configs
@configs ||= {}
end
end
end
module BaseInterface
include GraphQL::Schema::Interface
# Use this overridden field class
field_class BaseField
# These methods are available to child interfaces
definition_methods do
def upcased_field(*args, **kwargs, &block)
field(*args, upcase: true, **kwargs, &block)
end
end
end
class BaseEnumValue < GraphQL::Schema::EnumValue
def initialize(*args, custom_setting: nil, **kwargs, &block)
@custom_setting = custom_setting
super(*args, **kwargs, &block)
end
end
class BaseEnum < GraphQL::Schema::Enum
enum_value_class BaseEnumValue
end
# Some arbitrary global ID scheme
# *Type suffix is removed automatically
module GloballyIdentifiableType
include BaseInterface
description "A fetchable object in the system"
field(
name: :id,
type: ID,
null: false,
description: "A unique identifier for this object",
)
upcased_field :upcased_id, ID, null: false, resolver_method: :id # upcase: true added by helper
def id
GloballyIdentifiableType.to_id(@object)
end
def self.to_id(object)
"#{object.class.name.split("::").last}/#{object.name}"
end
def self.find(id)
class_name, object_name = id.split("/")
Models.data[class_name].find { |obj| obj.name == object_name }
end
end
module WithNameField
def self.prepended(base)
base.field :name, String, null: false
end
end
module NamedEntity
include BaseInterface
prepend WithNameField
end
class PrivateMembership < GraphQL::Schema::TypeMembership
def initialize(*args, visibility: nil, **kwargs)
@visibility = visibility
super(*args, **kwargs)
end
def visible?(ctx)
return true if @visibility.nil?
@visibility[:private] && ctx[:private]
end
end
module PrivateNameEntity
include BaseInterface
type_membership_class PrivateMembership
field :private_name, String, null: false
def private_name
"private name"
end
end
module InvisibleNameEntity
include BaseInterface
field :invisible_name, String, null: false
field :overridden_name, String, null: false
def self.visible?(ctx)
ctx[:private]
end
end
# test field inheritance
class ObjectWithUpcasedName < BaseObject
# Test extra arguments:
field :upcase_name, String, null: false, upcase: true
def upcase_name
object.name # upcase is applied by the superclass
end
end
module HasMusicians
include BaseInterface
field :musicians, "[Jazz::Musician]", null: false
end
# Here's a new-style GraphQL type definition
class Ensemble < ObjectWithUpcasedName
# Test string type names
# This method should override inherited one
field :name, "String", null: false, resolver_method: :overridden_name
implements GloballyIdentifiableType, NamedEntity, HasMusicians, InvisibleNameEntity
implements PrivateNameEntity, visibility: { private: true }
description "A group of musicians playing together"
config :config, :configged
field :formed_at, String, hash_key: "formedAtDate"
# This overrides the visibility from PrivateNameEntity
field :overridden_name, String, null: false
def overridden_name
@object.name.sub("Robert Glasper", "ROBERT GLASPER")
end
def self.authorized?(object, context)
# Spinal Tap is top-secret, don't show it to anyone.
obj_name = object.is_a?(Hash) ? object[:name] : object.name
obj_name != "Spinal Tap"
end
end
class Family < BaseEnum
description "Groups of musical instruments"
# support string and symbol
value "STRING", "Makes a sound by vibrating strings", value: :str, custom_setting: 1
value :WOODWIND, "Makes a sound by vibrating air in a pipe"
value :BRASS, "Makes a sound by amplifying the sound of buzzing lips"
value "PERCUSSION", "Makes a sound by hitting something that vibrates",
value_method: :precussion_custom_value_method
value "DIDGERIDOO", "Makes a sound by amplifying the sound of buzzing lips", deprecation_reason: "Merged into BRASS"
value "KEYS" do
description "Neither here nor there, really"
end
value "SILENCE", "Makes no sound", value: false
end
class InstrumentType < BaseObject
implements NamedEntity
implements GloballyIdentifiableType
field :upcased_id, ID, null: false
def upcased_id
GloballyIdentifiableType.to_id(object).upcase
end
field :family, Family, null: false
end
class Key < GraphQL::Schema::Scalar
description "A musical key"
def self.coerce_input(val, ctx)
Models::Key.from_notation(val)
end
def self.coerce_result(val, ctx)
val.to_notation
end
end
class Musician < BaseObject
implements GloballyIdentifiableType
implements NamedEntity
description "Someone who plays an instrument"
field :instrument, InstrumentType, null: false do
description "An object played in order to produce music"
end
field :favorite_key, Key
# Test lists with nullable members:
field :inspect_context, [String, null: true], null: false
field :add_error, String, null: false, extras: [:execution_errors]
def inspect_context
[
@context.custom_method,
@context[:magic_key],
@context[:normal_key],
nil,
]
end
def add_error(execution_errors:)
execution_errors.add("this has a path")
"done"
end
end
class StylishMusician < Musician
field :sunglasses_type, String, null: false
def sunglasses_type
"cool 😎"
end
end
# Since this is not a legacy input type, this test can be removed
class LegacyInputType < GraphQL::Schema::InputObject
argument :int_value, Int
end
class FullyOptionalInput < GraphQL::Schema::InputObject
argument :optional_value, String, required: false
end
class InspectableInput < GraphQL::Schema::InputObject
argument :ensemble_id, ID, required: false, loads: Ensemble
argument :string_value, String, description: "Test description kwarg"
argument :nested_input, InspectableInput, required: false
argument :legacy_input, LegacyInputType, required: false
def helper_method
[
# Context is available in the InputObject
context[:message],
# ~~A GraphQL::Query::Arguments instance is available~~ not anymore
self[:string_value],
# Legacy inputs have underscored method access too
legacy_input ? legacy_input.int_value : "-",
# Access by method call is available
"(#{nested_input ? nested_input.helper_method : "-"})",
].join(", ")
end
end
class InspectableKey < BaseObject
field :root, String, null: false
field :is_sharp, Boolean, null: false, method: :sharp
field :is_flat, Boolean, null: false, method: :flat
end
class PerformingActVisibility < GraphQL::Schema::TypeMembership
def initialize(*args, visibility: nil, **kwargs)
@visibility = visibility
super(*args, **kwargs)
end
def visible?(ctx)
return true if @visibility.nil?
!ctx[@visibility]
end
end
class PerformingAct < GraphQL::Schema::Union
type_membership_class PerformingActVisibility
possible_types Musician
possible_types Ensemble, visibility: :hide_ensemble
def self.resolve_type(object, context)
GraphQL::Execution::Lazy.new do
if object.is_a?(Models::Ensemble)
Ensemble
else
Musician
end
end
end
end
class HashKeyTest < BaseObject
field :falsey, Boolean, null: false
end
class CamelizedBooleanInput < GraphQL::Schema::InputObject
argument :camelized_boolean, Boolean
end
# Another new-style definition, with method overrides
class Query < BaseObject
field :ensembles, [Ensemble], null: false
field :find, GloballyIdentifiableType do
argument :id, ID
end
field :instruments, [InstrumentType], null: false do
argument :family, Family, required: false
end
field :inspect_input, [String], null: false do
argument :input, InspectableInput, custom: :ok
end
field :inspect_key, InspectableKey, null: false do
argument :key, Key
end
field :now_playing, PerformingAct, null: false
def now_playing; Models.data["Ensemble"].first; end
# For asserting that the *resolver* object is initialized once:
# `method_conflict_warning: false` tells graphql-ruby that exposing Object#object_id was intentional
field :object_id, String, null: false, method_conflict_warning: false
field :inspect_context, [String], null: false
field :hashy_ensemble, Ensemble, null: false
field :echo_json, GraphQL::Types::JSON, null: false do
argument :input, GraphQL::Types::JSON
end
field :echo_first_json, GraphQL::Types::JSON, null: false do
argument :input, [GraphQL::Types::JSON]
end
field :upcase_check_1, String, resolver_method: :upcase_check, extras: [:upcase]
field :upcase_check_2, String, null: false, upcase: false, resolver_method: :upcase_check, extras: [:upcase]
field :upcase_check_3, String, null: false, upcase: true, resolver_method: :upcase_check, extras: [:upcase]
field :upcase_check_4, String, null: false, upcase: "why not?", resolver_method: :upcase_check, extras: [:upcase]
def upcase_check(upcase:)
upcase.inspect
end
field :input_object_camelization, String, null: false do
argument :input, CamelizedBooleanInput
end
def input_object_camelization(input:)
input.to_h.inspect
end
def ensembles
# Filter out the unauthorized one to avoid an error later
Models.data["Ensemble"].select { |e| e.name != "Spinal Tap" }
end
def find(id:)
if id == "MagicalSkipId"
context.skip
else
GloballyIdentifiableType.find(id)
end
end
def instruments(family: nil)
objs = Models.data["Instrument"]
if family
objs = objs.select { |i| i.family == family }
end
objs
end
# This is for testing input object behavior
def inspect_input(input:)
[
input.class.name,
input.helper_method,
# Access by method
input.string_value,
# Access by key:
input[:string_value],
input.key?(:string_value).to_s,
# ~~Access by legacy key~~ # not anymore
input[:string_value],
input.ensemble || "No ensemble",
input.key?(:ensemble).to_s,
]
end
def inspect_key(key:)
key
end
def inspect_context
[
context.custom_method,
context[:magic_key],
context[:normal_key],
]
end
def hashy_ensemble
# Both string and symbol keys are supported:
{
name: "The Grateful Dead",
"musicians" => [
OpenStruct.new(name: "Jerry Garcia"),
],
"formedAtDate" => "May 5, 1965",
}
end
def echo_json(input:)
input
end
def echo_first_json(input:)
input.first
end
field :hash_by_string, HashKeyTest, null: false
field :hash_by_sym, HashKeyTest, null: false
def hash_by_string
{"falsey" => false}
end
def hash_by_sym
{falsey: false}
end
field :named_entities, [NamedEntity, null: true], null: false
def named_entities
[Models.data["Ensemble"].first, nil]
end
field :default_value_test, String, null: false do
argument :arg_with_default, InspectableInput, required: false, default_value: { string_value: "S" }
end
def default_value_test(arg_with_default:)
"#{arg_with_default.class.name} -> #{arg_with_default.to_h}"
end
field :default_value_test_2, String, null: false, resolver_method: :default_value_test do
argument :arg_with_default, FullyOptionalInput, required: false, default_value: {}
end
field :complex_hash_key, String, null: false, hash_key: :'foo bar/fizz-buzz'
field :nullable_ensemble, Ensemble do
argument :ensemble_id, ID, required: false, loads: Ensemble
end
def nullable_ensemble(ensemble: nil)
ensemble
end
end
class EnsembleInput < GraphQL::Schema::InputObject
argument :name, String
end
class AddInstrument < GraphQL::Schema::Mutation
class << self
def prepare_name(value, context)
value.capitalize
end
end
null true
description "Register a new musical instrument in the database"
argument :name, String, prepare: :prepare_name
argument :family, Family
field :instrument, InstrumentType, null: false
# This is meaningless, but it's to test the conflict with `Hash#entries`
field :entries, [InstrumentType], null: false
# Test `extras` injection
field :ee, String, null: false
extras [:execution_errors]
def resolve(name:, family:, execution_errors:)
instrument = Jazz::Models::Instrument.new(name, family)
Jazz::Models.data["Instrument"] << instrument
{instrument: instrument, entries: Jazz::Models.data["Instrument"], ee: execution_errors.class.name}
end
end
class AddEnsembleRelay < GraphQL::Schema::RelayClassicMutation
argument :ensemble, EnsembleInput
field :ensemble, Ensemble, null: false
def resolve(ensemble:)
ens = Models::Ensemble.new(ensemble.name)
Models.data["Ensemble"] << ens
{ ensemble: ens }
end
end
class AddSitar < GraphQL::Schema::RelayClassicMutation
null true
description "Get Sitar to musical instrument"
field :instrument, InstrumentType, null: false
def resolve
instrument = Models::Instrument.new("Sitar", :str)
{instrument: instrument}
end
end
class HasExtras < GraphQL::Schema::RelayClassicMutation
null true
description "Test extras in RelayClassicMutation"
argument :int, Integer, required: false
extras [:ast_node]
field :node_class, String, null: false
field :int, Integer
def resolve(int: nil, ast_node:)
{
int: int,
node_class: ast_node.class.name,
}
end
end
class HasFieldExtras < GraphQL::Schema::RelayClassicMutation
null true
description "Test field with extras in RelayClassicMutation"
argument :int, Integer, required: false
field :lookahead_class, String, null: false
field :int, Integer
def resolve(int: nil, lookahead:)
{
int: int,
lookahead_class: lookahead.class.name,
}
end
end
class StripsExtras < GraphQL::Schema::RelayClassicMutation
extras [:lookahead]
def resolve_with_support(lookahead: , **rest)
context[:has_lookahead] = !!lookahead
super(**rest)
end
end
class HasExtrasStripped < StripsExtras
field :int, Integer, null: false
def authorized?
true
end
def resolve
{
int: 51,
}
end
end
class RenameNamedEntity < GraphQL::Schema::RelayClassicMutation
argument :named_entity_id, ID, loads: NamedEntity
argument :new_name, String
field :named_entity, NamedEntity, null: false
def resolve(named_entity:, new_name:)
# doesn't actually update the "database"
dup_named_entity = named_entity.dup
dup_named_entity.name = new_name
{
named_entity: dup_named_entity
}
end
end
class RenamePerformingAct < GraphQL::Schema::RelayClassicMutation
argument :performing_act_id, ID, loads: PerformingAct
argument :new_name, String
field :performing_act, PerformingAct, null: false
def resolve(performing_act:, new_name:)
# doesn't actually update the "database"
dup_performing_act = performing_act.dup
dup_performing_act.name = new_name
{
performing_act: dup_performing_act
}
end
end
class RenameEnsemble < GraphQL::Schema::RelayClassicMutation
argument :ensemble_id, ID, loads: Ensemble
argument :new_name, String
field :ensemble, Ensemble, null: false
def resolve(ensemble:, new_name:)
# doesn't actually update the "database"
dup_ensemble = ensemble.dup
dup_ensemble.name = new_name
{
ensemble: dup_ensemble,
}
end
end
class UpvoteEnsembles < GraphQL::Schema::RelayClassicMutation
argument :ensemble_ids, [ID], loads: Ensemble
field :ensembles, [Ensemble], null: false
def resolve(ensembles:)
{
ensembles: ensembles
}
end
end
class UpvoteEnsemblesAsBands < GraphQL::Schema::RelayClassicMutation
argument :ensemble_ids, [ID], loads: Ensemble, as: :bands
field :ensembles, [Ensemble], null: false
def resolve(bands:)
{
ensembles: bands
}
end
end
class UpvoteEnsemblesIds < GraphQL::Schema::RelayClassicMutation
argument :ensembles_ids, [ID], loads: Ensemble
field :ensembles, [Ensemble], null: false
def resolve(ensembles:)
{
ensembles: ensembles
}
end
end
class RenameEnsembleAsBand < RenameEnsemble
argument :ensemble_id, ID, loads: Ensemble, as: :band
# This is duplicate to the inherited one; make sure it overrides it
field :ensemble, Ensemble, null: false
def resolve(band:, new_name:)
super(ensemble: band, new_name: new_name)
end
end
class LoadAndReturnEnsemble < GraphQL::Schema::RelayClassicMutation
argument :ensemble_id, ID, required: false, loads: Ensemble
field :ensemble, Ensemble
def resolve(ensemble: nil)
{ ensemble: ensemble }
end
end
class DummyOutput < GraphQL::Schema::Object
graphql_name "DummyOutput"
field :name, String
end
class ReturnsMultipleErrors < GraphQL::Schema::Mutation
field :dummy_field, DummyOutput, null: false
def resolve
[
GraphQL::ExecutionError.new("First error"),
GraphQL::ExecutionError.new("Second error")
]
end
end
class ReturnInvalidNull < GraphQL::Schema::Mutation
field :int, Integer, null: false
def resolve
{ int: nil }
end
end
class Mutation < BaseObject
field :add_ensemble, Ensemble, null: false do
argument :input, EnsembleInput
end
field :add_instrument, mutation: AddInstrument
field :add_ensemble_relay, mutation: AddEnsembleRelay
field :add_sitar, mutation: AddSitar
field :rename_ensemble, mutation: RenameEnsemble
field :rename_named_entity, mutation: RenameNamedEntity
field :rename_performing_act, mutation: RenamePerformingAct
field :upvote_ensembles, mutation: UpvoteEnsembles
field :upvote_ensembles_as_bands, mutation: UpvoteEnsemblesAsBands
field :upvote_ensembles_ids, mutation: UpvoteEnsemblesIds
field :rename_ensemble_as_band, mutation: RenameEnsembleAsBand
field :load_and_return_ensemble, mutation: LoadAndReturnEnsemble
field :returns_multiple_errors, mutation: ReturnsMultipleErrors, null: false
field :has_extras, mutation: HasExtras
field :has_extras_stripped, mutation: HasExtrasStripped
field :has_field_extras, mutation: HasFieldExtras, extras: [:lookahead]
field :return_invalid_null, mutation: ReturnInvalidNull
def add_ensemble(input:)
ens = Models::Ensemble.new(input.name)
Models.data["Ensemble"] << ens
ens
end
field :prepare_input, Integer, null: false do
argument :input, Integer, prepare: :square, as: :squared_input
end
def prepare_input(squared_input:)
# Test that `square` is called
squared_input
end
def square(value)
value ** 2
end
end
class CustomContext < GraphQL::Query::Context
def [](key)
if key == :magic_key
"magic_value"
else
super
end
end
def custom_method
"custom_method"
end
end
module Introspection
class TypeType < GraphQL::Introspection::TypeType
def self.authorized?(_obj, ctx)
if ctx[:cant_introspect]
raise GraphQL::ExecutionError, "You're not allowed to introspect here"
else
super
end
end
def name
n = object.graphql_name
n && n.upcase
end
end
class NestedType < GraphQL::Introspection::TypeType
def name
object.name.upcase
end
class DeeplyNestedType < GraphQL::Introspection::TypeType
def name
object.name.upcase
end
end
end
class SchemaType < GraphQL::Introspection::SchemaType
graphql_name "__Schema"
field :is_jazzy, Boolean, null: false
def is_jazzy
true
end
end
class DynamicFields < GraphQL::Introspection::DynamicFields
field :__typename_length, Int, null: false
field :__ast_node_class, String, null: false, extras: [:ast_node]
def __typename_length
__typename.length
end
def __ast_node_class(ast_node:)
ast_node.class.name
end
end
class EntryPoints < GraphQL::Introspection::EntryPoints
field :__classname, String, "The Ruby class name of the root object", null: false
def __classname
object.object.class.name
end
end
end
# New-style Schema definition
class Schema < GraphQL::Schema
query(Query)
mutation(Mutation)
context_class CustomContext
introspection(Introspection)
def self.resolve_type(type, obj, ctx)
class_name = obj.class.name.split("::").last
ctx.schema.types[class_name] || raise("No type for #{obj.inspect}")
end
def self.object_from_id(id, ctx)
GloballyIdentifiableType.find(id)
end
BlogPost = Class.new(GraphQL::Schema::Object)
BlogPost.has_no_fields(true)
extra_types BlogPost
use GraphQL::Dataloader
use GraphQL::Schema::Warden if ADD_WARDEN
end
class SchemaWithoutIntrospection < GraphQL::Schema
query(Query)
disable_introspection_entry_points
use GraphQL::Dataloader
use GraphQL::Schema::Warden if ADD_WARDEN
end
class SchemaWithoutSchemaIntrospection < GraphQL::Schema
query(Query)
disable_schema_introspection_entry_point
use GraphQL::Schema::Warden if ADD_WARDEN
end
class SchemaWithoutTypeIntrospection < GraphQL::Schema
query(Query)
disable_type_introspection_entry_point
use GraphQL::Schema::Warden if ADD_WARDEN
end
class SchemaWithoutSchemaOrTypeIntrospection < GraphQL::Schema
query(Query)
disable_schema_introspection_entry_point
disable_type_introspection_entry_point
use GraphQL::Schema::Warden if ADD_WARDEN
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/rubocop_test_helpers.rb | spec/support/rubocop_test_helpers.rb | # frozen_string_literal: true
require "yaml"
module RubocopTestHelpers
def run_rubocop_on(fixture_path, autocorrect: false)
assert_cop_runs_on(fixture_path)
result = `bundle exec rubocop --debug #{autocorrect ? "--auto-correct" : ""} --config spec/fixtures/cop/.rubocop.yml #{fixture_path} 2>&1`
refute_includes result, "An error occurred", "Nothing went wrong"
result
end
def rubocop_errors(rubocop_result)
rubocop_result =~ /(\d) offenses? detected/
$1.to_i
end
def assert_rubocop_autocorrects_all(fixture_path)
autocorrect_target_path = fixture_path.sub(".rb", "_autocorrect.rb")
FileUtils.cp(fixture_path, autocorrect_target_path)
run_rubocop_on(autocorrect_target_path, autocorrect: true)
result2 = run_rubocop_on(autocorrect_target_path)
assert_equal 0, rubocop_errors(result2), "All errors were corrected in #{autocorrect_target_path}:
#{File.read(autocorrect_target_path)}
###
#{result2}"
expected_file = File.read(fixture_path.sub(".rb", "_corrected.rb"))
assert_equal expected_file, File.read(autocorrect_target_path), "The autocorrected file has the expected contents"
ensure
FileUtils.rm(autocorrect_target_path)
end
def assert_cop_runs_on(fixture_path)
@rubocop_config ||= YAML.load_file(File.expand_path("spec/fixtures/cop/.rubocop.yml"))
file_name = fixture_path.split("/").last
cop_name = "GraphQL/" + self.class.name.split("::").last
cop_config = @rubocop_config[cop_name] || raise("No config for #{cop_name.inspect} (#{@rubocop_config.inspect})")
assert cop_config["Enabled"], "#{cop_name} is enabled"
if cop_config.key?("Include")
assert cop_config["Include"].include?(file_name), "#{file_name.inspect} is included for #{cop_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/support/perfetto_snapshot.rb | spec/support/perfetto_snapshot.rb | # frozen_string_literal: true
module PerfettoSnapshot
def check_snapshot(data, snapshot_name)
prev_file = caller(1, 1).first.sub(/\/[a-z_]*\.rb:.*/, "")
snapshot_dir = prev_file + "/snapshots"
snapshot_path = "#{snapshot_dir}/#{snapshot_name}"
iid_table = { "debugAnnotationNames" => {}, "eventNames" => {}, "eventCategories" => {}, "debugAnnotationStringValues" => {} }
build_intern_map(data, iid_table)
if ENV["UPDATE_PERFETTO"]
puts "Updating PerfettoTrace snapshot: #{snapshot_path.inspect}"
snapshot_json = convert_to_snapshot(data, iid_table)
FileUtils.mkdir_p(snapshot_dir)
File.write(snapshot_path, JSON.pretty_generate(snapshot_json))
elsif !File.exist?(snapshot_path)
raise "Snapshot file not found: #{snapshot_path.inspect}"
else
snapshot_data = JSON.parse(File.read(snapshot_path))
cleaned_data = convert_to_snapshot(data, iid_table)
deep_snap_match(snapshot_data, cleaned_data, [])
end
end
def deep_snap_match(snapshot_data, data, path)
case snapshot_data
when String
assert_kind_of String, data, "Is String at #{path.join(".")}"
if snapshot_data.match(/\D/).nil? && data.match(/\D/).nil?
# Ok
elsif BASE64_PATTERN.match?(snapshot_data)
snapshot_data_decoded = Base64.decode64(snapshot_data)
data_decoded = Base64.decode64(data)
assert_equal snapshot_data_decoded, data_decoded, "Decoded match at #{path.join(".")}"
else
assert_equal snapshot_data, data, "Match at #{path.join(".")}"
end
when Numeric
assert_kind_of Numeric, data, "Is numeric at #{path.join(".")}"
when Hash
assert_equal snapshot_data.class, data.class, "Match at #{path.join(".")}"
extra_keys = snapshot_data.keys - data.keys
extra_keys += data.keys - snapshot_data.keys
assert_equal snapshot_data.keys.sort, data.keys.sort, "Match at #{path.join(".")} (#{extra_keys.map { |k| "#{k.inspect} => #{data[k].inspect}, snapshot: #{snapshot_data[k].inspect}"}.join(", ")})"
snapshot_data.each do |k, v|
next_data = data[k]
if k == "debugAnnotations"
next_data.sort_by! { |d| d["name"] }
end
deep_snap_match(v, data[k], path + [k])
end
when Array
assert_equal(snapshot_data.class, data.class, "Match at #{path.join(".")}")
snapshot_data.each_with_index do |snapshot_i, idx|
data_i = data[idx]
deep_snap_match(snapshot_i, data_i, path + [idx])
end
end
end
BASE64_PATTERN = /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?\n?$/
def replace_ids(str)
str.gsub(/ #\d+/, " #1010").split(/:0x[0-9a-z]+/).first
end
def convert_to_snapshot(value, iid_table)
case value
when String
if value.match(/\D/).nil?
"10101010101010"
elsif BASE64_PATTERN.match?(value)
decoded_value = Base64.decode64(value)
decoded_value = replace_ids(decoded_value)
Base64.encode64(decoded_value)
else
replace_ids(value)
end
when Numeric
101010101010
when Array
value.map { |v| convert_to_snapshot(v, iid_table) }
when Hash
h2 = {}
value.each do |k, v|
case k
when "debugAnnotations"
v.each { |d|
if d.key?("nameIid")
d["name"] = iid_table["debugAnnotationNames"][d["nameIid"]]
end
if d.key?("stringValueIid")
d["stringValue"] = iid_table["debugAnnotationNames"][d["stringValueIid"]]
end
}
v = v.sort_by { |d| d["name"] }
when "categoryIids"
h2["categories"] = v.map { |ciid| iid_table["eventCategories"][ciid] }
when "trackEvent"
if v.key?("nameIid")
v["name"] = iid_table["eventNames"][v["nameIid"]]
end
end
h2[k] = convert_to_snapshot(v, iid_table)
end
h2
when true, false, nil
value
else
raise ArgumentError, "Unexpected JSON value: #{value}"
end
end
def build_intern_map(data, iid_table)
case data
when Hash
if (id = data["internedData"])
id.each do |id_type, entries|
type_table = iid_table.fetch(id_type)
entries.each do |entry|
type_table[entry["iid"]] = entry["name"] || (entry["str"] ? Base64.decode64(entry["str"]) : nil)
end
end
end
data.each do |k, v|
build_intern_map(v, iid_table)
end
when Array
data.each { |v| build_intern_map(v, iid_table) }
else
# Done
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/support/appoptics.rb | spec/support/appoptics.rb | # frozen_string_literal: true
# A stub for the AppOpticsAPM agent, so we can make assertions about how it is used
if defined?(AppOpticsAPM) && !AppOpticsAPM.graphql_test
raise "Expected AppOpticsAPM to be undefined, so that we can define a stub for it."
end
module AppOpticsAPM
def self.loaded; true; end
module SDK
def self.trace(name, kvs)
$appoptics_tracing_spans << name
$appoptics_tracing_kvs << kvs.dup
yield
end
def self.get_transaction_name
$appoptics_tracing_name
end
def self.set_transaction_name(name)
$appoptics_tracing_name = name
end
end
module Config
class << self
def [](key)
config[key.to_sym]
end
def []=(key, value)
config[key.to_sym] = value
end
def clear
config.clear
end
def config
@config ||= {}
end
end
end
def self.graphql_test
true
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/mongoid_setup.rb | spec/support/mongoid_setup.rb | # frozen_string_literal: true
if testing_mongoid?
# TODO make this work with existing fixtures
Mongoid.load_configuration({
clients: {
default: {
database: 'graphql_ruby_test',
hosts: ['localhost:27017']
}
},
sessions: {
default: {
database: 'graphql_ruby_test',
hosts: ['localhost:27017']
}
}
})
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/scout_apm.rb | spec/support/scout_apm.rb | # frozen_string_literal: true
# A stub for the Scout agent, so we can make assertions about how it is used
if defined?(ScoutApm)
raise "Expected ScoutApm to be undefined, so that we could define a stub for it."
end
class ScoutApm
TRANSACTION_NAMES = []
EVENTS = []
def self.clear_all
TRANSACTION_NAMES.clear
EVENTS.clear
end
module Tracer
def self.instrument(type, name, options = {})
EVENTS << name
yield
end
end
class Layer
def initialize(type, name)
EVENTS << name
end
def subscopable!
nil
end
end
module RequestManager
def self.lookup
self
end
def self.start_layer(_layer)
nil
end
def self.stop_layer
nil
end
end
module Transaction
def self.rename(name)
ScoutApm::TRANSACTION_NAMES << 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/support/sentry.rb | spec/support/sentry.rb | # frozen_string_literal: true
# A stub for the Sentry agent, so we can make assertions about how it is used
if defined?(Sentry)
raise "Expected Sentry to be undefined, so that we could define a stub for it."
end
module Sentry
SPAN_OPS = []
SPAN_DATA = []
SPAN_DESCRIPTIONS = []
TRANSACTION_NAMES = []
class << self
attr_accessor :use_nil_span
end
def self.initialized?
true
end
def self.utc_now
Time.now.utc
end
def self.get_current_scope
self
end
def self.get_span
use_nil_span ? nil : DummySpan
end
def self.with_child_span(**args, &block)
SPAN_OPS << args[:op]
yield DummySpan
end
def self.configure_scope(&block)
yield DummyScope
end
def self.clear_all
SPAN_DATA.clear
SPAN_DESCRIPTIONS.clear
SPAN_OPS.clear
TRANSACTION_NAMES.clear
end
module DummySpan
module_function
def set_data(key, value)
Sentry::SPAN_DATA << [key, value]
end
def set_description(description)
Sentry::SPAN_DESCRIPTIONS << description
end
def start_child(op:)
SPAN_OPS << op
end
def finish
# no-op
end
end
module DummyScope
module_function
def set_transaction_name(name)
TRANSACTION_NAMES << 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/support/dummy_scheduler.rb | spec/support/dummy_scheduler.rb | # frozen_string_literal: true
# From the Ruby source (https://github.com/ruby/ruby/blob/master/test/fiber/scheduler.rb)
#
# This is an example and simplified scheduler for test purposes.
# It is not efficient for a large number of file descriptors as it uses IO.select().
# Production Fiber schedulers should use epoll/kqueue/etc.
require 'fiber'
require 'socket'
require 'io/nonblock'
class DummyScheduler
def initialize
@readable = {}
@writable = {}
@waiting = {}
@closed = false
@lock = Mutex.new
@blocking = 0
@ready = []
@urgent = IO.pipe
end
attr :readable
attr :writable
attr :waiting
def next_timeout
_fiber, timeout = @waiting.min_by{|key, value| value}
if timeout
offset = timeout - current_time
if offset < 0
return 0
else
return offset
end
end
end
def run
# $stderr.puts [__method__, Fiber.current].inspect
while !@readable.empty? or !@writable.empty? or !@waiting.empty? or @blocking.positive?
# Can only handle file descriptors up to 1024...
readable, writable = IO.select(@readable.keys + [@urgent.first], @writable.keys, [], next_timeout)
# puts "readable: #{readable}" if readable&.any?
# puts "writable: #{writable}" if writable&.any?
selected = {}
readable && readable.each do |io|
if fiber = @readable.delete(io)
selected[fiber] = IO::READABLE
elsif io == @urgent.first
@urgent.first.read_nonblock(1024)
end
end
writable && writable.each do |io|
if fiber = @writable.delete(io)
selected[fiber] |= IO::WRITABLE
end
end
selected.each do |fiber, events|
fiber.resume(events)
end
if !@waiting.empty?
time = current_time
waiting, @waiting = @waiting, {}
waiting.each do |fiber, timeout|
if fiber.alive?
if timeout <= time
fiber.resume
else
@waiting[fiber] = timeout
end
end
end
end
if !@ready.empty?
ready = nil
@lock.synchronize do
ready, @ready = @ready, []
end
ready.each do |fiber|
fiber.resume
end
end
end
end
def close
# $stderr.puts [__method__, Fiber.current].inspect
raise "Scheduler already closed!" if @closed
self.run
ensure
@urgent.each(&:close)
@urgent = nil
@closed = true
# We freeze to detect any unintended modifications after the scheduler is closed:
self.freeze
end
def closed?
@closed
end
def current_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def timeout_after(duration, klass, message, &block)
fiber = Fiber.current
self.fiber do
sleep(duration)
if fiber && fiber.alive?
fiber.raise(klass, message)
end
end
begin
yield(duration)
ensure
fiber = nil
end
end
def process_wait(pid, flags)
# $stderr.puts [__method__, pid, flags, Fiber.current].inspect
# This is a very simple way to implement a non-blocking wait:
Thread.new do
Process::Status.wait(pid, flags)
end.value
end
def io_wait(io, events, duration)
# $stderr.puts [__method__, io, events, duration, Fiber.current].inspect
unless (events & IO::READABLE).zero?
@readable[io] = Fiber.current
end
unless (events & IO::WRITABLE).zero?
@writable[io] = Fiber.current
end
Fiber.yield
end
# Used for Kernel#sleep and Mutex#sleep
def kernel_sleep(duration = nil)
# $stderr.puts [__method__, duration, Fiber.current].inspect
self.block(:sleep, duration)
return true
end
# Used when blocking on synchronization (Mutex#lock, Queue#pop, SizedQueue#push, ...)
def block(blocker, timeout = nil)
# $stderr.puts [__method__, blocker, timeout].inspect
if timeout
@waiting[Fiber.current] = current_time + timeout
begin
Fiber.yield
ensure
# Remove from @waiting in the case #unblock was called before the timeout expired:
@waiting.delete(Fiber.current)
end
else
@blocking += 1
begin
Fiber.yield
ensure
@blocking -= 1
end
end
end
# Used when synchronization wakes up a previously-blocked fiber (Mutex#unlock, Queue#push, ...).
# This might be called from another thread.
def unblock(blocker, fiber)
# $stderr.puts [__method__, blocker, fiber].inspect
# $stderr.puts blocker.backtrace.inspect
# $stderr.puts fiber.backtrace.inspect
@lock.synchronize do
@ready << fiber
end
io = @urgent.last
io.write_nonblock('.')
end
def fiber(&block)
fiber = Fiber.new(blocking: false, &block)
fiber.resume
return fiber
end
def address_resolve(hostname)
Thread.new do
Addrinfo.getaddrinfo(hostname, nil).map(&:ip_address).uniq
end.value
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/active_record_setup.rb | spec/support/active_record_setup.rb | # frozen_string_literal: true
if testing_rails?
# Remove the old sqlite database
sqlite_path = File.expand_path(File.join(__FILE__, "../../../_test_.db"))
puts "Removing #{sqlite_path}"
`rm -f #{sqlite_path}`
if ActiveRecord.respond_to?(:async_query_executor=) # Rails 7.1+
ActiveRecord.async_query_executor ||= :global_thread_pool
end
if ENV['DATABASE'] == 'POSTGRESQL'
ar_connection_options = {
host: "localhost",
adapter: "postgresql",
username: "postgres",
password: ENV["PGPASSWORD"], # empty in development, populated for GH Actions
database: "graphql_ruby_test",
}
ActiveRecord::Base.establish_connection(ar_connection_options.merge(
database: "postgres"
))
databases = ActiveRecord::Base.connection.execute("select datname from pg_database;")
test_db = databases.find { |d| d["datname"] == "graphql_ruby_test" }
if test_db
ActiveRecord::Base.connection.execute("drop database graphql_ruby_test;")
end
ActiveRecord::Base.connection.execute("create database graphql_ruby_test;")
ActiveRecord::Base.configurations = {
starwars: ar_connection_options,
starwars_replica: ar_connection_options,
}
SequelDB = Sequel.connect("postgres://postgres:#{ENV["PGPASSWORD"]}@localhost:5432/graphql_ruby_test")
else
ActiveRecord::Base.configurations = {
starwars: { adapter: "sqlite3", database: sqlite_path },
starwars_replica: { adapter: "sqlite3", database: sqlite_path },
}
SequelDB = Sequel.sqlite(sqlite_path)
end
ActiveRecord::Base.establish_connection(:starwars)
ActiveRecord::Schema.define(force: true) do
self.verbose = !!ENV["GITHUB_ACTIONS"]
create_table :bases, force: true do |t|
t.column :name, :string
t.column :planet, :string
t.column :faction_id, :integer
end
create_table :foods, force: true do |t|
t.column :name, :string
end
create_table :things, force: true do |t|
t.string :name
t.integer :other_thing_id
end
create_table :bands, force: true do |t|
t.string :name
t.integer :genre
t.integer :thing_id
t.string :thing_type
end
create_table :albums, force: true do |t|
t.string :name
t.integer :band_id
t.string :band_name
t.integer :band_genre
t.timestamps
end
create_table :books do |t|
t.string :title
t.integer :author_id
end
create_table :reviews do |t|
t.integer :stars
t.integer :user_id
t.integer :book_id
end
create_table :authors do |t|
t.string :name
end
create_table :users do |t|
t.string :username
end
create_table :input_test_users, force: true do |t|
t.datetime :created_at
t.date :birthday
t.integer :points
t.decimal :rating
t.references :friend, foreign_key: { to_table: :input_test_users}
end
create_table :test_users, force: true do |t|
t.datetime :created_at
t.date :birthday
t.integer :points, null: false
t.decimal :rating, null: false
end
end
class Food < ActiveRecord::Base
include GlobalID::Identification
end
class Album < ActiveRecord::Base
belongs_to :band
enum :band_genre, [:rock, :country, :jazz]
if Rails::VERSION::STRING > "8"
belongs_to :composite_band, foreign_key: [:band_name, :band_genre]
elsif Rails::VERSION::STRING > "7.1"
belongs_to :composite_band, query_constraints: [:band_name, :band_genre]
end
before_save :populate_band_fields
def populate_band_fields
self.band_name = self.band.name
self.band_genre = self.band.genre
end
end
class Band < ActiveRecord::Base
has_many :albums
enum :genre, [:rock, :country, :jazz]
belongs_to :thing, polymorphic: true
end
class AlternativeBand < Band
self.table_name = :bands
self.primary_key = :name
end
class CompositeBand < Band
self.table_name = :bands
self.primary_key = [:name, :genre]
end
v = Band.create!(id: 1, name: "Vulfpeck", genre: :rock)
t = Band.create!(id: 2, name: "Tom's Story", genre: :rock, thing: v)
c = Band.create!(id: 3, name: "Chon", genre: :rock, thing: v)
w = Band.create!(id: 4, name: "Wilco", genre: :country, thing: v)
v.albums.create!(id: 1, name: "Mit Peck")
v.albums.create!(id: 2, name: "My First Car")
t.albums.create!(id: 3, name: "Tom's Story")
c.albums.create!(id: 4, name: "Homey")
c.albums.create!(id: 5, name: "Chon")
w.albums.create!(id: 6, name: "Summerteeth")
class Author < ActiveRecord::Base
has_many :books
def self.inspect
sleep 0.2
super
end
end
class User < ActiveRecord::Base
has_many :reviews
end
class Book < ActiveRecord::Base
has_many :reviews
belongs_to :author
end
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :book
end
data = [
{
author: "William Shakespeare",
titles: [
"A Midsummer Night's Dream",
"The Merry Wives of Windsor",
"Much Ado about Nothing",
"Julius Caesar",
"Hamlet",
"King Lear",
"Macbeth",
"Romeo and Juliet",
"Othello"
]
},
{
author: "Beatrix Potter",
titles: [
"The Tale of Peter Rabbit",
"The Tale of Squirrel Nutkin",
"The Tailor of Gloucester",
"The Tale of Benjamin Bunny",
"The Tale of Two Bad Mice",
"The Tale of Mrs. Tiggy-Winkle",
"The Tale of The Pie and the Patty-Pan",
"The Tale of Mr. Jeremy Fisher",
"The Story of a Fierce Bad Rabbit",
]
},
{
author: "Charles Dickens",
titles: [
"The Pickwick Papers",
"Oliver Twist",
"A Christmas Carol",
"David Copperfield",
"Little Dorrit ",
"A Tale of Two Cities",
"Great Expectations",
]
},
{
author: "한강",
titles: [
"작별하지 않는다",
"흰",
"소년이 온다",
"노랑무늬영원"
]
}
]
data.each do |info|
author = Author.create!(name: info[:author])
info[:titles].each do |title|
Book.create!(author: author, title: title)
end
end
users = ["matz", "tenderlove", "dhh", "_why"].map { |un| User.create!(username: un) }
possible_stars = [1,2,3,4,5]
Book.all.each do |book|
users.each_with_index do |user, idx|
Review.create!(book: book, user: user, stars: possible_stars[idx])
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/support/dummy/data.rb | spec/support/dummy/data.rb | # frozen_string_literal: true
require 'ostruct'
module Dummy
module Data
Cheese = Struct.new(:id, :flavor, :origin, :fat_content, :source) do
def ==(other)
# This is buggy on purpose -- it shouldn't be called during execution.
other.id == id
end
# Alias for when this is treated as milk in EdibleAsMilkInterface
def fatContent # rubocop:disable Naming/MethodName
fat_content
end
end
Milk = Struct.new(:id, :fat_content, :origin, :source, :flavors)
Cow = Struct.new(:id, :name, :last_produced_dairy)
Goat = Struct.new(:id, :name, :last_produced_dairy)
end
CHEESES = {
1 => Data::Cheese.new(1, "Brie", "France", 0.19, 1),
2 => Data::Cheese.new(2, "Gouda", "Netherlands", 0.3, 1),
3 => Data::Cheese.new(3, "Manchego", "Spain", 0.065, "SHEEP")
}
MILKS = {
1 => Data::Milk.new(1, 0.04, "Antiquity", 1, ["Natural", "Chocolate", "Strawberry"]),
}
DAIRY = OpenStruct.new(
id: 1,
cheese: CHEESES[1],
milks: [MILKS[1]]
)
COWS = {
1 => Data::Cow.new(1, "Billy", MILKS[1])
}
GOATS = {
1 => Data::Goat.new(1, "Gilly", MILKS[1]),
}
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/dummy/schema.rb | spec/support/dummy/schema.rb | # frozen_string_literal: true
require "graphql"
require_relative "./data"
module Dummy
class NoSuchDairyError < StandardError; end
class BaseField < GraphQL::Schema::Field
end
class AdminField < GraphQL::Schema::Field
def visible?(context)
context[:admin] == true
end
end
module BaseInterface
include GraphQL::Schema::Interface
end
class BaseObject < GraphQL::Schema::Object
field_class BaseField
end
class BaseUnion < GraphQL::Schema::Union
end
class BaseEnum < GraphQL::Schema::Enum
end
class BaseInputObject < GraphQL::Schema::InputObject
end
class BaseScalar < GraphQL::Schema::Scalar
end
class BaseDirective < GraphQL::Schema::Directive
end
module LocalProduct
include BaseInterface
description "Something that comes from somewhere"
field :origin, String, null: false,
description: "Place the thing comes from"
end
module Edible
include BaseInterface
description "Something you can eat, yum"
field :fat_content, Float, null: false, description: "Percentage which is fat"
field :origin, String, null: false, description: "Place the edible comes from"
field :self_as_edible, Edible
def self_as_edible
object
end
end
module EdibleAsMilk
include Edible
description "Milk :+1:"
def self.resolve_type(obj, ctx)
Milk
end
end
class DairyAnimal < BaseEnum
description "An animal which can yield milk"
value("NONE", "No animal", value: nil)
value("COW", "Animal with black and white spots", value: 1)
value("DONKEY", "Animal with fur", value: :donkey)
value("GOAT", "Animal with horns")
value("REINDEER", "Animal with horns", value: 'reindeer')
value("SHEEP", "Animal with wool")
value("YAK", "Animal with long hair", deprecation_reason: "Out of fashion")
end
module AnimalProduct
include BaseInterface
description "Comes from an animal, no joke"
field :source, DairyAnimal, "Animal which produced this product", null: false
end
class Cheese < BaseObject
description "Cultured dairy product"
implements Edible
implements EdibleAsMilk
implements AnimalProduct
implements LocalProduct
def self.authorized?(obj, ctx)
-> { true }
end
field :id, Int, "Unique identifier", null: false
field :flavor, String, "Kind of Cheese", null: false
field :origin, String, "Place the cheese comes from", null: false
field :source, DairyAnimal,
"Animal which produced the milk for this cheese",
null: false
field :similar_cheese, Cheese, "Cheeses like this one" do
argument :source, [DairyAnimal]
argument :nullable_source, [DairyAnimal], required: false, default_value: [1]
end
def similar_cheese(source:, nullable_source:)
# get the strings out:
sources = source
if sources.include?("YAK")
raise NoSuchDairyError.new("No cheeses are made from Yak milk!")
else
CHEESES.values.find { |cheese| sources.include?(cheese.source) }
end
end
field :nullable_cheese, Cheese, "Not really a Cheese at all" do
argument :source, [DairyAnimal], required: false
end
def nullable_cheese; raise("NotImplemented"); end
field :dairy_product, "Dummy::DairyProduct", "Some related dairy product, perhaps" do
argument :input, "Dummy::DairyProductInput", required: false
end
def dairy_product; raise("NotImplemented"); end
field :deeply_nullable_cheese, Cheese, "Definitely not a cheese" do
argument :source, [[DairyAnimal, null: true], null: true], required: false
end
def deeply_nullable_cheese; raise("NotImplemented"); end
# Keywords can be used for definition methods
field :fat_content,
type: Float,
null: false,
description: "Percentage which is milkfat",
deprecation_reason: "Diet fashion has changed"
end
class Milk < BaseObject
description "Dairy beverage"
implements Edible
implements EdibleAsMilk
implements AnimalProduct
implements LocalProduct
field :id, ID, null: false
field :source, DairyAnimal, null: false, description: "Animal which produced this milk"
field :origin, String, null: false, description: "Place the milk comes from"
field :flavors, [String, null: true], description: "Chocolate, Strawberry, etc" do
argument :limit, Int, required: false
end
def flavors(limit: nil)
limit ? object.flavors.first(limit) : object.flavors
end
field :execution_error, String
def execution_error; raise(GraphQL::ExecutionError, "There was an execution error"); end
field :all_dairy, ["Dummy::DairyProduct", null: true]
def all_dairy; CHEESES.values + MILKS.values; end
end
class Beverage < BaseUnion
description "Something you can drink"
possible_types Milk
end
class Aspartame < BaseObject; end
module Sweetener
include BaseInterface
field :sweetness, Integer
orphan_types Aspartame
end
# No actual data; This type is an "orphan", only accessible through Interfaces
class Honey < BaseObject
description "Sweet, dehydrated bee barf"
field :flower_type, String, "What flower this honey came from"
implements Edible
implements AnimalProduct
implements Sweetener
end
# No actual data; Same as "Honey", but only accessible through an interface's orphans
class Aspartame < BaseObject
description "Sugar substitute with an off-flavor aftertaste"
field :manufacturer, String, "What manufacturer this aspartame came from"
implements Edible
implements Sweetener
end
class Dairy < BaseObject
description "A farm where milk is harvested and cheese is produced"
field :id, ID, null: false
field :cheese, Cheese
field :milks, [Milk, null: true]
end
class MaybeNull < BaseObject
description "An object whose fields return nil"
field :cheese, Cheese
end
class TracingScalar < BaseObject
description "An object which has traced scalars"
field :trace_nil, Integer
field :trace_false, Integer, trace: false
field :trace_true, Integer, trace: true
end
class DairyProduct < BaseUnion
description "Kinds of food made from milk"
# Test that these forms of declaration still work:
possible_types "Dummy::Milk", Cheese
end
class Cow < BaseObject
description "A bovine animal that produces milk"
field :id, ID, null: false
field :name, String
field :last_produced_dairy, DairyProduct
field :cant_be_null_but_is, String, null: false
def cant_be_null_but_is; nil; end
field :cant_be_null_but_raises_execution_error, String, null: false
def cant_be_null_but_raises_execution_error; raise(GraphQL::ExecutionError, "BOOM"); end
end
class Goat < BaseObject
description "An caprinae animal that produces milk"
field :id, ID, null: false
field :name, String
field :last_produced_dairy, DairyProduct
end
class Animal < BaseUnion
description "Species of living things"
possible_types Cow, Goat
end
class AnimalAsCow < BaseUnion
description "All animals go mooooo!"
possible_types Cow
def self.resolve_type(obj, ctx)
Cow
end
end
class ResourceOrder < BaseInputObject
graphql_name "ResourceOrderType"
description "Properties used to determine ordering"
argument :direction, String, description: "ASC or DESC"
end
class DairyProductInput < BaseInputObject
description "Properties for finding a dairy product"
argument :source, DairyAnimal, description: "Where it came from"
argument :origin_dairy, String, required: false, description: "Dairy which produced it", default_value: "Sugar Hollow Dairy"
argument :fat_content, Float, required: false, description: "How much fat it has", default_value: 0.3
argument :organic, Boolean, required: false, default_value: false
argument :order_by, ResourceOrder, required: false, default_value: { direction: "ASC" }, camelize: false
argument :old_source, String, required: false, deprecation_reason: "No longer supported"
end
class PreparedDateInput < BaseInputObject
description "Input with prepared value"
argument :date, String, description: "date as a string", required: false
argument :deprecated_date, String, description: "date as a string", required: false, deprecation_reason: "Use date"
def prepare
return nil unless date || deprecated_date
Date.parse(date || deprecated_date)
end
end
class DeepNonNull < BaseObject
field :non_null_int, Integer, null: false do
argument :returning, Integer, required: false
end
def non_null_int(returning: nil)
returning
end
field :deep_non_null, DeepNonNull, null: false
def deep_non_null; :deep_non_null; end
end
class Time < BaseScalar
description "Time since epoch in seconds"
specified_by_url "https://time.graphql"
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 FetchItem < GraphQL::Schema::Resolver
class << self
attr_accessor :data
end
def self.build(type:, data:, id_type: "Int")
Class.new(self) do
graphql_name("Fetch#{type.graphql_name}")
self.data = data
type(type, null: true)
description("Find a #{type.name} by id")
argument :id, id_type
end
end
def resolve(id:)
id_string = id.to_s # Cheese has Int type, Milk has ID type :(
_id, item = self.class.data.find { |item_id, _item| item_id.to_s == id_string }
item
end
end
class GetSingleton < GraphQL::Schema::Resolver
class << self
attr_accessor :data
end
def self.build(type:, data:)
Class.new(self) do
graphql_name("Get#{type.graphql_name}")
description("Find the only #{type.name}")
type(type, null: true)
self.data = data
end
end
def resolve
if context[:resolved_count]
context[:resolved_count] += 1
end
self.class.data
end
end
class DairyAppQuery < BaseObject
graphql_name "Query"
description "Query root of the system"
# Returns `root_value:`
field :root, String
def root
object
end
field :cheese, resolver: FetchItem.build(type: Cheese, data: CHEESES)
field :milk, resolver: FetchItem.build(type: Milk, data: MILKS, id_type: "ID")
field :dairy, resolver: GetSingleton.build(type: Dairy, data: DAIRY)
field :from_source, [Cheese, null: true], description: "Cheese from source" do
argument :source, DairyAnimal, required: false, default_value: 1
argument :old_source, String, required: false, deprecation_reason: "No longer supported"
end
def from_source(source:)
CHEESES.values.select { |c| c.source == source }
end
field :favorite_edible, Edible, description: "My favorite food"
def favorite_edible
MILKS[1]
end
field :cow, resolver: GetSingleton.build(type: Cow, data: COWS[1])
field :search_dairy, DairyProduct, null: false do
description "Find dairy products matching a description"
# This is a list just for testing 😬
argument :product, [DairyProductInput, null: true], required: false, default_value: [{source: "SHEEP"}]
argument :old_product, [DairyProductInput], required: false, deprecation_reason: "No longer supported"
argument :single_product, DairyProductInput, required: false
argument :product_ids, [String], required: false, deprecation_reason: "No longer supported"
argument :expires_after, Time, required: false
end
def search_dairy(product:, expires_after: nil)
source = product[0][:source]
products = CHEESES.values + MILKS.values
if !source.nil?
products = products.select { |pr| pr.source == source }
end
products.first
end
field :all_animal, [Animal, null: true], null: false
def all_animal
COWS.values + GOATS.values
end
field :all_animal_as_cow, [AnimalAsCow, null: true], null: false, resolver_method: :all_animal
field :all_dairy, [DairyProduct, null: true] do
argument :execution_error_at_index, Integer, required: false
end
def all_dairy(execution_error_at_index: nil)
result = CHEESES.values + MILKS.values
if execution_error_at_index
result[execution_error_at_index] = GraphQL::ExecutionError.new("missing dairy")
end
result
end
field :all_edible do
type [Edible, null: true]
end
def all_edible
CHEESES.values + MILKS.values
end
field :all_edible_as_milk, [EdibleAsMilk, null: true], resolver_method: :all_edible
field :error, String, description: "Raise an error"
def error
raise("This error was raised on purpose")
end
field :execution_error, String
def execution_error
raise(GraphQL::ExecutionError, "There was an execution error")
end
field :value_with_execution_error, Integer, null: false, extras: [:execution_errors]
def value_with_execution_error(execution_errors:)
execution_errors.add("Could not fetch latest value")
0
end
field :multiple_errors_on_non_nullable_field, String, null: false
def multiple_errors_on_non_nullable_field
[
GraphQL::ExecutionError.new("This is an error message for some error."),
GraphQL::ExecutionError.new("This is another error message for a different error.")
]
end
field :multiple_errors_on_non_nullable_list_field, [String], null: false
def multiple_errors_on_non_nullable_list_field
[
GraphQL::ExecutionError.new("The first error message for a field defined to return a list of strings."),
GraphQL::ExecutionError.new("The second error message for a field defined to return a list of strings.")
]
end
field :execution_error_with_options, Integer
def execution_error_with_options
GraphQL::ExecutionError.new("Permission Denied!", options: { "code" => "permission_denied" })
end
field :execution_error_with_extensions, Integer
def execution_error_with_extensions
GraphQL::ExecutionError.new("Permission Denied!", extensions: { code: "permission_denied" })
end
# To test possibly-null fields
field :maybe_null, MaybeNull
def maybe_null
OpenStruct.new(cheese: nil)
end
field :tracing_scalar, TracingScalar
def tracing_scalar
OpenStruct.new(
trace_nil: 2,
trace_false: 3,
trace_true: 5,
)
end
field :deep_non_null, null: false do
type(DeepNonNull)
end
def deep_non_null; :deep_non_null; end
field :huge_integer, Integer
def huge_integer
GraphQL::Types::Int::MAX + 1
end
field :example_beverage, Beverage # just to add this type to the schema
end
class AdminDairyAppQuery < BaseObject
field_class AdminField
field :admin_only_message, String
def admin_only_message
"This field is only visible to admin"
end
end
GLOBAL_VALUES = []
class ReplaceValuesInput < BaseInputObject
argument :values, [Integer]
end
class DairyAppMutation < BaseObject
graphql_name "Mutation"
description "The root for mutations in this schema"
field :push_value, [Integer], null: false, description: "Push a value onto a global array :D" do
argument :value, Integer, as: :val
argument :deprecated_test_input, DairyProductInput, required: false
argument :prepared_test_input, PreparedDateInput, required: false
end
def push_value(val:)
GLOBAL_VALUES << val
GLOBAL_VALUES
end
field :replace_values, [Integer], "Replace the global array with new values", null: false do
argument :input, ReplaceValuesInput
end
def replace_values(input:)
GLOBAL_VALUES.clear
GLOBAL_VALUES.concat(input[:values])
GLOBAL_VALUES
end
end
class DirectiveForVariableDefinition < BaseDirective
locations(VARIABLE_DEFINITION)
end
class Subscription < BaseObject
field :test, String
def test; "Test"; end
end
class Schema < GraphQL::Schema
query { DairyAppQuery }
mutation { DairyAppMutation }
subscription { Subscription }
max_depth 5
orphan_types Honey
trace_with GraphQL::Tracing::CallLegacyTracers
directives(DirectiveForVariableDefinition)
rescue_from(NoSuchDairyError) { |err| raise GraphQL::ExecutionError, err.message }
def self.resolve_type(type, obj, ctx)
-> { Schema.types[obj.class.name.split("::").last] }
end
# This is used to confirm that the hook is called:
MAGIC_INT_COERCE_VALUE = -1
def self.type_error(err, ctx)
if err.is_a?(GraphQL::IntegerEncodingError) && err.integer_value == 99**99
MAGIC_INT_COERCE_VALUE
else
super
end
end
use GraphQL::Dataloader
lazy_resolve(Proc, :call)
end
class AdminSchema < GraphQL::Schema
query AdminDairyAppQuery
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/support/star_wars/schema.rb | spec/support/star_wars/schema.rb | # frozen_string_literal: true
module StarWars
# Adapted from graphql-relay-js
# https://github.com/graphql/graphql-relay-js/blob/master/src/__tests__/starWarsSchema.js
class Ship < GraphQL::Schema::Object
implements GraphQL::Types::Relay::Node
global_id_field :id
field :name, String
# Test cyclical connection types:
field :ships, Ship.connection_type, null: false
end
class BaseType < GraphQL::Schema::Object
graphql_name "Base"
implements GraphQL::Types::Relay::Node
global_id_field :id
field :name, String, null: false
def name
LazyWrapper.new {
if object.id.nil?
raise GraphQL::ExecutionError, "Boom!"
else
object.name
end
}
end
field :planet, String
end
class BaseEdge < GraphQL::Types::Relay::BaseEdge
node_type(BaseType)
end
class BaseConnection < GraphQL::Types::Relay::BaseConnection
edge_type(BaseEdge)
end
class BaseConnectionWithoutNodes < GraphQL::Types::Relay::BaseConnection
edge_type(BaseEdge, nodes_field: false)
end
class BasesConnectionWithTotalCountType < GraphQL::Types::Relay::BaseConnection
edge_type(BaseEdge, nodes_field: false)
nodes_field
field :total_count, Integer
def total_count
object.items.count
end
end
class NewCustomBaseEdge < GraphQL::Pagination::Connection::Edge
def upcased_name
node.name.upcase
end
def upcased_parent_name
parent.name.upcase
end
end
class CustomBaseEdgeType < GraphQL::Types::Relay::BaseEdge
node_type(BaseType)
field :upcased_name, String
field :upcased_parent_name, String
field :edge_class_name, String
def edge_class_name
object.class.name
end
end
class CustomEdgeBaseConnectionType < GraphQL::Types::Relay::BaseConnection
edge_type(CustomBaseEdgeType, edge_class: NewCustomBaseEdge, nodes_field: true)
field :total_count_times_100, Integer
def total_count_times_100
object.items.count * 100
end
field :field_name, String
def field_name
object.field.name
end
end
class ShipsWithMaxPageSize < GraphQL::Schema::Resolver
argument :name_includes, String, required: false
type Ship.connection_type, null: true
def resolve(name_includes: nil)
all_ships = object.ships.map { |ship_id| StarWars::DATA["Ship"][ship_id] }
if name_includes
all_ships = all_ships.select { |ship| ship.name.include?(name_includes)}
end
all_ships
end
end
class ShipConnectionWithParentType < GraphQL::Types::Relay::BaseConnection
edge_type(Ship.edge_type)
field :parent_class_name, String, null: false
def parent_class_name
object.parent.class.name
end
end
class ShipsByResolver < GraphQL::Schema::Resolver
type ShipConnectionWithParentType, null: false
def resolve
object.ships.map { |ship_id| StarWars::DATA["Ship"][ship_id] }
end
end
class Faction < GraphQL::Schema::Object
implements GraphQL::Types::Relay::Node
field :id, ID, null: false
def id
GraphQL::Relay::GlobalIdResolve.new(type: Faction).call(object, {}, context)
end
field :name, String
field :ships, ShipConnectionWithParentType, connection: true, max_page_size: 1000, null: true do
argument :name_includes, String, required: false
end
field :ships_with_default_page_size, ShipConnectionWithParentType, method: :ships, connection: true, default_page_size: 500, null: true do
argument :name_includes, String, required: false
end
field :shipsByResolver, resolver: ShipsByResolver, connection: true
def ships(name_includes: nil)
all_ships = object.ships.map {|ship_id| StarWars::DATA["Ship"][ship_id] }
if name_includes
case name_includes
when "error"
all_ships = GraphQL::ExecutionError.new("error from within connection")
when "raisedError"
raise GraphQL::ExecutionError.new("error raised from within connection")
when "lazyError"
all_ships = LazyWrapper.new { GraphQL::ExecutionError.new("lazy error from within connection") }
when "lazyRaisedError"
all_ships = LazyWrapper.new { raise GraphQL::ExecutionError.new("lazy raised error from within connection") }
when "null"
all_ships = nil
when "lazyObject"
prev_all_ships = all_ships
all_ships = LazyWrapper.new { prev_all_ships }
else
all_ships = all_ships.select { |ship| ship.name.include?(name_includes)}
end
end
all_ships
end
field :shipsWithMaxPageSize, "Ships with max page size", max_page_size: 2, resolver: ShipsWithMaxPageSize
field :bases, BasesConnectionWithTotalCountType, connection: true do
argument :name_includes, String, required: false
argument :complex_order, Boolean, required: false
end
def bases(name_includes: nil, complex_order: nil)
all_bases = Base.where(id: object.bases)
if name_includes
all_bases = all_bases.where("name LIKE ?", "%#{name_includes}%")
end
if complex_order
all_bases = all_bases.order("bases.name DESC")
end
# Emulates ActiveRecord::Base.connected_to(role: :reading) do
# https://github.com/rails/rails/blob/d18fc329993df5a583ef721330cffb248ef9a213/activerecord/lib/active_record/connection_handling.rb#L355
all_bases.load
end
field :bases_clone, BaseConnection
field :bases_by_name, BaseConnection do
argument :order, String, default_value: "name", required: false
end
def bases_by_name(order: nil)
if order.present?
@object.bases.order(order)
else
@object.bases
end
end
def all_bases
Base.all
end
def all_bases_array
all_bases.to_a
end
field :basesWithMaxLimitRelation, BaseConnection, max_page_size: 2, resolver_method: :all_bases
field :basesWithMaxLimitArray, BaseConnection, max_page_size: 2, resolver_method: :all_bases_array
field :basesWithDefaultMaxLimitRelation, BaseConnection, resolver_method: :all_bases
field :basesWithDefaultMaxLimitArray, BaseConnection, resolver_method: :all_bases_array
field :basesWithLargeMaxLimitRelation, BaseConnection, max_page_size: 1000, resolver_method: :all_bases
field :basesWithoutNodes, BaseConnectionWithoutNodes, resolver_method: :all_bases_array
field :bases_as_sequel_dataset, BasesConnectionWithTotalCountType, connection: true, max_page_size: 1000 do
argument :name_includes, String, required: false
end
def bases_as_sequel_dataset(name_includes: nil)
all_bases = SequelBase.where(faction_id: @object.id)
if name_includes
all_bases = all_bases.where(Sequel.like(:name, "%#{name_includes}%"))
end
all_bases
end
field :basesWithCustomEdge, CustomEdgeBaseConnectionType, connection: true, resolver_method: :lazy_bases
def lazy_bases
LazyNodesWrapper.new(object.bases)
end
end
class IntroduceShipMutation < GraphQL::Schema::RelayClassicMutation
description "Add a ship to this faction"
# Nested under `input` in the query:
argument :ship_name, String, required: false
argument :faction_id, ID
# Result may have access to these fields:
field :ship_edge, Ship.edge_type
field :faction, Faction
field :aliased_faction, Faction, hash_key: :aliased_faction, null: true
def resolve(ship_name: nil, faction_id:)
if ship_name == 'Millennium Falcon'
GraphQL::ExecutionError.new("Sorry, Millennium Falcon ship is reserved")
elsif ship_name == 'Leviathan'
raise GraphQL::ExecutionError.new("🔥")
elsif ship_name == "Ebon Hawk"
LazyWrapper.new { raise GraphQL::ExecutionError.new("💥")}
else
ship = DATA.create_ship(ship_name, faction_id)
faction = DATA["Faction"][faction_id]
range_add = GraphQL::Relay::RangeAdd.new(
collection: faction.ships,
item: ship,
parent: faction,
context: context,
)
result = {
ship_edge: range_add.edge,
faction: range_add.parent,
aliased_faction: range_add.parent,
}
if ship_name == "Slave II"
LazyWrapper.new(result)
else
result
end
end
end
end
# GraphQL-Batch knockoff
class LazyLoader
def self.defer(ctx, model, id)
ids = ctx.namespace(:loading)[model] ||= []
ids << id
self.new(model: model, id: id, context: ctx)
end
def initialize(model:, id:, context:)
@model = model
@id = id
@context = context
end
def value
loaded = @context.namespace(:loaded)[@model] ||= {}
if loaded.empty?
ids = @context.namespace(:loading)[@model]
# Example custom tracing
@context.trace("lazy_loader", { ids: ids, model: @model}) do
records = @model.where(id: ids)
records.each do |record|
loaded[record.id.to_s] = record
end
end
end
loaded[@id]
end
end
class LazyWrapper
def initialize(value = nil, &block)
if block_given?
@lazy_value = block
else
@value = value
end
end
def value
@resolved_value = @value || @lazy_value.call
end
end
LazyNodesWrapper = Struct.new(:relation)
class NewLazyNodesRelationConnection < GraphQL::Pagination::ActiveRecordRelationConnection
def initialize(wrapper, **kwargs)
super(wrapper.relation, **kwargs)
end
def edge_nodes
LazyWrapper.new { super }
end
end
class QueryType < GraphQL::Schema::Object
graphql_name "Query"
field :rebels, Faction
def rebels
StarWars::DATA["Faction"]["1"]
end
field :empire, Faction
def empire
StarWars::DATA["Faction"]["2"]
end
field :largest_base, BaseType
def largest_base
Base.find(3)
end
field :newest_bases_grouped_by_faction, BaseConnection
def newest_bases_grouped_by_faction
Base
.having('id in (select max(id) from bases group by faction_id)')
.group(:id)
.order('faction_id desc')
end
field :bases_with_null_name, BaseConnection, null: false
def bases_with_null_name
[OpenStruct.new(id: nil)]
end
include GraphQL::Types::Relay::HasNodeField
field :node_with_custom_resolver, GraphQL::Types::Relay::Node do
argument :id, ID
end
def node_with_custom_resolver(id:)
StarWars::DATA["Faction"]["1"]
end
include GraphQL::Types::Relay::HasNodesField
field :nodes_with_custom_resolver, [GraphQL::Types::Relay::Node, null: true] do
argument :ids, [ID]
end
def nodes_with_custom_resolver(ids:)
[StarWars::DATA["Faction"]["1"], StarWars::DATA["Faction"]["2"]]
end
field :batched_base, BaseType do
argument :id, ID
end
def batched_base(id:)
LazyLoader.defer(@context, Base, id)
end
end
class MutationType < GraphQL::Schema::Object
graphql_name "Mutation"
field :introduceShip, mutation: IntroduceShipMutation
end
class Schema < GraphQL::Schema
query(QueryType)
mutation(MutationType)
default_max_page_size 3
connections.add(LazyNodesWrapper, NewLazyNodesRelationConnection)
def self.resolve_type(type, object, ctx)
if object == :test_error
:not_a_type
elsif object.is_a?(Base)
BaseType
elsif DATA["Faction"].values.include?(object)
Faction
elsif DATA["Ship"].values.include?(object)
Ship
else
nil
end
end
def self.object_from_id(node_id, ctx)
type_name, id = GraphQL::Schema::UniqueWithinType.decode(node_id)
StarWars::DATA[type_name][id]
end
def self.id_from_object(object, type, ctx)
GraphQL::Schema::UniqueWithinType.encode(type.graphql_name, object.id)
end
lazy_resolve(LazyWrapper, :value)
lazy_resolve(LazyLoader, :value)
end
# Create a secondary schema with a default_page_size set. This prevents us
# from breaking the existing default_max_page_size tests, while still
# allowing us to test the logic involved with default_page_size.
class SchemaWithDefaultPageSize < Schema
default_page_size 2
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/data.rb | spec/integration/rails/data.rb | # frozen_string_literal: true
require 'ostruct'
require "support/active_record_setup"
module StarWars
names = [
'X-Wing',
'Y-Wing',
'A-Wing',
'Millennium Falcon',
'Home One',
'TIE Fighter',
'TIE Interceptor',
'Executor',
]
class StarWarsModel < ActiveRecord::Base
self.abstract_class = true
connects_to database: { writing: :starwars, reading: :starwars_replica }
end
StarWarsModel.establish_connection(:starwars)
class Base < StarWarsModel
end
Base.create!(name: "Yavin", planet: "Yavin 4", faction_id: 1)
Base.create!(name: "Echo Base", planet: "Hoth", faction_id: 1)
Base.create!(name: "Secret Hideout", planet: "Dantooine", faction_id: 1)
Base.create!(name: "Death Star", planet: nil, faction_id: 2)
Base.create!(name: "Shield Generator", planet: "Endor", faction_id: 2)
Base.create!(name: "Headquarters", planet: "Coruscant", faction_id: 2)
class SequelBase < Sequel::Model(:bases)
end
class FactionRecord
attr_reader :id, :name, :ships, :bases, :bases_clone
def initialize(id:, name:, ships:, bases:, bases_clone:)
@id = id
@name = name
@ships = ships
@bases = bases
@bases_clone = bases_clone
end
end
rebels = FactionRecord.new(
id: '1',
name: 'Alliance to Restore the Republic',
ships: ['1', '2', '3', '4', '5'],
bases: Base.where(faction_id: 1),
bases_clone: Base.where(faction_id: 1),
)
empire = FactionRecord.new(
id: '2',
name: 'Galactic Empire',
ships: ['6', '7', '8'],
bases: Base.where(faction_id: 2),
bases_clone: Base.where(faction_id: 2),
)
DATA = {
"Faction" => {
"1" => rebels,
"2" => empire,
},
"Ship" => names.each_with_index.reduce({}) do |memo, (name, idx)|
id = (idx + 1).to_s
memo[id] = OpenStruct.new(name: name, id: id)
memo
end,
"Base" => Hash.new { |h, k| h[k] = Base.find(k) }
}
def DATA.create_ship(name, faction_id)
new_id = (self["Ship"].keys.map(&:to_i).max + 1).to_s
new_ship = OpenStruct.new(id: new_id, name: name)
self["Ship"][new_id] = new_ship
self["Faction"][faction_id].ships << new_id
new_ship
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/query_logs_spec.rb | spec/integration/rails/query_logs_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Integration with ActiveRecord::QueryLogs" do
class QueryLogSchema < GraphQL::Schema
class Thing < ActiveRecord::Base
belongs_to :other_thing, class_name: "Thing"
end
class ThingSource < GraphQL::Dataloader::Source
def fetch(ids)
things = Thing.where(id: ids)
ids.map { |id| things.find { |t| t.id == id } }
end
end
class OtherThingSource < GraphQL::Dataloader::Source
def fetch(ids)
things = dataloader.with(ThingSource).load_all(ids).compact
ot_ids = things.map(&:other_thing_id).compact
ots = Thing.where(id: ot_ids).compact
ids.map { |tid|
if (thing = things.find { |t| t.id == tid })
ots.find { |ot| ot.id == thing.other_thing_id }
end
}
end
end
class ThingType < GraphQL::Schema::Object
field :name, String
field :other_thing, self
end
class Query < GraphQL::Schema::Object
field :some_thing, ThingType
def some_thing
Thing.find(2)
end
field :thing, ThingType do
argument :id, ID
end
def thing(id:)
dataloader.with(ThingSource).load(id.to_i)
end
field :other_thing, ThingType do
argument :thing_id, ID
end
def other_thing(thing_id:)
dataloader.with(OtherThingSource).load(thing_id.to_i)
end
end
query(Query)
use GraphQL::Dataloader
end
t1 = QueryLogSchema::Thing.create!(name: "Fork")
QueryLogSchema::Thing.create!(name: "Spoon", other_thing: t1)
QueryLogSchema::Thing.create!(name: "Knife")
before do
@prev_tags = ActiveRecord::QueryLogs.tags
ActiveRecord.query_transformers << ActiveRecord::QueryLogs
ActiveRecord::QueryLogs.tags = [{
current_graphql_operation: -> { GraphQL::Current.operation_name },
current_graphql_field: -> { GraphQL::Current.field&.path },
current_dataloader_source: -> { GraphQL::Current.dataloader_source_class },
}]
end
after do
ActiveRecord::QueryLogs.tags = @prev_tags
ActiveRecord.query_transformers.delete(ActiveRecord::QueryLogs)
end
def exec_query(str)
QueryLogSchema.execute(str)
end
it "includes operation_name and field_name when configured" do
res = nil
log = with_active_record_log(colorize: false) do
res = exec_query("query OtherThingName { someThing { otherThing { name } } }")
end
assert_equal "Fork", res["data"]["someThing"]["otherThing"]["name"]
# These can appear in different orders in the SQL comment:
assert_includes log, "current_graphql_operation:OtherThingName"
assert_includes log, "current_graphql_field:Query.someThing"
assert_includes log, "current_graphql_field:Thing.otherThing"
end
it "includes dataloader source when configured" do
res = nil
log = with_active_record_log(colorize: false) do
res = exec_query("query GetThingNames { t1: thing(id: 1) { name } t2: thing(id: 2) { name } }")
end
assert_equal ["Fork", "Spoon"], [res["data"]["t1"]["name"], res["data"]["t2"]["name"]]
assert_includes log, 'SELECT "things".* FROM "things" WHERE "things"."id" IN (?, ?) '
assert_includes log, 'current_dataloader_source:QueryLogSchema::ThingSource'
assert_includes log, 'current_graphql_operation:GetThingNames'
end
it "works for nested dataloader sources" do
res = nil
log = with_active_record_log(colorize: false) do
res = exec_query("{ t1: otherThing(thingId: 1) { name } t2: otherThing(thingId: 2) { name } t5: otherThing(thingId: 5) { name } }")
end
assert_equal [nil, "Fork", nil], [res.dig("data", "t1", "name"), res.dig("data", "t2", "name"), res.dig("data", "t5")]
assert_includes log, 'SELECT "things".* FROM "things" WHERE "things"."id" IN (?, ?, ?) /*current_dataloader_source:QueryLogSchema::ThingSource*/'
assert_includes log, 'SELECT "things".* FROM "things" WHERE "things"."id" = ? /*current_dataloader_source:QueryLogSchema::OtherThingSource*/'
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/spec_helper.rb | spec/integration/rails/spec_helper.rb | # frozen_string_literal: true
require "rake"
require "rails/all"
require "rails/generators"
require "sequel"
if ENV['DATABASE'] == 'POSTGRESQL'
require 'pg'
else
require "sqlite3"
end
if ENV["ISOLATION_LEVEL_FIBER"]
ActiveSupport::IsolatedExecutionState.isolation_level = :fiber
puts "ActiveSupport::IsolatedExecutionState: #{ActiveSupport::IsolatedExecutionState.isolation_level}"
end
require_relative "generators/base_generator_test"
require_relative "data"
def with_active_record_log(colorize: true)
io = StringIO.new
prev_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(io)
# Work aroudn .logger = ... issue on Rails main
# https://github.com/rails/rails/issues/56230
if ActiveSupport.respond_to?(:event_reporter)
ActiveSupport.event_reporter.with_debug do
yield
end
else
yield
end
str = io.string
if !colorize
str.gsub!(/\e\[([;\d]+)?m/, '')
end
str
ensure
ActiveRecord::Base.logger = prev_logger
end
if ActiveSupport.respond_to?(:test_order=)
ActiveSupport.test_order = :random
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/graphql/dataloader_spec.rb | spec/integration/rails/graphql/dataloader_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Dataloader do
if defined?(ActiveRecord::Promise) && ENV['DATABASE'] == 'POSTGRESQL' # Rails 7.1+
class RailsPromiseSchema < GraphQL::Schema
class LoadAsyncSource < GraphQL::Dataloader::Source
LOG = []
def fetch(relations)
relations.each do |rel|
LOG << Time.now
rel.load_async
end
dataloader.yield
relations.each do |rel|
rel.load
LOG << Time.now
end
end
end
class SleepSource < GraphQL::Dataloader::Source
def initialize(duration)
@duration = duration
end
def fetch(durations)
# puts "[#{Time.now.to_f}] Starting #{durations}"
promise = ::Food.async_find_by_sql("SELECT pg_sleep(#{durations.first})")
# puts "[#{Time.now.to_f}] Yielding #{durations}"
dataloader.yield
# puts "[#{Time.now.to_f}] Finishing #{durations}"
promise.value
durations
end
end
class Query < GraphQL::Schema::Object
field :sleep, Float do
argument :duration, Float
end
def sleep(duration:)
dataloader.with(SleepSource, duration).load(duration)
end
field :things, Integer do
argument :first, Integer
end
def things(first:)
relation = Food
.where(name: "Zucchini")
.select("pg_sleep(0.3)")
.limit(first)
items = dataloader.with(LoadAsyncSource).load(relation)
items.size
end
end
query(Query)
use GraphQL::Dataloader
end
before do
Food.create!(name: "Zucchini")
RailsPromiseSchema::LoadAsyncSource::LOG.clear
end
after do
Food.find_by(name: "Zucchini").destroy
end
it "Supports async queries" do
assert ActiveRecord::Base.connection.async_enabled?, "ActiveRecord must support real async queries"
end
describe "using ActiveRecord::Promise for manual parallelism" do
it "runs queries in parallel" do
query_str = "
{
s1: sleep(duration: 0.1)
s2: sleep(duration: 0.2)
s3: sleep(duration: 0.3)
}"
t1 = Time.now
result = RailsPromiseSchema.execute(query_str)
t2 = Time.now
assert_equal({ "s1" => 0.1, "s2" => 0.2, "s3" => 0.3}, result["data"])
assert_in_delta 0.3, t2 - t1, 0.06, "Sleeps were in parallel"
end
end
describe "using load_async for parallelism" do
it "runs queries in parallel" do
query_str = "
{
t1: things(first: 5)
t2: things(first: 10)
t3: things(first: 100)
}"
t1 = Time.now
result = RailsPromiseSchema.execute(query_str)
t2 = Time.now
load_async_1, load_async_2, load_async_3, load_1, load_2, load_3 = RailsPromiseSchema::LoadAsyncSource::LOG
assert_in_delta load_async_1, load_async_2, 0.06, "load_async happened first"
assert_in_delta load_async_1, load_async_3, 0.06, "the third load_async happened right after"
assert_in_delta load_async_1, load_1, 0.35, "load came 0.3s after"
assert_in_delta load_1, load_2, 0.06, "the second load didn't have to wait because it was already done"
assert_in_delta load_1, load_3, 0.06, "the third load didn't have to wait because it was already done"
assert_equal({ "t1" => 1, "t2" => 1, "t3" => 1}, result["data"])
assert_in_delta 0.3, t2 - t1, 0.06, "Sleeps were in parallel"
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/integration/rails/graphql/schema_spec.rb | spec/integration/rails/graphql/schema_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema do
let(:schema) { Dummy::Schema }
let(:admin_schema) { Dummy::AdminSchema }
let(:relay_schema) { StarWars::Schema }
let(:empty_schema) { Class.new(GraphQL::Schema) }
describe "#find" do
it "finds a member using a string path" do
field = schema.find("Edible.fatContent")
assert_equal "fatContent", field.name
end
end
describe "#union_memberships" do
it "returns a list of unions that include the type" do
skip("Not implemented for Visibility::Profile") if GraphQL::Schema.use_visibility_profile?
assert_equal [schema.types["Animal"], schema.types["AnimalAsCow"]], schema.union_memberships(schema.types["Cow"])
end
end
describe "#to_document" do
it "returns the AST for the schema IDL" do
expected = GraphQL::Language::DocumentFromSchemaDefinition.new(schema).document
assert_equal expected.to_query_string, schema.to_document.to_query_string
end
end
describe "#root_types" do
it "returns a list of the schema's root types" do
assert_equal(
[
Dummy::DairyAppQuery,
Dummy::DairyAppMutation,
Dummy::Subscription
],
schema.root_types
)
end
end
describe "#references_to" do
it "returns a list of Field and Arguments of that type" do
skip "Not implemented when using Visibility::Profile" if GraphQL::Schema.use_visibility_profile?
cow_field = schema.get_field("Query", "cow")
cow_t = schema.get_type("Cow")
assert_equal [cow_field], schema.references_to(cow_t)
end
it "returns an empty list when type is not referenced by any field or argument" do
assert_equal [], schema.references_to(Jazz::InstrumentType)
end
end
describe "#to_definition" do
it "prints out the schema definition" do
assert_equal schema.to_definition, GraphQL::Schema::Printer.print_schema(schema)
end
end
describe "#resolve_type" do
describe "when the return value is nil" do
it "returns nil" do
result = relay_schema.resolve_type(123, nil, GraphQL::Query::NullContext.instance)
assert_equal([nil, nil], result)
end
end
describe "when the return value is not a BaseType" do
it "raises an error " do
err = assert_raises(RuntimeError) {
relay_schema.resolve_type(nil, :test_error, GraphQL::Query::NullContext.instance)
}
assert_includes err.message, "not_a_type (Symbol)"
end
end
describe "when the hook wasn't implemented" do
it "raises not implemented" do
assert_raises(GraphQL::RequiredImplementationMissingError) {
empty_schema.resolve_type(Class.new(GraphQL::Schema::Union), nil, nil)
}
end
end
end
describe "#disable_introspection_entry_points" do
it "enables entry points by default" do
refute_empty empty_schema.introspection_system.entry_points
end
describe "when disable_introspection_entry_points is configured" do
let(:schema) do
Class.new(GraphQL::Schema) do
disable_introspection_entry_points
end
end
it "clears entry points" do
assert_empty schema.introspection_system.entry_points
end
end
end
describe "object_from_id" do
describe "when the hook wasn't implemented" do
it "raises not implemented" do
assert_raises(GraphQL::RequiredImplementationMissingError) {
empty_schema.object_from_id(nil, nil)
}
end
end
end
describe "id_from_object" do
describe "when the hook wasn't implemented" do
it "raises not implemented" do
assert_raises(GraphQL::RequiredImplementationMissingError) {
empty_schema.id_from_object(nil, nil, nil)
}
end
end
describe "when a schema is defined with a node field, but no hook" do
it "raises not implemented" do
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
include GraphQL::Types::Relay::HasNodeField
end
thing_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Thing"
implements GraphQL::Types::Relay::Node
end
schema = Class.new(GraphQL::Schema) {
query(query_type)
orphan_types(thing_type)
}
assert_raises(GraphQL::RequiredImplementationMissingError) {
schema.execute("{ node(id: \"1\") { id } }")
}
end
end
end
describe "directives" do
describe "when directives are not overwritten" do
it "contains built-in directives" do
schema = GraphQL::Schema
assert_equal ['deprecated', 'include', 'oneOf', 'skip', 'specifiedBy'], schema.directives.keys.sort
assert_equal GraphQL::Schema::Directive::Deprecated, schema.directives['deprecated']
assert_equal GraphQL::Schema::Directive::Include, schema.directives['include']
assert_equal GraphQL::Schema::Directive::Skip, schema.directives['skip']
assert_equal GraphQL::Schema::Directive::OneOf, schema.directives['oneOf']
assert_equal GraphQL::Schema::Directive::SpecifiedBy, schema.directives['specifiedBy']
end
end
end
describe ".from_definition" do
it "uses BuildFromSchema to build a schema from a definition string" do
schema = <<-SCHEMA
type Query {
str: String
}
SCHEMA
built_schema = GraphQL::Schema.from_definition(schema)
assert_equal schema, GraphQL::Schema::Printer.print_schema(built_schema)
end
it "builds from a file" do
schema = GraphQL::Schema.from_definition("spec/support/magic_cards/schema.graphql")
assert_instance_of Class, schema
expected_types = ["Card", "Color", "Expansion", "Printing"]
assert_equal expected_types, (expected_types & schema.types.keys)
end
end
describe ".from_introspection" do
let(:schema) {
# This type would easily be mistaken for a connection... but it's not one.
db_connection = Class.new(GraphQL::Schema::Object) do
graphql_name "DatabaseConnection"
field :name, String, null: false
end
query_root = Class.new(GraphQL::Schema::Object) do
graphql_name 'Query'
field :str, String
field :db, db_connection, null: false, connection: false
end
Class.new(GraphQL::Schema) do
query query_root
end
}
let(:schema_json) {
schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY)
}
it "uses Schema::Loader to build a schema from an introspection result" do
built_schema = GraphQL::Schema.from_introspection(schema_json)
assert_equal GraphQL::Schema::Printer.print_schema(schema), GraphQL::Schema::Printer.print_schema(built_schema)
end
end
describe "#instrument" do
module VariableCountTrace
def execute_query(query:)
query.context[:counter] << query.variables.length
super
ensure
query.context[:counter] << :end
end
end
# Use this to assert instrumenters are called as a stack
module StackCheckTrace
def execute_query(query:)
query.context[:counter] << :in
super
ensure
query.context[:counter] << :out
end
end
let(:variable_counts) {
[]
}
let(:schema) {
Class.new(GraphQL::Schema) do
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 == 13 ? raise("13 is unlucky") : value
end
end
query(query_type)
trace_with VariableCountTrace
trace_with StackCheckTrace
end
}
it "can wrap query execution" do
schema.execute("query getInt($val: Int = 5){ int(value: $val) } ", context: { counter: variable_counts })
schema.execute("query getInt($val: Int = 5, $val2: Int = 3){ int(value: $val) int2: int(value: $val2) } ", context: { counter: variable_counts })
assert_equal [:in, 1, :end, :out, :in, 2, :end, :out], variable_counts
end
it "runs even when a runtime error occurs" do
schema.execute("query getInt($val: Int = 5){ int(value: $val) } ", context: { counter: variable_counts })
assert_raises(RuntimeError) {
schema.execute("query getInt($val: Int = 13){ int(value: $val) } ", context: { counter: variable_counts })
}
assert_equal [:in, 1, :end, :out, :in, 1, :end, :out], variable_counts
end
end
describe "#lazy? / #lazy_method_name" do
class LazyObj; end
class LazyObjChild < LazyObj; end
let(:schema) {
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
end
Class.new(GraphQL::Schema) do
query(query_type)
lazy_resolve(Integer, :itself)
lazy_resolve(LazyObj, :dup)
end
}
it "returns registered lazy method names by class/superclass, or returns nil" do
assert_equal :itself, schema.lazy_method_name(68)
assert_equal true, schema.lazy?(77)
assert_equal :dup, schema.lazy_method_name(LazyObj.new)
assert_equal true, schema.lazy?(LazyObj.new)
assert_equal :dup, schema.lazy_method_name(LazyObjChild.new)
assert_equal true, schema.lazy?(LazyObjChild.new)
assert_nil schema.lazy_method_name({})
assert_equal false, schema.lazy?({})
end
end
describe "#validate" do
it "returns errors on the query string" do
errors = schema.validate("{ cheese(id: 1) { flavor flavor: id } }")
assert_equal 1, errors.length
assert_equal "Field 'flavor' has a field conflict: flavor or id?", errors.first.message
errors = schema.validate("{ cheese(id: 1) { flavor id } }")
assert_equal [], errors
end
it "accepts a list of custom rules" do
custom_rules = GraphQL::StaticValidation::ALL_RULES - [GraphQL::StaticValidation::FragmentsAreNamed]
errors = schema.validate("fragment on Cheese { id }", rules: custom_rules)
assert_equal([], errors)
end
it "accepts a context hash" do
context = { admin: false }
# AdminSchema is a barebones dummy schema, where fields are visible only with context[:admin] == true
errors = admin_schema.validate('query { adminOnlyMessage }', context: context)
assert_equal 1, errors.length
assert_equal("Field 'adminOnlyMessage' doesn't exist on type 'AdminDairyAppQuery'", errors.first.message)
context = { admin: true }
errors = admin_schema.validate('query { adminOnlyMessage }', context: context)
assert_equal([], errors)
end
describe "with error limiting" do
describe("disabled") do
it "does not limit errors when not enabled" do
disabled_schema = Class.new(schema) { validate_max_errors(nil) }
errors = disabled_schema.validate("{ cheese(id: 1) { flavor flavor: id, cow } }")
messages = errors.map { |e| e.message }
assert_equal([
"Field 'flavor' has a field conflict: flavor or id?",
"Field 'cow' doesn't exist on type 'Cheese'"
], messages)
end
end
describe("enabled") do
it "does limit errors when enabled" do
enabled_schema = Class.new(schema) { validate_max_errors(1) }
errors = enabled_schema.validate("{ cheese(id: 1) { flavor flavor: id, cow } }")
messages = errors.map { |e| e.message }
assert_equal([
"Field 'flavor' has a field conflict: flavor or id?",
], messages)
end
end
end
end
describe "#as_json / #to_json" do
it "returns the introspection result" do
result = schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY)
assert_equal result, schema.as_json
assert_equal result, JSON.parse(schema.to_json)
end
end
describe "#as_json" do
it "returns a hash" do
result = schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY)
assert_equal result.as_json.class, Hash
end
end
describe "#get_field" do
it "returns fields by type or type name" do
field = schema.get_field("Cheese", "id")
assert_instance_of Dummy::BaseField, field
field_2 = schema.get_field(Dummy::Cheese, "id")
assert_equal field, field_2
end
end
describe "class-based schemas" do
it "implements methods" do
# Not delegated:
assert_equal Jazz::Query, Jazz::Schema.query
assert Jazz::Schema.respond_to?(:query)
# Delegated
assert_equal [], Jazz::Schema.tracers
assert Jazz::Schema.respond_to?(:tracers)
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/integration/rails/graphql/input_object_spec.rb | spec/integration/rails/graphql/input_object_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema::InputObject do
let(:input_object) do
Dummy::DairyProductInput.new(
nil,
ruby_kwargs: { source: 'COW', fatContent: 0.8 },
defaults_used: Set.new,
context: GraphQL::Query::NullContext.instance)
end
describe '#to_json' do
it 'returns JSON serialized representation of the variables hash' do
# Regression note: Previously, calling `to_json` on input objects caused stack too deep errors
assert_equal input_object.to_json, { source: "COW", fatContent: 0.8 }.to_json
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/integration/rails/graphql/query/variables_spec.rb | spec/integration/rails/graphql/query/variables_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::Variables do
let(:query_string) {%|
query getCheese(
$animals: [DairyAnimal!],
$intDefaultNull: Int = null,
$int: Int,
$intWithDefault: Int = 10)
{
cheese(id: 1) {
similarCheese(source: $animals)
}
}
|}
let(:ast_variables) { GraphQL.parse(query_string).definitions.first.variables }
let(:schema) { Dummy::Schema }
let(:query_context) { GraphQL::Query.new(schema, "{ __typename }").context }
let(:variables) {
GraphQL::Query::Variables.new(
query_context,
ast_variables,
provided_variables)
}
describe "#to_h" do
let(:provided_variables) { { "animals" => "YAK" } }
it "returns a hash representation including default values" do
expected_hash = {
"animals" => "YAK", # This is converted to a single-item list later on
"intDefaultNull" => nil,
"intWithDefault" => 10,
}
assert_equal expected_hash, variables.to_h
end
end
describe "#initialize" do
describe "validating input objects" do
let(:query_string) {%|
query searchMyDairy (
$product: DairyProductInput
) {
searchDairy(product: $product) {
... on Cheese {
flavor
}
}
}
|}
describe "when provided input is an array" do
let(:provided_variables) { { "product" => [] } }
it "validates invalid input objects" do
expected = "Variable $product of type DairyProductInput was provided invalid value"
assert_equal expected, variables.errors.first.message
end
end
describe "when provided input cannot be coerced" do
let(:query_string) {%|
query searchMyDairy (
$time: Time
) {
searchDairy(expiresAfter: $time) {
... on Cheese {
flavor
}
}
}
|}
let(:provided_variables) { { "time" => "a" } }
it "validates invalid input objects" do
expected = "Variable $time of type Time was provided invalid value"
assert_equal expected, variables.errors.first.message
end
end
end
describe "nullable variables" do
module ObjectWithThingsCount
def self.thingsCount(args, ctx) # rubocop:disable Naming/MethodName
1
end
end
let(:schema) { GraphQL::Schema.from_definition(%|
type Query {
thingsCount(ids: [ID!]): Int!
}
|)
}
let(:query_string) {%|
query getThingsCount($ids: [ID!]) {
thingsCount(ids: $ids)
}
|}
let(:result) {
schema.execute(query_string, variables: provided_variables, root_value: ObjectWithThingsCount)
}
describe "when they are present, but null" do
let(:provided_variables) { { "ids" => nil } }
it "ignores them" do
assert_equal 1, result["data"]["thingsCount"]
end
end
describe "when they are not present" do
let(:provided_variables) { {} }
it "ignores them" do
assert_equal 1, result["data"]["thingsCount"]
end
end
describe "when a non-nullable list has a null in it" do
let(:provided_variables) { { "ids" => [nil] } }
it "returns an error" do
assert_equal 1, result["errors"].length
assert_nil result["data"]
end
end
end
describe "coercing null" do
let(:provided_variables) {
{
"intWithVariable" => nil,
"intWithDefault" => nil,
"complexValWithVariable" => {
"val" => 1,
"val_with_default" => 2,
},
"complexValWithDefaultAndVariable" => {
"val" => 8,
},
}
}
let(:args) { {} }
let(:schema) {
args_cache = args
complex_val = Class.new(GraphQL::Schema::InputObject) do
graphql_name "ComplexVal"
argument :val, Integer, required: false, camelize: false
argument :val_with_default, Integer, required: false, default_value: 13, camelize: false
end
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
field :variables_test, Integer, extras: [:ast_node], camelize: false do
argument :val, Integer, required: false
argument :val_with_default, Integer, required: false, default_value: 13, camelize: false
argument :complex_val, complex_val, required: false, camelize: false
end
def variables_test(ast_node:, **args)
context.schema.args_cache[ast_node.alias] = args
1
end
end
Class.new(GraphQL::Schema) do
query(query_type)
class << self
attr_accessor :args_cache
end
self.args_cache = args_cache
end
}
let(:query_string) {<<-GRAPHQL
query testVariables(
$intWithVariable: Int,
$intWithDefault: Int = 10,
$intDefaultNull: Int = null,
$intWithoutVariable: Int,
$complexValWithVariable: ComplexVal,
$complexValWithoutVariable: ComplexVal,
$complexValWithOneDefault: ComplexVal = { val: 10 },
$complexValWithTwoDefaults: ComplexVal = { val: 11, val_with_default: 11 },
$complexValWithNullDefaults: ComplexVal = { val: null, val_with_default: null },
$complexValWithDefaultAndVariable: ComplexVal = { val: 99 },
) {
aa: variables_test(val: $intWithVariable)
ab: variables_test(val: $intWithoutVariable)
ac: variables_test(val: $intWithDefault)
ad: variables_test(val: $intDefaultNull)
ba: variables_test(val_with_default: $intWithVariable)
bb: variables_test(val_with_default: $intWithoutVariable)
bc: variables_test(val_with_default: $intWithDefault)
bd: variables_test(val_with_default: $intDefaultNull)
ca: variables_test(complex_val: { val: $intWithVariable })
cb: variables_test(complex_val: { val: $intWithoutVariable })
cc: variables_test(complex_val: { val: $intWithDefault })
cd: variables_test(complex_val: { val: $intDefaultNull })
da: variables_test(complex_val: { val_with_default: $intWithVariable })
db: variables_test(complex_val: { val_with_default: $intWithoutVariable })
dc: variables_test(complex_val: { val_with_default: $intWithDefault })
dd: variables_test(complex_val: { val_with_default: $intDefaultNull })
ea: variables_test(complex_val: $complexValWithVariable)
eb: variables_test(complex_val: $complexValWithoutVariable)
ec: variables_test(complex_val: $complexValWithOneDefault)
ed: variables_test(complex_val: $complexValWithTwoDefaults)
ee: variables_test(complex_val: $complexValWithNullDefaults)
ef: variables_test(complex_val: $complexValWithDefaultAndVariable)
}
GRAPHQL
}
let(:run_query) {
schema.execute(query_string, variables: provided_variables)
}
let(:variables) { GraphQL::Query::Variables.new(
query_context,
ast_variables,
provided_variables)
}
def assert_has_key_with_value(hash, key, has_key, value)
assert_equal(has_key, hash.key?(key))
if value.nil?
assert_nil hash[key]
else
assert_equal(value, hash[key])
end
end
it "preserves explicit null" do
assert_has_key_with_value(variables, "intWithVariable", true, nil)
run_query
# Provided `nil` should be passed along to args
# and override any defaults (variable defaults and arg defaults)
assert_has_key_with_value(args["aa"], :val, true, nil)
assert_has_key_with_value(args["ba"], :val_with_default, true, nil)
assert_has_key_with_value(args["ca"][:complex_val], :val, true, nil)
assert_has_key_with_value(args["da"][:complex_val], :val_with_default, true, nil)
end
it "doesn't contain variables that weren't present" do
assert_has_key_with_value(variables, "intWithoutVariable", false, nil)
run_query
assert_has_key_with_value(args["ab"], :val, false, nil)
# This one _is_ present, it gets the argument.default_value
assert_has_key_with_value(args["bb"], :val_with_default, true, 13)
assert_has_key_with_value(args["cb"][:complex_val], :val, false, nil)
# This one _is_ present, it gets the argument.default_value
assert_has_key_with_value(args["db"][:complex_val], :val_with_default, true, 13)
end
it "preserves explicit null when variable has a default value" do
assert_has_key_with_value(variables, "intWithDefault", true, nil)
run_query
assert_has_key_with_value(args["ac"], :val, true, nil)
assert_has_key_with_value(args["bc"], :val_with_default, true, nil)
assert_has_key_with_value(args["cc"][:complex_val], :val, true, nil)
assert_has_key_with_value(args["dc"][:complex_val], :val_with_default, true, nil)
end
it "uses null default value" do
assert_has_key_with_value(variables, "intDefaultNull", true, nil)
run_query
assert_has_key_with_value(args["ad"], :val, true, nil)
assert_has_key_with_value(args["bd"], :val_with_default, true, nil)
assert_has_key_with_value(args["cd"][:complex_val], :val, true, nil)
assert_has_key_with_value(args["dd"][:complex_val], :val_with_default, true, nil)
end
it "applies argument default values" do
run_query
# It wasn't present in the query string, but it gets argument.default_value:
assert_has_key_with_value(args["aa"], :val_with_default, true, 13)
end
it "applies coercion to input objects passed as variables" do
run_query
assert_has_key_with_value(args["ea"][:complex_val], :val, true, 1)
assert_has_key_with_value(args["ea"][:complex_val], :val_with_default, true, 2)
# Since the variable wasn't provided, it's not present at all:
assert_has_key_with_value(args["eb"], :complex_val, false, nil)
assert_has_key_with_value(args["ec"][:complex_val], :val, true, 10)
assert_has_key_with_value(args["ec"][:complex_val], :val_with_default, true, 13)
assert_has_key_with_value(args["ed"][:complex_val], :val, true, 11)
assert_has_key_with_value(args["ed"][:complex_val], :val_with_default, true, 11)
assert_has_key_with_value(args["ee"][:complex_val], :val, true, nil)
assert_has_key_with_value(args["ee"][:complex_val], :val_with_default, true, nil)
assert_has_key_with_value(args["ef"][:complex_val], :val, true, 8)
assert_has_key_with_value(args["ef"][:complex_val], :val_with_default, true, 13)
end
end
end
if ActionPack::VERSION::MAJOR > 3
describe "with a ActionController::Parameters" do
let(:query_string) { <<-GRAPHQL
query getCheeses($source: DairyAnimal!, $fatContent: Float!){
searchDairy(product: [{source: $source, fatContent: $fatContent}]) {
... on Cheese { flavor }
}
}
GRAPHQL
}
let(:params) do
ActionController::Parameters.new(
"variables" => {
"source" => "COW",
"fatContent" => 0.4,
}
)
end
it "works" do
res = schema.execute(query_string, variables: params["variables"])
assert_equal 1, res["data"]["searchDairy"].length
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/integration/rails/graphql/relay/connection_type_spec.rb | spec/integration/rails/graphql/relay/connection_type_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Relay::ConnectionType" do
describe ".create_type" do
describe "connections with custom Edge classes / EdgeTypes" do
let(:query_string) {%|
query($testNames: Boolean!) {
rebels {
basesWithCustomEdge {
totalCountTimes100
fieldName @include(if: $testNames)
edges {
upcasedName @include(if: $testNames)
upcasedParentName @include(if: $testNames)
edgeClassName
node {
name
}
cursor
}
}
}
}
|}
it "uses the custom edge and custom connection" do
result = star_wars_query(query_string, { "testNames" => true })
bases = result["data"]["rebels"]["basesWithCustomEdge"]
assert_equal 300, bases["totalCountTimes100"]
assert_equal 'basesWithCustomEdge', bases["fieldName"]
assert_equal ["YAVIN", "ECHO BASE", "SECRET HIDEOUT"] , bases["edges"].map { |e| e["upcasedName"] }
upcased_rebels_name = "ALLIANCE TO RESTORE THE REPUBLIC"
assert_equal [upcased_rebels_name] , bases["edges"].map { |e| e["upcasedParentName"] }.uniq
assert_equal ["Yavin", "Echo Base", "Secret Hideout"] , bases["edges"].map { |e| e["node"]["name"] }
assert_equal ["StarWars::NewCustomBaseEdge"] , bases["edges"].map { |e| e["edgeClassName"] }.uniq
end
end
describe "connections with nodes field" do
let(:query_string) {%|
{
rebels {
bases {
nodes {
name
}
}
basesWithCustomEdge {
nodes {
name
}
}
}
}
|}
it "uses the custom edge and custom connection" do
result = star_wars_query(query_string)
bases = result["data"]["rebels"]["bases"]
assert_equal ["Yavin", "Echo Base", "Secret Hideout"] , bases["nodes"].map { |e| e["name"] }
bases_with_custom_edge = result["data"]["rebels"]["basesWithCustomEdge"]
assert_equal ["Yavin", "Echo Base", "Secret Hideout"] , bases_with_custom_edge["nodes"].map { |e| e["name"] }
end
end
describe "connections without nodes field" do
let(:query_string) {%|
{
rebels {
basesWithoutNodes {
nodes {
name
}
}
}
}
|}
it "raises error" do
result = star_wars_query(query_string)
assert_includes result["errors"][0]["message"], "Field 'nodes' doesn't exist"
end
end
describe "when an execution error is raised" do
let(:query_string) {%|
{
basesWithNullName {
edges {
node {
name
}
}
}
}
|}
it "nullifies the parent and adds an error" do
result = star_wars_query(query_string)
assert_nil result["data"]["basesWithNullName"]["edges"][0]["node"]
assert_equal "Boom!", result["errors"][0]["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/integration/rails/graphql/relay/page_info_spec.rb | spec/integration/rails/graphql/relay/page_info_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Relay::PageInfo" do
def get_page_info(result)
result["data"]["empire"]["bases"]["pageInfo"]
end
def get_first_cursor(result)
result["data"]["empire"]["bases"]["edges"].first["cursor"]
end
def get_last_cursor(result)
result["data"]["empire"]["bases"]["edges"].last["cursor"]
end
let(:cursor_of_last_base) {
result = star_wars_query(query_string, { "first" => 100 })
get_last_cursor(result)
}
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String, $nameIncludes: String){
empire {
bases(first: $first, after: $after, last: $last, before: $before, nameIncludes: $nameIncludes) {
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
},
edges {
cursor
}
}
}
}
|}
describe 'hasNextPage / hasPreviousPage' do
it "hasNextPage is true if there are more items" do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"], "hasPreviousPage is false if 'last' is missing")
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "first" => 100, "after" => last_cursor })
assert_equal(false, get_page_info(result)["hasNextPage"])
assert_equal(true, get_page_info(result)["hasPreviousPage"])
assert_equal("Mw", get_page_info(result)["startCursor"])
assert_equal("Mw", get_page_info(result)["endCursor"])
end
it "hasPreviousPage if there are more items" do
result = star_wars_query(query_string, { "last" => 100, "before" => cursor_of_last_base })
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
result = star_wars_query(query_string, { "last" => 1, "before" => cursor_of_last_base })
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(true, get_page_info(result)["hasPreviousPage"])
assert_equal("Mg", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
end
it "has both if first and last are present" do
result = star_wars_query(query_string, { "last" => 1, "first" => 1, "before" => cursor_of_last_base })
assert_equal(true, get_page_info(result)["hasNextPage"])
# I think this was actually a bug in the previous implementation.
# This query returns the first node in the list:
# Base64.decode64("MQ") # => "1"
# So, there is _not_ a previous page.
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("MQ", get_page_info(result)["endCursor"])
end
it "startCursor and endCursor are the cursors of the first and last edge" do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mg", get_last_cursor(result))
result = star_wars_query(query_string, { "first" => 1, "after" => get_page_info(result)["endCursor"] })
assert_equal(false, get_page_info(result)["hasNextPage"])
assert_equal(true, get_page_info(result)["hasPreviousPage"])
assert_equal("Mw", get_page_info(result)["startCursor"])
assert_equal("Mw", get_page_info(result)["endCursor"])
assert_equal("Mw", get_first_cursor(result))
assert_equal("Mw", get_last_cursor(result))
result = star_wars_query(query_string, { "last" => 1, "before" => get_page_info(result)["endCursor"] })
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(true, get_page_info(result)["hasPreviousPage"])
assert_equal("Mg", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
assert_equal("Mg", get_first_cursor(result))
assert_equal("Mg", get_last_cursor(result))
end
end
it "can be redefined" do
conn_type = Class.new(GraphQL::Schema::Object) do
include GraphQL::Types::Relay::ConnectionBehaviors
get_field("pageInfo").type = GraphQL::Types::Int.to_non_null_type
end
assert_equal "Int!", conn_type.fields["pageInfo"].type.to_type_signature
# The original is unchanged:
assert_equal "PageInfo!", GraphQL::Types::Relay::BaseConnection.fields["pageInfo"].type.to_type_signature
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/graphql/relay/connection_resolve_spec.rb | spec/integration/rails/graphql/relay/connection_resolve_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Relay::ConnectionResolve" do
let(:query_string) { <<-GRAPHQL
query getShips($name: String!, $testParentName: Boolean = false){
rebels {
ships(nameIncludes: $name) {
edges {
node {
name
}
}
parentClassName @include(if: $testParentName)
}
}
}
GRAPHQL
}
describe "when an execution error is returned" do
it "adds an error" do
result = star_wars_query(query_string, { "name" => "error"})
assert_equal 1, result["errors"].length
assert_equal "error from within connection", result["errors"][0]["message"]
end
it "adds an error for a lazy error" do
result = star_wars_query(query_string, { "name" => "lazyError"})
assert_equal 1, result["errors"].length
assert_equal "lazy error from within connection", result["errors"][0]["message"]
end
it "adds an error for a lazy raised error" do
result = star_wars_query(query_string, { "name" => "lazyRaisedError"})
assert_equal 1, result["errors"].length
assert_equal "lazy raised error from within connection", result["errors"][0]["message"]
end
it "adds an error for a raised error" do
result = star_wars_query(query_string, { "name" => "raisedError"})
assert_equal 1, result["errors"].length
assert_equal "error raised from within connection", result["errors"][0]["message"]
end
end
describe "when nil is returned" do
it "becomes null" do
result = star_wars_query(query_string, { "name" => "null" })
conn = result["data"]["rebels"]["ships"]
assert_nil conn
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/integration/rails/graphql/relay/array_connection_spec.rb | spec/integration/rails/graphql/relay/array_connection_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "GraphQL::Relay::ArrayConnection" do
def get_names(result)
ships = result["data"]["rebels"]["ships"]["edges"]
ships.map { |e| e["node"]["name"] }
end
def get_last_cursor(result)
result["data"]["rebels"]["ships"]["edges"].last["cursor"]
end
def get_page_info(result, key = "bases")
result["data"]["rebels"][key]["pageInfo"]
end
describe "results" do
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String, $nameIncludes: String){
rebels {
ships(first: $first, after: $after, last: $last, before: $before, nameIncludes: $nameIncludes) {
edges {
cursor
node {
name
}
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
}
}
|}
it 'limits the result' do
result = star_wars_query(query_string, { "first" => 2 })
number_of_ships = get_names(result).length
assert_equal(2, number_of_ships)
assert_equal(true, result["data"]["rebels"]["ships"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasPreviousPage"])
assert_equal("MQ", result["data"]["rebels"]["ships"]["pageInfo"]["startCursor"])
assert_equal("Mg", result["data"]["rebels"]["ships"]["pageInfo"]["endCursor"])
result = star_wars_query(query_string, { "first" => 3 })
number_of_ships = get_names(result).length
assert_equal(3, number_of_ships)
end
it 'provides pageInfo' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(true, result["data"]["rebels"]["ships"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasPreviousPage"])
assert_equal("MQ", result["data"]["rebels"]["ships"]["pageInfo"]["startCursor"])
assert_equal("Mg", result["data"]["rebels"]["ships"]["pageInfo"]["endCursor"])
result = star_wars_query(query_string, { "first" => 100 })
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasPreviousPage"])
assert_equal("MQ", result["data"]["rebels"]["ships"]["pageInfo"]["startCursor"])
assert_equal("NQ", result["data"]["rebels"]["ships"]["pageInfo"]["endCursor"])
end
it 'slices the result' do
result = star_wars_query(query_string, { "first" => 1 })
assert_equal(["X-Wing"], get_names(result))
# After the last result, find the next 2:
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "after" => last_cursor, "first" => 2 })
assert_equal(["Y-Wing", "A-Wing"], get_names(result))
# After the last result, find the next 2:
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "after" => last_cursor, "first" => 2 })
assert_equal(["Millennium Falcon", "Home One"], get_names(result))
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 2 })
assert_equal(["X-Wing", "Y-Wing"], get_names(result))
result = star_wars_query(query_string, { "last" => 2 })
assert_equal(["Millennium Falcon", "Home One"], get_names(result))
result = star_wars_query(query_string, { "last" => 10 })
assert_equal(["X-Wing", "Y-Wing", "A-Wing", "Millennium Falcon", "Home One"], get_names(result))
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasPreviousPage"])
end
it 'works with before and after specified together' do
result = star_wars_query(query_string, { "first" => 1 })
assert_equal(["X-Wing"], get_names(result))
first_cursor = get_last_cursor(result)
# There is no records between before and after if they point to the same cursor
result = star_wars_query(query_string, { "before" => first_cursor, "after" => first_cursor, "last" => 2 })
assert_equal([], get_names(result))
result = star_wars_query(query_string, { "after" => first_cursor, "first" => 2 })
assert_equal(["Y-Wing", "A-Wing"], get_names(result))
third_cursor = get_last_cursor(result)
# There is only 1 result between the cursors
result = star_wars_query(query_string, { "after" => first_cursor, "before" => third_cursor, "first" => 5 })
assert_equal(["Y-Wing"], get_names(result))
end
it 'handles cursors beyond the bounds of the array' do
overreaching_cursor = Base64.strict_encode64("100")
result = star_wars_query(query_string, { "after" => overreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it 'applies custom arguments' do
result = star_wars_query(query_string, { "nameIncludes" => "Wing", "first" => 2 })
names = get_names(result)
assert_equal(2, names.length)
after = get_last_cursor(result)
result = star_wars_query(query_string, { "nameIncludes" => "Wing", "after" => after, "first" => 3 })
names = get_names(result)
assert_equal(1, names.length)
end
it 'works without first/last/after/before' do
result = star_wars_query(query_string)
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["rebels"]["ships"]["pageInfo"]["hasPreviousPage"])
assert_equal("MQ", result["data"]["rebels"]["ships"]["pageInfo"]["startCursor"])
assert_equal("NQ", result["data"]["rebels"]["ships"]["pageInfo"]["endCursor"])
assert_equal(5, result["data"]["rebels"]["ships"]["edges"].length)
end
describe "applying max_page_size" do
def get_names(result)
result["data"]["rebels"]["bases"]["edges"].map { |e| e["node"]["name"] }
end
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String){
rebels {
bases: basesWithMaxLimitArray(first: $first, after: $after, last: $last, before: $before) {
edges {
cursor
node {
name
}
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
}
|}
it "applies to queries by `first`" do
result = star_wars_query(query_string, { "first" => 100 })
assert_equal(["Yavin", "Echo Base"], get_names(result))
assert_equal(true, get_page_info(result)["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_wars_query(query_string)
assert_equal(["Yavin", "Echo Base"], get_names(result))
assert_equal(true, get_page_info(result)["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
last_cursor = "Ng=="
result = star_wars_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
assert_equal(true, get_page_info(result)["hasPreviousPage"])
result = star_wars_query(query_string, { "before" => last_cursor })
assert_equal(["Yavin", "Echo Base"], get_names(result))
assert_equal(false, get_page_info(result)["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
third_cursor = "Mw"
first_and_second_names = ["Yavin", "Echo Base"]
result = star_wars_query(query_string, { "last" => 100, "before" => third_cursor })
assert_equal(first_and_second_names, get_names(result))
result = star_wars_query(query_string, { "before" => third_cursor })
assert_equal(first_and_second_names, get_names(result))
end
end
describe "applying default_max_page_size" do
def get_names(result)
result["data"]["rebels"]["bases"]["edges"].map { |e| e["node"]["name"] }
end
def get_page_info(result)
result["data"]["rebels"]["bases"]["pageInfo"]
end
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String){
rebels {
bases: basesWithDefaultMaxLimitArray(first: $first, after: $after, last: $last, before: $before) {
edges {
cursor
node {
name
}
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
}
|}
it "applies to queries by `first`" do
result = star_wars_query(query_string, { "first" => 100 })
assert_equal(["Yavin", "Echo Base", "Secret Hideout"], get_names(result))
assert_equal(true, get_page_info(result)["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_wars_query(query_string)
assert_equal(["Yavin", "Echo Base", "Secret Hideout"], get_names(result))
assert_equal(true, get_page_info(result)["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
last_cursor = "Ng=="
result = star_wars_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(["Secret Hideout", "Death Star", "Shield Generator"], get_names(result))
assert_equal(true, get_page_info(result)["hasPreviousPage"])
result = star_wars_query(query_string, { "before" => last_cursor })
assert_equal(["Yavin", "Echo Base", "Secret Hideout"], get_names(result))
assert_equal(false, get_page_info(result)["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
fourth_cursor = "NA=="
first_second_and_third_names = ["Yavin", "Echo Base", "Secret Hideout"]
result = star_wars_query(query_string, { "last" => 100, "before" => fourth_cursor })
assert_equal(first_second_and_third_names, get_names(result))
result = star_wars_query(query_string, { "before" => fourth_cursor })
assert_equal(first_second_and_third_names, get_names(result))
end
end
describe "bidirectional pagination" do
it "provides bidirectional_pagination by default" do
result = star_wars_query(query_string, { "first" => 1 })
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "first" => 3, "after" => last_cursor })
assert_equal(true, get_page_info(result, "ships")["hasNextPage"])
assert_equal(true, get_page_info(result, "ships")["hasPreviousPage"])
# When going backwards, bi-directional pagination
# returns true for `hasNextPage`
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "last" => 2, "before" => last_cursor })
assert_equal(true, get_page_info(result, "ships")["hasNextPage"])
assert_equal(true, get_page_info(result, "ships")["hasPreviousPage"])
end
it "returns correct page info when the before cursor belongs to the last element in the array" do
result = star_wars_query(query_string, { "last" => 1 })
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 1 })
assert_equal(true, get_page_info(result, "ships")["hasNextPage"])
assert_equal(true, get_page_info(result, "ships")["hasPreviousPage"])
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/integration/rails/graphql/relay/range_add_spec.rb | spec/integration/rails/graphql/relay/range_add_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Relay::RangeAdd do
# Make sure that the encoder is found through `ctx.schema`:
module PassThroughEncoder
def self.encode(unencoded_text, nonce: false)
"__#{unencoded_text}"
end
def self.decode(encoded_text, nonce: false)
encoded_text[2..-1]
end
end
let(:schema) {
menus = [
OpenStruct.new(
name: "Los Primos",
items: [
OpenStruct.new(name: "California Burrito", price: 699),
OpenStruct.new(name: "Fish Taco", price: 399),
]
)
]
item = Class.new(GraphQL::Schema::Object) do
graphql_name "Item"
field :price, Integer, null: false
field :name, String, null: false
end
menu = Class.new(GraphQL::Schema::Object) do
graphql_name "Menu"
field :name, String, null: false
field :items, item.connection_type, null: false
end
query = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
field :menus, [menu], null: false
define_method :menus do
menus
end
end
add_item = Class.new(GraphQL::Schema::RelayClassicMutation) do
graphql_name "AddItem"
argument :name, String
argument :price, Integer
argument :menu_idx, Integer
field :item_edge, item.edge_type, null: false
field :items, item.connection_type, null: false
field :menu, menu, null: false
define_method :resolve do |input|
this_menu = menus[input[:menu_idx]]
new_item = OpenStruct.new(name: input[:name], price: input[:price])
this_menu.items << new_item
range_add = GraphQL::Relay::RangeAdd.new(
parent: this_menu,
item: new_item,
collection: this_menu.items,
context: context,
)
{
menu: range_add.parent,
items: range_add.connection,
item_edge: range_add.edge,
}
end
end
mutation = Class.new(GraphQL::Schema::Object) do
graphql_name "Mutation"
field :add_item, mutation: add_item
end
Class.new(GraphQL::Schema) do
self.query(query)
self.mutation(mutation)
self.cursor_encoder(PassThroughEncoder)
end
}
describe "returning Relay objects" do
let(:query_str) { <<-GRAPHQL
mutation {
addItem(input: {name: "Chilaquiles", price: 699, menuIdx: 0}) {
menu {
name
}
itemEdge {
node {
name
price
}
}
items {
edges {
node {
name
}
cursor
}
}
}
}
GRAPHQL
}
it "returns a connection and an edge" do
res = schema.execute(query_str)
mutation_res = res["data"]["addItem"]
assert_equal("Los Primos", mutation_res["menu"]["name"])
assert_equal({"name"=>"Chilaquiles", "price"=>699}, mutation_res["itemEdge"]["node"])
assert_equal(["California Burrito", "Fish Taco", "Chilaquiles"], mutation_res["items"]["edges"].map { |e| e["node"]["name"] })
assert_equal(["__1", "__2", "__3"], mutation_res["items"]["edges"].map { |e| e["cursor"] })
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/integration/rails/graphql/relay/relation_connection_spec.rb | spec/integration/rails/graphql/relay/relation_connection_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "GraphQL::Relay::RelationConnection" do
def get_names(result)
ships = result["data"]["empire"]["bases"]["edges"]
ships.map { |e| e["node"]["name"] }
end
def get_page_info(result)
result["data"]["empire"]["bases"]["pageInfo"]
end
def get_first_cursor(result)
result["data"]["empire"]["bases"]["edges"].first["cursor"]
end
def get_last_cursor(result)
result["data"]["empire"]["bases"]["edges"].last["cursor"]
end
describe "results" do
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String, $nameIncludes: String){
empire {
bases(first: $first, after: $after, last: $last, before: $before, nameIncludes: $nameIncludes) {
... basesConnection
}
}
}
fragment basesConnection on BasesConnectionWithTotalCount {
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
},
totalCount,
edges {
cursor
node {
name
}
}
}
|}
it 'limits the result' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(2, get_names(result).length)
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mg", get_last_cursor(result))
result = star_wars_query(query_string, { "first" => 3 })
assert_equal(3, get_names(result).length)
assert_equal(false, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mw", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mw", get_last_cursor(result))
end
it 'returns the correct hasNextPage value' do
first_page_result = star_wars_query(query_string, { "first" => 2})
assert_equal(true, get_page_info(first_page_result)["hasNextPage"])
result = star_wars_query(query_string, { "first" => 2, "after" => get_page_info(first_page_result)["endCursor"] })
assert_equal(false, get_page_info(result)["hasNextPage"])
end
it "uses unscope(:order) count(*) when the relation has some complicated SQL" do
query_s = <<-GRAPHQL
query getShips($first: Int, $after: String, $complexOrder: Boolean){
empire {
bases(first: $first, after: $after, complexOrder: $complexOrder) {
edges {
node {
name
}
}
pageInfo {
hasNextPage
}
}
}
}
GRAPHQL
result = nil
log = with_active_record_log do
result = star_wars_query(query_s, { "first" => 1, "after" => "MQ==", "complexOrder" => true })
end
conn = result["data"]["empire"]["bases"]
assert_equal(1, conn["edges"].size)
assert_equal(true, conn["pageInfo"]["hasNextPage"])
log_entries = log.split("\n")
assert_equal 1, log_entries.size, "It should run 1 sql query"
edges_query, = log_entries.first
assert_includes edges_query, "ORDER BY bases.name", "The query for edges _is_ ordered"
end
it 'provides custom fields on the connection type' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(
StarWars::Base.where(faction_id: 2).count,
result["data"]["empire"]["bases"]["totalCount"]
)
end
it "makes one sql query for items and another for count" do
query_str = <<-GRAPHQL
{
empire {
bases(first: 2) {
totalCount
edges {
cursor
node {
name
}
}
}
}
}
GRAPHQL
result = nil
log = with_active_record_log do
result = star_wars_query(query_str, { "first" => 2 })
end
assert_equal 2, log.scan("\n").count, "Two log entries"
assert_equal 3, result["data"]["empire"]["bases"]["totalCount"]
assert_equal 2, result["data"]["empire"]["bases"]["edges"].size
end
it "does bidirectional pagination by default" do
result = star_wars_query(query_string, { "first" => 1 })
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "first" => 1, "after" => last_cursor })
assert_equal true, get_page_info(result)["hasNextPage"]
assert_equal true, get_page_info(result)["hasPreviousPage"]
result = star_wars_query(query_string, { "first" => 100 })
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "last" => 1, "before" => last_cursor })
assert_equal true, get_page_info(result)["hasNextPage"]
assert_equal true, get_page_info(result)["hasPreviousPage"]
end
it 'slices the result' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
# After the last result, find the next 2:
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "after" => last_cursor, "first" => 2 })
assert_equal(["Headquarters"], get_names(result))
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 1 })
assert_equal(["Shield Generator"], get_names(result))
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 2 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 10 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
result = star_wars_query(query_string, { "last" => 2 })
assert_equal(["Shield Generator", "Headquarters"], get_names(result))
result = star_wars_query(query_string, { "last" => 10 })
assert_equal(["Death Star", "Shield Generator", "Headquarters"], get_names(result))
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"])
end
it 'works with before and after specified together' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
first_cursor = get_last_cursor(result)
# There is no records between before and after if they point to the same cursor
result = star_wars_query(query_string, { "before" => first_cursor, "after" => first_cursor, "last" => 2 })
assert_equal([], get_names(result))
result = star_wars_query(query_string, { "after" => first_cursor, "first" => 2 })
assert_equal(["Headquarters"], get_names(result))
second_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "after" => first_cursor, "before" => second_cursor, "first" => 3 })
assert_equal([], get_names(result))
end
it 'handles cursors above the bounds of the array' do
overreaching_cursor = Base64.strict_encode64("100")
result = star_wars_query(query_string, { "after" => overreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it 'handles cursors below the bounds of the array' do
underreaching_cursor = Base64.strict_encode64("1")
result = star_wars_query(query_string, { "before" => underreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it 'handles grouped connections with only last argument' do
grouped_conn_query = <<-GRAPHQL
query {
newestBasesGroupedByFaction(last: 2) {
edges {
node {
name
}
}
}
}
GRAPHQL
result = star_wars_query(grouped_conn_query)
names = result['data']['newestBasesGroupedByFaction']['edges'].map { |edge| edge['node']['name'] }
assert_equal(['Headquarters', 'Secret Hideout'], names)
end
it "applies custom arguments" do
result = star_wars_query(query_string, { "first" => 1, "nameIncludes" => "ea" })
assert_equal(["Death Star"], get_names(result))
after = get_last_cursor(result)
result = star_wars_query(query_string, { "first" => 2, "nameIncludes" => "ea", "after" => after })
assert_equal(["Headquarters"], get_names(result))
before = get_last_cursor(result)
result = star_wars_query(query_string, { "last" => 1, "nameIncludes" => "ea", "before" => before })
assert_equal(["Death Star"], get_names(result))
end
it 'works without first/last/after/before' do
result = star_wars_query(query_string)
assert_equal(3, result["data"]["empire"]["bases"]["edges"].length)
end
describe "applying max_page_size" do
let(:query_string) {%|
query getBases($first: Int, $after: String, $last: Int, $before: String){
empire {
bases: basesWithMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
... basesConnection
}
}
}
fragment basesConnection on BaseConnection {
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it "applies to queries by `first`" do
result = star_wars_query(query_string, { "first" => 100 })
assert_equal(2, result["data"]["empire"]["bases"]["edges"].size)
assert_equal(true, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_wars_query(query_string)
assert_equal(2, result["data"]["empire"]["bases"]["edges"].size)
assert_equal(true, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
second_to_last_two_names = ["Death Star", "Shield Generator"]
first_and_second_names = ["Yavin", "Echo Base"]
last_cursor = "Ng=="
result = star_wars_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(second_to_last_two_names, get_names(result))
assert_equal(true, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_wars_query(query_string, { "before" => last_cursor })
assert_equal(first_and_second_names, get_names(result))
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
third_cursor = "Mw"
result = star_wars_query(query_string, { "last" => 100, "before" => third_cursor })
assert_equal(first_and_second_names, get_names(result))
result = star_wars_query(query_string, { "before" => third_cursor })
assert_equal(first_and_second_names, get_names(result))
end
end
describe "applying default_max_page_size" do
let(:query_string) {%|
query getBases($first: Int, $after: String, $last: Int, $before: String){
empire {
bases: basesWithDefaultMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
... basesConnection
}
}
}
fragment basesConnection on BaseConnection {
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it "applies to queries by `first`" do
result = star_wars_query(query_string, { "first" => 100 })
assert_equal(3, result["data"]["empire"]["bases"]["edges"].size)
assert_equal(true, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_wars_query(query_string)
assert_equal(3, result["data"]["empire"]["bases"]["edges"].size)
assert_equal(true, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
second_to_last_three_names = ["Secret Hideout", "Death Star", "Shield Generator"]
first_second_and_third_names = ["Yavin", "Echo Base", "Secret Hideout"]
last_cursor = "Ng=="
result = star_wars_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(second_to_last_three_names, get_names(result))
assert_equal(true, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_wars_query(query_string, { "before" => last_cursor })
assert_equal(first_second_and_third_names, get_names(result))
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
fourth_cursor = "NA=="
result = star_wars_query(query_string, { "last" => 100, "before" => fourth_cursor })
assert_equal(first_second_and_third_names, get_names(result))
result = star_wars_query(query_string, { "before" => fourth_cursor })
assert_equal(first_second_and_third_names, get_names(result))
end
end
end
describe "applying a max_page_size bigger than the results" do
let(:query_string) {%|
query getBases($first: Int, $after: String, $last: Int, $before: String){
empire {
bases: basesWithLargeMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
... basesConnection
}
}
}
fragment basesConnection on BaseConnection {
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it "applies to queries by `first`" do
result = star_wars_query(query_string, { "first" => 100 })
assert_equal(6, result["data"]["empire"]["bases"]["edges"].size)
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_wars_query(query_string)
assert_equal(6, result["data"]["empire"]["bases"]["edges"].size)
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
all_names = ["Yavin", "Echo Base", "Secret Hideout", "Death Star", "Shield Generator", "Headquarters"]
last_cursor = "Ng=="
result = star_wars_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(all_names[0..4], get_names(result))
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_wars_query(query_string, { "last" => 100 })
assert_equal(all_names, get_names(result))
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_wars_query(query_string, { "before" => last_cursor })
assert_equal(all_names[0..4], get_names(result))
assert_equal(false, result["data"]["empire"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
fourth_cursor = "NA=="
result = star_wars_query(query_string, { "last" => 100, "before" => fourth_cursor })
assert_equal(all_names[0..2], get_names(result))
result = star_wars_query(query_string, { "before" => fourth_cursor })
assert_equal(all_names[0..2], get_names(result))
end
end
describe "without a block" do
let(:query_string) {%|
{
empire {
basesClone(first: 10) {
edges {
node {
name
}
}
}
}
}|}
it "uses default resolve" do
result = star_wars_query(query_string)
bases = result["data"]["empire"]["basesClone"]["edges"]
assert_equal(3, bases.length)
end
end
describe "custom ordering" do
let(:query_string) {%|
query getBases {
empire {
basesByName(first: 30) { ... basesFields }
bases(first: 30) { ... basesFields2 }
}
}
fragment basesFields on BaseConnection {
edges {
node {
name
}
}
}
fragment basesFields2 on BasesConnectionWithTotalCount {
edges {
node {
name
}
}
}
|}
def get_names(result, field_name)
bases = result["data"]["empire"][field_name]["edges"]
bases.map { |b| b["node"]["name"] }
end
it "applies the default value" do
result = star_wars_query(query_string)
bases_by_id = ["Death Star", "Shield Generator", "Headquarters"]
bases_by_name = ["Death Star", "Headquarters", "Shield Generator"]
assert_equal(bases_by_id, get_names(result, "bases"))
assert_equal(bases_by_name, get_names(result, "basesByName"))
end
end
describe "with a Sequel::Dataset" do
def get_names(result)
ships = result["data"]["empire"]["basesAsSequelDataset"]["edges"]
ships.map { |e| e["node"]["name"] }
end
def get_page_info(result)
result["data"]["empire"]["basesAsSequelDataset"]["pageInfo"]
end
def get_first_cursor(result)
result["data"]["empire"]["basesAsSequelDataset"]["edges"].first["cursor"]
end
def get_last_cursor(result)
result["data"]["empire"]["basesAsSequelDataset"]["edges"].last["cursor"]
end
describe "results" do
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String, $nameIncludes: String){
empire {
basesAsSequelDataset(first: $first, after: $after, last: $last, before: $before, nameIncludes: $nameIncludes) {
... basesConnection
}
}
}
fragment basesConnection on BasesConnectionWithTotalCount {
totalCount,
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it 'limits the result' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(2, get_names(result).length)
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mg", get_last_cursor(result))
result = star_wars_query(query_string, { "first" => 3 })
assert_equal(3, get_names(result).length)
assert_equal(false, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mw", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mw", get_last_cursor(result))
end
it 'provides custom fields on the connection type' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(
StarWars::Base.where(faction_id: 2).count,
result["data"]["empire"]["basesAsSequelDataset"]["totalCount"]
)
end
it 'slices the result' do
result = star_wars_query(query_string, { "first" => 2 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
# After the last result, find the next 2:
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "after" => last_cursor, "first" => 2 })
assert_equal(["Headquarters"], get_names(result))
last_cursor = get_last_cursor(result)
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 1 })
assert_equal(["Shield Generator"], get_names(result))
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 2 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
result = star_wars_query(query_string, { "before" => last_cursor, "last" => 10 })
assert_equal(["Death Star", "Shield Generator"], get_names(result))
end
it 'handles cursors above the bounds of the array' do
overreaching_cursor = Base64.strict_encode64("100")
result = star_wars_query(query_string, { "after" => overreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it 'handles cursors below the bounds of the array' do
underreaching_cursor = Base64.strict_encode64("1")
result = star_wars_query(query_string, { "before" => underreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it "applies custom arguments" do
result = star_wars_query(query_string, { "first" => 1, "nameIncludes" => "ea" })
assert_equal(["Death Star"], get_names(result))
after = get_last_cursor(result)
result = star_wars_query(query_string, { "first" => 2, "nameIncludes" => "ea", "after" => after })
assert_equal(["Headquarters"], get_names(result))
before = get_last_cursor(result)
result = star_wars_query(query_string, { "last" => 1, "nameIncludes" => "ea", "before" => before })
assert_equal(["Death Star"], get_names(result))
end
it "makes one sql query for items and another for count" do
query_str = <<-GRAPHQL
{
empire {
basesAsSequelDataset(first: 2) {
totalCount
edges {
cursor
node {
name
}
}
}
}
}
GRAPHQL
result = nil
io = StringIO.new
begin
SequelDB.loggers << Logger.new(io)
result = star_wars_query(query_str, { "first" => 2 })
ensure
SequelDB.loggers.pop
end
assert_equal 2, io.string.scan("SELECT").count
assert_equal 3, result["data"]["empire"]["basesAsSequelDataset"]["totalCount"]
assert_equal 2, result["data"]["empire"]["basesAsSequelDataset"]["edges"].size
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/integration/rails/graphql/tracing/active_support_notifications_tracing_spec.rb | spec/integration/rails/graphql/tracing/active_support_notifications_tracing_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Tracing::ActiveSupportNotificationsTracing do
let(:schema) {
Class.new(StarWars::Schema) do
tracer GraphQL::Tracing::ActiveSupportNotificationsTracing
end
}
it "pushes through AS::N" do
traces = []
callback = ->(name, started, finished, id, data) {
path_str = if data.key?(:field)
" (#{data[:field].path})"
else
""
end
traces << "#{name}#{path_str}"
}
query_string = <<-GRAPHQL
query Bases($id1: ID!, $id2: ID!){
b1: batchedBase(id: $id1) { name }
b2: batchedBase(id: $id2) { name }
}
GRAPHQL
first_id = StarWars::Base.first.id
last_id = StarWars::Base.last.id
ActiveSupport::Notifications.subscribed(callback, /graphql$/) do
schema.execute(query_string, variables: {
"id1" => first_id,
"id2" => last_id,
})
end
expected_traces = [
(USING_C_PARSER ? "lex.graphql" : nil),
"parse.graphql",
"validate.graphql",
"analyze_query.graphql",
"analyze_multiplex.graphql",
"authorized.graphql",
"execute_field.graphql (Query.batchedBase)",
"execute_field.graphql (Query.batchedBase)",
"execute_query.graphql",
"lazy_loader.graphql",
"execute_field_lazy.graphql (Query.batchedBase)",
"authorized.graphql",
"execute_field.graphql (Base.name)",
"execute_field_lazy.graphql (Query.batchedBase)",
"authorized.graphql",
"execute_field.graphql (Base.name)",
"execute_field_lazy.graphql (Base.name)",
"execute_field_lazy.graphql (Base.name)",
"execute_query_lazy.graphql",
"execute_multiplex.graphql",
].compact
assert_equal expected_traces, traces
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/graphql/types/iso_8601_duration_spec.rb | spec/integration/rails/graphql/types/iso_8601_duration_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Types::ISO8601Duration do
module DurationTest
class Schema < GraphQL::Schema
def self.type_error(err, ctx)
raise err
end
end
end
let(:context) { GraphQL::Query.new(DurationTest::Schema, "{ __typename }").context }
# 3 years, 6 months, 4 days, 12 hours, 30 minutes, and 5.12345 seconds
let (:duration_str) { "P3Y6M4DT12H30M5.12345S" }
let (:duration) { ActiveSupport::Duration.parse(duration_str) }
describe "coerce_result" do
describe "coercing ActiveSupport::Duration" do
it "coerces defaulting to same precision as input precision" do
assert_equal duration_str, GraphQL::Types::ISO8601Duration.coerce_result(duration, context)
end
it "coerces with seconds_precision when set" do
initial_precision = GraphQL::Types::ISO8601Duration.seconds_precision
GraphQL::Types::ISO8601Duration.seconds_precision = 2
assert_equal duration.iso8601(precision: 2), GraphQL::Types::ISO8601Duration.coerce_result(duration, context)
GraphQL::Types::ISO8601Duration.seconds_precision = initial_precision
end
end
describe "coercing String" do
it "defaults to same precision as input precision" do
assert_equal duration_str, GraphQL::Types::ISO8601Duration.coerce_result(duration_str, context)
end
it "coerces with seconds_precision when set" do
initial_precision = GraphQL::Types::ISO8601Duration.seconds_precision
GraphQL::Types::ISO8601Duration.seconds_precision = 2
assert_equal duration.iso8601(precision: 2), GraphQL::Types::ISO8601Duration.coerce_result(duration_str, context)
GraphQL::Types::ISO8601Duration.seconds_precision = initial_precision
end
end
describe "coercing incompatible objects" do
it "raises GraphQL::Error" do
assert_raises GraphQL::Error do
GraphQL::Types::ISO8601Duration.coerce_result(Object.new, context)
end
end
end
end
describe "coerce_input" do
describe "coercing ActiveSupport::Duration" do
it "returns itself" do
assert_equal duration, GraphQL::Types::ISO8601Duration.coerce_input(duration, context)
end
end
describe "coercing nil" do
it "returns nil" do
assert_nil GraphQL::Types::ISO8601Duration.coerce_input(nil, context)
end
end
describe "coercing String" do
it "returns a ActiveSupport::Duration for ISO8601-formatted durations" do
assert_equal duration, GraphQL::Types::ISO8601Duration.coerce_input(duration_str, context)
end
it "raises GraphQL::DurationEncodingError for incorrectly formatted strings" do
assert_raises GraphQL::DurationEncodingError do
# ISO8601 dates are not durations
GraphQL::Types::ISO8601Duration.coerce_input("2007-03-01T13:00:00Z", context)
end
end
end
describe "coercing other objects" do
it "raises GraphQL::DurationEncodingError" do
assert_raises GraphQL::DurationEncodingError do
# ISO8601 dates are not durations
GraphQL::Types::ISO8601Duration.coerce_input(Object.new, context)
end
end
end
end
describe "when ActiveSupport is not defined" do
it "coerce_result and coerce_input raise GraphQL::Error" do
old_active_support = defined?(ActiveSupport) ? ActiveSupport : nil
Object.send(:remove_const, :ActiveSupport) if defined?(ActiveSupport)
assert_raises GraphQL::Error do
GraphQL::Types::ISO8601Duration.coerce_result("", context)
end
assert_raises GraphQL::Error do
GraphQL::Types::ISO8601Duration.coerce_input("", context)
end
ActiveSupport = old_active_support unless old_active_support.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/integration/rails/graphql/dataloader/async_dataloader_spec.rb | spec/integration/rails/graphql/dataloader/async_dataloader_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Dataloader::AsyncDataloader do
class RailsAsyncSchema < GraphQL::Schema
class CustomAsyncDataloader < GraphQL::Dataloader::AsyncDataloader
def cleanup_fiber
end
def get_fiber_variables
vars = super
vars[:connected_to] = {
role: StarWars::StarWarsModel.current_role,
shard: StarWars::StarWarsModel.current_shard,
prevent_writes: StarWars::StarWarsModel.current_preventing_writes
}
vars
end
def set_fiber_variables(vars)
connection_config = vars.delete(:connected_to)
StarWars::StarWarsModel.connecting_to(**connection_config)
super(vars)
end
end
class BaseSource < GraphQL::Dataloader::Source
def fetch(ids)
bases = StarWars::Base.where(id: ids)
ids.map { |id| bases.find { |b| b.id == id } }
end
end
class SelfSource < GraphQL::Dataloader::Source
def fetch(ids)
ids
end
end
class Query < GraphQL::Schema::Object
field :base_name, String do
argument :id, Int
end
def base_name(id:)
base = dataloader.with(BaseSource).load(id)
base&.name
end
field :query, Query
field :inline_base_name, String do
argument :id, Int
end
def inline_base_name(id:)
StarWars::Base.where(id: id).first&.name
end
def query
dataloader.with(SelfSource).load(:query)
end
field :role, String
def role
StarWars::StarWarsModel.current_role.to_s
end
end
query(Query)
use CustomAsyncDataloader
end
before {
skip("Only test when isolation_level = :fiber") unless ENV["ISOLATION_LEVEL_FIBER"]
}
it "cleans up database connections" do
starting_connections = ActiveRecord::Base.connection_pool.connections.size
query_str = "{
b1: baseName(id: 1) b2: baseName(id: 2)
ib1: inlineBaseName(id: 1)
query {
b3: baseName(id: 3)
query {
b4: baseName(id: 4)
ib2: inlineBaseName(id: 2)
}
}
}"
res = RailsAsyncSchema.execute(query_str)
assert_equal({
"b1" => "Yavin", "b2" => "Echo Base", "ib1" => "Yavin",
"query" => {
"b3" => "Secret Hideout",
"query" => { "b4" => "Death Star", "ib2" => "Echo Base" }
}
}, res["data"])
RailsAsyncSchema.execute(query_str)
RailsAsyncSchema.execute(query_str)
ending_connections = ActiveRecord::Base.connection_pool.connections.size
retained_connections = ending_connections - starting_connections
assert_equal 0, retained_connections, "No connections are retained by GraphQL"
end
it "uses the `connected_to` role" do
query_str = "{ role query { role } }"
result = StarWars::StarWarsModel.connected_to(role: :reading) do
RailsAsyncSchema.execute(query_str)
end
expected_res = { "role" => "reading", "query" => { "role" => "reading" }}
assert_graphql_equal expected_res, 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/integration/rails/generators/base_generator_test.rb | spec/integration/rails/generators/base_generator_test.rb | # frozen_string_literal: true
class BaseGeneratorTest < Rails::Generators::TestCase
destination File.expand_path("../../tmp", File.dirname(__FILE__))
setup :prepare_destination
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/relay_generator_spec.rb | spec/integration/rails/generators/graphql/relay_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/relay_generator"
require "generators/graphql/install_generator"
class GraphQLGeneratorsRelayGeneratorTest < Rails::Generators::TestCase
tests Graphql::Generators::RelayGenerator
destination File.expand_path("../../../tmp/dummy", File.dirname(__FILE__))
setup do
prepare_destination
FileUtils.cd(File.join(destination_root, '..')) do
`rails new dummy --skip-active-record --skip-test-unit --skip-spring --skip-bundle --skip-webpack-install`
Graphql::Generators::InstallGenerator.start(["--skip-graphiql"], { destination_root: destination_root })
end
end
test "it adds node and connection stuff" do
run_generator
assert_file "app/graphql/types/node_type.rb" do |content|
assert_includes content, "module NodeType"
assert_includes content, "include Types::BaseInterface"
assert_includes content, "include GraphQL::Types::Relay::NodeBehaviors"
end
assert_file "app/graphql/types/base_connection.rb" do |content|
assert_includes content, "class BaseConnection < Types::BaseObject"
assert_includes content, "include GraphQL::Types::Relay::ConnectionBehaviors"
end
assert_file "app/graphql/types/base_edge.rb" do |content|
assert_includes content, "class BaseEdge < Types::BaseObject"
assert_includes content, "include GraphQL::Types::Relay::EdgeBehaviors"
end
base_return_types = [
"app/graphql/types/base_union.rb",
"app/graphql/types/base_interface.rb",
"app/graphql/types/base_object.rb",
]
base_return_types.each do |base_type_path|
assert_file base_type_path do |content|
assert_includes content, "connection_type_class(Types::BaseConnection)", "#{base_type_path} has base connection setup"
assert_includes content, "edge_type_class(Types::BaseEdge)", "#{base_type_path} has base edge setup"
end
end
assert_file "app/graphql/types/query_type.rb" do |content|
assert_includes content, "field :node, Types::NodeType"
assert_includes content, "field :nodes, [Types::NodeType, null: true]"
end
assert_file "app/graphql/dummy_schema.rb" do |content|
assert_includes content, "def self.object_from_id"
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/scalar_generator_spec.rb | spec/integration/rails/generators/graphql/scalar_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/scalar_generator"
class GraphQLGeneratorsScalarGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::ScalarGenerator
test "it generates scalar class" do
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class DateType < Types::BaseScalar
def self.coerce_input(input_value, context)
# Override this to prepare a client-provided GraphQL value for your Ruby code
input_value
end
def self.coerce_result(ruby_value, context)
# Override this to serialize a Ruby value for the GraphQL response
ruby_value.to_s
end
end
end
RUBY
run_generator(["Date"])
assert_file "app/graphql/types/date_type.rb", expected_content
end
test "it generates scalar class with object and graphql type namespacing" do
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class Scalars::Time::DateType < Types::BaseScalar
def self.coerce_input(input_value, context)
# Override this to prepare a client-provided GraphQL value for your Ruby code
input_value
end
def self.coerce_result(ruby_value, context)
# Override this to serialize a Ruby value for the GraphQL response
ruby_value.to_s
end
end
end
RUBY
run_generator(["time/Date", "--namespaced-types"])
assert_file "app/graphql/types/scalars/time/date_type.rb", expected_content
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/mutation_delete_generator_spec.rb | spec/integration/rails/generators/graphql/mutation_delete_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/mutation_delete_generator"
class GraphQLGeneratorsMutationDeleteGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::MutationDeleteGenerator
destination File.expand_path("../../../tmp/dummy", File.dirname(__FILE__))
setup :prepare_destination
# Use this to account for `.destroy` vs `.destroy!` in https://github.com/rails/rails/pull/43501
example_orm_instance = Rails::Generators::ActiveModel.new "names_name"
NAMESPACED_DELETE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::NameDelete < BaseMutation
description "Deletes a name by ID"
field :name, Types::Objects::Names::NameType, null: false
argument :id, ID, required: true
def resolve(id:)
names_name = ::Names::Name.find(id)
raise GraphQL::ExecutionError.new "Error deleting name", extensions: names_name.errors.to_hash unless #{example_orm_instance.destroy}
{ name: names_name }
end
end
end
RUBY
DELETE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::NameDelete < BaseMutation
description "Deletes a name by ID"
field :name, Types::Names::NameType, null: false
argument :id, ID, required: true
def resolve(id:)
names_name = ::Names::Name.find(id)
raise GraphQL::ExecutionError.new "Error deleting name", extensions: names_name.errors.to_hash unless #{example_orm_instance.destroy}
{ name: names_name }
end
end
end
RUBY
EXPECTED_DELETE_MUTATION_TYPE = <<-RUBY
# frozen_string_literal: true
module Types
class MutationType < Types::BaseObject
field :name_delete, mutation: Mutations::Names::NameDelete
# TODO: remove me
field :test_field, String, null: false,
description: "An example field added by the generator"
def test_field
"Hello World"
end
end
end
RUBY
test "it generates a delete resolver by name, and inserts the field into the MutationType" do
run_generator(["names/name", "--schema", "dummy"])
assert_file "app/graphql/mutations/names/name_delete.rb", DELETE_NAME_MUTATION
assert_file "app/graphql/types/mutation_type.rb", EXPECTED_DELETE_MUTATION_TYPE
end
test "it generates a namespaced delete resolver by name" do
run_generator(["names/name", "--schema", "dummy", "--namespaced-types"])
assert_file "app/graphql/mutations/names/name_delete.rb", NAMESPACED_DELETE_NAME_MUTATION
end
test "it allows for user-specified directory, delete" do
run_generator(["names/name", "--schema", "dummy", "--directory", "app/mydirectory"])
assert_file "app/mydirectory/mutations/names/name_delete.rb", DELETE_NAME_MUTATION
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/object_generator_spec.rb | spec/integration/rails/generators/graphql/object_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/object_generator"
class GraphQLGeneratorsObjectGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::ObjectGenerator
# rubocop:disable Style/ClassAndModuleChildren
class ::TestUser < ActiveRecord::Base
end
# rubocop:enable Style/ClassAndModuleChildren
test "it generates fields with types" do
commands = [
# GraphQL-style:
["Bird", "wingspan:Int!", "foliage:[Color]"],
# Ruby-style:
["BirdType", "wingspan:!Integer", "foliage:[Types::ColorType]"],
# Mixed
["BirdType", "wingspan:!Int", "foliage:[Color]"],
]
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class BirdType < Types::BaseObject
field :wingspan, Integer, null: false
field :foliage, [Types::ColorType]
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/bird_type.rb", expected_content
end
end
test "it generates fields with namespaced types" do
commands = [
# GraphQL-style:
["Bird", "wingspan:Int!", "foliage:[Color]"],
# Ruby-style:
["BirdType", "wingspan:!Integer", "foliage:[Types::ColorType]"],
# Mixed
["BirdType", "wingspan:!Int", "foliage:[Color]"],
].map { |c| c + ["--namespaced-types"]}
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class Objects::BirdType < Types::BaseObject
field :wingspan, Integer, null: false
field :foliage, [Types::ColorType]
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/objects/bird_type.rb", expected_content
end
end
test "it generates namespaced classified file" do
run_generator(["books/page"])
assert_file "app/graphql/types/books/page_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class Books::PageType < Types::BaseObject
end
end
RUBY
end
test "it makes Relay nodes" do
run_generator(["Page", "--node"])
assert_file "app/graphql/types/page_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class PageType < Types::BaseObject
implements GraphQL::Types::Relay::Node
end
end
RUBY
end
test "it generates objects based on ActiveRecord schema, with namespaced types" do
run_generator(["TestUser", "--namespaced-types"])
assert_file "app/graphql/types/objects/test_user_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class Objects::TestUserType < Types::BaseObject
field :id, ID, null: false
field :created_at, GraphQL::Types::ISO8601DateTime
field :birthday, GraphQL::Types::ISO8601Date
field :points, Integer, null: false
field :rating, Float, null: false
end
end
RUBY
end
test "it generates objects based on ActiveRecord schema with additional custom fields" do
run_generator(["TestUser", "name:!String", "email:!Citext", "settings:jsonb"])
assert_file "app/graphql/types/test_user_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class TestUserType < Types::BaseObject
field :id, ID, null: false
field :created_at, GraphQL::Types::ISO8601DateTime
field :birthday, GraphQL::Types::ISO8601Date
field :points, Integer, null: false
field :rating, Float, null: false
field :name, String, null: false
field :email, String, null: false
field :settings, GraphQL::Types::JSON
end
end
RUBY
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/union_generator_spec.rb | spec/integration/rails/generators/graphql/union_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/union_generator"
class GraphQLGeneratorsUnionGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::UnionGenerator
test "it generates a union with possible types" do
commands = [
# GraphQL-style:
["WingedCreature", "Insect", "Bird"],
# Ruby-style:
["Types::WingedCreatureType", "Types::InsectType", "Types::BirdType"],
]
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class WingedCreatureType < Types::BaseUnion
possible_types Types::InsectType, Types::BirdType
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/winged_creature_type.rb", expected_content
end
end
test "it generates an union with possible namespaced types" do
commands = [
# GraphQL-style:
["WingedCreature", "Insect", "Bird"],
# Ruby-style:
["Types::WingedCreatureType", "Types::InsectType", "Types::BirdType"],
].map { |c| c + ["--namespaced-types"]}
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class Unions::WingedCreatureType < Types::BaseUnion
possible_types Types::InsectType, Types::BirdType
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/unions/winged_creature_type.rb", expected_content
end
end
test "it accepts a user-specified directory" do
command = ["WingedCreature", "--directory", "app/mydirectory"]
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class WingedCreatureType < Types::BaseUnion
end
end
RUBY
prepare_destination
run_generator(command)
assert_file "app/mydirectory/types/winged_creature_type.rb", expected_content
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/interface_generator_spec.rb | spec/integration/rails/generators/graphql/interface_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/interface_generator"
class GraphQLGeneratorsInterfaceGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::InterfaceGenerator
test "it generates fields with types" do
commands = [
# GraphQL-style:
["Bird", "wingspan:Int!", "foliage:[Color]"],
# Ruby-style:
["BirdType", "wingspan:Integer!", "foliage:[Types::ColorType]"],
# Mixed
["BirdType", "wingspan:!Int", "foliage:[Color]"],
]
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
module BirdType
include Types::BaseInterface
field :wingspan, Integer, null: false
field :foliage, [Types::ColorType]
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/bird_type.rb", expected_content
end
end
test "it generates fields with namespaced types" do
commands = [
# GraphQL-style:
["animals/Bird", "wingspan:Int!", "foliage:[Color]"],
# Ruby-style:
["animals/BirdType", "wingspan:Integer!", "foliage:[Types::ColorType]"],
# Mixed
["animals/BirdType", "wingspan:!Int", "foliage:[Color]"],
].map { |c| c + ["--namespaced-types"]}
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
module Interfaces::Animals::BirdType
include Types::BaseInterface
field :wingspan, Integer, null: false
field :foliage, [Types::ColorType]
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/interfaces/animals/bird_type.rb", expected_content
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/integration/rails/generators/graphql/mutation_create_generator_spec.rb | spec/integration/rails/generators/graphql/mutation_create_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/mutation_create_generator"
class GraphQLGeneratorsMutationCreateGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::MutationCreateGenerator
destination File.expand_path("../../../tmp/dummy", File.dirname(__FILE__))
setup :prepare_destination
NAMESPACED_CREATE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::NameCreate < BaseMutation
description "Creates a new name"
field :name, Types::Objects::Names::NameType, null: false
argument :name_input, Types::Inputs::Names::NameInputType, required: true
def resolve(name_input:)
names_name = ::Names::Name.new(**name_input)
raise GraphQL::ExecutionError.new "Error creating name", extensions: names_name.errors.to_hash unless names_name.save
{ name: names_name }
end
end
end
RUBY
CREATE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::NameCreate < BaseMutation
description "Creates a new name"
field :name, Types::Names::NameType, null: false
argument :name_input, Types::Names::NameInputType, required: true
def resolve(name_input:)
names_name = ::Names::Name.new(**name_input)
raise GraphQL::ExecutionError.new "Error creating name", extensions: names_name.errors.to_hash unless names_name.save
{ name: names_name }
end
end
end
RUBY
EXPECTED_MUTATION_TYPE = <<-RUBY
# frozen_string_literal: true
module Types
class MutationType < Types::BaseObject
field :name_create, mutation: Mutations::Names::NameCreate
# TODO: remove me
field :test_field, String, null: false,
description: "An example field added by the generator"
def test_field
"Hello World"
end
end
end
RUBY
test "it generates a create resolver by name, and inserts the field into the MutationType" do
run_generator(["names/name", "--schema", "dummy"])
assert_file "app/graphql/mutations/names/name_create.rb", CREATE_NAME_MUTATION
assert_file "app/graphql/types/mutation_type.rb", EXPECTED_MUTATION_TYPE
end
test "it generates a namespaced create resolver by name" do
run_generator(["names/name", "--schema", "dummy", "--namespaced-types"])
assert_file "app/graphql/mutations/names/name_create.rb", NAMESPACED_CREATE_NAME_MUTATION
end
test "it allows for user-specified directory" do
run_generator(["names/name", "--schema", "dummy", "--directory", "app/mydirectory"])
assert_file "app/mydirectory/mutations/names/name_create.rb", CREATE_NAME_MUTATION
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/input_generator_spec.rb | spec/integration/rails/generators/graphql/input_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/input_generator"
class GraphQLGeneratorsInputGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::InputGenerator
# rubocop:disable Style/ClassAndModuleChildren
class ::InputTestUser < ActiveRecord::Base
end
# rubocop:enable Style/ClassAndModuleChildren
test "it generates arguments with types" do
commands = [
# GraphQL-style:
["Bird", "wingspan:Int!", "foliage:[Color]"],
# Ruby-style:
["BirdType", "wingspan:!Integer", "foliage:[Types::ColorType]"],
# Mixed
["BirdType", "wingspan:!Int", "foliage:[Color]"],
]
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class BirdInputType < Types::BaseInputObject
argument :wingspan, Integer, required: false
argument :foliage, [Types::ColorType], required: false
end
end
RUBY
commands.each do |c|
prepare_destination
run_generator(c)
assert_file "app/graphql/types/bird_input_type.rb", expected_content
end
end
test "it generates classified file" do
run_generator(["page"])
assert_file "app/graphql/types/page_input_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class PageInputType < Types::BaseInputObject
end
end
RUBY
end
test "it generates namespaced classified file" do
run_generator(["page", "--namespaced-types"])
assert_file "app/graphql/types/inputs/page_input_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class Inputs::PageInputType < Types::BaseInputObject
end
end
RUBY
end
test "it generates objects based on ActiveRecord schema" do
run_generator(["InputTestUser"])
assert_file "app/graphql/types/input_test_user_input_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class InputTestUserInputType < Types::BaseInputObject
argument :id, ID, required: false
argument :created_at, GraphQL::Types::ISO8601DateTime, required: false
argument :birthday, GraphQL::Types::ISO8601Date, required: false
argument :points, Integer, required: false
argument :rating, Float, required: false
argument :friend_id, Integer, required: false
end
end
RUBY
end
test "it generates namespaced objects based on ActiveRecord schema" do
run_generator(["InputTestUser", "--namespaced-types"])
assert_file "app/graphql/types/inputs/input_test_user_input_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class Inputs::InputTestUserInputType < Types::BaseInputObject
argument :id, ID, required: false
argument :created_at, GraphQL::Types::ISO8601DateTime, required: false
argument :birthday, GraphQL::Types::ISO8601Date, required: false
argument :points, Integer, required: false
argument :rating, Float, required: false
argument :friend_id, Integer, required: false
end
end
RUBY
end
test "it generates objects based on ActiveRecord schema with additional custom arguments" do
run_generator(["InputTestUser", "name:!String", "email:!Citext", "settings:jsonb"])
assert_file "app/graphql/types/input_test_user_input_type.rb", <<-RUBY
# frozen_string_literal: true
module Types
class InputTestUserInputType < Types::BaseInputObject
argument :id, ID, required: false
argument :created_at, GraphQL::Types::ISO8601DateTime, required: false
argument :birthday, GraphQL::Types::ISO8601Date, required: false
argument :points, Integer, required: false
argument :rating, Float, required: false
argument :friend_id, Integer, required: false
argument :name, String, required: false
argument :email, String, required: false
argument :settings, GraphQL::Types::JSON, required: false
end
end
RUBY
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/loader_generator_spec.rb | spec/integration/rails/generators/graphql/loader_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/loader_generator"
class GraphQLGeneratorsLoaderGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::LoaderGenerator
test "it generates an empty loader by name" do
run_generator(["RecordLoader"])
expected_content = <<-RUBY
# frozen_string_literal: true
module Loaders
class RecordLoader < GraphQL::Batch::Loader
# Define `initialize` to store grouping arguments, eg
#
# Loaders::RecordLoader.for(group).load(value)
#
# def initialize()
# end
# `keys` contains each key from `.load(key)`.
# Find the corresponding values, then
# call `fulfill(key, value)` or `fulfill(key, nil)`
# for each key.
def perform(keys)
end
end
end
RUBY
assert_file "app/graphql/loaders/record_loader.rb", expected_content
end
test "it generates a namespaced loader by name" do
run_generator(["active_record::record_loader"])
expected_content = <<-RUBY
# frozen_string_literal: true
module Loaders
class ActiveRecord::RecordLoader < GraphQL::Batch::Loader
# Define `initialize` to store grouping arguments, eg
#
# Loaders::ActiveRecord::RecordLoader.for(group).load(value)
#
# def initialize()
# end
# `keys` contains each key from `.load(key)`.
# Find the corresponding values, then
# call `fulfill(key, value)` or `fulfill(key, nil)`
# for each key.
def perform(keys)
end
end
end
RUBY
assert_file "app/graphql/loaders/active_record/record_loader.rb", expected_content
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/mutation_update_generator_spec.rb | spec/integration/rails/generators/graphql/mutation_update_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/mutation_update_generator"
class GraphQLGeneratorsMutationUpdateGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::MutationUpdateGenerator
destination File.expand_path("../../../tmp/dummy", File.dirname(__FILE__))
setup :prepare_destination
NAMESPACED_UPDATE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::NameUpdate < BaseMutation
description "Updates a name by id"
field :name, Types::Objects::Names::NameType, null: false
argument :id, ID, required: true
argument :name_input, Types::Inputs::Names::NameInputType, required: true
def resolve(id:, name_input:)
names_name = ::Names::Name.find(id)
raise GraphQL::ExecutionError.new "Error updating name", extensions: names_name.errors.to_hash unless names_name.update(**name_input)
{ name: names_name }
end
end
end
RUBY
UPDATE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::NameUpdate < BaseMutation
description "Updates a name by id"
field :name, Types::Names::NameType, null: false
argument :id, ID, required: true
argument :name_input, Types::Names::NameInputType, required: true
def resolve(id:, name_input:)
names_name = ::Names::Name.find(id)
raise GraphQL::ExecutionError.new "Error updating name", extensions: names_name.errors.to_hash unless names_name.update(**name_input)
{ name: names_name }
end
end
end
RUBY
EXPECTED_UPDATE_MUTATION_TYPE = <<-RUBY
# frozen_string_literal: true
module Types
class MutationType < Types::BaseObject
field :name_update, mutation: Mutations::Names::NameUpdate
# TODO: remove me
field :test_field, String, null: false,
description: "An example field added by the generator"
def test_field
"Hello World"
end
end
end
RUBY
test "it generates an update resolver by name, and inserts the field into the MutationType" do
run_generator(["names/name", "--schema", "dummy"])
assert_file "app/graphql/mutations/names/name_update.rb", UPDATE_NAME_MUTATION
assert_file "app/graphql/types/mutation_type.rb", EXPECTED_UPDATE_MUTATION_TYPE
end
test "it generates a namespaced update resolver by name" do
run_generator(["names/name", "--schema", "dummy", "--namespaced-types"])
assert_file "app/graphql/mutations/names/name_update.rb", NAMESPACED_UPDATE_NAME_MUTATION
end
test "it allows for user-specified directory, update" do
run_generator(["names/name", "--schema", "dummy", "--directory", "app/mydirectory"])
assert_file "app/mydirectory/mutations/names/name_update.rb", UPDATE_NAME_MUTATION
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/mutation_generator_spec.rb | spec/integration/rails/generators/graphql/mutation_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/mutation_generator"
require "generators/graphql/install_generator"
class GraphQLGeneratorsMutationGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::MutationGenerator
setup :prepare_destination
UPDATE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class UpdateName < BaseMutation
# TODO: define return fields
# field :post, Types::PostType, null: false
# TODO: define arguments
# argument :name, String, required: true
# TODO: define resolve method
# def resolve(name:)
# { post: ... }
# end
end
end
RUBY
EXPECTED_MUTATION_TYPE = <<-RUBY
# frozen_string_literal: true
module Types
class MutationType < Types::BaseObject
field :update_name, mutation: Mutations::UpdateName
# TODO: remove me
field :test_field, String, null: false,
description: "An example field added by the generator"
def test_field
"Hello World"
end
end
end
RUBY
NAMESPACED_UPDATE_NAME_MUTATION = <<-RUBY
# frozen_string_literal: true
module Mutations
class Names::UpdateName < BaseMutation
# TODO: define return fields
# field :post, Types::PostType, null: false
# TODO: define arguments
# argument :name, String, required: true
# TODO: define resolve method
# def resolve(name:)
# { post: ... }
# end
end
end
RUBY
NAMESPACED_EXPECTED_MUTATION_TYPE = <<-RUBY
# frozen_string_literal: true
module Types
class MutationType < Types::BaseObject
field :update_name, mutation: Mutations::Names::UpdateName
# TODO: remove me
field :test_field, String, null: false,
description: "An example field added by the generator"
def test_field
"Hello World"
end
end
end
RUBY
test "it generates an empty resolver by name and inserts the field into the MutationType" do
run_generator(["UpdateName", "--schema", "dummy"])
assert_file "app/graphql/mutations/update_name.rb", UPDATE_NAME_MUTATION
assert_file "app/graphql/types/mutation_type.rb", EXPECTED_MUTATION_TYPE
end
test "it generates and inserts a namespaced resolver" do
run_generator(["names/update_name", "--schema", "dummy"])
assert_file "app/graphql/mutations/names/update_name.rb", NAMESPACED_UPDATE_NAME_MUTATION
assert_file "app/graphql/types/mutation_type.rb", NAMESPACED_EXPECTED_MUTATION_TYPE
end
test "it allows for user-specified directory" do
run_generator(["UpdateName", "--schema", "dummy", "--directory", "app/mydirectory"])
assert_file "app/mydirectory/mutations/update_name.rb", UPDATE_NAME_MUTATION
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/install_generator_spec.rb | spec/integration/rails/generators/graphql/install_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/install_generator"
class GraphQLGeneratorsInstallGeneratorTest < Rails::Generators::TestCase
tests Graphql::Generators::InstallGenerator
destination File.expand_path("../../../tmp/dummy", File.dirname(__FILE__))
setup do
prepare_destination
FileUtils.cd(File.join(destination_root, '..')) do
`rails new dummy --skip-active-record --skip-test-unit --skip-spring --skip-bundle --skip-webpack-install`
end
end
def refute_file(path)
assert !File.exist?(path), "No file at #{path.inspect}"
end
test "it generates a folder structure" do
run_generator([ "--relay", "false"])
assert_file "app/graphql/types/.keep"
assert_file "app/graphql/mutations/.keep"
assert_file "app/graphql/mutations/base_mutation.rb"
["base_input_object", "base_enum", "base_scalar", "base_union"].each do |base_type|
assert_file "app/graphql/types/#{base_type}.rb"
end
expected_query_route = %|post "/graphql", to: "graphql#execute"|
expected_graphiql_route = %|
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
|
assert_file "config/routes.rb" do |contents|
assert_includes contents, expected_query_route
assert_includes contents, expected_graphiql_route
end
assert_file "app/graphql/resolvers/base_resolver.rb" do |contents|
assert_includes contents, "module Resolvers"
assert_includes contents, "class BaseResolver < GraphQL::Schema::Resolver"
end
assert_file "Gemfile" do |contents|
assert_match %r{gem ('|")graphiql-rails('|"), :?group(:| =>) :development}, contents
end
expected_schema = <<-RUBY
# frozen_string_literal: true
class DummySchema < GraphQL::Schema
mutation(Types::MutationType)
query(Types::QueryType)
# For batch-loading (see https://graphql-ruby.org/dataloader/overview.html)
use GraphQL::Dataloader
# GraphQL-Ruby calls this when something goes wrong while running a query:
def self.type_error(err, context)
# if err.is_a?(GraphQL::InvalidNullError)
# # report to your bug tracker here
# return nil
# end
super
end
# Union and Interface Resolution
def self.resolve_type(abstract_type, obj, ctx)
# TODO: Implement this method
# to return the correct GraphQL object type for `obj`
raise(GraphQL::RequiredImplementationMissingError)
end
# Limit the size of incoming queries:
max_query_string_tokens(5000)
# Stop validating when it encounters this many errors:
validate_max_errors(100)
end
RUBY
assert_file "app/graphql/dummy_schema.rb", expected_schema
expected_base_mutation = <<-RUBY
# frozen_string_literal: true
module Mutations
class BaseMutation < GraphQL::Schema::RelayClassicMutation
argument_class Types::BaseArgument
field_class Types::BaseField
input_object_class Types::BaseInputObject
object_class Types::BaseObject
end
end
RUBY
assert_file "app/graphql/mutations/base_mutation.rb", expected_base_mutation
expected_query_type = <<-RUBY
# frozen_string_literal: true
module Types
class QueryType < Types::BaseObject
# Add root-level fields here.
# They will be entry points for queries on your schema.
# TODO: remove me
field :test_field, String, null: false,
description: \"An example field added by the generator\"
def test_field
\"Hello World!\"
end
end
end
RUBY
assert_file "app/graphql/types/query_type.rb", expected_query_type
assert_file "app/controllers/graphql_controller.rb", EXPECTED_GRAPHQLS_CONTROLLER
expected_base_field = <<-RUBY
# frozen_string_literal: true
module Types
class BaseField < GraphQL::Schema::Field
argument_class Types::BaseArgument
end
end
RUBY
assert_file "app/graphql/types/base_field.rb", expected_base_field
expected_base_argument = <<-RUBY
# frozen_string_literal: true
module Types
class BaseArgument < GraphQL::Schema::Argument
end
end
RUBY
assert_file "app/graphql/types/base_argument.rb", expected_base_argument
expected_base_object = <<-RUBY
# frozen_string_literal: true
module Types
class BaseObject < GraphQL::Schema::Object
field_class Types::BaseField
end
end
RUBY
assert_file "app/graphql/types/base_object.rb", expected_base_object
expected_base_interface = <<-RUBY
# frozen_string_literal: true
module Types
module BaseInterface
include GraphQL::Schema::Interface
field_class Types::BaseField
end
end
RUBY
assert_file "app/graphql/types/base_interface.rb", expected_base_interface
expected_query_log_hook = "current_graphql_operation: -> { GraphQL::Current.operation_name }"
assert_file "config/application.rb" do |contents|
assert_includes contents, expected_query_log_hook
end
# Run it again and make sure the gemfile only contains graphiql-rails once
FileUtils.cd(File.join(destination_root)) do
run_generator(["--relay", "false", "--force"])
end
assert_file "Gemfile" do |contents|
assert_equal 1, contents.scan(/graphiql-rails/).length
end
# It doesn't seem like this works on Rails 4, oh well
if Rails::VERSION::STRING > "5"
FileUtils.cd(File.join(destination_root)) do
run_generator(["--relay", "false", "--force"], behavior: :revoke)
end
refute_file "app/graphql/types/base_object.rb"
refute_file "app/graphql/types/base_interface.rb"
refute_file "app/graphql/types/base_argument.rb"
refute_file "app/graphql/types/base_field.rb"
refute_file "app/graphql/types/query_type.rb"
refute_file "app/graphql/dummy_schema.rb"
assert_file "config/routes.rb" do |contents|
refute_includes contents, expected_query_route
# This doesn't work for some reason....
# refute_includes contents, expected_graphiql_route
end
assert_file "Gemfile" do |contents|
refute_match %r{gem ('|")graphiql-rails('|"), :?group(:| =>) :development}, contents
end
assert_file "config/application.rb" do |contents|
refute_includes contents, expected_query_log_hook
end
end
end
test "it allows for a user-specified install directory" do
run_generator(["--directory", "app/mydirectory", "--relay", "false"])
assert_file "app/mydirectory/types/.keep"
assert_file "app/mydirectory/mutations/.keep"
end
if Rails::VERSION::STRING > "3.9"
# This test doesn't work on Rails 3 because it tries to boot the app
# between the batch and relay generators, but `bundle install`
# hasn't run yet, so graphql-batch isn't present
test "it generates graphql-batch and relay boilerplate" do
run_generator(["--batch"])
assert_file "app/graphql/loaders/.keep"
assert_file "Gemfile" do |contents|
assert_match %r{gem ('|")graphql-batch('|")}, contents
end
expected_query_type = <<-RUBY
# frozen_string_literal: true
module Types
class QueryType < Types::BaseObject
field :node, Types::NodeType, null: true, description: "Fetches an object given its ID." do
argument :id, ID, required: true, description: "ID of the object."
end
def node(id:)
context.schema.object_from_id(id, context)
end
field :nodes, [Types::NodeType, null: true], null: true, description: "Fetches a list of objects given a list of IDs." do
argument :ids, [ID], required: true, description: "IDs of the objects."
end
def nodes(ids:)
ids.map { |id| context.schema.object_from_id(id, context) }
end
# Add root-level fields here.
# They will be entry points for queries on your schema.
# TODO: remove me
field :test_field, String, null: false,
description: \"An example field added by the generator\"
def test_field
\"Hello World!\"
end
end
end
RUBY
assert_file "app/graphql/types/query_type.rb", expected_query_type
assert_file "app/graphql/dummy_schema.rb", EXPECTED_RELAY_BATCH_SCHEMA
end
end
test "it doesn't install graphiql when API Only" do
run_generator(['--api'])
assert_file "Gemfile" do |contents|
refute_includes contents, "graphiql-rails"
end
assert_file "config/routes.rb" do |contents|
refute_includes contents, "GraphiQL::Rails"
end
end
test "it can skip keeps, skip graphiql, skip query logs and customize schema name" do
run_generator(["--skip-keeps", "--skip-graphiql", "--schema=CustomSchema","--skip-query-logs"])
assert_no_file "app/graphql/types/.keep"
assert_no_file "app/graphql/mutations/.keep"
assert_file "app/graphql/types"
assert_file "app/graphql/mutations"
assert_file "Gemfile" do |contents|
refute_includes contents, "graphiql-rails"
end
assert_file "config/routes.rb" do |contents|
refute_includes contents, "GraphiQL::Rails"
end
assert_file "config/application.rb" do |contents|
refute_includes contents, "graphql"
end
assert_file "app/graphql/custom_schema.rb", /class CustomSchema < GraphQL::Schema/
assert_file "app/controllers/graphql_controller.rb", /CustomSchema\.execute/
end
test "it can add GraphQL Playground as an IDE through the --playground option and modify existing query tags" do
# Make it look like QueryLogs was already added:
config_file_path = File.expand_path("config/application.rb", destination_root)
config_file_contents = File.read(config_file_path)
config_file_contents.sub!("class Application < Rails::Application", "class Application < Rails::Application
config.active_record.query_log_tags_enabled = true
config.active_record.query_log_tags = [ :application, :controller, :action, :job ]
")
File.write(config_file_path, config_file_contents)
run_generator(["--playground"])
assert_file "Gemfile" do |contents|
assert_includes contents, "graphql_playground-rails"
end
expected_playground_route = %|
if Rails.env.development?
mount GraphqlPlayground::Rails::Engine, at: "/playground", graphql_path: "/graphql"
end
|
assert_file "config/routes.rb" do |contents|
assert_includes contents, expected_playground_route
end
assert_file "config/application.rb" do |contents|
assert_includes contents, "
config.active_record.query_log_tags = [ :application, :controller, :action, :job ,
# GraphQL-Ruby query log tags:
current_graphql_operation: -> { GraphQL::Current.operation_name },
current_graphql_field: -> { GraphQL::Current.field&.path },
current_dataloader_source: -> { GraphQL::Current.dataloader_source_class },
]
"
end
end
EXPECTED_GRAPHQLS_CONTROLLER = <<-'RUBY'
# frozen_string_literal: true
class GraphqlController < ApplicationController
# If accessing from outside this domain, nullify the session
# This allows for outside API access while preventing CSRF attacks,
# but you'll have to authenticate your user separately
# protect_from_forgery with: :null_session
def execute
variables = prepare_variables(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
# current_user: current_user,
}
result = DummySchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue StandardError => e
raise e unless Rails.env.development?
handle_error_in_development(e)
end
private
# Handle variables in form data, JSON body, or a blank value
def prepare_variables(variables_param)
case variables_param
when String
if variables_param.present?
JSON.parse(variables_param) || {}
else
{}
end
when Hash
variables_param
when ActionController::Parameters
variables_param.to_unsafe_hash # GraphQL-Ruby will validate name and type of incoming variables.
when nil
{}
else
raise ArgumentError, "Unexpected parameter: #{variables_param}"
end
end
def handle_error_in_development(e)
logger.error e.message
logger.error e.backtrace.join("\n")
render json: { errors: [{ message: e.message, backtrace: e.backtrace }], data: {} }, status: 500
end
end
RUBY
EXPECTED_RELAY_BATCH_SCHEMA = '# frozen_string_literal: true
class DummySchema < GraphQL::Schema
mutation(Types::MutationType)
query(Types::QueryType)
# GraphQL::Batch setup:
use GraphQL::Batch
# GraphQL-Ruby calls this when something goes wrong while running a query:
def self.type_error(err, context)
# if err.is_a?(GraphQL::InvalidNullError)
# # report to your bug tracker here
# return nil
# end
super
end
# Union and Interface Resolution
def self.resolve_type(abstract_type, obj, ctx)
# TODO: Implement this method
# to return the correct GraphQL object type for `obj`
raise(GraphQL::RequiredImplementationMissingError)
end
# Limit the size of incoming queries:
max_query_string_tokens(5000)
# Stop validating when it encounters this many errors:
validate_max_errors(100)
# Relay-style Object Identification:
# Return a string UUID for `object`
def self.id_from_object(object, type_definition, query_ctx)
# For example, use Rails\' GlobalID library (https://github.com/rails/globalid):
object.to_gid_param
end
# Given a string UUID, find the object
def self.object_from_id(global_id, query_ctx)
# For example, use Rails\' GlobalID library (https://github.com/rails/globalid):
GlobalID.find(global_id)
end
end
'
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/rails/generators/graphql/enum_generator_spec.rb | spec/integration/rails/generators/graphql/enum_generator_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "generators/graphql/enum_generator"
class GraphQLGeneratorsEnumGeneratorTest < BaseGeneratorTest
tests Graphql::Generators::EnumGenerator
test "it generate enums with values" do
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class FamilyType < Types::BaseEnum
description "Family enum"
value "NIGHTSHADE"
value "BRASSICA", value: Family::COLE
value "UMBELLIFER", value: :umbellifer
value "LEGUME", value: "bean & friends"
value "CURCURBITS", value: 5
end
end
RUBY
run_generator(["Family",
"NIGHTSHADE",
"BRASSICA:Family::COLE",
"UMBELLIFER::umbellifer",
'LEGUME:"bean & friends"',
"CURCURBITS:5"
])
assert_file "app/graphql/types/family_type.rb", expected_content
end
test "it generates namespaced enums with values" do
expected_content = <<-RUBY
# frozen_string_literal: true
module Types
class Enums::FamilyType < Types::BaseEnum
description "Family enum"
value "NIGHTSHADE"
value "BRASSICA", value: Family::COLE
value "UMBELLIFER", value: :umbellifer
value "LEGUME", value: "bean & friends"
value "CURCURBITS", value: 5
end
end
RUBY
run_generator(["Family",
"NIGHTSHADE",
"BRASSICA:Family::COLE",
"UMBELLIFER::umbellifer",
'LEGUME:"bean & friends"',
"CURCURBITS:5",
"--namespaced-types"
])
assert_file "app/graphql/types/enums/family_type.rb", expected_content
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/mongoid/graphql/relay/mongo_relation_connection_spec.rb | spec/integration/mongoid/graphql/relay/mongo_relation_connection_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe "GraphQL::Relay::MongoRelationConnection" do
def get_names(result)
ships = result["data"]["federation"]["bases"]["edges"]
ships.map { |e| e["node"]["name"] }
end
def get_residents(ship)
ship["residents"]["edges"].map { |e| e["node"]["name"] }
end
def get_ships_residents(result)
ships = result["data"]["federation"]["bases"]["edges"]
Hash[ships.map { |e| [e["node"]["name"], get_residents(e["node"])] }]
end
def get_page_info(result)
result["data"]["federation"]["bases"]["pageInfo"]
end
def get_first_cursor(result)
result["data"]["federation"]["bases"]["edges"].first["cursor"]
end
def get_last_cursor(result)
result["data"]["federation"]["bases"]["edges"].last["cursor"]
end
describe "results" do
let(:query_string) {%|
query getShips($first: Int, $after: String, $last: Int, $before: String, $nameIncludes: String){
federation {
bases(first: $first, after: $after, last: $last, before: $before, nameIncludes: $nameIncludes) {
... basesConnection
}
}
}
fragment basesConnection on BasesConnectionWithTotalCount {
totalCount,
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it 'limits the result' do
result = star_trek_query(query_string, { "first" => 2 })
assert_equal(2, get_names(result).length)
assert_equal(true, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mg", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mg", get_last_cursor(result))
result = star_trek_query(query_string, { "first" => 3 })
assert_equal(3, get_names(result).length)
assert_equal(false, get_page_info(result)["hasNextPage"])
assert_equal(false, get_page_info(result)["hasPreviousPage"])
assert_equal("MQ", get_page_info(result)["startCursor"])
assert_equal("Mw", get_page_info(result)["endCursor"])
assert_equal("MQ", get_first_cursor(result))
assert_equal("Mw", get_last_cursor(result))
end
it 'provides custom fields on the connection type' do
result = star_trek_query(query_string, { "first" => 2 })
assert_equal(
StarTrek::Base.where(faction_id: 1).count,
result["data"]["federation"]["bases"]["totalCount"]
)
end
it "provides bidirectional_pagination by default" do
result = star_trek_query(query_string, { "first" => 1 })
last_cursor = get_last_cursor(result)
result = star_trek_query(query_string, { "first" => 1, "after" => last_cursor })
assert_equal true, get_page_info(result)["hasNextPage"]
assert_equal true, get_page_info(result)["hasPreviousPage"]
last_cursor = get_last_cursor(result)
result = star_trek_query(query_string, { "last" => 1, "before" => last_cursor })
assert_equal true, get_page_info(result)["hasNextPage"]
assert_equal false, get_page_info(result)["hasPreviousPage"]
result = star_trek_query(query_string, { "first" => 100 })
last_cursor = get_last_cursor(result)
result = star_trek_query(query_string, { "last" => 1, "before" => last_cursor })
assert_equal true, get_page_info(result)["hasNextPage"]
assert_equal true, get_page_info(result)["hasPreviousPage"]
end
it 'slices the result' do
result = star_trek_query(query_string, { "first" => 2 })
assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))
# After the last result, find the next 2:
last_cursor = get_last_cursor(result)
result = star_trek_query(query_string, { "after" => last_cursor, "first" => 2 })
assert_equal(["Deep Space Nine"], get_names(result))
last_cursor = get_last_cursor(result)
result = star_trek_query(query_string, { "before" => last_cursor, "last" => 1 })
assert_equal(["Regula I"], get_names(result))
result = star_trek_query(query_string, { "before" => last_cursor, "last" => 2 })
assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))
result = star_trek_query(query_string, { "before" => last_cursor, "last" => 10 })
assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))
result = star_trek_query(query_string, { "last" => 2 })
assert_equal(["Regula I", "Deep Space Nine"], get_names(result))
result = star_trek_query(query_string, { "last" => 10 })
assert_equal(["Deep Space Station K-7", "Regula I", "Deep Space Nine"], get_names(result))
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])
end
it 'works with before and after specified together' do
result = star_trek_query(query_string, { "first" => 2 })
assert_equal(["Deep Space Station K-7", "Regula I"], get_names(result))
first_cursor = get_last_cursor(result)
# There is no records between before and after if they point to the same cursor
result = star_trek_query(query_string, { "before" => first_cursor, "after" => first_cursor, "last" => 2 })
assert_equal([], get_names(result))
result = star_trek_query(query_string, { "after" => first_cursor, "first" => 2 })
assert_equal(["Deep Space Nine"], get_names(result))
second_cursor = get_last_cursor(result)
result = star_trek_query(query_string, { "after" => first_cursor, "before" => second_cursor, "first" => 3 })
assert_equal([], get_names(result)) # TODO: test fails. fixme
end
it 'handles cursors above the bounds of the array' do
overreaching_cursor = Base64.strict_encode64("100")
result = star_trek_query(query_string, { "after" => overreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it 'handles cursors below the bounds of the array' do
underreaching_cursor = Base64.strict_encode64("1")
result = star_trek_query(query_string, { "before" => underreaching_cursor, "first" => 2 })
assert_equal([], get_names(result))
end
it 'handles grouped connections with only last argument' do
grouped_conn_query = <<-GRAPHQL
query {
newestBasesGroupedByFaction(last: 2) {
edges {
node {
name
}
}
}
}
GRAPHQL
result = star_trek_query(grouped_conn_query)
names = result['data']['newestBasesGroupedByFaction']['edges'].map { |edge| edge['node']['name'] }
assert_equal(['Ganalda Space Station', 'Deep Space Nine'], names)
end
it "applies custom arguments" do
result = star_trek_query(query_string, { "first" => 1, "nameIncludes" => "eep" })
assert_equal(["Deep Space Station K-7"], get_names(result))
after = get_last_cursor(result)
result = star_trek_query(query_string, { "first" => 2, "nameIncludes" => "eep", "after" => after })
assert_equal(["Deep Space Nine"], get_names(result))
before = get_last_cursor(result)
result = star_trek_query(query_string, { "last" => 1, "nameIncludes" => "eep", "before" => before })
assert_equal(["Deep Space Station K-7"], get_names(result))
end
it 'works without first/last/after/before' do
result = star_trek_query(query_string)
assert_equal(3, result["data"]["federation"]["bases"]["edges"].length)
end
describe "applying max_page_size" do
let(:query_string) {%|
query getBases($first: Int, $after: String, $last: Int, $before: String){
federation {
bases: basesWithMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
... basesConnection
}
}
}
fragment basesConnection on BaseConnection {
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it "applies to queries by `first`" do
result = star_trek_query(query_string, { "first" => 100 })
assert_equal(2, result["data"]["federation"]["bases"]["edges"].size)
assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_trek_query(query_string)
assert_equal(2, result["data"]["federation"]["bases"]["edges"].size)
assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
second_to_last_two_names = ["Firebase P'ok", "Ganalda Space Station"]
first_and_second_names = ["Deep Space Station K-7", "Regula I"]
last_cursor = "Ng=="
result = star_trek_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(second_to_last_two_names, get_names(result))
assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_trek_query(query_string, { "before" => last_cursor })
assert_equal(first_and_second_names, get_names(result))
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
third_cursor = "Mw"
result = star_trek_query(query_string, { "last" => 100, "before" => third_cursor })
assert_equal(first_and_second_names, get_names(result))
result = star_trek_query(query_string, { "before" => third_cursor })
assert_equal(first_and_second_names, get_names(result))
end
end
describe "applying default_max_page_size" do
let(:query_string) {%|
query getBases($first: Int, $after: String, $last: Int, $before: String){
federation {
bases: basesWithDefaultMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
... basesConnection
}
}
}
fragment basesConnection on BaseConnection {
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it "applies to queries by `first`" do
result = star_trek_query(query_string, { "first" => 100 })
assert_equal(3, result["data"]["federation"]["bases"]["edges"].size)
assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_trek_query(query_string)
assert_equal(3, result["data"]["federation"]["bases"]["edges"].size)
assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
second_to_last_three_names = ["Deep Space Nine", "Firebase P'ok", "Ganalda Space Station"]
first_second_and_third_names = ["Deep Space Station K-7", "Regula I", "Deep Space Nine"]
last_cursor = "Ng=="
result = star_trek_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(second_to_last_three_names, get_names(result))
assert_equal(true, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_trek_query(query_string, { "before" => last_cursor })
assert_equal(first_second_and_third_names, get_names(result))
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
fourth_cursor = "NA=="
result = star_trek_query(query_string, { "last" => 100, "before" => fourth_cursor })
assert_equal(first_second_and_third_names, get_names(result))
result = star_trek_query(query_string, { "before" => fourth_cursor })
assert_equal(first_second_and_third_names, get_names(result))
end
end
end
describe "applying a max_page_size bigger than the results" do
let(:query_string) {%|
query getBases($first: Int, $after: String, $last: Int, $before: String){
federation {
bases: basesWithLargeMaxLimitRelation(first: $first, after: $after, last: $last, before: $before) {
... basesConnection
}
}
}
fragment basesConnection on BaseConnection {
edges {
cursor
node {
name
}
},
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
|}
it "applies to queries by `first`" do
result = star_trek_query(query_string, { "first" => 100 })
assert_equal(6, result["data"]["federation"]["bases"]["edges"].size)
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"])
# Max page size is applied _without_ `first`, also
result = star_trek_query(query_string)
assert_equal(6, result["data"]["federation"]["bases"]["edges"].size)
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasNextPage"], "hasNextPage is false when first is not specified")
end
it "applies to queries by `last`" do
all_names = ["Deep Space Station K-7", "Regula I", "Deep Space Nine", "Firebase P'ok", "Ganalda Space Station", "Rh'Ihho Station"]
last_cursor = "Ng=="
result = star_trek_query(query_string, { "last" => 100, "before" => last_cursor })
assert_equal(all_names[0..4], get_names(result))
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_trek_query(query_string, { "last" => 100 })
assert_equal(all_names, get_names(result))
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"])
result = star_trek_query(query_string, { "before" => last_cursor })
assert_equal(all_names[0..4], get_names(result))
assert_equal(false, result["data"]["federation"]["bases"]["pageInfo"]["hasPreviousPage"], "hasPreviousPage is false when last is not specified")
fourth_cursor = "NA=="
result = star_trek_query(query_string, { "last" => 100, "before" => fourth_cursor })
assert_equal(all_names[0..2], get_names(result))
result = star_trek_query(query_string, { "before" => fourth_cursor })
assert_equal(all_names[0..2], get_names(result))
end
end
describe "without a block" do
let(:query_string) {%|
{
federation {
basesClone(first: 10) {
edges {
node {
name
}
}
}
}
}|}
it "uses default resolve" do
result = star_trek_query(query_string)
bases = result["data"]["federation"]["basesClone"]["edges"]
assert_equal(3, bases.length)
end
end
describe "custom ordering" do
let(:query_string) {%|
query getBases {
federation {
basesByName(first: 30) { ... basesFields }
bases(first: 30) { ... basesFields2 }
}
}
fragment basesFields on BaseConnection {
edges {
node {
name
}
}
}
fragment basesFields2 on BasesConnectionWithTotalCount {
edges {
node {
name
}
}
}
|}
def get_names(result, field_name)
bases = result["data"]["federation"][field_name]["edges"]
bases.map { |b| b["node"]["name"] }
end
it "applies the default value" do
result = star_trek_query(query_string)
bases_by_id = ["Deep Space Station K-7", "Regula I", "Deep Space Nine"]
bases_by_name = ["Deep Space Nine", "Deep Space Station K-7", "Regula I"]
assert_equal(bases_by_id, get_names(result, "bases"))
assert_equal(bases_by_name, get_names(result, "basesByName"))
end
end
describe "relations" do
let(:query_string) {%|
query getShips {
federation {
bases {
... basesConnection
}
}
}
fragment basesConnection on BasesConnectionWithTotalCount {
edges {
cursor
node {
name
residents {
edges {
node {
name
}
}
}
}
}
}
|}
it "Mongoid::Association::Referenced::HasMany::Targets::Enumerable" do
result = star_trek_query(query_string)
assert_equal get_ships_residents(result), {
"Deep Space Station K-7" => [
"Shir th'Talias",
"Lurry",
"Mackenzie Calhoun"
],
"Regula I" => [
"V. Madison",
"D. March",
"C. Marcus"
],
"Deep Space Nine" => []
}
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/integration/mongoid/star_trek/data.rb | spec/integration/mongoid/star_trek/data.rb | # frozen_string_literal: true
require 'ostruct'
require 'support/mongoid_setup'
module StarTrek
names = [
'USS Enterprise',
'USS Excelsior',
'USS Reliant',
'IKS Koraga',
'IKS Kronos One',
'IRW Khazara',
'IRW Praetus',
]
# Set up "Bases" in MongoDB
class Base
include Mongoid::Document
field :name, type: String
field :sector, type: String
field :faction_id, type: Integer
has_many :residents, class_name: 'StarTrek::Resident', inverse_of: :base
end
class Resident
include Mongoid::Document
field :name, type: String
belongs_to :base, class_name: 'StarTrek::Base'
end
Base.collection.drop
dsk7 = Base.create!(name: "Deep Space Station K-7", sector: "Mempa", faction_id: 1)
dsk7.residents.create!(name: "Shir th'Talias")
dsk7.residents.create!(name: "Lurry")
dsk7.residents.create!(name: "Mackenzie Calhoun")
r1 = Base.create!(name: "Regula I", sector: "Mutara", faction_id: 1)
r1.residents.create!(name: "V. Madison")
r1.residents.create!(name: "D. March")
r1.residents.create!(name: "C. Marcus")
Base.create!(name: "Deep Space Nine", sector: "Bajoran", faction_id: 1)
Base.create!(name: "Firebase P'ok", sector: nil, faction_id: 2)
Base.create!(name: "Ganalda Space Station", sector: "Archanis", faction_id: 2)
Base.create!(name: "Rh'Ihho Station", sector: "Rator", faction_id: 3)
class FactionRecord
attr_reader :id, :name, :ships, :bases, :bases_clone
def initialize(id:, name:, ships:, bases:, bases_clone:)
@id = id
@name = name
@ships = ships
@bases = bases
@bases_clone = bases_clone
end
end
federation = FactionRecord.new(
id: '1',
name: 'United Federation of Planets',
ships: ['1', '2', '3'],
bases: Base.where(faction_id: 1),
bases_clone: Base.where(faction_id: 1),
)
klingon = FactionRecord.new(
id: '2',
name: 'Klingon Empire',
ships: ['4', '5'],
bases: Base.where(faction_id: 2),
bases_clone: Base.where(faction_id: 2),
)
romulan = FactionRecord.new(
id: '2',
name: 'Romulan Star Empire',
ships: ['6', '7'],
bases: Base.where(faction_id: 3),
bases_clone: Base.where(faction_id: 3),
)
DATA = {
"Faction" => {
"1" => federation,
"2" => klingon,
"3" => romulan,
},
"Ship" => names.each_with_index.reduce({}) do |memo, (name, idx)|
id = (idx + 1).to_s
memo[id] = OpenStruct.new(name: name, id: id)
memo
end,
"Base" => Hash.new { |h, k| h[k] = Base.find(k) }
}
def DATA.create_ship(name, faction_id)
new_id = (self["Ship"].keys.map(&:to_i).max + 1).to_s
new_ship = OpenStruct.new(id: new_id, name: name)
self["Ship"][new_id] = new_ship
self["Faction"][faction_id].ships << new_id
new_ship
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/integration/mongoid/star_trek/schema.rb | spec/integration/mongoid/star_trek/schema.rb | # frozen_string_literal: true
module StarTrek
# Adapted from graphql-relay-js
# https://github.com/graphql/graphql-relay-js/blob/master/src/__tests__/StarTrekSchema.js
class Ship < GraphQL::Schema::Object
implements GraphQL::Types::Relay::Node
global_id_field :id
field :name, String
# Test cyclical connection types:
field :ships, Ship.connection_type, null: false
end
class ResidentType < GraphQL::Schema::Object
global_id_field :id
field :name, String
end
class BaseType < GraphQL::Schema::Object
graphql_name "Base"
implements GraphQL::Types::Relay::Node
global_id_field :id
field :name, String, null: false
def name
LazyWrapper.new {
if object.id.nil?
raise GraphQL::ExecutionError, "Boom!"
else
object.name
end
}
end
field :sector, String
field :residents, ResidentType.connection_type
end
class BaseConnectionWithTotalCountType < GraphQL::Types::Relay::BaseConnection
graphql_name "BasesConnectionWithTotalCount"
edge_type(BaseType.edge_type)
field :total_count, Integer
def total_count
object.items.count
end
end
class CustomBaseEdge < GraphQL::Pagination::Connection::Edge
def upcased_name
node.name.upcase
end
def upcased_parent_name
parent.name.upcase
end
end
class CustomBaseEdgeType < GraphQL::Types::Relay::BaseEdge
node_type(BaseType)
field :upcased_name, String
field :upcased_parent_name, String
field :edge_class_name, String
def edge_class_name
object.class.name
end
end
class CustomEdgeBaseConnectionType < GraphQL::Types::Relay::BaseConnection
edge_type(CustomBaseEdgeType, edge_class: CustomBaseEdge)
field :total_count_times_100, Integer
def total_count_times_100
obj.items.to_a.count * 100
end
field :field_name, String
def field_name
object.field.name
end
end
class ShipsWithMaxPageSize < GraphQL::Schema::Resolver
argument :name_includes, String, required: false
type Ship.connection_type, null: true
def resolve(name_includes: nil)
all_ships = object.ships.map { |ship_id| StarTrek::DATA["Ship"][ship_id] }
if name_includes
all_ships = all_ships.select { |ship| ship.name.include?(name_includes)}
end
all_ships
end
end
class ShipConnectionWithParentType < GraphQL::Types::Relay::BaseConnection
edge_type(Ship.edge_type)
graphql_name "ShipConnectionWithParent"
field :parent_class_name, String, null: false
def parent_class_name
object.parent.class.name
end
end
class Faction < GraphQL::Schema::Object
implements GraphQL::Types::Relay::Node
field :name, String
field :ships, ShipConnectionWithParentType, connection: true, max_page_size: 1000, null: true do
argument :name_includes, String, required: false
end
def ships(name_includes: nil)
all_ships = object.ships.map {|ship_id| StarTrek::DATA["Ship"][ship_id] }
if name_includes
case name_includes
when "error"
all_ships = GraphQL::ExecutionError.new("error from within connection")
when "raisedError"
raise GraphQL::ExecutionError.new("error raised from within connection")
when "lazyError"
all_ships = LazyWrapper.new { GraphQL::ExecutionError.new("lazy error from within connection") }
when "lazyRaisedError"
all_ships = LazyWrapper.new { raise GraphQL::ExecutionError.new("lazy raised error from within connection") }
when "null"
all_ships = nil
when "lazyObject"
prev_all_ships = all_ships
all_ships = LazyWrapper.new { prev_all_ships }
else
all_ships = all_ships.select { |ship| ship.name.include?(name_includes)}
end
end
all_ships
end
field :shipsWithMaxPageSize, "Ships with max page size", max_page_size: 2, resolver: ShipsWithMaxPageSize
field :bases, BaseConnectionWithTotalCountType, connection: true do
argument :name_includes, String, required: false
end
def bases(name_includes: nil)
all_bases = object.bases
if name_includes
all_bases = all_bases.where(name: Regexp.new(name_includes))
end
all_bases
end
field :bases_clone, BaseType.connection_type
field :bases_by_name, BaseType.connection_type do
argument :order, String, default_value: "name", required: false
end
def bases_by_name(order: nil)
if order.present?
@object.bases.order_by(name: order)
else
@object.bases
end
end
def all_bases
Base.all
end
def all_bases_array
all_bases.to_a
end
field :basesWithMaxLimitRelation, BaseType.connection_type, max_page_size: 2, resolver_method: :all_bases
field :basesWithMaxLimitArray, BaseType.connection_type, max_page_size: 2, resolver_method: :all_bases_array
field :basesWithDefaultMaxLimitRelation, BaseType.connection_type, resolver_method: :all_bases
field :basesWithDefaultMaxLimitArray, BaseType.connection_type, resolver_method: :all_bases_array
field :basesWithLargeMaxLimitRelation, BaseType.connection_type, max_page_size: 1000, resolver_method: :all_bases
field :bases_with_custom_edge, CustomEdgeBaseConnectionType, connection: true
def bases_with_custom_edge
LazyNodesWrapper.new(object.bases)
end
end
class IntroduceShipMutation < GraphQL::Schema::RelayClassicMutation
description "Add a ship to this faction"
# Nested under `input` in the query:
argument :ship_name, String, required: false
argument :faction_id, ID
# Result may have access to these fields:
field :ship_edge, Ship.edge_type
field :faction, Faction
field :aliased_faction, Faction, hash_key: :aliased_faction, null: true
def resolve(ship_name: nil, faction_id:)
if ship_name == 'USS Voyager'
GraphQL::ExecutionError.new("Sorry, USS Voyager ship is reserved")
elsif ship_name == 'IKS Korinar'
raise GraphQL::ExecutionError.new("🔥")
elsif ship_name == 'Scimitar'
LazyWrapper.new { raise GraphQL::ExecutionError.new("💥")}
end
end
end
# GraphQL-Batch knockoff
class LazyLoader
def self.defer(ctx, model, id)
ids = ctx.namespace(:loading)[model] ||= []
ids << id
self.new(model: model, id: id, context: ctx)
end
def initialize(model:, id:, context:)
@model = model
@id = id
@context = context
end
def value
loaded = @context.namespace(:loaded)[@model] ||= {}
if loaded.empty?
ids = @context.namespace(:loading)[@model]
# Example custom tracing
@context.trace("lazy_loader", { ids: ids, model: @model}) do
records = @model.where(id: ids)
records.each do |record|
loaded[record.id.to_s] = record
end
end
end
loaded[@id]
end
end
class LazyWrapper
def initialize(value = nil, &block)
if block_given?
@lazy_value = block
else
@value = value
end
end
def value
@resolved_value = @value || @lazy_value.call
end
end
LazyNodesWrapper = Struct.new(:relation)
class LazyNodesRelationConnection < GraphQL::Pagination::MongoidRelationConnection
def initialize(wrapper, *args)
super(wrapper.relation, *args)
end
def edge_nodes
LazyWrapper.new { super }
end
end
class QueryType < GraphQL::Schema::Object
graphql_name "Query"
field :federation, Faction
def federation
StarTrek::DATA["Faction"]["1"]
end
field :klingons, Faction
def klingons
StarTrek::DATA["Faction"]["2"]
end
field :romulans, Faction
def romulans
StarTrek::DATA["Faction"]["3"]
end
field :largest_base, BaseType
def largest_base
Base.find(3)
end
field :newest_bases_grouped_by_faction, BaseType.connection_type
def newest_bases_grouped_by_faction
agg = Base.collection.aggregate([{
"$group" => {
"_id" => "$faction_id",
"baseId" => { "$max" => "$_id" }
}
}])
Base.
in(id: agg.map { |doc| doc['baseId'] }).
order_by(faction_id: -1)
end
field :bases_with_null_name, BaseType.connection_type, null: false
def bases_with_null_name
[OpenStruct.new(id: nil)]
end
include GraphQL::Types::Relay::HasNodeField
field :node_with_custom_resolver, GraphQL::Types::Relay::Node do
argument :id, ID
end
def node_with_custom_resolver(id:)
StarTrek::DATA["Faction"]["1"]
end
include GraphQL::Types::Relay::HasNodesField
field :nodes_with_custom_resolver, [GraphQL::Types::Relay::Node, null: true] do
argument :ids, [ID]
end
def nodes_with_custom_resolver(ids:)
[StarTrek::DATA["Faction"]["1"], StarTrek::DATA["Faction"]["2"]]
end
field :batched_base, BaseType do
argument :id, ID
end
def batched_base(id:)
LazyLoader.defer(@context, Base, id)
end
end
class MutationType < GraphQL::Schema::Object
graphql_name "Mutation"
field :introduceShip, mutation: IntroduceShipMutation
end
class Schema < GraphQL::Schema
query(QueryType)
mutation(MutationType)
default_max_page_size 3
def self.resolve_type(type, object, ctx)
if object == :test_error
:not_a_type
elsif object.is_a?(Base)
BaseType
elsif DATA["Faction"].values.include?(object)
Faction
elsif DATA["Ship"].values.include?(object)
Ship
else
nil
end
end
connections.add(LazyNodesWrapper, LazyNodesRelationConnection)
def self.object_from_id(node_id, ctx)
type_name, id = GraphQL::Schema::UniqueWithinType.decode(node_id)
StarTrek::DATA[type_name][id]
end
def self.id_from_object(object, type, ctx)
GraphQL::Schema::UniqueWithinType.encode(type.graphql_name, object.id)
end
lazy_resolve(LazyWrapper, :value)
lazy_resolve(LazyLoader, :value)
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/lazy_module/lazy_class.rb | spec/fixtures/lazy_module/lazy_class.rb | # frozen_string_literal: true
module LazyModule
module LazyClass
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/root_types.rb | spec/fixtures/cop/root_types.rb | class MyAppSchema < GraphQL::Schema
query Types::Query
mutation Types::Mutation
subscription Types::Subscription
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/field_type.rb | spec/fixtures/cop/field_type.rb | class Types::Query
field :current_account, Types::Account, null: false, description: "The account of the current viewer"
field :find_account, Types::Account do
argument :id, ID
end
# Don't modify these:
field :current_time, String, description: "The current time in the viewer's timezone"
field :current_time, Integer, description: "The current time in the viewer's timezone"
field :current_time, Int, description: "The current time in the viewer's timezone"
field :current_time, Float, description: "The current time in the viewer's timezone"
field :current_time, Boolean, description: "The current time in the viewer's timezone"
field(:all_accounts, [Types::Account, null: false]) {
argument :active, Boolean, default_value: false
}
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/root_types_corrected.rb | spec/fixtures/cop/root_types_corrected.rb | class MyAppSchema < GraphQL::Schema
query { Types::Query }
mutation { Types::Mutation }
subscription { Types::Subscription }
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/null_true.rb | spec/fixtures/cop/null_true.rb | class Types::Something < Types::BaseObject
field :name, String, null: true
field :other_name, String,
null: true,
description: "Here's a description"
field :described, [String, null: true], null: true, description: "Something"
field :ok_field, String
field :also_ok_field, String, null: false
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/required_true.rb | spec/fixtures/cop/required_true.rb | class Types::Something < Types::BaseObject
field :name, String do
argument :id_1, ID, required: true
argument :id_2,
ID,
required: true,
description: "Described"
argument :id_3, ID, other_config: { something: false, required: true }, required: true, description: "Something"
argument :id_4, ID, required: false
argument :id_5, ID
end
field :name2, String do |f|
f.argument(:id_1, ID, required: true)
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/small_field_type.rb | spec/fixtures/cop/small_field_type.rb | class Types::Admin::FooType < Types::FooType
field :bar, Types::BarType
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/null_true_corrected.rb | spec/fixtures/cop/null_true_corrected.rb | class Types::Something < Types::BaseObject
field :name, String
field :other_name, String,
description: "Here's a description"
field :described, [String, null: true], description: "Something"
field :ok_field, String
field :also_ok_field, String, null: false
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/field_type_array_corrected.rb | spec/fixtures/cop/field_type_array_corrected.rb | class Types::FooType < Types::BaseObject
field :other, [String]
field :bar, null: false do
type [Thing]
argument :baz, String
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/field_type_interface.rb | spec/fixtures/cop/field_type_interface.rb | module Types::FooType
include Types::BaseInterface
field :thing, Thing
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/field_type_interface_corrected.rb | spec/fixtures/cop/field_type_interface_corrected.rb | module Types::FooType
include Types::BaseInterface
field :thing do
type Thing
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/field_type_corrected.rb | spec/fixtures/cop/field_type_corrected.rb | class Types::Query
field :current_account, null: false, description: "The account of the current viewer" do
type Types::Account
end
field :find_account do
type Types::Account
argument :id, ID
end
# Don't modify these:
field :current_time, String, description: "The current time in the viewer's timezone"
field :current_time, Integer, description: "The current time in the viewer's timezone"
field :current_time, Int, description: "The current time in the viewer's timezone"
field :current_time, Float, description: "The current time in the viewer's timezone"
field :current_time, Boolean, description: "The current time in the viewer's timezone"
field(:all_accounts) {
type [Types::Account, null: false]
argument :active, Boolean, default_value: false
}
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/required_true_corrected.rb | spec/fixtures/cop/required_true_corrected.rb | class Types::Something < Types::BaseObject
field :name, String do
argument :id_1, ID
argument :id_2,
ID,
description: "Described"
argument :id_3, ID, other_config: { something: false, required: true }, description: "Something"
argument :id_4, ID, required: false
argument :id_5, ID
end
field :name2, String do |f|
f.argument(:id_1, ID)
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/cop/field_type_array.rb | spec/fixtures/cop/field_type_array.rb | class Types::FooType < Types::BaseObject
field :other, [String]
field :bar, [Thing], null: false do
argument :baz, String
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/eager_module/eager_class.rb | spec/fixtures/eager_module/eager_class.rb | # frozen_string_literal: true
module EagerModule
module EagerClass
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/eager_module/nested_eager_module.rb | spec/fixtures/eager_module/nested_eager_module.rb | # frozen_string_literal: true
module EagerModule
module NestedEagerModule
extend GraphQL::Autoload
autoload(:NestedEagerClass, "fixtures/eager_module/nested_eager_module/nested_eager_class")
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/eager_module/other_eager_class.rb | spec/fixtures/eager_module/other_eager_class.rb | # frozen_string_literal: true
module EagerModule
module OtherEagerClass
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/fixtures/eager_module/nested_eager_module/nested_eager_class.rb | spec/fixtures/eager_module/nested_eager_module/nested_eager_class.rb | # frozen_string_literal: true
module EagerModule
module NestedEagerModule
class NestedEagerClass
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/non_null_type_spec.rb | spec/graphql/non_null_type_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::NonNullType" do
describe "when a non-null field returns null" do
it "nulls out the parent selection" do
query_string = %|{ cow { name cantBeNullButIs } }|
result = Dummy::Schema.execute(query_string)
assert_equal({"cow" => nil }, result["data"])
assert_equal([{
"message" => "Cannot return null for non-nullable field Cow.cantBeNullButIs",
"path" => ["cow", "cantBeNullButIs"],
"locations" => [{"line" => 1, "column" => 14}],
}], result["errors"])
end
it "propagates the null up to the next nullable field" do
query_string = %|
{
nn1: deepNonNull {
nni1: nonNullInt(returning: 1)
nn2: deepNonNull {
nni2: nonNullInt(returning: 2)
nn3: deepNonNull {
nni3: nonNullInt
}
}
}
}
|
result = Dummy::Schema.execute(query_string)
assert_nil(result["data"])
assert_equal([{
"message" => "Cannot return null for non-nullable field DeepNonNull.nonNullInt",
"path" => ["nn1", "nn2", "nn3", "nni3"],
"locations" => [{"line" => 8, "column" => 15}],
}], result["errors"])
end
describe "when type_error is configured to raise an error" do
it "crashes query execution" do
raise_schema = Class.new(Dummy::Schema) {
def self.type_error(type_err, ctx)
raise type_err
end
}
query_string = %|{ cow { name cantBeNullButIs } }|
err = assert_raises(GraphQL::InvalidNullError) { raise_schema.execute(query_string) }
assert_equal("Cannot return null for non-nullable field Cow.cantBeNullButIs", err.message)
assert_equal("Cow", err.parent_type.graphql_name)
assert_equal("cantBeNullButIs", err.field.name)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/dataloader_spec.rb | spec/graphql/dataloader_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "fiber"
if defined?(Console) && defined?(Async)
Console.logger.disable(Async::Task)
end
describe GraphQL::Dataloader do
class BatchedCallsCounter
def initialize
@count = 0
end
def increment
@count += 1
end
attr_reader :count
end
class FiberSchema < GraphQL::Schema
module Database
extend self
DATA = {}
[
{ id: "1", name: "Wheat", type: "Grain" },
{ id: "2", name: "Corn", type: "Grain" },
{ id: "3", name: "Butter", type: "Dairy" },
{ id: "4", name: "Baking Soda", type: "LeaveningAgent" },
{ id: "5", name: "Cornbread", type: "Recipe", ingredient_ids: ["1", "2", "3", "4"] },
{ id: "6", name: "Grits", type: "Recipe", ingredient_ids: ["2", "3", "7"] },
{ id: "7", name: "Cheese", type: "Dairy" },
].each { |d| DATA[d[:id]] = d }
def log
@log ||= []
end
def mget(ids)
log << [:mget, ids.sort]
ids.map { |id| DATA[id] }
end
def find_by(attribute, values)
log << [:find_by, attribute, values.sort]
values.map { |v| DATA.each_value.find { |dv| dv[attribute] == v } }
end
end
class DataObject < GraphQL::Dataloader::Source
def initialize(column = :id)
@column = column
end
def fetch(keys)
if @column == :id
Database.mget(keys)
else
Database.find_by(@column, keys)
end
end
end
class ToString < GraphQL::Dataloader::Source
def fetch(keys)
keys.map(&:to_s)
end
end
class NestedDataObject < GraphQL::Dataloader::Source
def fetch(ids)
@dataloader.with(DataObject).load_all(ids)
end
end
class SlowDataObject < GraphQL::Dataloader::Source
def initialize(batch_key)
# This is just so that I can force different instances in test
@batch_key = batch_key
end
def fetch(keys)
t = Thread.new {
sleep 0.5
Database.mget(keys)
}
dataloader.yield
t.value
end
end
class CustomBatchKeySource < GraphQL::Dataloader::Source
def initialize(batch_key)
@batch_key = batch_key
end
def self.batch_key_for(batch_key)
Database.log << [:batch_key_for, batch_key]
# Ignore it altogether
:all_the_same
end
def fetch(keys)
Database.mget(keys)
end
end
class KeywordArgumentSource < GraphQL::Dataloader::Source
def initialize(column:)
@column = column
end
def fetch(keys)
if @column == :id
Database.mget(keys)
else
Database.find_by(@column, keys)
end
end
end
class AuthorizedSource < GraphQL::Dataloader::Source
def initialize(counter)
@counter = counter
end
def fetch(recipes)
@counter&.increment
recipes.map { true }
end
end
class ErrorSource < GraphQL::Dataloader::Source
def fetch(ids)
raise GraphQL::Error, "Source error on: #{ids.inspect}"
end
end
module Ingredient
include GraphQL::Schema::Interface
field :name, String, null: false
field :id, ID, null: false
field :name_by_scoped_context, String
def name_by_scoped_context
context[:ingredient_name]
end
end
class Grain < GraphQL::Schema::Object
implements Ingredient
end
class LeaveningAgent < GraphQL::Schema::Object
implements Ingredient
end
class Dairy < GraphQL::Schema::Object
implements Ingredient
end
class Recipe < GraphQL::Schema::Object
def self.authorized?(obj, ctx)
ctx.dataloader.with(AuthorizedSource, ctx[:batched_calls_counter]).load(obj)
end
field :name, String, null: false
field :ingredients, [Ingredient], null: false
def ingredients
ingredients = dataloader.with(DataObject).load_all(object[:ingredient_ids])
ingredients
end
field :slow_ingredients, [Ingredient], null: false
def slow_ingredients
# Use `object[:id]` here to force two different instances of the loader in the test
dataloader.with(SlowDataObject, object[:id]).load_all(object[:ingredient_ids])
end
end
class Cookbook < GraphQL::Schema::Object
field :featured_recipe, Recipe
def featured_recipe
-> { Database.mget([object[:featured_recipe]]).first }
end
end
class Query < GraphQL::Schema::Object
field :recipes, [Recipe], null: false
def recipes
Database.mget(["5", "6"])
end
field :ingredient, Ingredient do
argument :id, ID
end
def ingredient(id:)
dataloader.with(DataObject).load(id)
end
field :ingredient_by_name, Ingredient do
argument :name, String
end
def ingredient_by_name(name:)
ing = dataloader.with(DataObject, :name).load(name)
context.scoped_set!(:ingredient_name, "Scoped:#{name}")
ing
end
field :nested_ingredient, Ingredient do
argument :id, ID
end
def nested_ingredient(id:)
dataloader.with(NestedDataObject).load(id)
end
field :slow_recipe, Recipe do
argument :id, ID
end
def slow_recipe(id:)
dataloader.with(SlowDataObject, id).load(id)
end
field :recipe, Recipe do
argument :id, ID, loads: Recipe, as: :recipe
end
def recipe(recipe:)
recipe
end
field :recipe_by_id_using_load, Recipe do
argument :id, ID, required: false
end
def recipe_by_id_using_load(id:)
dataloader.with(DataObject).load(id)
end
field :recipes_by_id_using_load_all, [Recipe] do
argument :ids, [ID, null: true]
end
def recipes_by_id_using_load_all(ids:)
dataloader.with(DataObject).load_all(ids)
end
field :recipes_by_id, [Recipe] do
argument :ids, [ID], loads: Recipe, as: :recipes
end
def recipes_by_id(recipes:)
recipes
end
field :key_ingredient, Ingredient do
argument :id, ID
end
def key_ingredient(id:)
dataloader.with(KeywordArgumentSource, column: :id).load(id)
end
class RecipeIngredientInput < GraphQL::Schema::InputObject
argument :id, ID
argument :ingredient_number, Int
end
field :recipe_ingredient, Ingredient do
argument :recipe, RecipeIngredientInput
end
def recipe_ingredient(recipe:)
recipe_object = dataloader.with(DataObject).load(recipe[:id])
ingredient_idx = recipe[:ingredient_number] - 1
ingredient_id = recipe_object[:ingredient_ids][ingredient_idx]
dataloader.with(DataObject).load(ingredient_id)
end
field :common_ingredients, [Ingredient] do
argument :recipe_1_id, ID
argument :recipe_2_id, ID
end
def common_ingredients(recipe_1_id:, recipe_2_id:)
req1 = dataloader.with(DataObject).request(recipe_1_id)
req2 = dataloader.with(DataObject).request(recipe_2_id)
recipe1 = req1.load
recipe2 = req2.load
common_ids = recipe1[:ingredient_ids] & recipe2[:ingredient_ids]
dataloader.with(DataObject).load_all(common_ids)
end
field :common_ingredients_with_load, [Ingredient], null: false do
argument :recipe_1_id, ID, loads: Recipe
argument :recipe_2_id, ID, loads: Recipe
end
def common_ingredients_with_load(recipe_1:, recipe_2:)
common_ids = recipe_1[:ingredient_ids] & recipe_2[:ingredient_ids]
dataloader.with(DataObject).load_all(common_ids)
end
field :common_ingredients_from_input_object, [Ingredient], null: false do
class CommonIngredientsInput < GraphQL::Schema::InputObject
argument :recipe_1_id, ID, loads: Recipe
argument :recipe_2_id, ID, loads: Recipe
end
argument :input, CommonIngredientsInput
end
def common_ingredients_from_input_object(input:)
recipe_1 = input[:recipe_1]
recipe_2 = input[:recipe_2]
common_ids = recipe_1[:ingredient_ids] & recipe_2[:ingredient_ids]
dataloader.with(DataObject).load_all(common_ids)
end
field :ingredient_with_custom_batch_key, Ingredient do
argument :id, ID
argument :batch_key, String
end
def ingredient_with_custom_batch_key(id:, batch_key:)
dataloader.with(CustomBatchKeySource, batch_key).load(id)
end
field :recursive_ingredient_name, String do
argument :id, ID
end
def recursive_ingredient_name(id:)
res = context.schema.execute("{ ingredient(id: #{id}) { name } }")
res["data"]["ingredient"]["name"]
end
field :test_error, String do
argument :source, Boolean, required: false, default_value: false
end
def test_error(source:)
if source
dataloader.with(ErrorSource).load(1)
else
raise GraphQL::Error, "Field error"
end
end
class LookaheadInput < GraphQL::Schema::InputObject
argument :id, ID
argument :batch_key, String
end
field :lookahead_ingredient, Ingredient, extras: [:lookahead] do
argument :input, LookaheadInput
end
def lookahead_ingredient(input:, lookahead:)
lookahead.arguments # forces a dataloader.run_isolated call
dataloader.with(CustomBatchKeySource, input[:batch_key]).load(input[:id])
end
field :cookbooks, [Cookbook]
def cookbooks
[
{ featured_recipe: "5" },
{ featured_recipe: "6" },
]
end
end
query(Query)
class Mutation1 < GraphQL::Schema::Mutation
argument :argument_1, String, prepare: ->(val, ctx) {
raise FieldTestError
}
field :value, String
def resolve(argument_1:)
{ value: argument_1 }
end
end
class Mutation2 < GraphQL::Schema::Mutation
argument :argument_2, String, prepare: ->(val, ctx) {
raise FieldTestError
}
field :value, String
def resolve(argument_2:)
{ value: argument_2 }
end
end
class Mutation3 < GraphQL::Schema::Mutation
argument :label, String
type String
def resolve(label:)
log = context[:mutation_log] ||= []
log << "begin #{label}"
dataloader.with(DataObject).load(1)
log << "end #{label}"
label
end
end
class GetCache < GraphQL::Schema::Mutation
type String
def resolve
dataloader.with(ToString).load(1)
end
end
class Mutation < GraphQL::Schema::Object
field :mutation_1, mutation: Mutation1
field :mutation_2, mutation: Mutation2
field :mutation_3, mutation: Mutation3
field :set_cache, String do
argument :input, String
end
def set_cache(input:)
dataloader.with(ToString).merge({ 1 => input })
input
end
field :get_cache, mutation: GetCache
end
mutation(Mutation)
def self.object_from_id(id, ctx)
ctx.dataloader.with(DataObject).load(id)
end
def self.resolve_type(type, obj, ctx)
get_type(obj[:type])
end
orphan_types(Grain, Dairy, Recipe, LeaveningAgent)
use GraphQL::Dataloader
lazy_resolve Proc, :call
class FieldTestError < StandardError; end
rescue_from(FieldTestError) do |err, obj, args, ctx, field|
errs = ctx[:errors] ||= []
errs << "FieldTestError @ #{ctx[:current_path]}, #{field.path} / #{ctx[:current_field].path}"
nil
end
end
class UsageAnalyzer < GraphQL::Analysis::Analyzer
def initialize(query)
@query = query
@fields = Set.new
end
def on_enter_field(node, parent, visitor)
args = @query.arguments_for(node, visitor.field_definition)
# This bug has been around for a while,
# see https://github.com/rmosolgo/graphql-ruby/issues/3321
if args.is_a?(GraphQL::Execution::Lazy)
args = args.value
end
@fields << [node.name, args.keys]
end
def result
@fields
end
end
def database_log
FiberSchema::Database.log
end
before do
database_log.clear
end
ALL_FIBERS = []
class PartsSchema < GraphQL::Schema
class FieldSource < GraphQL::Dataloader::Source
DATA = [
{"id" => 1, "name" => "a"},
{"id" => 2, "name" => "b"},
{"id" => 3, "name" => "c"},
{"id" => 4, "name" => "d"},
]
def fetch(fields)
@previously_fetched ||= Set.new
fields.each do |f|
if !@previously_fetched.add?(f)
raise "Duplicate fetch for #{f.inspect}"
end
end
Array.new(fields.size, DATA)
end
end
class StringFilter < GraphQL::Schema::InputObject
argument :equal_to_any_of, [String]
end
class ComponentFilter < GraphQL::Schema::InputObject
argument :name, StringFilter
end
class FetchObjects < GraphQL::Schema::Resolver
argument :filter, ComponentFilter, required: false
def resolve(**_kwargs)
context.dataloader.with(FieldSource).load("#{field.path}/#{object&.fetch("id")}")
end
end
class Component < GraphQL::Schema::Object
field :name, String
end
class Part < GraphQL::Schema::Object
field :components, [Component], resolver: FetchObjects
end
class Manufacturer < GraphQL::Schema::Object
field :parts, [Part], resolver: FetchObjects
end
class Query < GraphQL::Schema::Object
field :manufacturers, [Manufacturer], resolver: FetchObjects
end
query(Query)
use GraphQL::Dataloader
end
module DataloaderAssertions
module FiberCounting
class << self
attr_accessor :starting_fiber_count, :last_spawn_fiber_count, :last_max_fiber_count
def current_fiber_count
count_active_fibers - starting_fiber_count
end
def count_active_fibers
GC.start
ObjectSpace.each_object(Fiber).count
end
end
def initialize(*args, **kwargs, &block)
super
FiberCounting.starting_fiber_count = FiberCounting.count_active_fibers
FiberCounting.last_max_fiber_count = 0
FiberCounting.last_spawn_fiber_count = 0
end
def spawn_fiber
result = super
update_fiber_counts
result
end
def spawn_source_task(parent_task, condition, trace)
result = super
if result
update_fiber_counts
end
result
end
private
def update_fiber_counts
FiberCounting.last_spawn_fiber_count += 1
current_count = FiberCounting.current_fiber_count
if current_count > FiberCounting.last_max_fiber_count
FiberCounting.last_max_fiber_count = current_count
end
end
end
def self.included(child_class)
child_class.class_eval do
let(:schema) { make_schema_from(FiberSchema) }
let(:parts_schema) { make_schema_from(PartsSchema) }
it "Works with request(...)" do
res = schema.execute <<-GRAPHQL
{
commonIngredients(recipe1Id: 5, recipe2Id: 6) {
name
}
}
GRAPHQL
expected_data = {
"data" => {
"commonIngredients" => [
{ "name" => "Corn" },
{ "name" => "Butter" },
]
}
}
assert_graphql_equal expected_data, res
assert_equal [[:mget, ["5", "6"]], [:mget, ["2", "3"]]], database_log
end
it "runs mutations sequentially" do
res = schema.execute <<-GRAPHQL
mutation {
first: mutation3(label: "first")
second: mutation3(label: "second")
}
GRAPHQL
assert_equal({ "first" => "first", "second" => "second" }, res["data"])
assert_equal ["begin first", "end first", "begin second", "end second"], res.context[:mutation_log]
end
it "clears the cache between mutations" do
res = schema.execute <<-GRAPHQL
mutation {
setCache(input: "Salad")
getCache
}
GRAPHQL
assert_equal({"setCache" => "Salad", "getCache" => "1"}, res["data"])
end
it "batch-loads" do
res = schema.execute <<-GRAPHQL
{
i1: ingredient(id: 1) { id name }
i2: ingredient(id: 2) { name }
__typename
r1: recipe(id: 5) {
# This loads Ingredients 3 and 4
ingredients { name }
}
# This loads Ingredient 7
ri1: recipeIngredient(recipe: { id: 6, ingredientNumber: 3 }) {
name
}
}
GRAPHQL
expected_data = {
"i1" => { "id" => "1", "name" => "Wheat" },
"i2" => { "name" => "Corn" },
"__typename" => "Query",
"r1" => {
"ingredients" => [
{ "name" => "Wheat" },
{ "name" => "Corn" },
{ "name" => "Butter" },
{ "name" => "Baking Soda" },
],
},
"ri1" => {
"name" => "Cheese",
},
}
assert_graphql_equal(expected_data, res["data"])
expected_log = [
[:mget, [
"1", "2", # The first 2 ingredients
"5", # The first recipe
"6", # recipeIngredient recipeId
]],
[:mget, [
"7", # recipeIngredient ingredient_id
]],
[:mget, [
"3", "4", # The two unfetched ingredients the first recipe
]],
]
assert_equal expected_log, database_log
end
it "caches and batch-loads across a multiplex" do
context = {}
result = schema.multiplex([
{ query: "{ i1: ingredient(id: 1) { name } i2: ingredient(id: 2) { name } }", },
{ query: "{ i2: ingredient(id: 2) { name } r1: recipe(id: 5) { ingredients { name } } }", },
{ query: "{ i1: ingredient(id: 1) { name } ri1: recipeIngredient(recipe: { id: 5, ingredientNumber: 2 }) { name } }", },
], context: context)
expected_result = [
{"data"=>{"i1"=>{"name"=>"Wheat"}, "i2"=>{"name"=>"Corn"}}},
{"data"=>{"i2"=>{"name"=>"Corn"}, "r1"=>{"ingredients"=>[{"name"=>"Wheat"}, {"name"=>"Corn"}, {"name"=>"Butter"}, {"name"=>"Baking Soda"}]}}},
{"data"=>{"i1"=>{"name"=>"Wheat"}, "ri1"=>{"name"=>"Corn"}}},
]
assert_graphql_equal expected_result, result
expected_log = [
[:mget, ["1", "2", "5"]],
[:mget, ["3", "4"]],
]
assert_equal expected_log, database_log
end
it "works with calls within sources" do
res = schema.execute <<-GRAPHQL
{
i1: nestedIngredient(id: 1) { name }
i2: nestedIngredient(id: 2) { name }
}
GRAPHQL
expected_data = { "i1" => { "name" => "Wheat" }, "i2" => { "name" => "Corn" } }
assert_graphql_equal expected_data, res["data"]
assert_equal [[:mget, ["1", "2"]]], database_log
end
it "works with batch parameters" do
res = schema.execute <<-GRAPHQL
{
i1: ingredientByName(name: "Butter") { id }
i2: ingredientByName(name: "Corn") { id }
i3: ingredientByName(name: "Gummi Bears") { id }
}
GRAPHQL
expected_data = {
"i1" => { "id" => "3" },
"i2" => { "id" => "2" },
"i3" => nil,
}
assert_graphql_equal expected_data, res["data"]
assert_equal [[:find_by, :name, ["Butter", "Corn", "Gummi Bears"]]], database_log
end
it "works with manual parallelism" do
start = Time.now.to_f
schema.execute <<-GRAPHQL
{
i1: slowRecipe(id: 5) { slowIngredients { name } }
i2: slowRecipe(id: 6) { slowIngredients { name } }
}
GRAPHQL
finish = Time.now.to_f
# For some reason Async adds some overhead to this manual parallelism.
# But who cares, you wouldn't use Thread#join in that case
delta = schema.dataloader_class == GraphQL::Dataloader ? 0.1 : 0.5
# Each load slept for 0.5 second, so sequentially, this would have been 2s sequentially
assert_in_delta 1, finish - start, delta, "Load threads are executed in parallel"
expected_log = [
# These were separated because of different recipe IDs:
[:mget, ["5"]],
[:mget, ["6"]],
# These were cached separately because of different recipe IDs:
[:mget, ["2", "3", "7"]],
[:mget, ["1", "2", "3", "4"]],
]
# Sort them because threads may have returned in slightly different order
assert_equal expected_log.sort, database_log.sort
end
it "Works with multiple-field selections and __typename" do
query_str = <<-GRAPHQL
{
ingredient(id: 1) {
__typename
name
}
}
GRAPHQL
res = schema.execute(query_str)
expected_data = {
"ingredient" => {
"__typename" => "Grain",
"name" => "Wheat",
}
}
assert_graphql_equal expected_data, res["data"]
end
it "Works when the parent field didn't yield" do
query_str = <<-GRAPHQL
{
recipes {
ingredients {
name
}
}
}
GRAPHQL
res = schema.execute(query_str)
expected_data = {
"recipes" =>[
{ "ingredients" => [
{"name"=>"Wheat"},
{"name"=>"Corn"},
{"name"=>"Butter"},
{"name"=>"Baking Soda"}
]},
{ "ingredients" => [
{"name"=>"Corn"},
{"name"=>"Butter"},
{"name"=>"Cheese"}
]},
]
}
assert_graphql_equal expected_data, res["data"]
expected_log = [
[:mget, ["5", "6"]],
[:mget, ["1", "2", "3", "4", "7"]],
]
assert_equal expected_log, database_log
end
it "loads arguments in batches, even with request" do
query_str = <<-GRAPHQL
{
commonIngredientsWithLoad(recipe1Id: 5, recipe2Id: 6) {
name
}
}
GRAPHQL
res = schema.execute(query_str)
expected_data = {
"commonIngredientsWithLoad" => [
{"name"=>"Corn"},
{"name"=>"Butter"},
]
}
assert_graphql_equal expected_data, res["data"]
expected_log = [
[:mget, ["5", "6"]],
[:mget, ["2", "3"]],
]
assert_equal expected_log, database_log
end
it "works with sources that use keyword arguments in the initializer" do
query_str = <<-GRAPHQL
{
keyIngredient(id: 1) {
__typename
name
}
}
GRAPHQL
res = schema.execute(query_str)
expected_data = {
"keyIngredient" => {
"__typename" => "Grain",
"name" => "Wheat",
}
}
assert_graphql_equal expected_data, res["data"]
end
it "Works with analyzing arguments with `loads:`, even with .request" do
query_str = <<-GRAPHQL
{
commonIngredientsWithLoad(recipe1Id: 5, recipe2Id: 6) {
name
}
}
GRAPHQL
query = GraphQL::Query.new(schema, query_str)
results = GraphQL::Analysis.analyze_query(query, [UsageAnalyzer])
expected_results = [
["commonIngredientsWithLoad", [:recipe_1, :recipe_2]],
["name", []],
]
normalized_results = results.first.to_a
normalized_results.each do |key, values|
values.sort!
end
assert_equal expected_results, results.first.to_a
end
it "Works with input objects, load and request" do
query_str = <<-GRAPHQL
{
commonIngredientsFromInputObject(input: { recipe1Id: 5, recipe2Id: 6 }) {
name
}
}
GRAPHQL
res = schema.execute(query_str)
expected_data = {
"commonIngredientsFromInputObject" => [
{"name"=>"Corn"},
{"name"=>"Butter"},
]
}
assert_graphql_equal expected_data, res["data"]
expected_log = [
[:mget, ["5", "6"]],
[:mget, ["2", "3"]],
]
assert_equal expected_log, database_log
end
it "batches calls in .authorized?" do
query_str = "{ r1: recipe(id: 5) { name } r2: recipe(id: 6) { name } }"
context = { batched_calls_counter: BatchedCallsCounter.new }
schema.execute(query_str, context: context)
assert_equal 1, context[:batched_calls_counter].count
query_str = "{ recipes { name } }"
context = { batched_calls_counter: BatchedCallsCounter.new }
schema.execute(query_str, context: context)
assert_equal 1, context[:batched_calls_counter].count
query_str = "{ recipesById(ids: [5, 6]) { name } }"
context = { batched_calls_counter: BatchedCallsCounter.new }
schema.execute(query_str, context: context)
assert_equal 1, context[:batched_calls_counter].count
end
it "batches nested object calls in .authorized? after using lazy_resolve" do
query_str = "{ cookbooks { featuredRecipe { name } } }"
context = { batched_calls_counter: BatchedCallsCounter.new }
result = schema.execute(query_str, context: context)
assert_equal ["Cornbread", "Grits"], result["data"]["cookbooks"].map { |c| c["featuredRecipe"]["name"] }
refute result.key?("errors")
assert_equal 1, context[:batched_calls_counter].count
end
it "works when passing nil into source" do
query_str = <<-GRAPHQL
query($id: ID) {
recipe: recipeByIdUsingLoad(id: $id) {
name
}
}
GRAPHQL
res = schema.execute(query_str, variables: { id: nil })
expected_data = { "recipe" => nil }
assert_graphql_equal expected_data, res["data"]
query_str = <<-GRAPHQL
query($ids: [ID]!) {
recipes: recipesByIdUsingLoadAll(ids: $ids) {
name
}
}
GRAPHQL
res = schema.execute(query_str, variables: { ids: [nil] })
expected_data = { "recipes" => nil }
assert_graphql_equal expected_data, res["data"]
end
it "Works with input objects using variables, load and request" do
query_str = <<-GRAPHQL
query($input: CommonIngredientsInput!) {
commonIngredientsFromInputObject(input: $input) {
name
}
}
GRAPHQL
res = schema.execute(query_str, variables: { input: { recipe1Id: 5, recipe2Id: 6 }})
expected_data = {
"commonIngredientsFromInputObject" => [
{"name"=>"Corn"},
{"name"=>"Butter"},
]
}
assert_graphql_equal expected_data, res["data"]
expected_log = [
[:mget, ["5", "6"]],
[:mget, ["2", "3"]],
]
assert_equal expected_log, database_log
end
it "supports general usage" do
a = b = c = nil
res = GraphQL::Dataloader.with_dataloading { |dataloader|
dataloader.append_job {
a = dataloader.with(FiberSchema::DataObject).load("1")
}
dataloader.append_job {
b = dataloader.with(FiberSchema::DataObject).load("1")
}
dataloader.append_job {
r1 = dataloader.with(FiberSchema::DataObject).request("2")
r2 = dataloader.with(FiberSchema::DataObject).request("3")
c = [
r1.load,
r2.load
]
}
:finished
}
assert_equal :finished, res
assert_equal [[:mget, ["1", "2", "3"]]], database_log
assert_equal "Wheat", a[:name]
assert_equal "Wheat", b[:name]
assert_equal ["Corn", "Butter"], c.map { |d| d[:name] }
end
it "works with scoped context" do
query_str = <<-GRAPHQL
{
i1: ingredientByName(name: "Corn") { nameByScopedContext }
i2: ingredientByName(name: "Wheat") { nameByScopedContext }
i3: ingredientByName(name: "Butter") { nameByScopedContext }
}
GRAPHQL
expected_data = {
"i1" => { "nameByScopedContext" => "Scoped:Corn" },
"i2" => { "nameByScopedContext" => "Scoped:Wheat" },
"i3" => { "nameByScopedContext" => "Scoped:Butter" },
}
result = schema.execute(query_str)
assert_graphql_equal expected_data, result["data"]
end
it "works when the schema calls itself" do
result = schema.execute("{ recursiveIngredientName(id: 1) }")
assert_equal "Wheat", result["data"]["recursiveIngredientName"]
end
it "uses .batch_key_for in source classes" do
query_str = <<-GRAPHQL
{
i1: ingredientWithCustomBatchKey(id: 1, batchKey: "abc") { name }
i2: ingredientWithCustomBatchKey(id: 2, batchKey: "def") { name }
i3: ingredientWithCustomBatchKey(id: 3, batchKey: "ghi") { name }
}
GRAPHQL
res = schema.execute(query_str)
expected_data = { "i1" => { "name" => "Wheat" }, "i2" => { "name" => "Corn" }, "i3" => { "name" => "Butter" } }
assert_graphql_equal expected_data, res["data"]
expected_log = [
# Each batch key is given to the source class:
[:batch_key_for, "abc"],
[:batch_key_for, "def"],
[:batch_key_for, "ghi"],
# But since they return the same value,
# all keys are fetched in the same call:
[:mget, ["1", "2", "3"]]
]
assert_equal expected_log, database_log
end
it "uses cached values from .merge" do
query_str = "{ ingredient(id: 1) { id name } }"
assert_equal "Wheat", schema.execute(query_str)["data"]["ingredient"]["name"]
assert_equal [[:mget, ["1"]]], database_log
database_log.clear
dataloader = schema.dataloader_class.new
data_source = dataloader.with(FiberSchema::DataObject)
data_source.merge({ "1" => { name: "Kamut", id: "1", type: "Grain" } })
assert_equal "Kamut", data_source.load("1")[:name]
res = schema.execute(query_str, context: { dataloader: dataloader })
assert_equal [], database_log
assert_equal "Kamut", res["data"]["ingredient"]["name"]
end
it "raises errors from fields" do
err = assert_raises GraphQL::Error do
schema.execute("{ testError }")
end
assert_equal "Field error", err.message
end
it "raises errors from sources" do
err = assert_raises GraphQL::Error do
schema.execute("{ testError(source: true) }")
end
assert_equal "Source error on: [1]", err.message
end
it "works with very very large queries" do
query_str = "{".dup
fields = 1100
fields.times do |i|
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | true |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/subscriptions_spec.rb | spec/graphql/subscriptions_spec.rb | # frozen_string_literal: true
require "spec_helper"
class InMemoryBackend
MAX_COMPLEXITY = 5
class Subscriptions < GraphQL::Subscriptions
attr_reader :deliveries, :pushes, :extra, :queries, :events
def initialize(schema:, extra:, **rest)
super
@extra = extra
@queries = {}
# { topic => { fingerprint => [sub_id, ... ] } }
@events = Hash.new { |h,k| h[k] = Hash.new { |h2, k2| h2[k2] = [] } }
@deliveries = Hash.new { |h, k| h[k] = [] }
@pushes = []
end
def write_subscription(query, events)
subscription_id = query.context[:subscription_id] = build_id
@queries[subscription_id] = query
events.each do |ev|
@events[ev.topic][ev.fingerprint] << subscription_id
end
end
def read_subscription(subscription_id)
query = @queries[subscription_id]
if query
{
query_string: query.query_string,
operation_name: query.operation_name,
variables: query.provided_variables,
context: {
me: query.context[:me],
validate_update: query.context[:validate_update],
other_int: query.context[:other_int],
hidden_event: query.context[:hidden_event],
shared_stream: query.context[:shared_stream],
},
transport: :socket,
}
else
nil
end
end
def delete_subscription(subscription_id)
@queries.delete(subscription_id)
@events.each do |topic, sub_ids_by_fp|
sub_ids_by_fp.each do |fp, sub_ids|
sub_ids.delete(subscription_id)
if sub_ids.empty?
sub_ids_by_fp.delete(fp)
if sub_ids_by_fp.empty?
@events.delete(topic)
end
end
end
end
end
def execute_all(event, object)
topic = event.topic
sub_ids_by_fp = @events[topic]
sub_ids_by_fp.each do |fingerprint, sub_ids|
result = execute_update(sub_ids.first, event, object)
if !result.nil?
sub_ids.each do |sub_id|
deliver(sub_id, result)
end
end
end
end
def deliver(subscription_id, result)
query = @queries[subscription_id]
socket = query.context[:socket] || subscription_id
@deliveries[socket] << result
end
def execute_update(subscription_id, event, object)
query = @queries[subscription_id]
if query
@pushes << query.context[:socket]
end
super
end
# Just for testing:
def reset
@queries.clear
@events.clear
@deliveries.clear
@pushes.clear
end
end
# Just a random stateful object for tracking what happens:
class SubscriptionPayload
attr_reader :str
def initialize
@str = "Update"
@counter = 0
end
def int
@counter += 1
end
end
end
class ClassBasedInMemoryBackend < InMemoryBackend
class Payload < GraphQL::Schema::Object
field :str, String, null: false
field :int, Integer, null: false do
def visible?(context)
!context[:other_int]
end
end
field :int, Integer, null: false, resolver_method: :other_int do
def visible?(context)
!!context[:other_int]
end
end
def other_int
1000 + object.int
end
end
class PayloadType < GraphQL::Schema::Enum
graphql_name "PayloadType"
# Arbitrary "kinds" of payloads which may be
# subscribed to separately
value "ONE"
value "TWO"
end
class StreamInput < GraphQL::Schema::InputObject
argument :user_id, ID, camelize: false
argument :payload_type, PayloadType, required: false, default_value: "ONE", prepare: ->(e, ctx) { e ? e.downcase : e }
end
class EventSubscription < GraphQL::Schema::Subscription
argument :user_id, ID, as: :user
argument :payload_type, PayloadType, required: false, default_value: "ONE", prepare: ->(e, ctx) { e ? e.downcase : e }
field :payload, Payload
end
class FilteredStream < GraphQL::Schema::Subscription
subscription_scope :segment
argument :channel, Integer, required: false
field :message, String, null: false
def update(channel: nil)
if channel && object.channel != channel
NO_UPDATE
else
super
end
end
def self.topic_for(arguments:, field:, scope:)
"#{field.graphql_name}:#{scope}"
end
end
class SharedEvent < GraphQL::Schema::Subscription
subscription_scope :shared_stream
field :ok, Boolean
def self.topic_for(arguments:, field:, scope:)
scope.to_s
end
end
class OtherSharedEvent < SharedEvent
end
class Subscription < GraphQL::Schema::Object
field :payload, Payload, null: false do
argument :id, ID
end
field :event, Payload do
argument :stream, StreamInput, required: false
end
field :event_subscription, subscription: EventSubscription
field :my_event, Payload, subscription_scope: :me do
argument :payload_type, PayloadType, required: false
end
field :failed_event, Payload, null: false do
argument :id, ID
end
def failed_event(id:)
raise GraphQL::ExecutionError.new("unauthorized")
end
field :filtered_stream, subscription: FilteredStream
field :hidden_event, Payload do
def visible?(context)
!!context[:hidden_event]
end
end
field :shared_event, subscription: SharedEvent
field :other_shared_event, subscription: OtherSharedEvent
end
class Query < GraphQL::Schema::Object
field :dummy, Integer
end
class Schema < GraphQL::Schema
query { Query }
subscription { Subscription }
use InMemoryBackend::Subscriptions, extra: 123
max_complexity(InMemoryBackend::MAX_COMPLEXITY)
complexity_cost_calculation_mode(:future)
use GraphQL::Schema::Warden if ADD_WARDEN
end
end
class FromDefinitionInMemoryBackend < InMemoryBackend
SchemaDefinition = <<-GRAPHQL
type Subscription {
payload(id: ID!): Payload!
event(stream: StreamInput): Payload
eventSubscription(userId: ID, payloadType: PayloadType = ONE): EventSubscriptionPayload
myEvent(payloadType: PayloadType): Payload
failedEvent(id: ID!): Payload!
}
type Payload {
str: String!
int: Int!
}
type EventSubscriptionPayload {
payload: Payload
}
input StreamInput {
user_id: ID!
payloadType: PayloadType = ONE
}
# Arbitrary "kinds" of payloads which may be
# subscribed to separately
enum PayloadType {
ONE
TWO
}
type Query {
dummy: Int
}
GRAPHQL
DEFAULT_SUBSCRIPTION_RESOLVE = ->(o,a,c) {
if c.query.subscription_update?
o
else
c.skip
end
}
Resolvers = {
"Subscription" => {
"payload" => DEFAULT_SUBSCRIPTION_RESOLVE,
"myEvent" => DEFAULT_SUBSCRIPTION_RESOLVE,
"event" => DEFAULT_SUBSCRIPTION_RESOLVE,
"eventSubscription" => ->(o,a,c) { nil },
"failedEvent" => ->(o,a,c) { raise GraphQL::ExecutionError.new("unauthorized") },
},
}
Schema = GraphQL::Schema.from_definition(SchemaDefinition, default_resolve: Resolvers, using: {InMemoryBackend::Subscriptions => { extra: 123 }})
Schema.max_complexity(MAX_COMPLEXITY)
Schema.complexity_cost_calculation_mode(:future)
# TODO don't hack this (no way to add metadata from IDL parser right now)
Schema.get_field("Subscription", "myEvent").subscription_scope = :me
end
class ToParamUser
def initialize(id)
@id = id
end
def to_param
@id
end
end
describe GraphQL::Subscriptions do
[ClassBasedInMemoryBackend, FromDefinitionInMemoryBackend].each do |in_memory_backend_class|
describe "using #{in_memory_backend_class}" do
before do
schema.subscriptions.reset
end
let(:root_object) {
OpenStruct.new(
payload: in_memory_backend_class::SubscriptionPayload.new,
)
}
let(:schema) { in_memory_backend_class::Schema }
let(:implementation) { schema.subscriptions }
let(:deliveries) { implementation.deliveries }
let(:subscriptions_by_topic) {
implementation.events.each_with_object({}) do |(k, v), obj|
obj[k] = v.size
end
}
describe "pushing updates" do
it "sends updated data" do
query_str = <<-GRAPHQL
subscription ($id: ID!){
firstPayload: payload(id: $id) { str, int }
}
GRAPHQL
# Initial subscriptions
res_1 = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object)
res_2 = schema.execute(query_str, context: { socket: "2" }, variables: { "id" => "200" }, root_value: root_object)
empty_response = {}
# Initial response is nil, no broadcasts yet
assert_equal(empty_response, res_1["data"])
assert_equal(empty_response, res_2["data"])
assert_equal [], deliveries["1"]
assert_equal [], deliveries["2"]
# Application stuff happens.
# The application signals graphql via `subscriptions.trigger`:
schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload)
schema.subscriptions.trigger("payload", {"id" => "200"}, root_object.payload)
# Symbols are OK too
schema.subscriptions.trigger(:payload, {:id => "100"}, root_object.payload)
schema.subscriptions.trigger("payload", {"id" => "300"}, nil)
# Let's see what GraphQL sent over the wire:
assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["firstPayload"])
assert_equal({"str" => "Update", "int" => 2}, deliveries["2"][0]["data"]["firstPayload"])
assert_equal({"str" => "Update", "int" => 3}, deliveries["1"][1]["data"]["firstPayload"])
end
end
it "works with the introspection query" do
res = schema.execute("{ __schema { subscriptionType { name } } }")
assert_equal "Subscription", res["data"]["__schema"]["subscriptionType"]["name"]
end
if in_memory_backend_class != FromDefinitionInMemoryBackend # No way to specify this when using IDL
it "supports filtering in the subscription class" do
query_str = "subscription($channel: Int) { filteredStream(channel: $channel) { message } }"
# Unfiltered:
schema.execute(query_str, context: { socket: "1", segment: "A" }, variables: {})
# Filtered:
schema.execute(query_str, context: { socket: "2", segment: "A" }, variables: { channel: 1 })
schema.execute(query_str, context: { socket: "3", segment: "A" }, variables: { channel: 2 })
# Another Subscription scope:
schema.execute(query_str, context: { socket: "4", segment: "B" }, variables: {})
schema.execute(query_str, context: { socket: "5", segment: "B" }, variables: { channel: 1 })
schema.subscriptions.trigger(:filtered_stream, {}, OpenStruct.new(channel: 1, message: "Message 1"), scope: "A")
schema.subscriptions.trigger(:filtered_stream, {}, OpenStruct.new(channel: 2, message: "Message 2"), scope: "A")
schema.subscriptions.trigger(:filtered_stream, {}, OpenStruct.new(channel: 3, message: "Message 3"), scope: "A")
# Unfiltered, received all updates:
assert_equal 3, deliveries["1"].size
# Only received updates that matched `channel`:
assert_equal 1, deliveries["2"].size
assert_equal 1, deliveries["3"].size
# Different segment, no updates:
assert_equal 0, deliveries["4"].size
assert_equal 0, deliveries["5"].size
schema.subscriptions.trigger(:filtered_stream, {}, OpenStruct.new(channel: 1, message: "Message 4"), scope: "B")
schema.subscriptions.trigger(:filtered_stream, {}, OpenStruct.new(channel: 2, message: "Message 5"), scope: "B")
# These should be unchanged because the later triggers had a different scope value:
assert_equal 3, deliveries["1"].size
assert_equal 1, deliveries["2"].size
assert_equal 1, deliveries["3"].size
# These received updates from the second set of triggers:
assert_equal 2, deliveries["4"].size
assert_equal 1, deliveries["5"].size
end
it "runs visibility checks when calling .trigger" do
query_str = "subscription { hiddenEvent { int } }"
res_1 = schema.execute(query_str, context: { socket: "1", hidden_event: true }, root_value: root_object)
assert_equal({}, res_1["data"])
schema.subscriptions.trigger(:hidden_event, {}, root_object.payload, context: { hidden_event: true })
assert_equal({"hiddenEvent" => { "int" => 1 }}, deliveries["1"][0]["data"])
err = assert_raises GraphQL::Subscriptions::InvalidTriggerError do
schema.subscriptions.trigger(:hidden_event, {}, root_object.payload)
end
assert_equal "No subscription matching trigger: hidden_event (looked for Subscription.hiddenEvent)", err.message
end
end
describe "passing a document into #execute" do
it "sends the updated data" do
query_str = <<-GRAPHQL
subscription ($id: ID!){
payload(id: $id) { str, int }
}
GRAPHQL
document = GraphQL.parse(query_str)
# Initial subscriptions
response = schema.execute(nil, document: document, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object)
empty_response = {}
# Initial response is empty, no broadcasts yet
assert_equal(empty_response, response["data"])
assert_equal [], deliveries["1"]
# Application stuff happens.
# The application signals graphql via `subscriptions.trigger`:
schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload)
# Symbols are OK too
schema.subscriptions.trigger(:payload, {:id => "100"}, root_object.payload)
schema.subscriptions.trigger("payload", {"id" => "300"}, nil)
# Let's see what GraphQL sent over the wire:
assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["payload"])
assert_equal({"str" => "Update", "int" => 2}, deliveries["1"][1]["data"]["payload"])
end
end
describe "subscribing" do
it "doesn't call the subscriptions for invalid queries" do
query_str = <<-GRAPHQL
subscription ($id: ID){
payload(id: $id) { str, int }
}
GRAPHQL
res = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object)
assert_equal true, res.key?("errors")
assert_equal 0, implementation.events.size
assert_equal 0, implementation.queries.size
end
end
describe "trigger" do
let(:error_payload_class) {
Class.new {
def int
raise "Boom!"
end
def str
raise GraphQL::ExecutionError.new("This is handled")
end
}
}
it "uses the provided queue" do
query_str = <<-GRAPHQL
subscription ($id: ID!){
payload(id: $id) { str, int }
}
GRAPHQL
schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object)
schema.subscriptions.trigger("payload", { "id" => "8"}, root_object.payload)
assert_equal ["1"], implementation.pushes
end
it "pushes errors" do
query_str = <<-GRAPHQL
subscription ($id: ID!){
payload(id: $id) { str, int }
}
GRAPHQL
schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object)
schema.subscriptions.trigger("payload", { "id" => "8"}, OpenStruct.new(str: nil, int: nil))
delivery = deliveries["1"].first
assert_nil delivery.fetch("data")
assert_equal 1, delivery["errors"].length
end
it "unsubscribes when `read_subscription` returns nil" do
query_str = <<-GRAPHQL
subscription ($id: ID!){
payload(id: $id) { str, int }
}
GRAPHQL
schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object)
assert_equal 1, implementation.events.size
sub_id = implementation.queries.keys.first
# Mess with the private storage so that `read_subscription` will be nil
implementation.queries.delete(sub_id)
assert_equal 1, implementation.events.size
assert_nil implementation.read_subscription(sub_id)
# The trigger should clean up the lingering subscription:
schema.subscriptions.trigger("payload", { "id" => "8"}, OpenStruct.new(str: nil, int: nil))
assert_equal 0, implementation.events.size
assert_equal 0, implementation.queries.size
end
it "coerces args" do
query_str = <<-GRAPHQL
subscription($type: PayloadType) {
e1: event(stream: { user_id: "3", payloadType: $type }) { int }
}
GRAPHQL
# Subscribe with explicit `TYPE`
schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object)
# Subscribe with default `TYPE`
schema.execute(query_str, context: { socket: "2" }, root_value: root_object)
# Subscribe with non-matching `TYPE`
schema.execute(query_str, context: { socket: "3" }, variables: { "type" => "TWO" }, root_value: root_object)
# Subscribe with explicit null
schema.execute(query_str, context: { socket: "4" }, variables: { "type" => nil }, root_value: root_object)
# The class-based schema has a "prepare" behavior, so it expects these downcased values in `.trigger`
if schema == ClassBasedInMemoryBackend::Schema
one = "one"
two = "two"
else
one = "ONE"
two = "TWO"
end
# Trigger the subscription with coerceable args, different orders:
schema.subscriptions.trigger("event", { "stream" => {"user_id" => 3, "payloadType" => one} }, OpenStruct.new(str: "", int: 1))
schema.subscriptions.trigger("event", { "stream" => {"payloadType" => one, "user_id" => "3"} }, OpenStruct.new(str: "", int: 2))
# This is a non-trigger
schema.subscriptions.trigger("event", { "stream" => {"user_id" => "3", "payloadType" => two} }, OpenStruct.new(str: "", int: 3))
# These get default value of ONE (underscored / symbols are ok)
schema.subscriptions.trigger("event", { stream: { user_id: "3"} }, OpenStruct.new(str: "", int: 4))
# Trigger with null updates subscriptions to null
schema.subscriptions.trigger("event", { "stream" => {"user_id" => 3, "payloadType" => nil} }, OpenStruct.new(str: "", int: 5))
assert_equal [1,2,4], deliveries["1"].map { |d| d["data"]["e1"]["int"] }
# Same as socket_1
assert_equal [1,2,4], deliveries["2"].map { |d| d["data"]["e1"]["int"] }
# Received the "non-trigger"
assert_equal [3], deliveries["3"].map { |d| d["data"]["e1"]["int"] }
# Received the trigger with null
assert_equal [5], deliveries["4"].map { |d| d["data"]["e1"]["int"] }
end
it "allows context-scoped subscriptions" do
query_str = <<-GRAPHQL
subscription($type: PayloadType) {
myEvent(payloadType: $type) { int }
}
GRAPHQL
# Subscriptions for user 1
schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object)
schema.execute(query_str, context: { socket: "2", me: "1" }, variables: { "type" => "TWO" }, root_value: root_object)
# Subscription for user 2
schema.execute(query_str, context: { socket: "3", me: "2" }, variables: { "type" => "ONE" }, root_value: root_object)
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 1), scope: "1")
schema.subscriptions.trigger("myEvent", { "payloadType" => "TWO" }, OpenStruct.new(str: "", int: 2), scope: "1")
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 3), scope: "2")
# Delivered to user 1
assert_equal [1], deliveries["1"].map { |d| d["data"]["myEvent"]["int"] }
assert_equal [2], deliveries["2"].map { |d| d["data"]["myEvent"]["int"] }
# Delivered to user 2
assert_equal [3], deliveries["3"].map { |d| d["data"]["myEvent"]["int"] }
end
if defined?(GlobalID)
it "allows complex object subscription scopes" do
query_str = <<-GRAPHQL
subscription($type: PayloadType) {
myEvent(payloadType: $type) { int }
}
GRAPHQL
# Global ID Backed User
schema.execute(query_str, context: { socket: "1", me: GlobalIDUser.new(1) }, variables: { "type" => "ONE" }, root_value: root_object)
schema.execute(query_str, context: { socket: "2", me: GlobalIDUser.new(1) }, variables: { "type" => "TWO" }, root_value: root_object)
# ToParam Backed User
schema.execute(query_str, context: { socket: "3", me: ToParamUser.new(2) }, variables: { "type" => "ONE" }, root_value: root_object)
# Array of Objects
schema.execute(query_str, context: { socket: "4", me: [GlobalIDUser.new(4), ToParamUser.new(5)] }, variables: { "type" => "ONE" }, root_value: root_object)
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 1), scope: GlobalIDUser.new(1))
schema.subscriptions.trigger("myEvent", { "payloadType" => "TWO" }, OpenStruct.new(str: "", int: 2), scope: GlobalIDUser.new(1))
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 3), scope: ToParamUser.new(2))
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 4), scope: [GlobalIDUser.new(4), ToParamUser.new(5)])
# Delivered to GlobalIDUser
assert_equal [1], deliveries["1"].map { |d| d["data"]["myEvent"]["int"] }
assert_equal [2], deliveries["2"].map { |d| d["data"]["myEvent"]["int"] }
# Delivered to ToParamUser
assert_equal [3], deliveries["3"].map { |d| d["data"]["myEvent"]["int"] }
# Delivered to Array of GlobalIDUser and ToParamUser
assert_equal [4], deliveries["4"].map { |d| d["data"]["myEvent"]["int"] }
end
end
describe "building topic string when `prepare:` is given" do
it "doesn't apply with a Subscription class" do
query_str = <<-GRAPHQL
subscription($type: PayloadType = TWO) {
eventSubscription(userId: "3", payloadType: $type) { payload { int } }
}
GRAPHQL
query_str_2 = <<-GRAPHQL
subscription {
eventSubscription(userId: "4", payloadType: ONE) { payload { int } }
}
GRAPHQL
query_str_3 = <<-GRAPHQL
subscription {
eventSubscription(userId: "4") { payload { int } }
}
GRAPHQL
# Value from variable
schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object)
# Default value for variable
schema.execute(query_str, context: { socket: "1" }, root_value: root_object)
# Query string literal value
schema.execute(query_str_2, context: { socket: "1" }, root_value: root_object)
# Schema default value
schema.execute(query_str_3, context: { socket: "1" }, root_value: root_object)
# There's no way to add `prepare:` when using SDL, so only the Ruby-defined schema has it
expected_sub_count = if schema == ClassBasedInMemoryBackend::Schema
{
":eventSubscription:payloadType:one:userId:3" => 1,
":eventSubscription:payloadType:one:userId:4" => 2,
":eventSubscription:payloadType:two:userId:3" => 1,
}
else
{
":eventSubscription:payloadType:ONE:userId:3" => 1,
":eventSubscription:payloadType:ONE:userId:4" => 2,
":eventSubscription:payloadType:TWO:userId:3" => 1,
}
end
assert_equal expected_sub_count, subscriptions_by_topic
schema.subscriptions.trigger(:event_subscription, { user_id: 3 }, {})
assert_equal 1, deliveries["1"].size
end
it "doesn't apply for plain fields" do
query_str = <<-GRAPHQL
subscription($type: PayloadType = TWO) {
e1: event(stream: { user_id: "3", payloadType: $type }) { int }
}
GRAPHQL
query_str_2 = <<-GRAPHQL
subscription {
event(stream: { user_id: "4", payloadType: ONE}) { int }
}
GRAPHQL
query_str_3 = <<-GRAPHQL
subscription {
event(stream: { user_id: "4" }) { int }
}
GRAPHQL
# Value from variable
schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object)
# Default value for variable
schema.execute(query_str, context: { socket: "1" }, root_value: root_object)
# Query string literal value
schema.execute(query_str_2, context: { socket: "1" }, root_value: root_object)
# Schema default value
schema.execute(query_str_3, context: { socket: "1" }, root_value: root_object)
# There's no way to add `prepare:` when using SDL, so only the Ruby-defined schema has it
expected_sub_count = if schema == ClassBasedInMemoryBackend::Schema
{
":event:stream:payloadType:one:user_id:3" => 1,
":event:stream:payloadType:two:user_id:3" => 1,
":event:stream:payloadType:one:user_id:4" => 2,
}
else
{
":event:stream:payloadType:ONE:user_id:3" => 1,
":event:stream:payloadType:TWO:user_id:3" => 1,
":event:stream:payloadType:ONE:user_id:4" => 2,
}
end
assert_equal expected_sub_count, subscriptions_by_topic
end
end
describe "errors" do
it "avoid subscription on resolver error" do
res = schema.execute(<<-GRAPHQL, context: { socket: "1" }, variables: { "id" => "100" })
subscription ($id: ID!){
failedEvent(id: $id) { str, int }
}
GRAPHQL
assert_nil res["data"]
assert_equal "unauthorized", res["errors"][0]["message"]
assert_equal 0, subscriptions_by_topic.size
end
it "lets unhandled errors crash" do
query_str = <<-GRAPHQL
subscription($type: PayloadType) {
myEvent(payloadType: $type) { int }
}
GRAPHQL
schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object)
err = assert_raises(RuntimeError) {
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, error_payload_class.new, scope: "1")
}
assert_equal "Boom!", err.message
end
end
it "sends query errors to the subscriptions" do
query_str = <<-GRAPHQL
subscription($type: PayloadType) {
myEvent(payloadType: $type) { str }
}
GRAPHQL
schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object)
schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, error_payload_class.new, scope: "1")
res = deliveries["1"].first
assert_equal "This is handled", res["errors"][0]["message"]
end
end
describe "implementation" do
it "is initialized with keywords" do
assert_equal 123, schema.subscriptions.extra
end
end
describe "#build_id" do
it "returns a unique ID string" do
assert_instance_of String, schema.subscriptions.build_id
refute_equal schema.subscriptions.build_id, schema.subscriptions.build_id
end
end
describe ".trigger" do
it "raises when event name is not found" do
err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do
schema.subscriptions.trigger(:nonsense_field, {}, nil)
end
assert_includes err.message, "trigger: nonsense_field"
assert_includes err.message, "Subscription.nonsenseField"
end
it "raises when argument is not found" do
err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do
schema.subscriptions.trigger(:event, { scream: {"user_id" => "😱"} }, nil)
end
assert_includes err.message, "arguments: scream"
assert_includes err.message, "arguments of Subscription.event"
err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do
schema.subscriptions.trigger(:event, { stream: { user_id_number: "😱"} }, nil)
end
assert_includes err.message, "arguments: user_id_number"
assert_includes err.message, "arguments of StreamInput"
end
end
describe "max_complexity" do
it "rejects subscriptions with errors" do
query_str = <<-GRAPHQL
subscription($type: PayloadType) {
myEvent(payloadType: $type) {
s1: str
s2: str
s3: str
s4: str
s5: str
s6: str
}
}
GRAPHQL
res = schema.execute(query_str, context: { socket: "1"})
errs = ["Query has complexity of 7, which exceeds max complexity of 5"]
assert_equal errs, res["errors"].map { |e| e["message"] }
assert_equal 0, implementation.events.size
assert_equal 0, implementation.queries.size
end
end
end
end
it "can share topics" do
schema = ClassBasedInMemoryBackend::Schema
schema.subscriptions.reset
schema.execute("subscription { sharedEvent { ok } }", context: { shared_stream: "stream-1", socket: "1" } )
schema.execute("subscription { otherSharedEvent { ok __typename } }", context: { shared_stream: "stream-1", socket: "2" } )
schema.subscriptions.trigger(:shared_event, {}, OpenStruct.new(ok: true), scope: "stream-1")
schema.subscriptions.trigger(:other_shared_event, {}, OpenStruct.new(ok: false), scope: "stream-1")
pushed_results = schema.subscriptions.deliveries.map do |socket, results|
[socket, results.map { |r| r["data"] }]
end
expected_results = [
["1", [{ "sharedEvent" => { "ok" => true } }, { "sharedEvent" => { "ok" => false } }]],
["2", [{ "otherSharedEvent" => {"ok" => true, "__typename" => "OtherSharedEventPayload" } }, { "otherSharedEvent" => { "ok" => false, "__typename" => "OtherSharedEventPayload" } }]]
]
assert_equal expected_results, pushed_results
end
describe "broadcast: true" do
let(:schema) { BroadcastTrueSchema }
before do
BroadcastTrueSchema::COUNTERS.clear
end
class BroadcastTrueSchema < GraphQL::Schema
COUNTERS = Hash.new(0)
class Subscription < GraphQL::Schema::Object
class BroadcastableCounter < GraphQL::Schema::Subscription
field :value, Integer, null: false
def update
{
value: COUNTERS[:broadcastable] += 1
}
end
end
class IsolatedCounter < GraphQL::Schema::Subscription
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | true |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/query_spec.rb | spec/graphql/query_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query do
let(:query_string) { %|
query getFlavor($cheeseId: Int!) {
brie: cheese(id: 1) { ...cheeseFields, taste: flavor },
cheese(id: $cheeseId) {
__typename,
id,
...cheeseFields,
... edibleFields,
... on Cheese { cheeseKind: flavor },
}
fromSource(source: COW) { id }
fromSheep: fromSource(source: SHEEP) { id }
firstSheep: searchDairy(product: [{source: SHEEP}]) {
__typename,
... dairyFields,
... milkFields
}
favoriteEdible { __typename, fatContent }
}
fragment cheeseFields on Cheese { flavor }
fragment edibleFields on Edible { fatContent }
fragment milkFields on Milk { source }
fragment dairyFields on AnimalProduct {
... on Cheese { flavor }
... on Milk { source }
}
|}
let(:operation_name) { nil }
let(:query_variables) { {"cheeseId" => 2} }
let(:schema) { Dummy::Schema }
let(:document) { GraphQL.parse(query_string) }
let(:query) { GraphQL::Query.new(
schema,
query_string,
variables: query_variables,
operation_name: operation_name
)}
let(:result) { query.result }
it "applies the max validation errors config" do
limited_schema = Class.new(schema) { validate_max_errors(2) }
res = limited_schema.execute("{ a b c d }")
assert_equal 2, res["errors"].size
refute res.key?("data")
end
describe "when passed both a query string and a document" do
it "returns an error to the client when query kwarg is used" do
assert_raises ArgumentError do
GraphQL::Query.new(
schema,
query: "{ fromSource(source: COW) { id } }",
document: document
)
end
end
it "returns an error to the client" do
assert_raises ArgumentError do
GraphQL::Query.new(
schema,
"{ fromSource(source: COW) { id } }",
document: document
)
end
end
end
describe "when passed no query string or document" do
it 'returns an error to the client' do
res = GraphQL::Query.new(
schema,
variables: query_variables,
operation_name: operation_name
).result
assert_equal 1, res["errors"].length
assert_equal "No query string was present", res["errors"][0]["message"]
end
it 'can be assigned later' do
query = GraphQL::Query.new(
schema,
variables: query_variables,
operation_name: operation_name
)
query.query_string = '{ __type(name: """Cheese""") { name } }'
assert_equal "Cheese", query.result["data"] ["__type"]["name"]
end
end
describe "when passed a query_string with an invalid type" do
it "returns an error to the client" do
assert_raises(ArgumentError) {
GraphQL::Query.new(schema, {"default" => "{ fromSource(source: COW) { id } }"})
}
end
end
describe "when passed a query with an invalid type" do
it "returns an error to the client" do
assert_raises(ArgumentError) {
GraphQL::Query.new(schema, query: {"default" => "{ fromSource(source: COW) { id } }"})
}
end
end
describe "#operation_name" do
describe "when provided" do
let(:query_string) { <<-GRAPHQL
query q1 { cheese(id: 1) { flavor } }
query q2 { cheese(id: 2) { flavor } }
GRAPHQL
}
let(:operation_name) { "q2" }
it "returns the provided name" do
assert_equal "q2", query.operation_name
end
end
describe "when inferred" do
let(:query_string) { <<-GRAPHQL
query q3 { cheese(id: 3) { flavor } }
GRAPHQL
}
it "returns nil" do
assert_nil query.operation_name
end
end
describe "#selected_operation_name" do
describe "when an operation isprovided" do
let(:query_string) { <<-GRAPHQL
query q1 { cheese(id: 1) { flavor } }
query q2 { cheese(id: 2) { flavor } }
GRAPHQL
}
let(:operation_name) { "q2" }
it "returns the provided name" do
assert_equal "q2", query.selected_operation_name
end
end
describe "when operation is inferred" do
let(:query_string) { <<-GRAPHQL
query q3 { cheese(id: 3) { flavor } }
GRAPHQL
}
it "returns the inferred operation name" do
assert_equal "q3", query.selected_operation_name
end
end
describe "when there are no operations" do
let(:query_string) { <<-GRAPHQL
# Only Comments
# In this Query
GRAPHQL
}
it "returns the inferred operation name" do
assert_nil query.selected_operation_name
end
end
end
describe "assigning operation_name=" do
let(:query_string) { <<-GRAPHQL
query q3 { manchego: cheese(id: 3) { flavor } }
query q2 { gouda: cheese(id: 2) { flavor } }
GRAPHQL
}
it "runs the assigned name" do
query = GraphQL::Query.new(Dummy::Schema, query_string, operation_name: "q3")
query.operation_name = "q2"
res = query.result
assert_equal "Gouda", res["data"]["gouda"]["flavor"]
end
end
end
describe "when passed a document instance" do
let(:query) { GraphQL::Query.new(
schema,
document: document,
variables: query_variables,
operation_name: operation_name
)}
it "runs the query using the already parsed document" do
expected = {"data"=> {
"brie" => { "flavor" => "Brie", "taste" => "Brie" },
"cheese" => {
"__typename" => "Cheese",
"id" => 2,
"flavor" => "Gouda",
"fatContent" => 0.3,
"cheeseKind" => "Gouda",
},
"fromSource" => [{ "id" => 1 }, {"id" => 2}],
"fromSheep"=>[{"id"=>3}],
"firstSheep" => { "__typename" => "Cheese", "flavor" => "Manchego" },
"favoriteEdible"=>{"__typename"=>"Milk", "fatContent"=>0.04},
}}
assert_equal(expected, result)
end
end
describe '#result' do
it "returns fields on objects" do
expected = {"data"=> {
"brie" => { "flavor" => "Brie", "taste" => "Brie" },
"cheese" => {
"__typename" => "Cheese",
"id" => 2,
"flavor" => "Gouda",
"fatContent" => 0.3,
"cheeseKind" => "Gouda",
},
"fromSource" => [{ "id" => 1 }, {"id" => 2}],
"fromSheep"=>[{"id"=>3}],
"firstSheep" => { "__typename" => "Cheese", "flavor" => "Manchego" },
"favoriteEdible"=>{"__typename"=>"Milk", "fatContent"=>0.04},
}}
assert_equal(expected, result)
end
describe "when it hits null objects" do
let(:query_string) {%|
{
maybeNull {
cheese {
flavor,
similarCheese(source: [SHEEP]) { flavor }
}
}
}
|}
it "skips null objects" do
expected = {"data"=> {
"maybeNull" => { "cheese" => nil }
}}
assert_equal(expected, result)
end
end
describe "queries in execute_mutation hooks" do
module ErrorLogTrace
ERROR_LOG = []
def execute_multiplex(multiplex:)
super
ensure
multiplex.queries.each do |q|
ERROR_LOG << q.result["errors"]
end
end
end
let(:schema) {
Class.new(Dummy::Schema) {
trace_with(ErrorLogTrace)
}
}
before do
ErrorLogTrace::ERROR_LOG.clear
end
it "can access #result" do
result
assert_equal [nil], ErrorLogTrace::ERROR_LOG
end
it "can access result from an unhandled error" do
query = GraphQL::Query.new(schema, "{ error }")
assert_raises RuntimeError do
query.result
end
assert_equal [nil], ErrorLogTrace::ERROR_LOG
end
it "can access result from an handled error" do
query = GraphQL::Query.new(schema, "{ executionError }")
query.result
expected_err = {
"message" => "There was an execution error",
"locations" => [{"line"=>1, "column"=>3}],
"path" => ["executionError"]
}
assert_equal [[expected_err]], ErrorLogTrace::ERROR_LOG
end
it "can access static validation errors" do
query = GraphQL::Query.new(schema, "{ noField }")
query.result
expected_err = {
"message" => "Field 'noField' doesn't exist on type 'Query'",
"locations" => [{"line"=>1, "column"=>3}],
"path" => ["query", "noField"],
"extensions" => {"code"=>"undefinedField", "typeName"=>"Query", "fieldName"=>"noField"},
}
assert_equal [[expected_err]], ErrorLogTrace::ERROR_LOG
end
end
describe "when an error propagated through execution" do
module ExtensionsTrace
LOG = []
def execute_multiplex(multiplex:)
super
ensure
multiplex.queries.each do |q|
q.result["extensions"] = { "a" => 1 }
LOG << :ok
end
end
end
let(:schema) {
Class.new(Dummy::Schema) {
trace_with(ExtensionsTrace)
}
}
it "can add to extensions" do
ExtensionsTrace::LOG.clear
assert_raises(RuntimeError) do
schema.execute "{ error }"
end
assert_equal [:ok], ExtensionsTrace::LOG
end
end
end
describe '#executed?' do
it "returns false if the query hasn't been executed" do
refute query.executed?
end
it "returns true if the query has been executed" do
query.result
assert query.executed?
end
end
it "uses root_value as the object for the root type" do
result = GraphQL::Query.new(schema, '{ root }', root_value: "I am root").result
assert_equal 'I am root', result.fetch('data').fetch('root')
end
it "exposes fragments" do
assert_equal(GraphQL::Language::Nodes::FragmentDefinition, query.fragments["cheeseFields"].class)
end
it "exposes the original string" do
assert_equal(query_string, query.query_string)
end
describe "merging fragments with different keys" do
let(:query_string) { %|
query getCheeseFieldsThroughDairy {
... cheeseFrag3
dairy {
...flavorFragment
...fatContentFragment
}
}
fragment flavorFragment on Dairy {
cheese {
flavor
}
milks {
id
}
}
fragment fatContentFragment on Dairy {
cheese {
fatContent
}
milks {
fatContent
}
}
fragment cheeseFrag1 on Query {
cheese(id: 1) {
id
}
}
fragment cheeseFrag2 on Query {
cheese(id: 1) {
flavor
}
}
fragment cheeseFrag3 on Query {
... cheeseFrag2
... cheeseFrag1
}
|}
it "should include keys from each fragment" do
expected = {"data" => {
"dairy" => {
"cheese" => {
"flavor" => "Brie",
"fatContent" => 0.19
},
"milks" => [
{
"id" => "1",
"fatContent" => 0.04,
}
],
},
"cheese" => {
"id" => 1,
"flavor" => "Brie"
},
}}
assert_equal(expected, result)
end
end
describe "field argument default values" do
let(:query_string) {%|
query getCheeses(
$search: [DairyProductInput]
$searchWithDefault: [DairyProductInput] = [{source: COW}]
){
noVariable: searchDairy(product: $search) {
... cheeseFields
}
noArgument: searchDairy {
... cheeseFields
}
variableDefault: searchDairy(product: $searchWithDefault) {
... cheeseFields
}
convertedDefault: fromSource {
... cheeseFields
}
}
fragment cheeseFields on Cheese { flavor }
|}
it "has a default value" do
default_value = schema.query.fields["searchDairy"].arguments["product"].default_value
default_source = default_value[0][:source]
assert_equal("SHEEP", default_source)
end
describe "when a variable is used, but not provided" do
it "uses the default_value" do
assert_equal("Manchego", result["data"]["noVariable"]["flavor"])
end
end
describe "when the argument isn't passed at all" do
it "uses the default value" do
assert_equal("Manchego", result["data"]["noArgument"]["flavor"])
end
end
describe "when the variable has a default" do
it "uses the variable default" do
assert_equal("Brie", result["data"]["variableDefault"]["flavor"])
end
end
describe "when the variable has a default needing conversion" do
it "uses the converted variable default" do
assert_equal([{"flavor" => "Brie"}, {"flavor" => "Gouda"}], result["data"]["convertedDefault"])
end
end
end
describe "query variables" do
let(:query_string) {%|
query getCheese($cheeseId: Int!){
cheese(id: $cheeseId) { flavor }
}
|}
describe "when they can't be coerced" do
let(:query_variables) { {"cheeseId" => "2"} }
it "raises an error" do
expected = {
"errors" => [
{
"message" => "Variable $cheeseId of type Int! was provided invalid value",
"locations"=>[{ "line" => 2, "column" => 23 }],
"extensions" => {
"value" => "2",
"problems" => [{ "path" => [], "explanation" => 'Could not coerce value "2" to Int' }]
}
}
]
}
assert_equal(expected, result)
end
end
describe "when they aren't provided" do
let(:query_variables) { {} }
it "raises an error" do
expected = {
"errors" => [
{
"message" => "Variable $cheeseId of type Int! was provided invalid value",
"locations" => [{"line" => 2, "column" => 23}],
"extensions" => {
"value" => nil,
"problems" => [{ "path" => [], "explanation" => "Expected value to not be null" }]
}
}
]
}
assert_equal(expected, result)
end
end
describe "when they are non-null and provided a null value" do
let(:query_variables) { { "cheeseId" => nil } }
it "raises an error" do
expected = {
"errors" => [
{
"message" => "Variable $cheeseId of type Int! was provided invalid value",
"locations" => [{"line" => 2, "column" => 23}],
"extensions" => {
"value" => nil,
"problems" => [{ "path" => [], "explanation" => "Expected value to not be null" }]
}
}
]
}
assert_equal(expected, result)
end
end
describe "when they're a string" do
let(:query_variables) { '{ "var" : 1 }' }
it "raises an error" do
assert_raises(ArgumentError) { result }
end
end
describe "default values" do
let(:query_string) {%|
query getCheese($cheeseId: Int = 3){
cheese(id: $cheeseId) { id, flavor }
}
|}
describe "when no value is provided" do
let(:query_variables) { {} }
it "uses the default" do
assert(3, result["data"]["cheese"]["id"])
assert("Manchego", result["data"]["cheese"]["flavor"])
end
end
describe "when a value is provided" do
it "uses the provided variable" do
assert(2, result["data"]["cheese"]["id"])
assert("Gouda", result["data"]["cheese"]["flavor"])
end
end
describe "when complex values" do
let(:query_variables) { {"search" => [{"source" => "COW"}]} }
let(:query_string) {%|
query getCheeses($search: [DairyProductInput]!){
cow: searchDairy(product: $search) {
... on Cheese {
flavor
}
}
}
|}
it "coerces recursively" do
assert_equal("Brie", result["data"]["cow"]["flavor"])
end
end
end
describe "when given as an object type and accessed in ruby" do
it "returns an error to the client and is an empty hash" do
result = schema.execute(<<~GRAPHQL)
query($ch: Cheese) {
__typename
}
GRAPHQL
expected_messages = [
"Cheese isn't a valid input type (on $ch)",
"Variable $ch is declared by anonymous query but not used",
]
assert_equal expected_messages, result["errors"].map { |err| err["message"] }
assert_equal({}, result.query.variables.to_h)
end
end
end
describe "max_depth" do
let(:query_string) {
<<-GRAPHQL
{
cheese(id: 1) {
similarCheese(source: SHEEP) {
similarCheese(source: SHEEP) {
similarCheese(source: SHEEP) {
similarCheese(source: SHEEP) {
id
}
}
}
}
}
}
GRAPHQL
}
it "defaults to the schema's max_depth" do
# Constrained by schema's setting of 5
assert_equal 1, result["errors"].length
end
describe "overriding max_depth" do
let(:query) {
GraphQL::Query.new(
schema,
query_string,
variables: query_variables,
operation_name: operation_name,
max_depth: 12
)
}
it "overrides the schema's max_depth" do
assert result["data"].key?("cheese")
assert_nil result["errors"]
end
end
end
describe "#provided_variables" do
it "returns the originally-provided object" do
assert_equal({"cheeseId" => 2}, query.provided_variables)
end
end
describe "parse errors" do
let(:invalid_query_string) {
<<-GRAPHQL
{
getStuff
nonsense
This is broken 1
}
GRAPHQL
}
it "adds an entry to the errors key" do
res = schema.execute(" { ")
assert_equal 1, res["errors"].length
if USING_C_PARSER
expected_err = "syntax error, unexpected end of file at [1, 2]"
else
expected_err = "Expected NAME, actual: (none) (\" \") at [1, 2]"
end
expected_locations = [{"line" => 1, "column" => 2}]
assert_equal expected_err, res["errors"][0]["message"]
assert_equal expected_locations, res["errors"][0]["locations"]
res = schema.execute("{")
assert_equal 1, res["errors"].length
if USING_C_PARSER
expected_err = "syntax error, unexpected end of file at [1, 1]"
else
expected_err = "Expected NAME, actual: (none) (\"\") at [1, 1]"
end
expected_locations = [{"line" => 1, "column" => 1}]
assert_equal expected_err, res["errors"][0]["message"]
assert_equal expected_locations, res["errors"][0]["locations"]
res = schema.execute(invalid_query_string)
assert_equal 1, res["errors"].length
expected_error = if USING_C_PARSER
"syntax error, unexpected INT (\"1\") at [4, 26]"
else
%|Expected NAME, actual: INT ("1") at [4, 26]|
end
assert_equal expected_error, res["errors"][0]["message"]
assert_equal({"line" => 4, "column" => 26}, res["errors"][0]["locations"][0])
end
it "can be configured to raise" do
raise_schema = Class.new(schema) do
def self.parse_error(err, ctx)
raise err
end
end
assert_raises(GraphQL::ParseError) {
raise_schema.execute(invalid_query_string)
}
end
end
describe "#mutation?" do
let(:query_string) { <<-GRAPHQL
query Q { __typename }
mutation M { pushValue(value: 1) }
GRAPHQL
}
it "returns true if the selected operation is a mutation" do
query_query = GraphQL::Query.new(schema, query_string, operation_name: "Q")
assert_equal false, query_query.mutation?
assert_equal true, query_query.query?
mutation_query = GraphQL::Query.new(schema, query_string, operation_name: "M")
assert_equal true, mutation_query.mutation?
assert_equal false, mutation_query.query?
end
end
describe "validate: false" do
it "doesn't validate the query" do
invalid_query_string = "{ nonExistantField }"
# Can assign attribute
query = GraphQL::Query.new(schema, invalid_query_string)
query.validate = false
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
# Can pass keyword argument
query = GraphQL::Query.new(schema, invalid_query_string, validate: false)
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
# Can pass `true`
query = GraphQL::Query.new(schema, invalid_query_string, validate: true)
assert_equal false, query.valid?
assert_equal 1, query.static_errors.length
# Can assign attribute after calling methods that use the AST
query = GraphQL::Query.new(schema, invalid_query_string)
assert query.fingerprint
query.validate = false
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
end
it "can't be reassigned after validating" do
query = GraphQL::Query.new(schema, "{ nonExistingField }")
assert query.fingerprint
query.validate = false
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
err = assert_raises ArgumentError do
query.validate = true
end
err2 = assert_raises ArgumentError do
query.validate = false
end
expected_message = "Can't reassign Query#validate= after validation has run, remove this assignment."
assert_equal expected_message, err.message
assert_equal expected_message, err2.message
end
end
describe "static_validator" do
module ZebraRule
def on_field(node, _parent)
if node.name != "zebra"
add_error(GraphQL::StaticValidation::Error.new("Invalid field name", nodes: node))
else
super
end
end
end
it "provides a custom validator for the query" do
validator = GraphQL::StaticValidation::Validator.new(schema: schema, rules: [ZebraRule])
query = GraphQL::Query.new(schema, "{ zebra }")
query.static_validator = validator
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
query = GraphQL::Query.new(schema, "{ zebra }", static_validator: validator)
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
query = GraphQL::Query.new(schema, "{ arbez }", static_validator: validator)
assert_equal false, query.valid?
assert_equal 1, query.static_errors.length
end
it "must be a GraphQL::StaticValidation::Validator" do
invalid_validator = {}
err1 = assert_raises ArgumentError do
GraphQL::Query.new(schema, "{ zebra }", static_validator: invalid_validator)
end
err2 = assert_raises ArgumentError do
GraphQL::Query.new(schema, "{ zebra }")
query.static_validator = invalid_validator
end
expected_message = "Expected a `GraphQL::StaticValidation::Validator` instance."
assert_equal expected_message, err1.message
assert_equal expected_message, err2.message
end
it "can't be reassigned after validating" do
query = GraphQL::Query.new(schema, "{ zebra }")
query.static_validator = GraphQL::StaticValidation::Validator.new(schema: schema, rules: [ZebraRule])
assert_equal true, query.valid?
assert_equal 0, query.static_errors.length
err = assert_raises ArgumentError do
query.static_validator = GraphQL::StaticValidation::Validator.new(schema: schema, rules: [ZebraRule])
end
expected_message = "Can't reassign Query#static_validator= after validation has run, remove this assignment."
assert_equal expected_message, err.message
end
end
describe "validating with optional arguments and variables: nil" do
it "works" do
query_str = <<-GRAPHQL
query($expiresAfter: Time) {
searchDairy(expiresAfter: $expiresAfter) {
__typename
}
}
GRAPHQL
query = GraphQL::Query.new(schema, query_str, variables: nil)
assert query.valid?
end
end
describe 'NullValue type arguments' do
let(:schema_definition) {
<<-GRAPHQL
type Query {
foo(id: [ID]): Int
}
GRAPHQL
}
let(:expected_args) { [] }
let(:default_resolver) do
{
'Query' => { 'foo' => ->(_obj, args, _ctx) { expected_args.push(args); 1 } },
}
end
let(:schema) { GraphQL::Schema.from_definition(schema_definition, default_resolve: default_resolver) }
it 'sets argument to nil when null is passed' do
query = <<-GRAPHQL
{
foo(id: null)
}
GRAPHQL
schema.execute(query)
assert(expected_args.first.key?(:id))
assert_nil(expected_args.first[:id])
end
it 'sets argument to nil when nil is passed via variable' do
query = <<-GRAPHQL
query baz($id: [ID]) {
foo(id: $id)
}
GRAPHQL
schema.execute(query, variables: { 'id' => nil })
assert(expected_args.first.key?(:id))
assert_nil(expected_args.first[:id])
end
it 'sets argument to [nil] when [null] is passed' do
query = <<-GRAPHQL
{
foo(id: [null])
}
GRAPHQL
schema.execute(query)
assert(expected_args.first.key?(:id))
assert_equal([nil], expected_args.first[:id])
end
it 'sets argument to [nil] when [nil] is passed via variable' do
query = <<-GRAPHQL
query baz($id: [ID]) {
foo(id: $id)
}
GRAPHQL
schema.execute(query, variables: { 'id' => [nil] })
assert(expected_args.first.key?(:id))
assert_equal([nil], expected_args.first[:id])
end
end
it "Accepts a passed-in warden" do
schema_class = Class.new(Jazz::Schema) do
def self.visible?(member, ctx)
false
end
end
warden = GraphQL::Schema::Warden.new(schema: schema_class, context: {})
res = Jazz::Schema.execute("{ __typename } ", warden: warden)
assert_equal ["Schema is not configured for queries"], res["errors"].map { |e| e["message"] }
end
describe "arguments_for" do
it "returns symbol-keyed, underscored hashes, regardless of literal or variable values" do
query_str = "
query($product: [DairyProductInput!]!) {
f1: searchDairy(product: [{source: SHEEP}]) {
__typename
}
f2: searchDairy(product: $product) {
__typename
}
}
"
query = GraphQL::Query.new(Dummy::Schema, query_str, variables: { "product" => [{"source" => "SHEEP"}]})
field_defn = Dummy::Schema.get_field("Query", "searchDairy")
node_1 = query.document.definitions.first.selections.first
node_2 = query.document.definitions.first.selections.last
argument_contexts = {
"literals" => node_1,
"variables" => node_2,
}
argument_contexts.each do |context_name, ast_node|
detailed_args = query.arguments_for(ast_node, field_defn)
assert_instance_of GraphQL::Execution::Interpreter::Arguments, detailed_args
args = detailed_args.keyword_arguments
assert_instance_of Hash, args, "it makes a hash for #{context_name}"
assert_equal [:product], args.keys, "it has a single symbol key for #{context_name}"
product_value = args[:product]
assert_instance_of Array, product_value
product_value_item = product_value[0]
assert_instance_of Dummy::DairyProductInput, product_value_item, "it initializes an input object for #{context_name}"
assert_equal "SHEEP", product_value_item[:source], "it adds the input value for #{context_name}"
# Default values are merged in
expected_h = {
source: "SHEEP",
origin_dairy: "Sugar Hollow Dairy",
fat_content: 0.3,
organic: false,
order_by: { direction: "ASC"}
}
assert_equal expected_h, product_value_item.to_h, "it makes a hash with defaults for #{context_name}"
end
end
it "returns argument metadata" do
query_str = <<-GRAPHQL
query($fatContent: Float, $organic: Boolean = false) {
searchDairy(product: [{source: SHEEP, fatContent: $fatContent, organic: $organic}]) {
__typename
}
}
GRAPHQL
query = GraphQL::Query.new(Dummy::Schema, query_str, variables: { "product" => [{"source" => "SHEEP"}]})
field_defn = Dummy::Schema.get_field("Query", "searchDairy")
node_1 = query.document.definitions.first
.selections.first
.arguments.first
.value.first
input_obj_defn = field_defn.arguments["product"].type.unwrap
detailed_args = query.arguments_for(node_1, input_obj_defn)
# Literal value
source_arg_value = detailed_args.argument_values[:source]
assert_equal false, source_arg_value.default_used?
assert_equal "SHEEP", detailed_args[:source]
assert_equal "SHEEP", detailed_args.fetch(:source)
assert_equal "SHEEP", source_arg_value.value
assert_equal "source", source_arg_value.definition.graphql_name
# Unused optional variable, uses default
fat_content_arg_value = detailed_args.argument_values[:fat_content]
assert_equal true, fat_content_arg_value.default_used?
assert_equal 0.3, detailed_args[:fat_content]
assert_equal 0.3, fat_content_arg_value.value
assert_equal "fatContent", fat_content_arg_value.definition.graphql_name
# Variable value
organic_arg_value = detailed_args.argument_values[:organic]
assert_equal false, organic_arg_value.default_used?
assert_equal false, detailed_args[:organic]
assert_equal false, organic_arg_value.value
assert_equal "organic", organic_arg_value.definition.graphql_name
# Absent value, uses default
order_by_argument_value = detailed_args.argument_values[:order_by]
assert_equal true, order_by_argument_value.default_used?
assert_equal({direction: "ASC"}, detailed_args[:order_by].to_h)
assert_equal({direction: "ASC"}, order_by_argument_value.value.to_h)
assert_equal "order_by", order_by_argument_value.definition.graphql_name
assert_equal [source_arg_value, fat_content_arg_value, organic_arg_value, order_by_argument_value, detailed_args.argument_values[:origin_dairy]].to_set,
detailed_args.each_value.to_set
end
it "provides access to nested input objects" do
query_str = <<-GRAPHQL
query($fatContent: Float, $organic: Boolean = false, $products: [DairyProductInput!]!) {
searchDairy(product: $products) {
__typename
}
}
GRAPHQL
query = GraphQL::Query.new(Dummy::Schema, query_str, variables: { "products" => [{"source" => "SHEEP"}]})
field_defn = Dummy::Schema.get_field("Query", "searchDairy")
node = query.document.definitions.first
.selections.first
args = query.arguments_for(node, field_defn)
product_args = args.argument_values[:product].value
first_product_args = product_args.first.arguments
source_arg_value = first_product_args.argument_values[:source]
assert_equal false, source_arg_value.default_used?
assert_equal "SHEEP", source_arg_value.value
assert_equal "source", source_arg_value.definition.graphql_name
order_by_argument_value = first_product_args.argument_values[:order_by]
assert_equal true, order_by_argument_value.default_used?
assert_equal({direction: "ASC"}, order_by_argument_value.value.to_h)
assert_equal "order_by", order_by_argument_value.definition.graphql_name
end
end
describe "when provided input object field names are not unique" do
let(:variables) { {} }
let(:result) { Dummy::Schema.execute(query_string, variables: variables) }
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | true |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/authorization_spec.rb | spec/graphql/authorization_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Authorization" do
module AuthTest
class Box
attr_reader :value
def initialize(value:)
@value = value
end
end
class BaseArgument < GraphQL::Schema::Argument
def visible?(context)
super && (context[:hide] ? @name != "hidden" : true)
end
def authorized?(parent_object, value, context)
super && parent_object != :hide2
end
end
class BaseInputObjectArgument < BaseArgument
def authorized?(parent_object, value, context)
super && parent_object != :hide3
end
end
class BaseInputObject < GraphQL::Schema::InputObject
argument_class BaseInputObjectArgument
end
class BaseField < GraphQL::Schema::Field
argument_class BaseArgument
def visible?(context)
super && (context[:hide] ? @name != "hidden" : true)
end
def authorized?(object, args, context)
if object == :raise
raise GraphQL::UnauthorizedFieldError.new("raised authorized field error", object: object)
end
return Box.new(value: context[:lazy_field_authorized]) if context.key?(:lazy_field_authorized)
super && object != :hide && object != :replace
end
end
class BaseObject < GraphQL::Schema::Object
field_class BaseField
end
module BaseInterface
include GraphQL::Schema::Interface
end
class BaseEnumValue < GraphQL::Schema::EnumValue
def initialize(*args, role: nil, **kwargs)
@role = role
super(*args, **kwargs)
end
def visible?(context)
super && (context[:hide] ? @role != :hidden : true)
end
def authorized?(context)
super && (context[:authorized] ? true : @role != :unauthorized)
end
end
class BaseEnum < GraphQL::Schema::Enum
enum_value_class(BaseEnumValue)
end
module HiddenInterface
include BaseInterface
definition_methods do
def visible?(ctx)
super && !ctx[:hide]
end
def resolve_type(obj, ctx)
HiddenObject
end
end
end
module HiddenDefaultInterface
if GraphQL::Schema.use_visibility_profile?
include HiddenInterface
else
# Warden will detect no possible types
include BaseInterface
end
def self.resolve_type(obj, ctx)
HiddenObject
end
end
class HiddenObject < BaseObject
implements HiddenInterface
implements HiddenDefaultInterface
def self.visible?(ctx)
super && !ctx[:hide]
end
field :some_field, String
end
class RelayObject < BaseObject
def self.visible?(ctx)
super && !ctx[:hidden_relay]
end
def self.authorized?(_val, ctx)
super && !ctx[:unauthorized_relay]
end
field :some_field, String
end
class UnauthorizedObject < BaseObject
def self.authorized?(value, context)
if context[:raise]
raise GraphQL::UnauthorizedError.new("raised authorized object error", object: value.object)
end
super && !context[:hide]
end
field :value, String, null: false, method: :itself
end
class UnauthorizedBox < BaseObject
# Hide `"a"`
def self.authorized?(value, context)
super && value != "a"
end
field :value, String, null: false, method: :itself
end
module UnauthorizedInterface
include BaseInterface
def self.resolve_type(obj, ctx)
if obj.is_a?(String)
UnauthorizedCheckBox
else
raise "Unexpected value: #{obj.inspect}"
end
end
end
class UnauthorizedCheckBox < BaseObject
implements UnauthorizedInterface
# This authorized check returns a lazy object, it should be synced by the runtime.
def self.authorized?(value, context)
if !value.is_a?(String)
raise "Unexpected box value: #{value.inspect}"
end
is_authed = super && value != "a"
# Make it many levels nested just to make sure we support nested lazy objects
Box.new(value: Box.new(value: Box.new(value: Box.new(value: is_authed))))
end
field :value, String, null: false, method: :itself
end
class IntegerObject < BaseObject
def self.authorized?(obj, ctx)
if !obj.is_a?(Integer)
raise "Unexpected IntegerObject: #{obj}"
end
is_allowed = !(ctx[:unauthorized_relay] || obj == ctx[:exclude_integer])
Box.new(value: Box.new(value: is_allowed))
end
field :value, Integer, null: false, method: :itself
end
class IntegerObjectEdge < GraphQL::Types::Relay::BaseEdge
node_type(IntegerObject)
end
class IntegerObjectConnection < GraphQL::Types::Relay::BaseConnection
edge_type(IntegerObjectEdge)
end
# This object responds with `replaced => false`,
# but if its replacement value is used, it gives `replaced => true`
class Replaceable
def replacement
{ replaced: true }
end
def replaced
false
end
end
class ReplacedObject < BaseObject
def self.authorized?(obj, ctx)
super && !ctx[:replace_me]
end
field :replaced, Boolean, null: false
end
class LandscapeFeature < BaseEnum
value "MOUNTAIN"
value "STREAM", role: :unauthorized
value "FIELD"
value "TAR_PIT", role: :hidden
end
class Query < BaseObject
def self.authorized?(obj, ctx)
!ctx[:query_unauthorized]
end
field :hidden, Integer, null: false
field :unauthorized, Integer, method: :itself
field :int2, Integer do
argument :int, Integer, required: false
argument :hidden, Integer, required: false
argument :unauthorized, Integer, required: false
end
def int2(**args)
args[:unauthorized] || 1
end
field :landscape_feature, LandscapeFeature, null: false do
argument :string, String, required: false
argument :enum, LandscapeFeature, required: false
end
def landscape_feature(string: nil, enum: nil)
string || enum
end
field :landscape_features, [LandscapeFeature], null: false do
argument :strings, [String], required: false
argument :enums, [LandscapeFeature], required: false
end
def landscape_features(strings: [], enums: [])
strings + enums
end
def empty_array; []; end
field :hidden_object, HiddenObject, null: false, resolver_method: :itself
field :hidden_interface, HiddenInterface, null: false, resolver_method: :itself
field :hidden_default_interface, HiddenDefaultInterface, null: false, resolver_method: :itself
field :hidden_connection, RelayObject.connection_type, null: :false, resolver_method: :empty_array
field :hidden_edge, RelayObject.edge_type, null: :false, resolver_method: :edge_object
field :unauthorized_object, UnauthorizedObject, resolver_method: :itself
field :unauthorized_connection, RelayObject.connection_type, null: false, resolver_method: :array_with_item
field :unauthorized_edge, RelayObject.edge_type, null: false, resolver_method: :edge_object
def edge_object
OpenStruct.new(node: 100)
end
def array_with_item
[1]
end
field :unauthorized_lazy_box, UnauthorizedBox do
argument :value, String
end
def unauthorized_lazy_box(value:)
# Make it extra nested, just for good measure.
Box.new(value: Box.new(value: value))
end
field :unauthorized_list_items, [UnauthorizedObject]
def unauthorized_list_items
[self, self]
end
field :unauthorized_lazy_check_box, UnauthorizedCheckBox, resolver_method: :unauthorized_lazy_box do
argument :value, String
end
field :unauthorized_interface, UnauthorizedInterface, resolver_method: :unauthorized_lazy_box do
argument :value, String
end
field :unauthorized_lazy_list_interface, [UnauthorizedInterface, null: true]
def unauthorized_lazy_list_interface
["z", Box.new(value: Box.new(value: "z2")), "a", Box.new(value: "a")]
end
field :integers, IntegerObjectConnection, null: false
def integers
[1,2,3]
end
field :lazy_integers, IntegerObjectConnection, null: false
def lazy_integers
Box.new(value: Box.new(value: [1,2,3]))
end
field :replaced_object, ReplacedObject, null: false
def replaced_object
Replaceable.new
end
end
class DoHiddenStuff < GraphQL::Schema::RelayClassicMutation
def self.visible?(ctx)
super && (ctx[:hidden_mutation] ? false : true)
end
end
class DoHiddenStuff2 < GraphQL::Schema::Mutation
def self.visible?(ctx)
super && !ctx[:hidden_mutation]
end
field :some_return_field, String
end
class DoUnauthorizedStuff < GraphQL::Schema::RelayClassicMutation
def self.authorized?(obj, ctx)
super && (ctx[:unauthorized_mutation] ? false : true)
end
end
class Mutation < BaseObject
field :do_hidden_stuff, mutation: DoHiddenStuff
field :do_hidden_stuff2, mutation: DoHiddenStuff2
field :do_unauthorized_stuff, mutation: DoUnauthorizedStuff
end
class Nothing < GraphQL::Schema::Directive
locations(FIELD)
def self.visible?(ctx)
!!ctx[:show_nothing_directive]
end
end
class Schema < GraphQL::Schema
query(Query)
mutation(Mutation)
directive(Nothing)
use GraphQL::Schema::Warden if ADD_WARDEN
lazy_resolve(Box, :value)
def self.unauthorized_object(err)
if err.object.respond_to?(:replacement)
err.object.replacement
elsif err.object == :replace
33
elsif err.object == :raise_from_object
raise GraphQL::ExecutionError, err.message
else
raise GraphQL::ExecutionError, "Unauthorized #{err.type.graphql_name}: #{err.object.inspect}"
end
end
end
class SchemaWithFieldHook < GraphQL::Schema
query(Query)
use GraphQL::Schema::Warden if ADD_WARDEN
lazy_resolve(Box, :value)
def self.unauthorized_field(err)
if err.object == :replace
42
elsif err.object == :raise
raise GraphQL::ExecutionError, "#{err.message} in field #{err.field.graphql_name}"
else
raise GraphQL::ExecutionError, "Unauthorized field #{err.field.graphql_name} on #{err.type.graphql_name}: #{err.object}"
end
end
end
end
def auth_execute(*args, **kwargs)
AuthTest::Schema.execute(*args, **kwargs)
end
describe "applying the visible? method" do
it "works in queries" do
res = auth_execute(" { int int2 } ", context: { hide: true })
assert_equal 1, res["errors"].size
end
it "applies return type visibility to fields" do
error_queries = {
"hiddenObject" => "{ hiddenObject { __typename } }",
"hiddenInterface" => "{ hiddenInterface { __typename } }",
"hiddenDefaultInterface" => "{ hiddenDefaultInterface { __typename } }",
}
error_queries.each do |name, q|
hidden_res = auth_execute(q, context: { hide: true})
assert_equal ["Field '#{name}' doesn't exist on type 'Query'#{name == "hiddenDefaultInterface" ? "" : " (Did you mean `hiddenConnection`?)"}"], hidden_res["errors"].map { |e| e["message"] }
visible_res = auth_execute(q)
# Both fields exist; the interface resolves to the object type, though
assert_equal "HiddenObject", visible_res["data"][name]["__typename"]
end
end
it "uses the mutation for derived fields, inputs and outputs" do
query = "mutation { doHiddenStuff(input: {}) { __typename } }"
res = auth_execute(query, context: { hidden_mutation: true })
assert_equal ["Field 'doHiddenStuff' doesn't exist on type 'Mutation'"], res["errors"].map { |e| e["message"] }
# `#resolve` isn't implemented, so this errors out:
assert_raises GraphQL::RequiredImplementationMissingError do
auth_execute(query)
end
introspection_q = <<-GRAPHQL
{
t1: __type(name: "DoHiddenStuffInput") { name }
t2: __type(name: "DoHiddenStuffPayload") { name }
}
GRAPHQL
hidden_introspection_res = auth_execute(introspection_q, context: { hidden_mutation: true })
assert_nil hidden_introspection_res["data"]["t1"]
assert_nil hidden_introspection_res["data"]["t2"]
visible_introspection_res = auth_execute(introspection_q)
assert_equal "DoHiddenStuffInput", visible_introspection_res["data"]["t1"]["name"]
assert_equal "DoHiddenStuffPayload", visible_introspection_res["data"]["t2"]["name"]
end
it "works with Schema::Mutation" do
query = "mutation { doHiddenStuff2 { __typename } }"
res = auth_execute(query, context: { hidden_mutation: true })
assert_equal ["Field 'doHiddenStuff2' doesn't exist on type 'Mutation'"], res["errors"].map { |e| e["message"] }
# `#resolve` isn't implemented, so this errors out:
assert_raises GraphQL::RequiredImplementationMissingError do
auth_execute(query)
end
end
it "uses the base type for edges and connections" do
query = <<-GRAPHQL
{
hiddenConnection { __typename }
hiddenEdge { __typename }
}
GRAPHQL
hidden_res = auth_execute(query, context: { hidden_relay: true })
assert_equal 2, hidden_res["errors"].size
visible_res = auth_execute(query)
assert_equal "RelayObjectConnection", visible_res["data"]["hiddenConnection"]["__typename"]
assert_equal "RelayObjectEdge", visible_res["data"]["hiddenEdge"]["__typename"]
end
it "treats hidden enum values as non-existent, even in lists" do
hidden_res_1 = auth_execute <<-GRAPHQL, context: { hide: true }
{
landscapeFeature(enum: TAR_PIT)
}
GRAPHQL
assert_equal ["Argument 'enum' on Field 'landscapeFeature' has an invalid value (TAR_PIT). Expected type 'LandscapeFeature'."], hidden_res_1["errors"].map { |e| e["message"] }
hidden_res_2 = auth_execute <<-GRAPHQL, context: { hide: true }
{
landscapeFeatures(enums: [STREAM, TAR_PIT])
}
GRAPHQL
assert_equal ["Argument 'enums' on Field 'landscapeFeatures' has an invalid value ([STREAM, TAR_PIT]). Expected type '[LandscapeFeature!]'."], hidden_res_2["errors"].map { |e| e["message"] }
success_res = auth_execute <<-GRAPHQL, context: { hide: false, authorized: true }
{
landscapeFeature(enum: TAR_PIT)
landscapeFeatures(enums: [STREAM, TAR_PIT])
}
GRAPHQL
assert_equal "TAR_PIT", success_res["data"]["landscapeFeature"]
assert_equal ["STREAM", "TAR_PIT"], success_res["data"]["landscapeFeatures"]
end
it "refuses to resolve to hidden enum values" do
expected_class = AuthTest::LandscapeFeature::UnresolvedValueError
assert_raises(expected_class) do
auth_execute <<-GRAPHQL, context: { hide: true }
{
landscapeFeature(string: "TAR_PIT")
}
GRAPHQL
end
assert_raises(expected_class) do
auth_execute <<-GRAPHQL, context: { hide: true }
{
landscapeFeatures(strings: ["STREAM", "TAR_PIT"])
}
GRAPHQL
end
end
it "rejects incoming unauthorized enum values" do
res = auth_execute <<-GRAPHQL, context: { }
{
landscapeFeature(enum: STREAM)
}
GRAPHQL
assert_equal ["Unauthorized LandscapeFeature: \"STREAM\""], res["errors"].map { |e| e["message"] }
end
it "rejects outgoing unauthorized enum values" do
err = assert_raises(AuthTest::LandscapeFeature::UnresolvedValueError) do
auth_execute <<-GRAPHQL, context: { }
{
landscapeFeature(string: "STREAM")
}
GRAPHQL
end
assert_equal "`Query.landscapeFeature` returned `\"STREAM\"` at `landscapeFeature`, but this value was unauthorized. Update the field or resolver to return a different value in this case (or return `nil`).", err.message
end
it "works in introspection" do
res = auth_execute <<-GRAPHQL, context: { hide: true, hidden_mutation: true }
{
query: __type(name: "Query") {
fields {
name
args { name }
}
}
hiddenObject: __type(name: "HiddenObject") { name }
hiddenInterface: __type(name: "HiddenInterface") { name }
landscapeFeatures: __type(name: "LandscapeFeature") { enumValues { name } }
}
GRAPHQL
query_field_names = res["data"]["query"]["fields"].map { |f| f["name"] }
refute_includes query_field_names, "int"
int2_arg_names = res["data"]["query"]["fields"].find { |f| f["name"] == "int2" }["args"].map { |a| a["name"] }
assert_equal ["int", "unauthorized"], int2_arg_names
assert_nil res["data"]["hiddenObject"]
assert_nil res["data"]["hiddenInterface"]
visible_landscape_features = res["data"]["landscapeFeatures"]["enumValues"].map { |v| v["name"] }
assert_equal ["MOUNTAIN", "STREAM", "FIELD"], visible_landscape_features
end
it "works when printing the SDL" do
full_sdl_lines = AuthTest::Schema.to_definition.split("\n")
restricted_sdl_lines = AuthTest::Schema.to_definition(context: { hide: true, hidden_mutation: true, hidden_relay: true }).split("\n")
expected_hidden_lines = [
"Autogenerated return type of DoHiddenStuff2.",
"type DoHiddenStuff2Payload {",
"Autogenerated input type of DoHiddenStuff",
"input DoHiddenStuffInput {",
"Autogenerated return type of DoHiddenStuff.",
"type DoHiddenStuffPayload {",
"interface HiddenDefaultInterface",
"interface HiddenInterface",
"type HiddenObject implements HiddenDefaultInterface & HiddenInterface {",
" doHiddenStuff(",
" Parameters for DoHiddenStuff",
" input: DoHiddenStuffInput!",
" ): DoHiddenStuffPayload",
" doHiddenStuff2: DoHiddenStuff2Payload",
" hidden: Int!",
" hiddenConnection(",
" hiddenDefaultInterface: HiddenDefaultInterface!",
" hiddenEdge: RelayObjectEdge",
" hiddenInterface: HiddenInterface!",
" hiddenObject: HiddenObject!",
" int2(hidden: Int, int: Int, unauthorized: Int): Int"
]
assert_equal expected_hidden_lines, full_sdl_lines.select { |l| l.include?("Hidden") || l.include?("hidden") }
assert_equal [], restricted_sdl_lines.select { |l| l.include?("Hidden") || l.include?("hidden") }
end
it "works with directives" do
query_str = "{ __typename @nothing }"
visible_response = auth_execute(query_str, context: { show_nothing_directive: true })
assert_equal "Query", visible_response["data"]["__typename"]
hidden_response = auth_execute(query_str)
assert_equal ["Directive @nothing is not defined"], hidden_response["errors"].map { |e| e["message"] }
end
end
describe "applying the authorized? method" do
it "halts on unauthorized objects, replacing the object with nil" do
query = "{ unauthorizedObject { __typename } }"
hidden_response = auth_execute(query, context: { hide: true })
assert_nil hidden_response["data"].fetch("unauthorizedObject")
visible_response = auth_execute(query, context: {})
assert_equal({ "__typename" => "UnauthorizedObject" }, visible_response["data"]["unauthorizedObject"])
end
it "halts on unauthorized mutations" do
query = "mutation { doUnauthorizedStuff(input: {}) { __typename } }"
res = auth_execute(query, context: { unauthorized_mutation: true })
assert_nil res["data"].fetch("doUnauthorizedStuff")
assert_raises GraphQL::RequiredImplementationMissingError do
auth_execute(query)
end
end
describe "field level authorization" do
describe "unauthorized field" do
describe "with an unauthorized field hook configured" do
describe "when the hook returns a value" do
it "replaces the response with the return value of the unauthorized field hook" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :replace)
assert_equal 42, response["data"].fetch("unauthorized")
end
end
describe "when the field hook raises an error" do
it "returns nil" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :hide)
assert_nil response["data"].fetch("unauthorized")
end
it "adds the error to the errors key" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :hide)
assert_equal ["Unauthorized field unauthorized on Query: hide"], response["errors"].map { |e| e["message"] }
end
end
describe "when the field authorization resolves lazily" do
it "returns value if authorized" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: 34, context: { lazy_field_authorized: true })
assert_equal 34, response["data"].fetch("unauthorized")
end
it "returns nil if not authorized" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: 34, context: { lazy_field_authorized: false })
assert_nil response["data"].fetch("unauthorized")
assert_equal ["Unauthorized field unauthorized on Query: 34"], response["errors"].map { |e| e["message"] }
end
end
describe "when the field authorization raises an UnauthorizedFieldError" do
it "receives the raised error" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: :raise)
assert_equal ["raised authorized field error in field unauthorized"], response["errors"].map { |e| e["message"] }
end
end
end
describe "with an unauthorized field hook not configured" do
describe "When the object hook replaces the field" do
it "delegates to the unauthorized object hook, which replaces the object" do
query = "{ unauthorized }"
response = AuthTest::Schema.execute(query, root_value: :replace)
assert_equal 33, response["data"].fetch("unauthorized")
end
end
describe "When the object hook raises an error" do
it "returns nil" do
query = "{ unauthorized }"
response = AuthTest::Schema.execute(query, root_value: :hide)
assert_nil response["data"].fetch("unauthorized")
end
it "adds the error to the errors key" do
query = "{ unauthorized }"
response = AuthTest::Schema.execute(query, root_value: :hide)
assert_equal ["Unauthorized Query: :hide"], response["errors"].map { |e| e["message"] }
end
end
end
end
describe "authorized field" do
it "returns the field data" do
query = "{ unauthorized }"
response = AuthTest::SchemaWithFieldHook.execute(query, root_value: 1)
assert_equal 1, response["data"].fetch("unauthorized")
end
end
end
it "halts on unauthorized fields, using the parent object" do
query = "{ unauthorized }"
hidden_response = auth_execute(query, root_value: :hide)
assert_nil hidden_response["data"].fetch("unauthorized")
visible_response = auth_execute(query, root_value: 1)
assert_equal 1, visible_response["data"]["unauthorized"]
end
it "halts on unauthorized arguments, using the parent object" do
query = "{ int2(unauthorized: 5) }"
hidden_response = auth_execute(query, root_value: :hide2)
assert_nil hidden_response["data"].fetch("int2")
visible_response = auth_execute(query)
assert_equal 5, visible_response["data"]["int2"]
end
it "works with edges and connections" do
query = <<-GRAPHQL
{
unauthorizedConnection {
__typename
edges {
__typename
node {
__typename
}
}
nodes {
__typename
}
}
unauthorizedEdge {
__typename
node {
__typename
}
}
}
GRAPHQL
unauthorized_res = auth_execute(query, context: { unauthorized_relay: true })
conn = unauthorized_res["data"].fetch("unauthorizedConnection")
assert_equal "RelayObjectConnection", conn.fetch("__typename")
# This is tricky: the previous behavior was to replace the _whole_
# list with `nil`. This was due to an implementation detail:
# The list field's return value (an array of integers) was wrapped
# _before_ returning, and during this wrapping, a cascading error
# caused the entire field to be nilled out.
#
# In the interpreter, each list item is contained and the error doesn't propagate
# up to the whole list.
#
# Originally, I thought that this was a _feature_ that obscured list entries.
# But really, look at the test below: you don't get this "feature" if
# you use `edges { node }`, so it can't be relied on in any way.
#
# All that to say, in the interpreter, `nodes` and `edges { node }` behave
# the same.
#
# TODO revisit the docs for this.
failed_nodes_value = [nil]
assert_equal failed_nodes_value, conn.fetch("nodes")
assert_equal [{"node" => nil, "__typename" => "RelayObjectEdge"}], conn.fetch("edges")
edge = unauthorized_res["data"].fetch("unauthorizedEdge")
assert_nil edge.fetch("node")
assert_equal "RelayObjectEdge", edge["__typename"]
unauthorized_object_paths = [
["unauthorizedConnection", "edges", 0, "node"],
["unauthorizedConnection", "nodes", 0],
["unauthorizedEdge", "node"]
]
assert_equal unauthorized_object_paths, unauthorized_res["errors"].map { |e| e["path"] }
authorized_res = auth_execute(query)
conn = authorized_res["data"].fetch("unauthorizedConnection")
assert_equal "RelayObjectConnection", conn.fetch("__typename")
assert_equal [{"__typename"=>"RelayObject"}], conn.fetch("nodes")
assert_equal [{"node" => {"__typename" => "RelayObject"}, "__typename" => "RelayObjectEdge"}], conn.fetch("edges")
edge = authorized_res["data"].fetch("unauthorizedEdge")
assert_equal "RelayObject", edge.fetch("node").fetch("__typename")
assert_equal "RelayObjectEdge", edge["__typename"]
end
it "authorizes _after_ resolving lazy objects" do
query = <<-GRAPHQL
{
a: unauthorizedLazyBox(value: "a") { value }
b: unauthorizedLazyBox(value: "b") { value }
}
GRAPHQL
unauthorized_res = auth_execute(query)
assert_nil unauthorized_res["data"].fetch("a")
assert_equal "b", unauthorized_res["data"]["b"]["value"]
end
it "authorizes items in a list" do
query = <<-GRAPHQL
{
unauthorizedListItems { __typename }
}
GRAPHQL
unauthorized_res = auth_execute(query, context: { hide: true })
assert_nil unauthorized_res["data"]["unauthorizedListItems"]
authorized_res = auth_execute(query, context: { hide: false })
assert_equal 2, authorized_res["data"]["unauthorizedListItems"].size
end
it "syncs lazy objects from authorized? checks" do
query = <<-GRAPHQL
{
a: unauthorizedLazyCheckBox(value: "a") { value }
b: unauthorizedLazyCheckBox(value: "b") { value }
}
GRAPHQL
unauthorized_res = auth_execute(query)
assert_nil unauthorized_res["data"].fetch("a")
assert_equal "b", unauthorized_res["data"]["b"]["value"]
# Also, the custom handler was called:
assert_equal ["Unauthorized UnauthorizedCheckBox: \"a\""], unauthorized_res["errors"].map { |e| e["message"] }
end
it "Works for lazy connections" do
query = <<-GRAPHQL
{
lazyIntegers { edges { node { value } } }
}
GRAPHQL
res = auth_execute(query)
assert_equal [1,2,3], res["data"]["lazyIntegers"]["edges"].map { |e| e["node"]["value"] }
end
it "Works for eager connections" do
query = <<-GRAPHQL
{
integers { edges { node { value } } }
}
GRAPHQL
res = auth_execute(query)
assert_equal [1,2,3], res["data"]["integers"]["edges"].map { |e| e["node"]["value"] }
end
it "filters out individual nodes by value" do
query = <<-GRAPHQL
{
integers { edges { node { value } } }
}
GRAPHQL
res = auth_execute(query, context: { exclude_integer: 1 })
assert_equal [nil,2,3], res["data"]["integers"]["edges"].map { |e| e["node"] && e["node"]["value"] }
assert_equal ["Unauthorized IntegerObject: 1"], res["errors"].map { |e| e["message"] }
end
it "works with lazy values / interfaces" do
query = <<-GRAPHQL
query($value: String!){
unauthorizedInterface(value: $value) {
... on UnauthorizedCheckBox {
value
}
}
}
GRAPHQL
res = auth_execute(query, variables: { value: "a"})
assert_nil res["data"]["unauthorizedInterface"]
res2 = auth_execute(query, variables: { value: "b"})
assert_equal "b", res2["data"]["unauthorizedInterface"]["value"]
end
it "works with lazy values / lists of interfaces" do
query = <<-GRAPHQL
{
unauthorizedLazyListInterface {
... on UnauthorizedCheckBox {
value
}
}
}
GRAPHQL
res = auth_execute(query)
# An error from two, values from the others
assert_equal ["Unauthorized UnauthorizedCheckBox: \"a\"", "Unauthorized UnauthorizedCheckBox: \"a\""], res["errors"].map { |e| e["message"] }
assert_equal [{"value" => "z"}, {"value" => "z2"}, nil, nil], res["data"]["unauthorizedLazyListInterface"]
end
describe "with an unauthorized field hook configured" do
it "replaces objects from the unauthorized_object hook" do
query = "{ replacedObject { replaced } }"
res = auth_execute(query, context: { replace_me: true })
assert_equal true, res["data"]["replacedObject"]["replaced"]
res = auth_execute(query, context: { replace_me: false })
assert_equal false, res["data"]["replacedObject"]["replaced"]
end
it "works when the query hook returns false and there's no root object" do
query = "{ __typename }"
res = auth_execute(query)
assert_equal "Query", res["data"]["__typename"]
unauth_res = auth_execute(query, context: { query_unauthorized: true })
assert_equal({
"errors" => [{"message"=>"Unauthorized Query: nil"}],
"data" => nil,
}, unauth_res.to_h)
end
describe "when the object authorization raises an UnauthorizedFieldError" do
it "receives the raised error" do
query = "{ unauthorizedObject { value } }"
response = auth_execute(query, context: { raise: true }, root_value: :raise_from_object)
assert_equal ["raised authorized object error"], response["errors"].map { |e| e["message"] }
end
end
end
end
describe "returning false" do
class FalseSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
def self.authorized?(obj, ctx)
false
end
field :int, Integer, null: false
def int
1
end
end
query(Query)
end
it "works out-of-the-box" do
res = FalseSchema.execute("{ int }")
assert_nil res.fetch("data")
refute res.key?("errors")
end
end
describe "overriding authorized_new" do
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | true |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/directive_spec.rb | spec/graphql/directive_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Directive" do
let(:variables) { {"t" => true, "f" => false} }
let(:result) { Dummy::Schema.execute(query_string, variables: variables) }
describe "on fields" do
let(:query_string) { %|query directives($t: Boolean!, $f: Boolean!) {
cheese(id: 1) {
# plain fields:
skipFlavor: flavor @skip(if: true)
dontSkipFlavor: flavor @skip(if: false)
dontSkipDontIncludeFlavor: flavor @skip(if: false), @include(if: false)
skipAndInclude: flavor @skip(if: true), @include(if: true)
includeFlavor: flavor @include(if: $t)
dontIncludeFlavor: flavor @include(if: $f)
# fields in fragments
... includeIdField
... dontIncludeIdField
... skipIdField
... dontSkipIdField
}
}
fragment includeIdField on Cheese { includeId: id @include(if: true) }
fragment dontIncludeIdField on Cheese { dontIncludeId: id @include(if: false) }
fragment skipIdField on Cheese { skipId: id @skip(if: true) }
fragment dontSkipIdField on Cheese { dontSkipId: id @skip(if: false) }
|
}
describe "child fields" do
let(:query_string) { <<-GRAPHQL
{
__type(name: """
Cheese
""") {
fields { name }
fields @skip(if: true) { isDeprecated }
}
}
GRAPHQL
}
it "skips child fields too" do
first_field = result["data"]["__type"]["fields"].first
assert first_field.key?("name")
assert !first_field.key?("isDeprecated")
end
end
describe "when directive uses argument with default value" do
describe "with false" do
let(:query_string) { <<-GRAPHQL
query($f: Boolean = false) {
cheese(id: 1) {
dontIncludeFlavor: flavor @include(if: $f)
dontSkipFlavor: flavor @skip(if: $f)
}
}
GRAPHQL
}
it "is not included" do
assert !result["data"]["cheese"].key?("dontIncludeFlavor")
end
it "is not skipped" do
assert result["data"]["cheese"].key?("dontSkipFlavor")
end
end
describe "with true" do
let(:query_string) { <<-GRAPHQL
query($t: Boolean = true) {
cheese(id: 1) {
includeFlavor: flavor @include(if: $t)
skipFlavor: flavor @skip(if: $t)
}
}
GRAPHQL
}
it "is included" do
assert result["data"]["cheese"].key?("includeFlavor")
end
it "is skipped" do
assert !result["data"]["cheese"].key?("skipFlavor")
end
end
end
it "intercepts fields" do
expected = { "data" =>{
"cheese" => {
"dontSkipFlavor" => "Brie",
"includeFlavor" => "Brie",
"includeId" => 1,
"dontSkipId" => 1,
},
}}
assert_equal(expected, result)
end
end
describe "on fragments spreads and inline fragments" do
let(:query_string) { %|query directives {
cheese(id: 1) {
... skipFlavorField @skip(if: true)
... dontSkipFlavorField @skip(if: false)
... includeFlavorField @include(if: true)
... dontIncludeFlavorField @include(if: false)
... on Cheese @skip(if: true) { skipInlineId: id }
... on Cheese @skip(if: false) { dontSkipInlineId: id }
... on Cheese @include(if: true) { includeInlineId: id }
... on Cheese @include(if: false) { dontIncludeInlineId: id }
... @skip(if: true) { skipNoType: id }
... @skip(if: false) { dontSkipNoType: id }
}
}
fragment includeFlavorField on Cheese { includeFlavor: flavor }
fragment dontIncludeFlavorField on Cheese { dontIncludeFlavor: flavor }
fragment skipFlavorField on Cheese { skipFlavor: flavor }
fragment dontSkipFlavorField on Cheese { dontSkipFlavor: flavor }
|}
it "intercepts fragment spreads" do
expected = { "data" => {
"cheese" => {
"dontSkipFlavor" => "Brie",
"includeFlavor" => "Brie",
"dontSkipInlineId" => 1,
"includeInlineId" => 1,
"dontSkipNoType" => 1,
},
}}
assert_equal(expected, result)
end
end
describe "merging @skip and @include" do
let(:field_included?) { r = result["data"]["cheese"]; r.has_key?('flavor') && r.has_key?('withVariables') }
let(:skip?) { false }
let(:include?) { true }
let(:variables) { {"skip" => skip?, "include" => include?} }
let(:query_string) {"
query getCheese ($include: Boolean!, $skip: Boolean!) {
cheese(id: 1) {
flavor @include(if: #{include?}) @skip(if: #{skip?}),
withVariables: flavor @include(if: $include) @skip(if: $skip)
}
}
"}
# behavior as defined in
# https://github.com/facebook/graphql/blob/master/spec/Section%203%20--%20Type%20System.md#include
describe "when @skip=false and @include=true" do
let(:skip?) { false }
let(:include?) { true }
it "is included" do assert field_included? end
end
describe "when @skip=false and @include=false" do
let(:skip?) { false }
let(:include?) { false }
it "is not included" do assert !field_included? end
end
describe "when @skip=true and @include=true" do
let(:skip?) { true }
let(:include?) { true }
it "is not included" do assert !field_included? end
end
describe "when @skip=true and @include=false" do
let(:skip?) { true }
let(:include?) { false }
it "is not included" do assert !field_included? end
end
describe "when evaluating skip on query selection and fragment" do
describe "with @skip" do
let(:query_string) {"
query getCheese ($skip: Boolean!) {
cheese(id: 1) {
flavor,
withVariables: flavor,
...F0
}
}
fragment F0 on Cheese {
flavor @skip(if: #{skip?})
withVariables: flavor @skip(if: $skip)
}
"}
describe "and @skip=false" do
let(:skip?) { false }
it "is included" do assert field_included? end
end
describe "and @skip=true" do
let(:skip?) { true }
it "is included" do assert field_included? end
end
end
end
describe "when evaluating conflicting @skip and @include on query selection and fragment" do
let(:query_string) {"
query getCheese ($include: Boolean!, $skip: Boolean!) {
cheese(id: 1) {
... on Cheese @include(if: #{include?}) {
flavor
}
withVariables: flavor @include(if: $include),
...F0
}
}
fragment F0 on Cheese {
flavor @skip(if: #{skip?}),
withVariables: flavor @skip(if: $skip)
}
"}
describe "when @skip=false and @include=true" do
let(:skip?) { false }
let(:include?) { true }
it "is included" do assert field_included? end
end
describe "when @skip=false and @include=false" do
let(:skip?) { false }
let(:include?) { false }
it "is included" do assert field_included? end
end
describe "when @skip=true and @include=true" do
let(:skip?) { true }
let(:include?) { true }
it "is included" do assert field_included? end
end
describe "when @skip=true and @include=false" do
let(:skip?) { true }
let(:include?) { false }
it "is not included" do
assert !field_included?
end
end
end
describe "when handling multiple fields at the same level" do
describe "when at least one occurrence would be included" do
let(:query_string) {"
query getCheese ($include: Boolean!, $skip: Boolean!) {
cheese(id: 1) {
... on Cheese {
flavor
}
flavor @include(if: #{include?}),
flavor @skip(if: #{skip?}),
withVariables: flavor,
withVariables: flavor @include(if: $include),
withVariables: flavor @skip(if: $skip)
}
}
"}
let(:skip?) { true }
let(:include?) { false }
it "is included" do assert field_included? end
end
describe "when no occurrence would be included" do
let(:query_string) {"
query getCheese ($include: Boolean!, $skip: Boolean!) {
cheese(id: 1) {
flavor @include(if: #{include?}),
flavor @skip(if: #{skip?}),
withVariables: flavor @include(if: $include),
withVariables: flavor @skip(if: $skip)
}
}
"}
let(:skip?) { true }
let(:include?) { false }
it "is not included" do assert !field_included? 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/analysis_spec.rb | spec/graphql/analysis_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Analysis do
class AstTypeCollector < GraphQL::Analysis::Analyzer
def initialize(query)
super
@types = []
end
def on_enter_operation_definition(node, parent, visitor)
@types << visitor.type_definition
end
def on_enter_field(memo, node, visitor)
@types << visitor.field_definition.type.unwrap
end
def result
@types
end
end
class AstNodeCounter < GraphQL::Analysis::Analyzer
def initialize(query)
super
@nodes = Hash.new { |h,k| h[k] = 0 }
end
def on_enter_abstract_node(node, parent, _visitor)
@nodes[node.class] += 1
end
alias :on_enter_operation_definition :on_enter_abstract_node
alias :on_enter_field :on_enter_abstract_node
alias :on_enter_argument :on_enter_abstract_node
def result
@nodes
end
end
class AstConditionalAnalyzer < GraphQL::Analysis::Analyzer
def initialize(query)
super
@i_have_been_called = false
end
def analyze?
!!query.context[:analyze]
end
def on_operation_definition(node, parent, visitor)
@i_have_been_called = true
end
def result
@i_have_been_called
end
end
class AstPrecomputedAnalyzer < GraphQL::Analysis::Analyzer
def initialize(query)
super
@i_have_been_visited = false
end
def visit?
query.context[:precomputed_result].nil?
end
def on_enter_field(node, parent, visitor)
@i_have_been_visited = true
end
def result
return query.context[:precomputed_result], @i_have_been_visited
end
end
class AstErrorAnalyzer < GraphQL::Analysis::Analyzer
def result
GraphQL::AnalysisError.new("An Error!")
end
end
class AstPreviousField < GraphQL::Analysis::Analyzer
def on_enter_field(node, parent, visitor)
@previous_field = visitor.previous_field_definition
end
def result
@previous_field
end
end
class AstArguments < GraphQL::Analysis::Analyzer
def on_enter_argument(node, parent, visitor)
@argument = visitor.argument_definition
@previous_argument = visitor.previous_argument_definition
end
def result
[@argument, @previous_argument]
end
end
class AstSkipInclude < GraphQL::Analysis::Analyzer
def initialize(query)
super
@included = []
end
def on_enter_field(node, parent, visitor)
@included << "enter #{node.name}" unless visitor.skipping?
end
def on_leave_field(node, parent, visitor)
@included << "leave #{node.name}" unless visitor.skipping?
end
def on_enter_inline_fragment(node, parent, visitor)
@included << "enter ...on #{node.type.name}" unless visitor.skipping?
end
def on_leave_inline_fragment(node, parent, visitor)
@included << "leave ...on #{node.type.name}" unless visitor.skipping?
end
def on_enter_fragment_spread(node, parent, visitor)
@included << "enter ...#{node.name}" unless visitor.skipping?
end
def on_leave_fragment_spread(node, parent, visitor)
@included << "leave ...#{node.name}" unless visitor.skipping?
end
def result
@included
end
end
describe "skip and include behaviors" do
let(:reduce_result) { GraphQL::Analysis.analyze_query(query, [AstSkipInclude]) }
let(:query) { GraphQL::Query.new(Dummy::Schema, query_string) }
let(:query_string) {%|{}|}
describe "for fields" do
let(:query_string) {%|
{
cheese {
flavor
origin @skip(if: true)
source @include(if: false)
}
cheese @skip(if: true) { flavor }
cheese @include(if: false) { flavor }
}
|}
it "tracks inclusions" do
expected = [
"enter cheese",
"enter flavor",
"leave flavor",
"leave cheese",
]
assert_equal expected, reduce_result.first
end
end
describe "for inline fragments" do
let(:query_string) {%|
{
cheese {
...on Cheese @skip(if: true) { origin }
...on Cheese { flavor }
...on Cheese @include(if: false) { source }
}
}
|}
it "tracks inclusions" do
expected = [
"enter cheese",
"enter ...on Cheese",
"enter flavor",
"leave flavor",
"leave ...on Cheese",
"leave cheese",
]
assert_equal expected, reduce_result.first
end
end
describe "for fragment spreads" do
let(:query_string) {%|
{
cheese {
...Original @skip(if: true)
...Flavorful
...Sourced @include(if: false)
}
}
fragment Flavorful on Cheese { flavor }
fragment Original on Cheese { origin }
fragment Sourced on Cheese { source }
|}
it "tracks inclusions" do
expected = [
"enter cheese",
"enter ...Flavorful",
"enter flavor",
"leave flavor",
"leave ...Flavorful",
"leave cheese",
]
assert_equal expected, reduce_result.first
end
end
end
describe "using the AST analysis engine" do
let(:schema) do
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name 'Query'
field :foobar, Integer, null: false
def foobar
1337
end
end
Class.new(GraphQL::Schema) do
query query_type
query_analyzer AstErrorAnalyzer
end
end
let(:query_string) {%|
query {
foobar
}
|}
let(:query) { GraphQL::Query.new(schema, query_string, variables: {}) }
it "runs the AST analyzers correctly" do
res = query.result
refute res.key?("data")
assert_equal ["An Error!"], res["errors"].map { |e| e["message"] }
end
end
describe ".analyze_query" do
let(:analyzers) { [AstTypeCollector, AstNodeCounter] }
let(:reduce_result) { GraphQL::Analysis.analyze_query(query, analyzers) }
let(:variables) { {} }
let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables) }
let(:query_string) {%|
{
cheese(id: 1) {
id
flavor
}
}
|}
describe "without a valid operation" do
let(:query_string) {%|
# A comment
# is an invalid operation
# Should break
|}
it "bails early when there is no selected operation to be executed" do
assert_equal 2, reduce_result.size
end
end
describe "conditional analysis" do
let(:analyzers) { [AstTypeCollector, AstConditionalAnalyzer] }
describe "when analyze? returns false" do
let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables, context: { analyze: false }) }
it "does not run the analyzer" do
# Only type_collector ran
assert_equal 1, reduce_result.size
end
end
describe "when analyze? returns true" do
let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables, context: { analyze: true }) }
it "it runs the analyzer" do
# Both analyzers ran
assert_equal 2, reduce_result.size
end
end
describe "Visitor#previous_field_definition" do
let(:analyzers) { [AstPreviousField] }
let(:query) { GraphQL::Query.new(Dummy::Schema, "{ __schema { types { name } } }") }
it "it runs the analyzer" do
prev_field = reduce_result.first
assert_equal "__Schema.types", prev_field.path
end
end
describe "Visitor#argument_definition" do
let(:analyzers) { [AstArguments] }
let(:query) do
GraphQL::Query.new(
Dummy::Schema,
'{ searchDairy(product: [{ source: "SHEEP" }]) { ... on Cheese { id } } }'
)
end
it "it runs the analyzer" do
argument, prev_argument = reduce_result.first
assert_equal "DairyProductInput.source", argument.path
assert_equal "Query.searchDairy.product", prev_argument.path
end
end
end
describe "precomputed analysis" do
let(:analyzers) { [AstPrecomputedAnalyzer] }
describe "when visit? returns true" do
let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables, context: {}) }
it "runs the analyzer with visitation" do
assert_equal [nil, true], reduce_result.first
end
end
describe "when visit? returns false" do
let(:query) { GraphQL::Query.new(Dummy::Schema, query_string, variables: variables, context: { precomputed_result: 23 }) }
it "runs the analyzer without visitation" do
assert_equal [23, false], reduce_result.first
end
end
end
it "calls the defined analyzers" do
collected_types, node_counts = reduce_result
expected_visited_types = [
Dummy::DairyAppQuery,
Dummy::Cheese,
GraphQL::Types::Int,
GraphQL::Types::String
]
assert_equal expected_visited_types, collected_types
expected_node_counts = {
GraphQL::Language::Nodes::OperationDefinition => 1,
GraphQL::Language::Nodes::Field => 3,
GraphQL::Language::Nodes::Argument => 1
}
assert_equal expected_node_counts, node_counts
end
class FinishedSchema < GraphQL::Schema
class FinishedAnalyzer < GraphQL::Analysis::Analyzer
def on_enter_field(node, parent, visitor)
if query.context[:force_prepare]
visitor.arguments_for(node, visitor.field_definition)
end
end
def result
query.context[:analysis_finished] = true
end
end
class Query < GraphQL::Schema::Object
field :f1, Int do
argument :arg, String, prepare: ->(val, ctx) {
ctx[:analysis_finished] ? val.to_i : raise("Prepared too soon!")
}
end
def f1(arg:)
arg
end
end
query(Query)
query_analyzer(FinishedAnalyzer)
end
it "doesn't call prepare hooks by default" do
res = FinishedSchema.execute("{ f1(arg: \"5\") }")
assert_equal 5, res["data"]["f1"]
err = assert_raises RuntimeError do
FinishedSchema.execute("{ f1(arg: \"5\") }", context: { force_prepare: true })
end
assert_equal "Prepared too soon!", err.message
end
describe "tracing" do
let(:query_string) { "{ t: __typename }"}
it "emits traces" do
traces = TestTracing.with_trace do
ctx = { tracers: [TestTracing] }
Dummy::Schema.execute(query_string, context: ctx)
end
# The query_trace is on the list _first_ because it finished first
if USING_C_PARSER
_lex, _parse, _validate, query_trace, multiplex_trace, *_rest = traces
else
_parse, _validate, query_trace, multiplex_trace, *_rest = traces
end
assert_equal "analyze_multiplex", multiplex_trace[:key]
assert_instance_of GraphQL::Execution::Multiplex, multiplex_trace[:multiplex]
assert_equal "analyze_query", query_trace[:key]
assert_instance_of GraphQL::Query, query_trace[:query]
end
end
class AstConnectionCounter < GraphQL::Analysis::Analyzer
def initialize(query)
super
@fields = 0
@connections = 0
end
def on_enter_field(node, parent, visitor)
if visitor.field_definition.connection?
@connections += 1
else
@fields += 1
end
end
def result
{
fields: @fields,
connections: @connections
}
end
end
describe "when processing fields" do
let(:analyzers) { [AstConnectionCounter] }
let(:reduce_result) { GraphQL::Analysis.analyze_query(query, analyzers) }
let(:query) { GraphQL::Query.new(StarWars::Schema, query_string, variables: variables) }
let(:query_string) {%|
query getBases {
empire {
basesByName(first: 30) { edges { cursor } }
bases(first: 30) { edges { cursor } }
}
}
|}
it "knows which fields are connections" do
connection_counts = reduce_result.first
expected_connection_counts = {
:fields => 5,
:connections => 2
}
assert_equal expected_connection_counts, connection_counts
end
end
end
describe "Detecting all-introspection queries" do
class AllIntrospectionSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :int, Int
end
query(Query)
end
class AllIntrospectionAnalyzer < GraphQL::Analysis::Analyzer
def initialize(query)
@is_introspection = true
super
end
def on_enter_field(node, parent, visitor)
@is_introspection &= (visitor.field_definition.introspection? || ((owner = visitor.field_definition.owner) && owner.introspection?))
end
def result
@is_introspection
end
end
def is_introspection?(query_str)
query = GraphQL::Query.new(AllIntrospectionSchema, query_str)
result = GraphQL::Analysis.analyze_query(query, [AllIntrospectionAnalyzer])
result.first
end
it "returns true for queries containing only introspection types and fields" do
assert is_introspection?("{ __typename }")
refute is_introspection?("{ int }")
assert is_introspection?(GraphQL::Introspection::INTROSPECTION_QUERY)
assert is_introspection?("{ __type(name: \"Something\") { fields { name } } }")
refute is_introspection?("{ int __type(name: \"Thing\") { name } }")
end
end
describe "when there's a hidden field" do
class HiddenAnalyzedFieldSchema < GraphQL::Schema
use GraphQL::Schema::Warden if ADD_WARDEN
class DoNothingAnalyzer < GraphQL::Analysis::Analyzer
def on_enter_field(node, parent, visitor)
@result ||= []
@result << [node.name, visitor.field_definition.class]
super
end
attr_reader :result
end
class BaseField < GraphQL::Schema::Field
def initialize(*args, visible: true, **kwargs, &block)
@visible = visible
super(*args, **kwargs, &block)
end
def visible?(context)
return @visible
end
end
class BaseObject < GraphQL::Schema::Object
field_class BaseField
end
class Article < BaseObject
field :title, String, null: false
end
class Query < BaseObject
field :article, String, visible: false do |f|
f.argument(:id, Integer)
end
def article(id:)
{ title: "hello world" }
end
end
query Query
end
it "uses nil for the field definition" do
gql = <<~GQL
{
article(id: 1) {
title
}
}
GQL
query = GraphQL::Query.new(HiddenAnalyzedFieldSchema, gql)
result = GraphQL::Analysis.analyze_query(query, [HiddenAnalyzedFieldSchema::DoNothingAnalyzer])
assert_equal [[["article", NilClass], ["title", NilClass]]], result
end
end
describe ".validate_timeout" do
class AnalysisTimeoutSchema < GraphQL::Schema
class SlowAnalyzer < GraphQL::Analysis::Analyzer
def initialize(...)
super
if query.context[:initialize_sleep]
sleep 0.6
end
end
def on_enter_field(node, parent, visitor)
if node.name != "__typename"
sleep 0.1
end
super
end
def on_enter_directive(...)
sleep 0.1
super
end
def on_enter_argument(...)
sleep 0.1
super
end
def on_enter_inline_fragment(...)
sleep 0.1
super
end
def on_enter_fragment_spread(node, _parent, _visitor)
if !node.name.include?("NoSleep")
sleep 0.1
end
super
end
def result
nil
end
end
class Query < GraphQL::Schema::Object
field :f1, Int do
argument :a, String, required: false
argument :b, String, required: false
argument :c, String, required: false
argument :d, String, required: false
argument :e, String, required: false
argument :f, String, required: false
end
def f1(...)
context[:int] ||= 0
context[:int] += 1
end
end
class Nothing < GraphQL::Schema::Directive
locations(GraphQL::Schema::Directive::FIELD)
repeatable(true)
end
directive(Nothing)
query(Query)
query_analyzer(SlowAnalyzer)
validate_timeout 0.5
end
it "covers analysis too" do
res = AnalysisTimeoutSchema.execute("{ f1: f1 f2: f1 }")
assert_equal({ "f1" => 1, "f2" => 2}, res["data"])
res2 = AnalysisTimeoutSchema.execute("{ f1: f1, f2: f1, f3: f1, f4: f1, f5: f1, f6: f1}")
assert_equal ["Timeout on validation of query"], res2["errors"].map { |e| e["message"]}
end
it "covers directives" do
res = AnalysisTimeoutSchema.execute("{ f1 @nothing @nothing }")
assert_equal({ "f1" => 1 }, res["data"])
res2 = AnalysisTimeoutSchema.execute("{ f1 @nothing @nothing @nothing @nothing @nothing }")
assert_equal ["Timeout on validation of query"], res2["errors"].map { |e| e["message"]}
end
it "covers arguments" do
res = AnalysisTimeoutSchema.execute("{ f1(a: \"a\", b: \"b\")}")
assert_equal({ "f1" => 1 }, res["data"])
res2 = AnalysisTimeoutSchema.execute('{ f1(a: "a", b: "b", c: "c", d: "d", e: "e", f: "f") }')
assert_equal ["Timeout on validation of query"], res2["errors"].map { |e| e["message"]}
end
it "covers inline fragments" do
res = AnalysisTimeoutSchema.execute("{ ... { f1 } ... { f1 } }")
assert_equal({ "f1" => 1 }, res["data"])
res2 = AnalysisTimeoutSchema.execute("{ ... { f1 } ... { f1 } ... { f1 } ... { f1 } ... { f1 } ... { f1 } }")
assert_equal ["Timeout on validation of query"], res2["errors"].map { |e| e["message"]}
end
it "covers operation definitions" do
res = AnalysisTimeoutSchema.execute('query Q1 { __typename }', operation_name: "Q1")
assert_equal({ "__typename" => "Query" }, res["data"])
res = AnalysisTimeoutSchema.execute('query Q1 { __typename }', operation_name: "Q1", context: { initialize_sleep: true })
assert_equal({ "__typename" => "Query" }, res["data"])
end
it "covers fragment spreads" do
res = AnalysisTimeoutSchema.execute("{ ...F } fragment F on Query { f1 }")
assert_equal({ "f1" => 1 }, res["data"])
res2 = AnalysisTimeoutSchema.execute('{ ...F ...F ...F ...F ...F ...F } fragment F on Query { f1 }')
assert_equal ["Timeout on validation of query"], res2["errors"].map { |e| e["message"]}
end
it "can be ignored" do
no_timeout_schema = Class.new(AnalysisTimeoutSchema) do
validate_timeout(nil)
end
res = no_timeout_schema.execute("{ f1 @nothing @nothing @nothing @nothing @nothing }")
assert_equal({ "f1" => 1 }, res["data"])
res2 = no_timeout_schema.execute('{ ...F ...F ...F ...F ...F ...F } fragment F on Query { f1 }')
assert_equal({ "f1" => 1 }, res2["data"])
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/tracing_spec.rb | spec/graphql/tracing_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Tracing do
class DummyTraceable
def initialize(*tracers)
@tracers = tracers
end
include GraphQL::Tracing::Traceable
end
describe "#trace" do
it "delivers the metadata to send_trace, with result and key" do
returned_value = nil
traceable = DummyTraceable.new(TestTracing)
traces = TestTracing.with_trace do
returned_value = traceable.trace("something", { some_stuff: true }) do
"do stuff"
end
end
assert_equal 1, traces.length
trace = traces.first
assert_equal "something", trace[:key]
assert_equal true, trace[:some_stuff]
# Any override of .trace must return the block's return value
assert_equal "do stuff", returned_value
end
module OtherRandomTracer
CALLS = []
def self.trace(key, metadata)
CALLS << key.upcase
yield
end
end
it "calls multiple tracers" do
OtherRandomTracer::CALLS.clear
traceable = DummyTraceable.new(TestTracing, OtherRandomTracer)
traces = TestTracing.with_trace do
traceable.trace("stuff", { }) { :stuff }
end
assert_equal ["stuff"], traces.map { |t| t[:key] }
assert_equal ["STUFF"], OtherRandomTracer::CALLS
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/backtrace_spec.rb | spec/graphql/backtrace_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Backtrace do
class LazyError
def raise_err
raise "Lazy Boom"
end
end
class ErrorAnalyzer < GraphQL::Analysis::Analyzer
def on_enter_operation_definition(node, parent_node, visitor)
if node.name == "raiseError"
raise GraphQL::AnalysisError, "this should not be wrapped by a backtrace, but instead, returned to the client"
end
end
def result
end
end
class NilInspectObject
# Oops, this is evil, but it happens and we should handle it.
def inspect; nil; end
end
module ErrorTrace
def initialize(required_arg:, **_rest)
super(**_rest)
end
def execute_multiplex(multiplex:)
super
raise "Instrumentation Boom"
end
end
let(:resolvers) {
{
"Query" => {
"field1" => Proc.new { :something },
"field2" => Proc.new { :something },
"nilInspect" => Proc.new { NilInspectObject.new },
"nestedList" => Proc.new { [ { thing: { name: "abc" } }, { thing: { name: :boom } } ] },
},
"Thing" => {
"name" => Proc.new { |obj| obj[:name] == :boom ? raise("Boom!") : obj[:name] },
"listField" => Proc.new { :not_a_list },
"raiseField" => Proc.new { |o, a| raise("This is broken: #{a[:message]}") },
"executionError" => Proc.new { raise GraphQL::ExecutionError, "Client-facing error" }
},
"ThingWrapper" => {
"thing" => Proc.new { |obj| obj[:thing] },
},
"OtherThing" => {
"strField" => Proc.new { LazyError.new },
},
}
}
let(:schema) {
defn = <<-GRAPHQL
type Query {
field1: Thing
field2: OtherThing
nilInspect: Thing
nestedList: [ThingWrapper]
}
type Thing {
name: String
listField: [OtherThing]
raiseField(message: String!): Int
executionError: Int
}
type ThingWrapper {
thing: Thing
}
type OtherThing {
strField: String
}
GRAPHQL
schema_class = GraphQL::Schema.from_definition(defn, default_resolve: resolvers)
schema_class.class_exec {
lazy_resolve(LazyError, :raise_err)
query_analyzer(ErrorAnalyzer)
}
schema_class
}
let(:backtrace_schema) {
Class.new(schema) do
use GraphQL::Backtrace
end
}
describe "GraphQL backtrace helpers" do
it "raises a TracedError when enabled" do
assert_raises(GraphQL::Backtrace::TracedError) {
backtrace_schema.execute("query BrokenList { field1 { listField { strField } } }")
}
assert_raises(GraphQL::Execution::Interpreter::ListResultFailedError) {
schema.execute("query BrokenList { field1 { listField { strField } } }")
}
end
it "works for objects inside lists" do
assert_raises(GraphQL::Backtrace::TracedError) do
backtrace_schema.execute("{ nestedList { thing { name } } }")
end
end
it "doesn't wrap GraphQL::ExecutionError" do
assert_equal ["Client-facing error"], backtrace_schema.execute("{ field1 { executionError } }")["errors"].map { |e| e["message"] }
end
it "annotates crashes from user code" do
err = assert_raises(GraphQL::Backtrace::TracedError) {
backtrace_schema.execute <<-GRAPHQL, root_value: "Root"
query($msg: String = \"Boom\") {
field1 {
boomError: raiseField(message: $msg)
}
}
GRAPHQL
}
# The original error info is present
assert_instance_of RuntimeError, err.cause
b = err.cause.backtrace
assert_backtrace_includes(b, file: "backtrace_spec.rb", method: "block")
assert_backtrace_includes(b, file: "field.rb", method: "resolve")
assert_backtrace_includes(b, file: "runtime.rb", method: "evaluate_selection")
assert_backtrace_includes(b, file: "interpreter.rb", method: "run_all")
# GraphQL backtrace is present
expected_graphql_backtrace = [
"3:13: Thing.raiseField as boomError",
"2:11: Query.field1",
"1:9: query",
]
assert_equal expected_graphql_backtrace, err.graphql_backtrace
hash_inspect = { message: "Boom" }.inspect
# The message includes the GraphQL context
rendered_table = [
'Loc | Field | Object | ' + "Arguments".ljust(hash_inspect.size) + ' | Result',
'3:13 | Thing.raiseField as boomError | :something | ' + hash_inspect + ' | #<RuntimeError: This is broken: Boom>',
'2:11 | Query.field1 | "Root" | ' + "{}".ljust(hash_inspect.size) + ' | {}',
'1:9 | query | "Root" | ' + {"msg" => "Boom"}.inspect.ljust(hash_inspect.size) + ' | {field1: {...}}',
].join("\n")
assert_includes err.message, "\n" + rendered_table
# The message includes the original error message
assert_includes err.message, "This is broken: Boom"
assert_includes err.message, "spec/graphql/backtrace_spec.rb:49", "It includes the original backtrace"
assert_includes err.message, "more lines"
end
it "annotates crashes from user code when using inline fragments" do
err = assert_raises(GraphQL::Backtrace::TracedError) {
backtrace_schema.execute <<-GRAPHQL, root_value: "Root"
query($msg: String = \"Boom\") {
field1 {
... on Thing {
boomError: raiseField(message: $msg)
}
}
}
GRAPHQL
}
# GraphQL backtrace is present
expected_graphql_backtrace = [
"4:15: Thing.raiseField as boomError",
"2:11: Query.field1",
"1:9: query",
]
assert_equal expected_graphql_backtrace, err.graphql_backtrace
hash_inspect = { message: "Boom" }.inspect
# The message includes the GraphQL context
rendered_table = [
'Loc | Field | Object | ' + "Arguments".ljust(hash_inspect.size) + ' | Result',
'4:15 | Thing.raiseField as boomError | :something | ' + hash_inspect + ' | #<RuntimeError: This is broken: Boom>',
'2:11 | Query.field1 | "Root" | ' + "{}".ljust(hash_inspect.size) + ' | {}',
'1:9 | query | "Root" | ' + {"msg" => "Boom"}.inspect.ljust(hash_inspect.size) + ' | {field1: {...}}',
].join("\n")
assert_includes err.message, "\n" + rendered_table
# The message includes the original error message
assert_includes err.message, "This is broken: Boom"
assert_includes err.message, "spec/graphql/backtrace_spec.rb:49", "It includes the original backtrace"
assert_includes err.message, "more lines"
end
it "annotates errors from Query#result" do
query_str = "query StrField { field2 { strField } __typename }"
context = { backtrace: true }
query = GraphQL::Query.new(schema, query_str, context: context)
err = assert_raises(GraphQL::Backtrace::TracedError) {
query.result
}
assert_instance_of RuntimeError, err.cause
end
it "annotates errors inside lazy resolution" do
# Test context-based flag
err = assert_raises(GraphQL::Backtrace::TracedError) {
schema.execute("query StrField { field2 { strField } __typename }", context: { backtrace: true })
}
assert_instance_of RuntimeError, err.cause
b = err.cause.backtrace
assert_backtrace_includes(b, file: "backtrace_spec.rb", method: "raise_err")
assert_backtrace_includes(b, file: "schema.rb", method: "sync_lazy")
assert_backtrace_includes(b, file: "interpreter.rb", method: "run_all")
expected_graphql_backtrace = [
"1:27: OtherThing.strField",
"1:18: Query.field2",
"1:1: query StrField",
]
assert_equal(expected_graphql_backtrace, err.graphql_backtrace)
rendered_table = [
'Loc | Field | Object | Arguments | Result',
'1:27 | OtherThing.strField | :something | {} | #<RuntimeError: Lazy Boom>',
'1:18 | Query.field2 | nil | {} | {strField: (unresolved)}',
'1:1 | query StrField | nil | {} | {field2: {...}, __typename: "Query"}',
].join("\n")
assert_includes err.message, rendered_table
end
it "returns analysis errors to the client" do
res = backtrace_schema.execute("query raiseError { __typename }")
assert_equal "this should not be wrapped by a backtrace, but instead, returned to the client", res["errors"].first["message"]
end
it "always stringifies the #inspect response" do
# test the schema plugin
err = assert_raises(GraphQL::Backtrace::TracedError) {
backtrace_schema.execute("query { nilInspect { raiseField(message: \"pop!\") } }")
}
hash_inspect = {message: "pop!"}.inspect # `=>` on Ruby < 3.4
rendered_table = [
'Loc | Field | Object | ' + "Arguments".ljust(hash_inspect.size) + ' | Result',
'1:22 | Thing.raiseField | | ' + hash_inspect + ' | #<RuntimeError: This is broken: pop!>',
'1:9 | Query.nilInspect | nil | ' + "{}".ljust(hash_inspect.size) + ' | {}',
'1:1 | query | nil | ' + "{}".ljust(hash_inspect.size) + ' | {nilInspect: {...}}',
'',
''
].join("\n")
table = err.message.split("GraphQL Backtrace:\n").last
assert_equal rendered_table, table
end
it "raises original exception instead of a TracedError when error does not occur during resolving" do
instrumentation_schema = Class.new(schema) do
trace_with(ErrorTrace, required_arg: true)
end
assert_raises(RuntimeError) {
instrumentation_schema.execute(GraphQL::Introspection::INTROSPECTION_QUERY, context: { backtrace: true })
}
end
end
# This will get brittle when execution code moves between files
# but I'm not sure how to be sure that the backtrace contains the right stuff!
def assert_backtrace_includes(backtrace, file:, method:)
includes_tag = if RUBY_VERSION < "3.4"
backtrace.any? { |s| s.include?(file) && s.include?("`" + method) }
elsif method == "block"
backtrace.any? { |s| s.include?(file) && s.include?("'block") }
else
backtrace.any? { |s| s.include?(file) && s.include?("#{method}'") }
end
assert includes_tag, "Backtrace should include #{file} inside method #{method}\n\n#{backtrace.join("\n")}"
end
it "works with stand-alone validation" do
res = backtrace_schema.validate("{ __typename }")
assert_equal [], res
end
it "works with stand-alone analysis" do
example_analyzer = Class.new(GraphQL::Analysis::Analyzer) do
def result
:finished
end
end
query = GraphQL::Query.new(backtrace_schema, "{ __typename }")
result = GraphQL::Analysis.analyze_query(query, [example_analyzer])
assert_equal [:finished], result
end
it "works with multiplex analysis" do
example_analyzer = Class.new(GraphQL::Analysis::Analyzer) do
def result
:finished
end
end
query = GraphQL::Query.new(backtrace_schema, "{ __typename }")
multiplex = GraphQL::Execution::Multiplex.new(
schema: schema,
queries: [query],
context: {},
max_complexity: nil,
)
result = GraphQL::Analysis.analyze_multiplex(multiplex, [example_analyzer])
assert_equal [:finished], result
end
it "works with multiplex queries" do
res = backtrace_schema.multiplex([
{ query: 'query { __typename }' },
{ query: 'query { __typename }' },
])
expected_res = [
{"data" => { "__typename" => "Query" }},
{"data" => { "__typename" => "Query" }},
]
assert_graphql_equal expected_res, res
end
it "includes other trace modules when backtrace is active" do
custom_trace = Module.new
schema = Class.new(GraphQL::Schema) do
trace_with(custom_trace)
end
query = GraphQL::Query.new(schema, "{ __typename }", context: { backtrace: true })
assert_includes query.current_trace.class.ancestors, custom_trace
end
describe "When validators are used" do
class ValidatorBacktraceSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :greeting, String do
argument :name, String, validates: { length: { minimum: 5 }}
end
def greeting(name:)
"Hello, #{name}!"
end
end
query(Query)
use GraphQL::Backtrace
end
it "works properly" do
assert_equal "Hello, Albert!", ValidatorBacktraceSchema.execute("{ greeting(name: \"Albert\") }")["data"]["greeting"]
assert_equal ["name is too short (minimum is 5)"], ValidatorBacktraceSchema.execute("{ greeting(name: \"Tim\") }")["errors"].map { |e| e["message"] }
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/graphql/schema_spec.rb | spec/graphql/schema_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema do
describe "inheritance" do
class DummyFeature1 < GraphQL::Schema::Directive::Feature
end
class DummyFeature2 < GraphQL::Schema::Directive::Feature
end
class Query < GraphQL::Schema::Object
field :some_field, String
end
class Mutation < GraphQL::Schema::Object
field :some_field, String
end
class Subscription < GraphQL::Schema::Object
field :some_field, String
end
class ExtraType < GraphQL::Schema::Object
end
class CustomSubscriptions < GraphQL::Subscriptions::ActionCableSubscriptions
end
let(:base_schema) do
Class.new(GraphQL::Schema) do
query Query
mutation Mutation
subscription Subscription
max_complexity 1
max_depth 2
default_max_page_size 3
default_page_size 2
disable_introspection_entry_points
orphan_types Jazz::Ensemble
introspection Module.new
cursor_encoder Object.new
context_class Class.new
directives [DummyFeature1]
extra_types ExtraType
query_analyzer Object.new
multiplex_analyzer Object.new
validate_timeout 100
max_query_string_tokens 500
rescue_from(StandardError) { }
use GraphQL::Backtrace
use GraphQL::Subscriptions::ActionCableSubscriptions, action_cable: nil, action_cable_coder: JSON
end
end
it "inherits configuration from its superclass" do
schema = Class.new(base_schema)
assert_equal base_schema.query, schema.query
assert_equal base_schema.mutation, schema.mutation
assert_equal base_schema.subscription, schema.subscription
assert_equal base_schema.introspection, schema.introspection
assert_equal base_schema.cursor_encoder, schema.cursor_encoder
assert_equal base_schema.validate_timeout, schema.validate_timeout
assert_equal base_schema.max_complexity, schema.max_complexity
assert_equal base_schema.max_depth, schema.max_depth
assert_equal base_schema.default_max_page_size, schema.default_max_page_size
assert_equal base_schema.default_page_size, schema.default_page_size
assert_equal base_schema.orphan_types, schema.orphan_types
assert_equal base_schema.context_class, schema.context_class
assert_equal base_schema.directives, schema.directives
assert_equal base_schema.max_query_string_tokens, schema.max_query_string_tokens
assert_equal base_schema.query_analyzers, schema.query_analyzers
assert_equal base_schema.multiplex_analyzers, schema.multiplex_analyzers
assert_equal base_schema.disable_introspection_entry_points?, schema.disable_introspection_entry_points?
expected_plugins = [
(GraphQL::Schema.use_visibility_profile? ? GraphQL::Schema::Visibility : nil),
GraphQL::Backtrace,
GraphQL::Subscriptions::ActionCableSubscriptions
].compact
assert_equal expected_plugins, schema.plugins.map(&:first)
assert_equal [ExtraType], base_schema.extra_types
assert_equal [ExtraType], schema.extra_types
assert_instance_of GraphQL::Subscriptions::ActionCableSubscriptions, schema.subscriptions
assert_equal GraphQL::Query, schema.query_class
end
it "can override configuration from its superclass" do
custom_query_class = Class.new(GraphQL::Query)
extra_type_2 = Class.new(GraphQL::Schema::Enum)
schema = Class.new(base_schema) do
use CustomSubscriptions, action_cable: nil, action_cable_coder: JSON
query_class(custom_query_class)
extra_types [extra_type_2]
max_query_string_tokens nil
end
query = Class.new(GraphQL::Schema::Object) do
graphql_name 'Query'
field :some_field, String
end
schema.query(query)
mutation = Class.new(GraphQL::Schema::Object) do
graphql_name 'Mutation'
field :some_field, String
end
schema.mutation(mutation)
subscription = Class.new(GraphQL::Schema::Object) do
graphql_name 'Subscription'
field :some_field, String
end
schema.subscription(subscription)
introspection = Module.new
schema.introspection(introspection)
cursor_encoder = Object.new
schema.cursor_encoder(cursor_encoder)
context_class = Class.new
schema.context_class(context_class)
schema.validate_timeout(10)
schema.max_complexity(10)
schema.max_depth(20)
schema.default_max_page_size(30)
schema.default_page_size(15)
schema.orphan_types(Jazz::InstrumentType)
schema.directives([DummyFeature2])
query_analyzer = Object.new
schema.query_analyzer(query_analyzer)
multiplex_analyzer = Object.new
schema.multiplex_analyzer(multiplex_analyzer)
schema.rescue_from(GraphQL::ExecutionError)
assert_equal query, schema.query
assert_equal mutation, schema.mutation
assert_equal subscription, schema.subscription
assert_equal introspection, schema.introspection
assert_equal cursor_encoder, schema.cursor_encoder
assert_nil schema.max_query_string_tokens
assert_equal context_class, schema.context_class
assert_equal 10, schema.validate_timeout
assert_equal 10, schema.max_complexity
assert_equal 20, schema.max_depth
assert_equal 30, schema.default_max_page_size
assert_equal 15, schema.default_page_size
assert_equal [Jazz::Ensemble, Jazz::InstrumentType], schema.orphan_types
assert_equal schema.directives, GraphQL::Schema.default_directives.merge(DummyFeature1.graphql_name => DummyFeature1, DummyFeature2.graphql_name => DummyFeature2)
assert_equal base_schema.query_analyzers + [query_analyzer], schema.query_analyzers
assert_equal base_schema.multiplex_analyzers + [multiplex_analyzer], schema.multiplex_analyzers
expected_plugins = [GraphQL::Backtrace, GraphQL::Subscriptions::ActionCableSubscriptions, CustomSubscriptions]
if GraphQL::Schema.use_visibility_profile?
expected_plugins.unshift(GraphQL::Schema::Visibility)
end
assert_equal expected_plugins, schema.plugins.map(&:first)
assert_equal custom_query_class, schema.query_class
assert_equal [ExtraType, extra_type_2], schema.extra_types
assert_instance_of CustomSubscriptions, schema.subscriptions
end
end
class ExampleOptionEnum < GraphQL::Schema::Enum
end
it "rejects non-object types to orphan_types" do
object_type = Class.new(GraphQL::Schema::Object)
err = assert_raises ArgumentError do
Class.new(GraphQL::Schema) do
orphan_types(ExampleOptionEnum, object_type)
end
end
expected_msg = "Only object type classes should be added as `orphan_types(...)`.
- Remove these no-op types from `orphan_types`: ExampleOptionEnum (ENUM)
- See https://graphql-ruby.org/type_definitions/interfaces.html#orphan-types
To add other types to your schema, you might want `extra_types`: https://graphql-ruby.org/schema/definition.html#extra-types
"
assert_equal expected_msg, err.message
end
describe ".references_to" do
it "doesn't include any duplicates" do
[Dummy::Schema, Jazz::Schema].each do |schema_class|
schema_class.references_to.each do |referent, references|
ref_paths = references.map { |r| "#{r.class}/#{r.path}"}.sort
assert_equal ref_paths.uniq, ref_paths, "#{schema_class}.references_to has unique entries for `#{referent}`"
end
end
end
end
describe "merged, inherited caches" do
METHODS_TO_CACHE = {
types: 1,
union_memberships: 1,
possible_types: 5, # The number of types with fields accessed in the query
}
let(:schema) do
Class.new(Dummy::Schema) do
def self.reset_calls
@calls = Hash.new(0)
@callers = Hash.new { |h, k| h[k] = [] }
end
METHODS_TO_CACHE.each do |method_name, allowed_calls|
define_singleton_method(method_name) do |*args, **kwargs, &block|
if @calls
call_count = @calls[method_name] += 1
@callers[method_name] << caller
else
call_count = 0
end
if call_count > allowed_calls
raise "Called #{method_name} more than #{allowed_calls} times, previous caller: \n#{@callers[method_name].first.join("\n")}"
end
super(*args, **kwargs, &block)
end
end
end
end
it "caches #{METHODS_TO_CACHE.keys} at runtime" do
query_str = "
query getFlavor($cheeseId: Int!) {
brie: cheese(id: 1) { ...cheeseFields, taste: flavor },
cheese(id: $cheeseId) {
__typename,
id,
...cheeseFields,
... edibleFields,
... on Cheese { cheeseKind: flavor },
}
fromSource(source: COW) { id }
fromSheep: fromSource(source: SHEEP) { id }
firstSheep: searchDairy(product: [{source: SHEEP}]) {
__typename,
... dairyFields,
... milkFields
}
favoriteEdible { __typename, fatContent }
}
fragment cheeseFields on Cheese { flavor }
fragment edibleFields on Edible { fatContent }
fragment milkFields on Milk { source }
fragment dairyFields on AnimalProduct {
... on Cheese { flavor }
... on Milk { source }
}
"
schema.reset_calls
res = schema.execute(query_str, variables: { cheeseId: 2 })
assert_equal "Brie", res["data"]["brie"]["flavor"]
end
end
describe "`use` works with plugins that attach instrumentation, trace modules, query analyzers" do
module NoOpTrace
def execute_query(query:)
query.context[:no_op_trace_ran_before_query] = true
super
ensure
query.context[:no_op_trace_ran_after_query] = true
end
end
class NoOpAnalyzer < GraphQL::Analysis::Analyzer
def initialize(query_or_multiplex)
query_or_multiplex.context[:no_op_analyzer_ran_initialize] = true
super
end
def on_leave_field(_node, _parent, visitor)
visitor.query.context[:no_op_analyzer_ran_on_leave_field] = true
end
def result
query.context[:no_op_analyzer_ran_result] = true
end
end
module PluginWithInstrumentationTracingAndAnalyzer
def self.use(schema_defn)
schema_defn.trace_with(NoOpTrace)
schema_defn.query_analyzer NoOpAnalyzer
end
end
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name 'Query'
field :foobar, Integer, null: false
def foobar; 1337; end
end
describe "when called on class definitions" do
let(:schema) do
Class.new(GraphQL::Schema) do
query query_type
use PluginWithInstrumentationTracingAndAnalyzer
end
end
let(:query) { GraphQL::Query.new(schema, "query { foobar }") }
it "attaches plugins correctly, runs all of their callbacks" do
res = query.result
assert res.key?("data")
assert_equal true, query.context[:no_op_trace_ran_before_query]
assert_equal true, query.context[:no_op_trace_ran_after_query]
assert_equal true, query.context[:no_op_analyzer_ran_initialize]
assert_equal true, query.context[:no_op_analyzer_ran_on_leave_field]
assert_equal true, query.context[:no_op_analyzer_ran_result]
end
end
describe "when called on schema subclasses" do
let(:schema) do
schema = Class.new(GraphQL::Schema) do
query query_type
end
# return a subclass
Class.new(schema) do
use PluginWithInstrumentationTracingAndAnalyzer
end
end
let(:query) { GraphQL::Query.new(schema, "query { foobar }") }
it "attaches plugins correctly, runs all of their callbacks" do
res = query.result
assert res.key?("data")
assert_equal true, query.context[:no_op_trace_ran_before_query]
assert_equal true, query.context[:no_op_trace_ran_after_query]
assert_equal true, query.context[:no_op_analyzer_ran_initialize]
assert_equal true, query.context[:no_op_analyzer_ran_on_leave_field]
assert_equal true, query.context[:no_op_analyzer_ran_result]
end
end
end
describe ".new_trace" do
module NewTrace1
def initialize(**opts)
@trace_opts = opts
end
attr_reader :trace_opts
end
module NewTrace2
end
it "returns an instance of the configured trace_class with trace_options" do
parent_schema = Class.new(GraphQL::Schema) do
trace_with NewTrace1, a: 1
end
child_schema = Class.new(parent_schema) do
trace_with NewTrace2, b: 2
end
parent_trace = parent_schema.new_trace
assert_equal({a: 1}, parent_trace.trace_opts)
assert_kind_of NewTrace1, parent_trace
refute_kind_of NewTrace2, parent_trace
assert_kind_of GraphQL::Tracing::Trace, parent_trace
child_trace = child_schema.new_trace
assert_equal({a: 1, b: 2}, child_trace.trace_opts)
assert_kind_of NewTrace1, child_trace
assert_kind_of NewTrace2, child_trace
assert_kind_of GraphQL::Tracing::Trace, child_trace
end
it "returns an instance of the parent configured trace_class with trace_options" do
parent_schema = Class.new(GraphQL::Schema) do
trace_with NewTrace1, a: 1
end
child_schema = Class.new(parent_schema) do
end
child_trace = child_schema.new_trace
assert_equal({a: 1}, child_trace.trace_opts)
assert_kind_of NewTrace1, child_trace
assert_kind_of GraphQL::Tracing::Trace, child_trace
end
end
describe ".possible_types" do
it "returns a single item for objects" do
assert_equal [Dummy::Cheese], Dummy::Schema.possible_types(Dummy::Cheese)
end
it "returns empty for abstract types without any possible types" do
unknown_union = Class.new(GraphQL::Schema::Union) { graphql_name("Unknown") }
assert_equal [], Dummy::Schema.possible_types(unknown_union)
end
it "returns correct types for interfaces based on the context" do
assert_equal [], Jazz::Schema.possible_types(Jazz::PrivateNameEntity, { private: false })
assert_equal [Jazz::Ensemble], Jazz::Schema.possible_types(Jazz::PrivateNameEntity, { private: true })
end
it "returns correct types for unions based on the context" do
assert_equal [Jazz::Musician], Jazz::Schema.possible_types(Jazz::PerformingAct, { hide_ensemble: true })
assert_equal [Jazz::Musician, Jazz::Ensemble], Jazz::Schema.possible_types(Jazz::PerformingAct, { hide_ensemble: false })
end
end
describe 'validate' do
let(:schema) { Dummy::Schema}
describe 'validate' do
it 'validates valid query ' do
query = "query sample { root }"
errors = schema.validate(query)
assert_empty errors
end
it 'validates invalid query ' do
query = "query sample { invalid }"
errors = schema.validate(query)
assert_equal(1, errors.size)
end
end
end
describe "requiring query" do
class QueryRequiredSchema < GraphQL::Schema
end
it "returns an error if no query type is defined" do
res = QueryRequiredSchema.execute("{ blah }")
assert_equal ["Schema is not configured for queries"], res["errors"].map { |e| e["message"] }
end
end
describe ".as_json" do
it "accepts options for the introspection query" do
introspection_schema = Class.new(Dummy::Schema) do
max_depth 20
end
default_res = introspection_schema.as_json
refute default_res["data"]["__schema"].key?("description")
directives = default_res["data"]["__schema"]["directives"]
refute directives.first.key?("isRepeatable")
refute default_res["data"]["__schema"]["types"].find { |t| t["kind"] == "SCALAR" }.key?("specifiedByURL")
refute default_res["data"]["__schema"]["types"].find { |t| t["kind"] == "INPUT_OBJECT" }.key?("isOneOf")
assert_includes default_res.to_s, "oldSource"
full_res = introspection_schema.as_json(
include_deprecated_args: false,
include_is_one_of: true,
include_is_repeatable: true,
include_schema_description: true,
include_specified_by_url: true,
)
assert full_res["data"]["__schema"].key?("description")
directives = full_res["data"]["__schema"]["directives"]
assert directives.first.key?("isRepeatable")
assert full_res["data"]["__schema"]["types"].find { |t| t["kind"] == "SCALAR" }.key?("specifiedByURL")
assert full_res["data"]["__schema"]["types"].find { |t| t["kind"] == "INPUT_OBJECT" }.key?("isOneOf")
refute_includes full_res.to_s, "oldSource"
end
end
it "starts with no references_to" do
assert_equal({}, GraphQL::Schema.references_to)
end
describe "DidYouMean support" do
class DidYouMeanSchema < GraphQL::Schema
class ExampleEnum < GraphQL::Schema::Enum
value "VALUE_ONE", "The first value"
value "VALUE_TWO", "The second value"
end
class Query < GraphQL::Schema::Object
field :first_field, String
field :second_field, String
field :second_fiel, String
field :scond_field, String
field :third_field, ExampleEnum
end
query(Query)
end
it "returns helpful messages" do
res = DidYouMeanSchema.execute("{ first_field }")
assert_equal ["Field 'first_field' doesn't exist on type 'Query' (Did you mean `firstField`?)"], res["errors"].map { |err| err["message"] }
res = DidYouMeanSchema.execute("{ seconField }")
assert_equal ["Field 'seconField' doesn't exist on type 'Query' (Did you mean `secondFiel`, `secondField` or `scondField`?)"], res["errors"].map { |err| err["message"] }
end
it "can disable those messages" do
no_dym_schema = Class.new(DidYouMeanSchema) do
did_you_mean(nil)
end
res = no_dym_schema.execute("{ first_field }")
assert_equal ["Field 'first_field' doesn't exist on type 'Query'"], res["errors"].map { |err| err["message"] }
res = no_dym_schema.execute("{ seconField }")
assert_equal ["Field 'seconField' doesn't exist on type 'Query'"], res["errors"].map { |err| err["message"] }
end
it "returns helpful message when non existing field is queried on a non-fields type" do
res = DidYouMeanSchema.execute("{ thirdField { foo } }")
assert_equal ["Selections can't be made on enums (field 'thirdField' returns ExampleEnum but has selections [\"foo\"])"], res["errors"].map { |err| err["message"] }
res = DidYouMeanSchema.execute("{ secondField { foo } }")
assert_equal ["Selections can't be made on scalars (field 'secondField' returns String but has selections [\"foo\"])"], res["errors"].map { |err| err["message"] }
end
end
it "defers root type blocks until those types are used" do
calls = []
schema = Class.new(GraphQL::Schema) do
use(GraphQL::Schema::Visibility)
query { calls << :query; Class.new(GraphQL::Schema::Object) { graphql_name("Query") } }
mutation { calls << :mutation; Class.new(GraphQL::Schema::Object) { graphql_name("Mutation") } }
subscription { calls << :subscription; Class.new(GraphQL::Schema::Object) { graphql_name("Subscription") } }
# Test this because it tries to modify `subscription` -- currently hardcoded in Schema.add_subscription_extension_if_necessary
use GraphQL::Subscriptions
end
assert_equal [], calls
assert_equal "Query", schema.query.graphql_name
assert_equal [:query], calls
assert_equal "Mutation", schema.mutation.graphql_name
assert_equal [:query, :mutation], calls
assert_equal "Subscription", schema.subscription.graphql_name
assert_equal [:query, :mutation, :subscription], calls
assert schema.instance_variable_get(:@subscription_extension_added)
end
it "adds the subscription extension if subscription(...) is called second" do
schema = Class.new(GraphQL::Schema) do
use GraphQL::Subscriptions
subscription(Class.new(GraphQL::Schema::Object) { graphql_name("Subscription") })
end
assert schema.subscription
assert schema.instance_variable_get(:@subscription_extension_added)
schema2 = Class.new(GraphQL::Schema) do
use(GraphQL::Schema::Visibility)
use GraphQL::Subscriptions
subscription(Class.new(GraphQL::Schema::Object) { graphql_name("Subscription") })
end
assert schema2.subscription
assert schema2.instance_variable_get(:@subscription_extension_added)
end
describe "backtrace error handling" do
class CustomError < RuntimeError; end
class Query < GraphQL::Schema::Object
field :test, Integer, null: false
def test
raise CustomError
end
end
it "raises a TracedError when backtrace is enabled" do
schema = Class.new(GraphQL::Schema) do
query(Query)
use GraphQL::Backtrace
end
query_str = '{ test }'
assert_raises(GraphQL::Backtrace::TracedError) do
schema.execute(query_str)
end
end
it "rescues them when using rescue_from with backtrace" do
schema = Class.new(GraphQL::Schema) do
query(Query)
use GraphQL::Backtrace
rescue_from(CustomError) do
raise GraphQL::ExecutionError.new('Handled CustomError')
end
end
query_str = '{ test }'
expected_errors = [
{
'message' => 'Handled CustomError',
'locations' => [{'line' => 1, 'column' => 3}],
'path' => ['test']
}
]
assert_equal expected_errors, schema.execute(query_str).to_h['errors']
end
end
describe ".validate_timeout" do
it "provides a default timeout when not explicitly set" do
schema = Class.new(GraphQL::Schema)
assert_equal 3, schema.validate_timeout
end
it "allows overriding the default timeout" do
schema = Class.new(GraphQL::Schema) do
validate_timeout 15
end
assert_equal 15, schema.validate_timeout
end
it "allows disabling the timeout" do
schema = Class.new(GraphQL::Schema) do
validate_timeout nil
end
assert_nil schema.validate_timeout
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/autoload_spec.rb | spec/graphql/autoload_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "open3"
describe GraphQL::Autoload do
module LazyModule
extend GraphQL::Autoload
autoload(:LazyClass, "fixtures/lazy_module/lazy_class")
end
module EagerModule
extend GraphQL::Autoload
autoload(:EagerClass, "fixtures/eager_module/eager_class")
autoload(:OtherEagerClass, "fixtures/eager_module/other_eager_class")
autoload(:NestedEagerModule, "fixtures/eager_module/nested_eager_module")
def self.eager_load!
super
NestedEagerModule.eager_load!
end
end
describe "#autoload" do
it "sets autoload" do
assert LazyModule.const_defined?(:LazyClass)
assert_equal("fixtures/lazy_module/lazy_class", LazyModule.autoload?(:LazyClass))
LazyModule::LazyClass
assert_nil(LazyModule.autoload?(:LazyClass))
end
end
describe "#eager_load!" do
it "eagerly loads autoload entries" do
assert EagerModule.autoload?(:EagerClass)
assert EagerModule.autoload?(:OtherEagerClass)
assert EagerModule.autoload?(:NestedEagerModule)
EagerModule.eager_load!
assert_nil(EagerModule.autoload?(:EagerClass))
assert_nil(EagerModule.autoload?(:OtherEagerClass))
assert_nil(EagerModule.autoload?(:NestedEagerModule))
assert_nil(EagerModule::NestedEagerModule.autoload?(:NestedEagerClass))
assert EagerModule::NestedEagerModule::NestedEagerClass
end
end
describe "loading nested files in the repo" do
it "can load them individually" do
files_to_load = Dir.glob("lib/**/tracing/*.rb")
assert_equal 29, files_to_load.size, "It found all the expected files"
files_to_load.each do |file|
require_path = file.sub("lib/", "").sub(".rb", "")
stderr_and_stdout, _status = Open3.capture2e("ruby -Ilib -e 'require \"#{require_path}\"'")
assert_equal "", stderr_and_stdout, "It loads #{require_path.inspect} in isolation"
stderr_and_stdout, _status = Open3.capture2e("ruby -Ilib -e 'require \"graphql\"; require \"#{require_path}\"'")
assert_equal "", stderr_and_stdout, "It loads #{require_path.inspect} after loading graphql"
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/invalid_null_error_spec.rb | spec/graphql/invalid_null_error_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::InvalidNullError" do
it "can be inspected" do
assert_equal "GraphQL::InvalidNullError", GraphQL::InvalidNullError.inspect
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/current_spec.rb | spec/graphql/current_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Current do
describe "when no query is running" do
it "returns nil for things" do
assert_nil GraphQL::Current.operation_name
assert_nil GraphQL::Current.field
assert_nil GraphQL::Current.dataloader_source_class
end
end
describe "in queries" do
class CurrentSchema < GraphQL::Schema
class ThingSource < GraphQL::Dataloader::Source
def initialize(context)
@context = context
end
def fetch(names)
@context[:current_operation_name] << GraphQL::Current.operation_name
@context[:current_source] << GraphQL::Current.dataloader_source_class
names
end
end
class Thing < GraphQL::Schema::Object
field :name, String
def name
context[:current_field] << GraphQL::Current.field.path
context.dataloader.with(ThingSource, context).load("thing")
end
end
class Query < GraphQL::Schema::Object
field :thing, Thing
def thing
context[:current_field] << GraphQL::Current.field.path
:thing
end
end
query(Query)
use GraphQL::Dataloader
end
it "returns execution information" do
ctx = {
current_field: [],
current_source: [],
current_operation_name: []
}
res = CurrentSchema.execute("query GetThingName { thing { name } }", context: ctx)
assert_equal "thing", res["data"]["thing"]["name"]
assert_equal ["GetThingName"], ctx[:current_operation_name]
assert_equal [CurrentSchema::ThingSource], ctx[:current_source]
assert_equal ["Query.thing", "Thing.name"], ctx[:current_field]
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/logger_spec.rb | spec/graphql/logger_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "Logger" do
describe "Schema.default_logger" do
if defined?(Rails)
it "When Rails is present, returns the Rails logger" do
prev_logger = Rails.logger # might be `nil`
Rails.logger = Object.new
assert_equal Rails.logger, GraphQL::Schema.default_logger
ensure
Rails.logger = prev_logger
end
it "When Rails is present but the logger is nil, it returns a new logger" do
prev_logger = Rails.logger
Rails.logger = nil
refute_equal Rails.logger, GraphQL::Schema.default_logger
assert_instance_of Logger, GraphQL::Schema.default_logger
ensure
Rails.logger = prev_logger
end
else
it "Without Rails, returns a new logger" do
assert_instance_of Logger, GraphQL::Schema.default_logger
end
it "Works when Rails doesn't have a logger" do
rails_mod = Module.new
Object.const_set(:Rails, rails_mod)
assert_equal rails_mod, Rails
assert_instance_of Logger, GraphQL::Schema.default_logger
rails_mod.define_singleton_method(:logger) { false }
assert Rails.respond_to?(:logger)
assert_equal false, Rails.logger
assert_instance_of Logger, GraphQL::Schema.default_logger
ensure
Object.send :remove_const, :Rails
end
end
it "can be overridden" do
new_logger = Logger.new($stdout)
schema = Class.new(GraphQL::Schema) do
default_logger(new_logger)
end
assert_equal new_logger, schema.default_logger
end
it "can be set to a null logger with nil" do
schema = Class.new(GraphQL::Schema)
schema.default_logger(nil)
nil_logger = schema.default_logger
std_out, std_err = capture_io do
nil_logger.error("Blah")
nil_logger.warn("Something")
nil_logger.error("Hi")
end
assert_equal "", std_out
assert_equal "", std_err
end
end
describe "during execution" do
module LoggerTest
class DefaultLoggerSchema < GraphQL::Schema
module Node
include GraphQL::Schema::Interface
field :id, ID
end
class Query < GraphQL::Schema::Object
field :node, Node do
argument :id, ID
end
def node(id:)
end
field :something_else, String
end
query(Query)
end
class CustomLoggerSchema < DefaultLoggerSchema
LOG_STRING = StringIO.new
LOGGER = Logger.new(LOG_STRING)
LOGGER.level = :debug
default_logger(LOGGER)
end
end
before do
LoggerTest::CustomLoggerSchema::LOG_STRING.truncate(0)
end
it "logs about hidden interfaces with no implementations" do
res = LoggerTest::CustomLoggerSchema.execute("{ node(id: \"5\") { id } }", context: { skip_visibility_migration_error: true })
if GraphQL::Schema.use_visibility_profile?
assert_nil res["data"]["node"], "Schema::Visibility::Profile doesn't warn in this case -- it doesn't check possible types because it doesn't have to"
else
assert_equal ["Field 'node' doesn't exist on type 'Query'"], res["errors"].map { |err| err["message"] }
assert_includes LoggerTest::CustomLoggerSchema::LOG_STRING.string, "Interface `Node` hidden because it has no visible implementers"
end
end
it "doesn't print messages by default" do
res = nil
stdout, stderr = capture_io do
res = LoggerTest::DefaultLoggerSchema.execute("{ node(id: \"5\") { id } }", context: { skip_visibility_migration_error: true })
end
if GraphQL::Schema.use_visibility_profile?
assert_nil res["data"]["node"], "Schema::Visibility::Profile doesn't warn in this case -- it doesn't check possible types because it doesn't have to"
else
assert_equal ["Field 'node' doesn't exist on type 'Query'"], res["errors"].map { |err| err["message"] }
end
assert_equal "", stdout
assert_equal "", stderr
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/rake_task_spec.rb | spec/graphql/rake_task_spec.rb | # frozen_string_literal: true
require "spec_helper"
rake_task_schema_defn = <<-GRAPHQL
type Query {
allowed(allowed: ID!, excluded: ID!): Int
excluded(excluded: ID!): Boolean
ignored(input: NotOneOf): Float
}
input NotOneOf {
arg: Int,
}
GRAPHQL
RakeTaskSchema = GraphQL::Schema.from_definition(rake_task_schema_defn)
class FilteredRakeTaskSchema < RakeTaskSchema
def self.visible?(member, ctx)
(
member.is_a?(Class) &&
member < GraphQL::Schema::Scalar &&
# Warden doesn't include these for some reason:
!(member.graphql_name.start_with?("Boolean", "String"))
) || (
ctx[:filtered] && ["Query", "allowed"].include?(member.graphql_name)
) || (
member.respond_to?(:introspection?) && member.introspection?
) || (
member.respond_to?(:owner) && member.owner.introspection?
)
end
end
# Default task
GraphQL::RakeTask.new(schema_name: "RakeTaskSchema")
# Configured task
GraphQL::RakeTask.new(idl_outfile: "tmp/configured_schema.graphql") do |t|
t.namespace = "graphql_custom"
t.load_context = ->(task) { {filtered: true } }
t.load_schema = ->(task) { FilteredRakeTaskSchema }
end
GraphQL::RakeTask.new(namespace: "custom_json", schema_name: "RakeTaskSchema", json_outfile: "tmp/custom_json.json", include_is_one_of: true, include_is_repeatable: true, include_specified_by_url: true)
describe GraphQL::RakeTask do
describe "default settings" do
after do
FileUtils.rm_rf("./schema.json")
FileUtils.rm_rf("./schema.graphql")
end
it "writes JSON" do
capture_io do
Rake::Task["graphql:schema:dump"].invoke
end
dumped_json = File.read("./schema.json")
expected_json = JSON.pretty_generate(RakeTaskSchema.execute(GraphQL::Introspection.query(include_deprecated_args: true)))
# Test that that JSON is logically equivalent, not serialized the same
assert_equal(JSON.parse(expected_json), JSON.parse(dumped_json))
# This was dumped with default options, so these are not present:
refute_includes dumped_json, "\"isOneOf\": "
refute_includes dumped_json, "\"specifiedByURL\": "
refute_includes dumped_json, "\"isRepeatable\": "
dumped_idl = File.read("./schema.graphql")
expected_idl = RakeTaskSchema.to_definition
assert_equal(expected_idl, dumped_idl, "The rake task output and #to_definition output match")
end
end
describe "customized settings" do
it "writes GraphQL" do
capture_io do
Rake::Task["graphql_custom:schema:idl"].invoke
end
dumped_idl = File.read("./tmp/configured_schema.graphql")
expected_idl = "type Query {
allowed(allowed: ID!): Int
}
"
assert_equal expected_idl, dumped_idl
end
it "writes JSON" do
capture_io do
Rake::Task["custom_json:schema:json"].invoke
end
dumped_json = File.read("./tmp/custom_json.json")
assert_includes dumped_json, "\"isOneOf\": "
assert_includes dumped_json, "\"specifiedByURL\": "
assert_includes dumped_json, "\"isRepeatable\": "
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_error_spec.rb | spec/graphql/execution_error_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::ExecutionError do
let(:result) { Dummy::Schema.execute(query_string) }
describe "when returned from a field" do
let(:query_string) {%|
{
cheese(id: 1) {
id
error1: similarCheese(source: [YAK]) {
... similarCheeseFields
}
error2: similarCheese(source: [YAK]) {
... similarCheeseFields
}
nonError: similarCheese(source: [SHEEP]) {
... similarCheeseFields
}
flavor
}
allDairy {
... on Cheese {
flavor
}
... on Milk {
source
executionError
}
}
dairyErrors: allDairy(executionErrorAtIndex: 1) {
__typename
}
dairy {
milks {
source
executionError
allDairy {
__typename
... on Milk {
origin
executionError
}
}
}
}
executionError
valueWithExecutionError
}
fragment similarCheeseFields on Cheese {
id, flavor
}
|}
it "the error is inserted into the errors key and the rest of the query is fulfilled" do
expected_result = {
"data"=>{
"dairy" => {
"milks" => [
{
"source" => "COW",
"executionError" => nil,
"allDairy" => [
{ "__typename" => "Cheese" },
{ "__typename" => "Cheese" },
{ "__typename" => "Cheese" },
{ "__typename" => "Milk", "origin" => "Antiquity", "executionError" => nil }
]
}
]
},
"executionError" => nil,
"valueWithExecutionError" => 0,
"cheese"=>{
"id" => 1,
"flavor" => "Brie",
"error1"=> nil,
"error2"=> nil,
"nonError"=> {
"id" => 3,
"flavor" => "Manchego",
},
},
"allDairy" => [
{ "flavor" => "Brie" },
{ "flavor" => "Gouda" },
{ "flavor" => "Manchego" },
{ "source" => "COW", "executionError" => nil }
],
"dairyErrors" => [
{ "__typename" => "Cheese" },
nil,
{ "__typename" => "Cheese" },
{ "__typename" => "Milk" }
],
},
"errors"=>[
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>41, "column"=>5}],
"path"=>["executionError"]
},
{
"message"=>"Could not fetch latest value",
"locations"=>[{"line"=>42, "column"=>5}],
"path"=>["valueWithExecutionError"]
},
{
"message"=>"missing dairy",
"locations"=>[{"line"=>25, "column"=>5}],
"path"=>["dairyErrors", 1]
},
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>31, "column"=>9}],
"path"=>["dairy", "milks", 0, "executionError"]
},
{
"message"=>"No cheeses are made from Yak milk!",
"locations"=>[{"line"=>5, "column"=>7}],
"path"=>["cheese", "error1"]
},
{
"message"=>"No cheeses are made from Yak milk!",
"locations"=>[{"line"=>8, "column"=>7}],
"path"=>["cheese", "error2"]
},
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>22, "column"=>9}],
"path"=>["allDairy", 3, "executionError"]
},
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>36, "column"=>13}],
"path"=>["dairy", "milks", 0, "allDairy", 3, "executionError"]
},
]
}
assert_equal(expected_result, result.to_h)
end
end
describe "named query when returned from a field" do
let(:query_string) {%|
query MilkQuery {
dairy {
milks {
source
executionError
allDairy {
__typename
... on Milk {
origin
executionError
}
}
}
}
}
|}
it "the error is inserted into the errors key and the rest of the query is fulfilled" do
expected_result = {
"data"=>{
"dairy" => {
"milks" => [
{
"source" => "COW",
"executionError" => nil,
"allDairy" => [
{ "__typename" => "Cheese" },
{ "__typename" => "Cheese" },
{ "__typename" => "Cheese" },
{ "__typename" => "Milk", "origin" => "Antiquity", "executionError" => nil }
]
}
]
}
},
"errors"=>[
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>6, "column"=>11}],
"path"=>["dairy", "milks", 0, "executionError"]
},
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>11, "column"=>15}],
"path"=>["dairy", "milks", 0, "allDairy", 3, "executionError"]
}
]
}
assert_equal(expected_result, result)
end
end
describe "minimal lazy non-error case" do
let(:query_string) {%|
{
cheese(id: 1) {
nonError: similarCheese(source: [SHEEP]) {
id
}
}
}
|}
it "does lazy non-errors right" do
# This is extracted from the test above -- it kept breaking
# when working on dataloader, so I isolated it to keep an eye
# on the minimal reproduction
#
# It's `def self.authorized?` is lazy, and it requires
# _both_ a lazy resolution and a dataloader run
# in order to resolve properly.
expected_result = {
"data"=>{
"cheese"=>{
"nonError"=> {
"id" => 3,
},
},
}
}
assert_equal(expected_result, result.to_h)
end
end
describe "fragment query when returned from a field" do
let(:query_string) {%|
query MilkQuery {
dairy {
...Dairy
}
}
fragment Dairy on Dairy {
milks {
source
executionError
allDairy {
__typename
...Milk
}
}
}
fragment Milk on Milk {
origin
executionError
}
|}
it "the error is inserted into the errors key and the rest of the query is fulfilled" do
expected_result = {
"data"=>{
"dairy" => {
"milks" => [
{
"source" => "COW",
"executionError" => nil,
"allDairy" => [
{ "__typename" => "Cheese" },
{ "__typename" => "Cheese" },
{ "__typename" => "Cheese" },
{ "__typename" => "Milk", "origin" => "Antiquity", "executionError" => nil }
]
}
]
}
},
"errors"=>[
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>11, "column"=>9}],
"path"=>["dairy", "milks", 0, "executionError"]
},
{
"message"=>"There was an execution error",
"locations"=>[{"line"=>21, "column"=>7}],
"path"=>["dairy", "milks", 0, "allDairy", 3, "executionError"]
}
]
}
assert_equal(expected_result, result)
end
end
describe "options in ExecutionError" do
let(:query_string) {%|
{
executionErrorWithOptions
}
|}
it "the error is inserted into the errors key and the rest of the query is fulfilled" do
expected_result = {
"data"=>{"executionErrorWithOptions"=>nil},
"errors"=>
[{"message"=>"Permission Denied!",
"locations"=>[{"line"=>3, "column"=>7}],
"path"=>["executionErrorWithOptions"],
"code"=>"permission_denied"}]
}
assert_equal(expected_result, result)
end
end
describe "extensions in ExecutionError" do
let(:query_string) {%|
{
executionErrorWithExtensions
}
|}
it "the error is inserted into the errors key with custom data set in `extensions`" do
expected_result = {
"data"=>{"executionErrorWithExtensions"=>nil},
"errors"=>
[{"message"=>"Permission Denied!",
"locations"=>[{"line"=>3, "column"=>7}],
"path"=>["executionErrorWithExtensions"],
"extensions"=>{"code"=>"permission_denied"}}]
}
assert_equal(expected_result, result)
end
end
describe "more than one ExecutionError" do
let(:query_string) { %|{ multipleErrorsOnNonNullableField} |}
it "the errors are inserted into the errors key and the data is nil even for a NonNullable field" do
expected_result = {
"data"=>nil,
"errors"=>
[{"message"=>"This is an error message for some error.",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["multipleErrorsOnNonNullableField"]},
{"message"=>"This is another error message for a different error.",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["multipleErrorsOnNonNullableField"]}],
}
assert_equal(expected_result, result)
end
describe "more than one ExecutionError on a field defined to return a list" do
let(:query_string) { %|{ multipleErrorsOnNonNullableListField} |}
it "the errors are inserted into the errors key and the data is nil even for a NonNullable field" do
expected_result = {
"data"=>{"multipleErrorsOnNonNullableListField"=>[nil, nil]},
"errors"=>
[{"message"=>"The first error message for a field defined to return a list of strings.",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["multipleErrorsOnNonNullableListField", 0]},
{"message"=>"The second error message for a field defined to return a list of strings.",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["multipleErrorsOnNonNullableListField", 1]}],
}
assert_equal(expected_result, result)
end
end
end
it "supports arrays containing only execution errors for list fields" do
schema = GraphQL::Schema.from_definition <<-GRAPHQL
type Query {
testArray: [String]!
}
GRAPHQL
root_value = OpenStruct.new(testArray: [GraphQL::ExecutionError.new("boom!"), GraphQL::ExecutionError.new("bang!"), "OK"])
result = schema.execute("{ testArray }", root_value: root_value)
assert_equal({ "testArray" => [nil, nil, "OK"]}, result["data"])
expected_errors = [
{
"message"=>"boom!",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["testArray", 0]
},
{
"message"=>"bang!",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["testArray", 1]
}
]
assert_equal(expected_errors, result["errors"])
root_value_errors_only = OpenStruct.new(testArray: [GraphQL::ExecutionError.new("zing!"), GraphQL::ExecutionError.new("fizz!")])
result = schema.execute("{ testArray }", root_value: root_value_errors_only)
assert_equal({ "testArray" => [nil, nil] }, result["data"])
expected_errors = [
{
"message"=>"zing!",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["testArray", 0]
},
{
"message"=>"fizz!",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["testArray", 1]
}
]
assert_equal(expected_errors, result["errors"])
end
describe "when ExecutionError is raised in resolve_type" do
let(:schema) do
test_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Test"
field :dummy, GraphQL::Types::Boolean
end
test_union = Class.new(GraphQL::Schema::Union) do
graphql_name "TestUnion"
possible_types test_type
end
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
field :test, test_union
define_method(:test) do
1
end
end
Class.new(GraphQL::Schema) do
query query_type
define_singleton_method(:resolve_type) do |abstract_type, obj, ctx|
raise GraphQL::ExecutionError.new("resolve_type")
end
end
end
it "return execution error with location and path" do
query = "{ test { ...on Test { dummy } } }"
result = schema.execute(query)
expected_result = {
"errors"=>[
{
"message"=>"resolve_type",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["test"]
}
],
"data"=>{"test"=>nil}
}
assert_equal(expected_result, result.to_h)
end
describe "when using DataLoaders" do
let(:schema) do
test_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Test"
field :dummy, GraphQL::Types::Boolean
end
test_union = Class.new(GraphQL::Schema::Union) do
graphql_name "TestUnion"
possible_types test_type
end
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
field :test, test_union
define_method(:test) do
1
end
end
Class.new(GraphQL::Schema) do
query query_type
use GraphQL::Dataloader
define_singleton_method(:resolve_type) do |abstract_type, obj, ctx|
raise GraphQL::ExecutionError.new("resolve_type")
end
end
end
it "return execution error with location and path" do
query = "{ test { ...on Test { dummy } } }"
result = schema.execute(query)
expected_result = {
"errors"=>[
{
"message"=>"resolve_type",
"locations"=>[{"line"=>1, "column"=>3}],
"path"=>["test"]
}
],
"data"=>{"test"=>nil}
}
assert_equal(expected_result, result.to_h)
end
end
end
describe "when using DataLoaders" do
let(:schema) do
item_error_loader = Class.new(GraphQL::Dataloader::Source) do
def fetch(keys)
keys.map { |key| GraphQL::ExecutionError.new("Error for #{key}") }
end
end
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "Query"
field :item, String do
argument :key, String
end
define_method(:item) do |key:|
dataloader.with(item_error_loader).load(key)
end
end
Class.new(GraphQL::Schema) do
query query_type
use GraphQL::Dataloader
end
end
let(:result) { schema.execute(query_string) }
describe "when querying for unique items" do
let(:query_string) {
<<-GRAPHQL
query {
query0: item(key: "a")
query1: item(key: "b")
}
GRAPHQL
}
it "returns unique execution errors locations and paths" do
expected_result = {
"data" => {
"query0" => nil,
"query1" => nil
},
"errors" => [
{
"message" => "Error for a",
"locations" => [{"line" => 2, "column" => 13}],
"path" => ["query0"]
},
{
"message" => "Error for b",
"locations" => [{"line" => 3, "column" => 13}],
"path" => ["query1"]
}
]
}
assert_equal(expected_result, result.to_h)
end
end
describe "when querying for duplicate items" do
let(:query_string) {
<<-GRAPHQL
query {
query0: item(key: "a")
query1: item(key: "a")
}
GRAPHQL
}
it "returns execution errors for duplicate items" do
expected_result = {
"data" => {
"query0" => nil,
"query1" => nil
},
"errors" => [
{
"message" => "Error for a",
"locations" => [{"line" => 2, "column" => 13}],
"path" => ["query0"]
},
{
"message" => "Error for a",
"locations" => [{"line" => 3, "column" => 13}],
"path" => ["query1"]
}
]
}
assert_equal(expected_result, result.to_h)
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/query/result_spec.rb | spec/graphql/query/result_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::Result do
let(:query_string) { '{ __type(name: "Cheese") { name } }' }
let(:schema) { Dummy::Schema }
let(:result) { schema.execute(query_string, context: { a: :b }) }
it "exposes hash-like methods" do
assert_equal "Cheese", result["data"]["__type"]["name"]
refute result.key?("errors")
assert_equal ["data"], result.keys
end
it "is equal with hashes" do
hash_result = {"data" => { "__type" => { "name" => "Cheese" } } }
assert_equal hash_result, result
end
it "tells the kind of operation" do
assert result.query?
refute result.mutation?
end
it "exposes the context" do
assert_instance_of GraphQL::Query::Context, result.context
expected_ctx = if GraphQL::Schema.use_visibility_profile? && result.context.schema.visibility.migration_errors?
{a: :b, visibility_migration_running: true}
else
{a: :b}
end
assert_equal(expected_ctx, result.context.to_h)
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/query/context_spec.rb | spec/graphql/query/context_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::Context do
after do
# Clean up test fixtures so they don't pollute later tests
# (Usually this is cleaned up by execution code, but many tests here don't actually execute queries)
Fiber[:__graphql_runtime_info] = nil
end
class ContextTestSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :context, String, resolver_method: :fetch_context_key do
argument :key, String
end
def fetch_context_key(key:)
context[key]
end
field :query_name, String
def query_name
context.query.class.name
end
field :push_query_error, Integer, null: false
def push_query_error
context.add_error(GraphQL::ExecutionError.new("Query-level error"))
1
end
end
query(Query)
end
let(:schema) { ContextTestSchema }
let(:result) { schema.execute(query_string, root_value: "rootval", context: {"some_key" => "some value"})}
describe "access to passed-in values" do
let(:query_string) { %|
query getCtx { context(key: "some_key") }
|}
it "passes context to fields" do
expected = {"data" => {"context" => "some value"}}
assert_equal(expected, result)
end
end
describe "access to the query" do
let(:query_string) { %|
query getCtx { queryName }
|}
it "provides access to the query object" do
expected = {"data" => {"queryName" => "GraphQL::Query"}}
assert_equal(expected, result)
end
end
describe "empty values" do
let(:context) { GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: nil) }
it "returns returns nil and reports key? => false" do
assert_nil(context[:some_key])
assert_equal(false, context.key?(:some_key))
assert_raises(KeyError) { context.fetch(:some_key) }
end
end
describe "assigning values" do
let(:context) { GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: nil) }
it "allows you to assign new contexts" do
assert_nil(context[:some_key])
context[:some_key] = "wow!"
assert_equal("wow!", context[:some_key])
end
describe "namespaces" do
let(:context) { GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: {a: 1}) }
it "doesn't conflict with base values" do
ns = context.namespace(:stuff)
ns[:b] = 2
assert_equal({a: 1}, context.to_h)
assert_equal({b: 2}, context.namespace(:stuff))
end
end
end
describe "read values" do
let(:context) { GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: {a: {b: 1}}) }
it "allows you to read values of contexts using []" do
assert_equal({b: 1}, context[:a])
end
it "allows you to read values of contexts using dig" do
assert_equal(1, context.dig(:a, :b))
Fiber[:__graphql_runtime_info] = { context.query => OpenStruct.new(current_arguments: {c: 1}) }
assert_equal 1, context.dig(:current_arguments, :c)
assert_equal({c: 1}, context.dig(:current_arguments))
end
end
describe "splatting" do
let(:context) { GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: {a: {b: 1}}) }
let(:splat) { ->(**context) { context } }
it "runs successfully" do
assert_equal({a: { b: 1 }}, splat.call(**context))
end
end
it "can override values set by runtime" do
context = GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: {a: {b: 1}})
Fiber[:__graphql_runtime_info] = { context.query => OpenStruct.new({ current_object: :runtime_value }) }
assert_equal :runtime_value, context[:current_object]
context[:current_object] = :override_value
assert_equal :override_value, context[:current_object]
end
describe "query-level errors" do
let(:query_string) { %|
{ pushQueryError }
|}
it "allows query-level errors" do
expected_err = { "message" => "Query-level error" }
assert_equal [expected_err], result["errors"]
end
end
describe "custom context class" do
it "can be specified" do
query_str = '{
inspectContext
find(id: "Musician/Herbie Hancock") {
... on Musician {
inspectContext
}
}
}'
res = Jazz::Schema.execute(query_str, context: { magic_key: :ignored, normal_key: "normal_value" })
expected_values = ["custom_method", "magic_value", "normal_value"]
expected_values_with_nil = expected_values + [nil]
assert_equal expected_values, res["data"]["inspectContext"]
assert_equal expected_values_with_nil, res["data"]["find"]["inspectContext"]
end
end
describe "scoped context" do
class LazyBlock
def initialize(&block)
@get_value = block
end
def value
@get_value.call
end
end
class PassthroughSource < GraphQL::Dataloader::Source
def fetch(keys)
keys
end
end
class IntArraySource < GraphQL::Dataloader::Source
def fetch(keys)
keys.map { |k| k.times.map { |i| i } }
end
end
class ContextQuery < GraphQL::Schema::Object
field :get_scoped_context, String do
argument :key, String
argument :lazy, Boolean, required: false, default_value: false
end
def get_scoped_context(key:, lazy:)
result = LazyBlock.new {
context[key]
}
return result if lazy
result.value
end
field :set_scoped_context, ContextQuery, null: false do
argument :key, String
argument :value, String
argument :lazy, Boolean, required: false, default_value: false
end
def set_scoped_context(key:, value:, lazy:)
if lazy
LazyBlock.new {
context.scoped_merge!(key => value)
LazyBlock.new {
self
}
}
else
context.scoped_merge!(key => value)
context.dataloader.with(PassthroughSource).load(self)
end
end
field :int_list, [ContextQuery], null: false
def int_list
context.scoped_set!("int_list", "assigned")
context.dataloader.with(IntArraySource).load(4)
end
field :set_scoped_int, ContextQuery, null: false
def set_scoped_int
context.scoped_set!("int", object.to_s)
object.to_s
end
end
class ContextSchema < GraphQL::Schema
query(ContextQuery)
lazy_resolve(LazyBlock, :value)
use GraphQL::Dataloader
end
it "can be set and does not leak to sibling fields" do
query_str = %|
{
before: getScopedContext(key: "a")
firstSetOuter: setScopedContext(key: "a", value: "1") {
before: getScopedContext(key: "a")
setInner: setScopedContext(key: "a", value: "2") {
only: getScopedContext(key: "a")
}
after: getScopedContext(key: "a")
}
secondSetOuter: setScopedContext(key: "a", value: "3") {
before: getScopedContext(key: "a")
setInner: setScopedContext(key: "a", value: "4") {
only: getScopedContext(key: "a")
}
after: getScopedContext(key: "a")
}
after: getScopedContext(key: "a")
}
|
expected = {
'before' => nil,
'firstSetOuter' => {
'before' => '1',
'setInner' => {
'only' => '2',
},
'after' => '1',
},
'secondSetOuter' => {
'before' => '3',
'setInner' => {
'only' => '4',
},
'after' => '3',
},
'after' => nil,
}
result = ContextSchema.execute(query_str).to_h['data']
assert_equal(expected, result)
end
it "can be set and does not leak to sibling fields when all resolvers are lazy values" do
query_str = %|
{
before: getScopedContext(key: "a", lazy: true)
setOuter: setScopedContext(key: "a", value: "1", lazy: true) {
before: getScopedContext(key: "a", lazy: true)
setInner: setScopedContext(key: "a", value: "2", lazy: true) {
only: getScopedContext(key: "a", lazy: true)
}
after: getScopedContext(key: "a", lazy: true)
}
after: getScopedContext(key: "a", lazy: true)
}
|
expected = {
'before' => nil,
'setOuter' => {
'before' => '1',
'setInner' => {
'only' => '2',
},
'after' => '1',
},
'after' => nil,
}
result = ContextSchema.execute(query_str).to_h['data']
assert_equal(expected, result)
end
it "can be set and does not leak to sibling fields when all get resolvers are lazy values" do
query_str = %|
{
before: getScopedContext(key: "a", lazy: true)
setOuter: setScopedContext(key: "a", value: "1") {
before: getScopedContext(key: "a", lazy: true)
setInner: setScopedContext(key: "a", value: "2") {
only: getScopedContext(key: "a", lazy: true)
}
after: getScopedContext(key: "a", lazy: true)
}
after: getScopedContext(key: "a", lazy: true)
}
|
expected = {
'before' => nil,
'setOuter' => {
'before' => '1',
'setInner' => {
'only' => '2',
},
'after' => '1',
},
'after' => nil,
}
result = ContextSchema.execute(query_str).to_h['data']
assert_equal(expected, result)
end
it "can be set and does not leak to sibling fields when all set resolvers are lazy values" do
query_str = %|
{
before: getScopedContext(key: "a")
setOuter: setScopedContext(key: "a", value: "1", lazy: true) {
before: getScopedContext(key: "a")
setInner: setScopedContext(key: "a", value: "2", lazy: true) {
only: getScopedContext(key: "a")
}
after: getScopedContext(key: "a")
}
after: getScopedContext(key: "a")
}
|
expected = {
'before' => nil,
'setOuter' => {
'before' => '1',
'setInner' => {
'only' => '2',
},
'after' => '1',
},
'after' => nil,
}
result = ContextSchema.execute(query_str).to_h['data']
assert_equal(expected, result)
end
it "doesn't leak inside lists" do
query_str = <<-GRAPHQL
{
intList {
before: getScopedContext(key: "int")
setScopedInt {
inside: getScopedContext(key: "int")
inside2: getScopedContext(key: "int_list")
}
after: getScopedContext(key: "int")
}
}
GRAPHQL
expected_data = {"intList"=>
[{"setScopedInt"=>{"inside"=>"0", "inside2" => "assigned"}, "before"=>nil, "after"=>nil},
{"setScopedInt"=>{"inside"=>"1", "inside2" => "assigned"}, "before"=>nil, "after"=>nil},
{"setScopedInt"=>{"inside"=>"2", "inside2" => "assigned"}, "before"=>nil, "after"=>nil},
{"setScopedInt"=>{"inside"=>"3", "inside2" => "assigned"}, "before"=>nil, "after"=>nil}]}
result = ContextSchema.execute(query_str)
assert_equal(expected_data, result["data"])
end
it "always retrieves a scoped context value if set" do
context = GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: nil)
dummy_runtime = OpenStruct.new(current_result: nil)
Fiber[:__graphql_runtime_info] = { context.query => dummy_runtime }
dummy_runtime.current_result = OpenStruct.new(path: ["somewhere"])
expected_key = :a
expected_value = :test
assert_nil(context[expected_key])
assert_equal({}, context.to_h)
refute(context.key?(expected_key))
assert_raises(KeyError) { context.fetch(expected_key) }
assert_nil(context.fetch(expected_key, nil))
assert_nil(context.dig(expected_key))
context.scoped_merge!(expected_key => nil)
context[expected_key] = expected_value
assert_nil(context[expected_key])
assert_equal({ expected_key => nil }, context.to_h)
assert(context.key?(expected_key))
assert_nil(context.fetch(expected_key))
assert_nil(context.dig(expected_key))
dummy_runtime.current_result = OpenStruct.new(path: ["something", "new"])
assert_equal(expected_value, context[expected_key])
assert_equal({ expected_key => expected_value}, context.to_h)
assert(context.key?(expected_key))
assert_equal(expected_value, context.fetch(expected_key))
assert_equal(expected_value, context.dig(expected_key))
# Enter a child field:
dummy_runtime.current_result = OpenStruct.new(path: ["somewhere", "child"])
assert_nil(context[expected_key])
assert_equal({ expected_key => nil }, context.to_h)
assert(context.key?(expected_key))
assert_nil(context.fetch(expected_key))
assert_nil(context.dig(expected_key))
# And a grandchild field
dummy_runtime.current_result = OpenStruct.new(path: ["somewhere", "child", "grandchild"])
context.scoped_set!(expected_key, :something_else)
context.scoped_set!(:another_key, :another_value)
assert_equal(:something_else, context[expected_key])
assert_equal({ expected_key => :something_else, another_key: :another_value }, context.to_h)
assert(context.key?(expected_key))
assert_equal(:something_else, context.fetch(expected_key))
assert_equal(:something_else, context.dig(expected_key))
end
it "sets a value using #scoped_set!" do
expected_key = :a
expected_value = :test
context = GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: nil)
assert_nil(context[expected_key])
context.scoped_set!(expected_key, expected_value)
assert_equal(expected_value, context[expected_key])
end
it "has a #current_path method" do
context = GraphQL::Query::Context.new(query: OpenStruct.new(schema: schema), values: nil)
current_result = OpenStruct.new(path: ["somewhere", "child", "grandchild"])
Fiber[:__graphql_runtime_info] = { context.query => OpenStruct.new(current_result: current_result) }
assert_equal ["somewhere", "child", "grandchild"], context.scoped_context.current_path
end
end
describe "Adding extensions to the response" do
class ResponseExtensionsSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :with_extension, String
def with_extension
context.response_extensions["Something"] = "Something else"
"OK"
end
end
query(Query)
end
it "adds .response_extensions" do
expected_response = {
"data" => { "withExtension" => "OK" },
"extensions" => { "Something" => "Something else" },
}
assert_equal(expected_response, ResponseExtensionsSchema.execute("{ withExtension }"))
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/query/variable_validation_error_spec.rb | spec/graphql/query/variable_validation_error_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::VariableValidationError do
let(:ast) { Struct.new(:name, :line, :col).new('input', 1, 2) }
let(:type) { Struct.new(:to_type_signature).new('TestType') }
let(:error_value) { 'some value' }
let(:problems) { [{'path' => ['path-to-problem'], 'explanation' => 'it broke'}] }
let(:validation_result) { Struct.new(:problems).new(problems) }
let(:subject) do
Class.new(GraphQL::Query::VariableValidationError) do
def extensions
{
code: 'ERROR',
}
end
end
end
describe '#to_h' do
it 'includes value and problems in extensions' do
error = subject.new(ast, type, error_value, validation_result)
as_hash = {
'message' => 'Variable $input of type TestType was provided invalid value for path-to-problem (it broke)',
'locations' => [ {'line' => 1, 'column' => 2} ],
'extensions' => {
'code' => 'ERROR',
'value' => error_value,
'problems' => problems
}
}
assert_equal error.to_h, as_hash
end
it 'when msg param is passed it overwrites the message and adds validation result message' do
error = subject.new(ast, type, error_value, validation_result, msg: "test")
as_hash = {
'message' => 'test for path-to-problem (it broke)',
'locations' => [ {'line' => 1, 'column' => 2} ],
'extensions' => {
'code' => 'ERROR',
'value' => error_value,
'problems' => problems
}
}
assert_equal error.to_h, as_hash
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/query/variables_spec.rb | spec/graphql/query/variables_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Query::Variables" do
module VariablesTest
class MaxValidationSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :items, [String], null: false do
argument :a, Int
argument :b, Int
argument :c, Int
end
def items(a:, b:, c:)
[a, b, c].map(&:to_s)
end
end
query(Query)
end
end
let(:variables) { {a: "1", b: "1", c: "1"} }
let(:query_string) { "query($a: Int!, $b: Int!, $c: Int!) { items(a: $a, b: $b, c: $c)}" }
describe "when there are no variable errors" do
let(:schema) { VariablesTest::MaxValidationSchema }
let(:variables) { {a: 1, b: 1, c: 1} }
it "does not return any error" do
res = schema.execute(query_string, variables: variables)
assert_nil res["errors"]
end
end
describe "when validate_max_errors is nil" do
let(:schema) { VariablesTest::MaxValidationSchema }
it "returns all errors" do
res = schema.execute(query_string, variables: variables)
assert_equal 3, res["errors"].count
end
end
describe "when max validation error is set" do
class TestSchema < VariablesTest::MaxValidationSchema
validate_max_errors(2)
end
let(:schema) { TestSchema }
describe "when errors are more than validate_max_value value" do
it "raises only as many errors as the validate_max_errors value and appends the too many errors message" do
res = schema.execute(query_string, variables: variables)
assert_equal 3, res["errors"].count
assert_match(/Too many errors processing variables/, res["errors"].last["message"])
end
end
describe "when errors are equal with validate_max_value" do
let(:variables) { {a: 1, b: "1", c: "1"} }
it "raises all errors" do
res = schema.execute(query_string, variables: variables)
assert_equal 2, res["errors"].count
end
end
describe "when variables are empty" do
let(:variables) { {} }
it "raises all errors" do
res = schema.execute(query_string, variables: variables)
assert_equal 3, res["errors"].count
assert_match(/Too many errors processing variables/, res["errors"].last["message"])
end
end
end
describe "when an invalid enum value is given" do
class EnumVariableSchema < GraphQL::Schema
class Filter < GraphQL::Schema::Enum
value(:contains) { def visible?(ctx); !ctx[:hide_enum_value]; end }
value(:equals) { def visible?(ctx); !ctx[:hide_enum_value]; end }
def self.visible?(ctx)
!ctx[:hide_enum]
end
end
class FilterInput < GraphQL::Schema::InputObject
argument :filter, Filter, default_value: "contains" do
def visible?(_ctx); true; end
end
end
class Query < GraphQL::Schema::Object
field :filter, String do
argument :input, FilterInput
end
def filter(input:)
input.filter.to_s
end
end
query(Query)
end
it "handles the error nicely" do
query_str = "query EchoFilter($input: FilterInput!) { filter(input: $input) }"
variables = { "input" => { "filter" => "contains" } }
query = GraphQL::Query.new(
EnumVariableSchema,
query_str,
variables: variables,
context: { hide_enum_value: true }
)
assert_raises GraphQL::Schema::Enum::MissingValuesError do
query.result
end
query2 = GraphQL::Query.new(
EnumVariableSchema,
query_str,
variables: variables,
context: { hide_enum_value: true, hide_enum: true }
)
expected_messages = [
"Variable $input of type FilterInput! was provided invalid value for filter (Field is not defined on FilterInput)"
]
assert query2.variables
assert_equal expected_messages, query2.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/query/null_context_spec.rb | spec/graphql/query/null_context_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::NullContext do
let(:null_context) { GraphQL::Query::NullContext.instance }
describe "#[]" do
it "returns nil" do
assert_nil(null_context[:foo])
end
end
describe "#fetch" do
it "returns the default value argument" do
assert_equal(:default, null_context.fetch(:foo, :default))
end
it "returns the block result" do
assert_equal(:default, null_context.fetch(:foo) { :default })
end
it "raises a KeyError when not passed a default value or a block" do
assert_raises(KeyError) { null_context.fetch(:foo) }
end
end
describe "#key?" do
it "returns false" do
assert(!null_context.key?(:foo))
end
end
describe "#dig?" do
it "returns nil" do
assert_nil(null_context.dig(:foo, :bar, :baz))
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/query/executor_spec.rb | spec/graphql/query/executor_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Query::Executor" do
let(:operation_name) { nil }
let(:schema) { Dummy::Schema }
let(:variables) { {"cheeseId" => 2} }
let(:query) { GraphQL::Query.new(
schema,
query_string,
variables: variables,
operation_name: operation_name,
)}
let(:result) { query.result }
describe "multiple operations" do
let(:query_string) { %|
query getCheese1 { cheese(id: 1) { flavor } }
query getCheese2 { cheese(id: 2) { flavor } }
|}
describe "when an operation is named" do
let(:operation_name) { "getCheese2" }
it "runs the named one" do
expected = {
"data" => {
"cheese" => {
"flavor" => "Gouda"
}
}
}
assert_equal(expected, result)
end
end
describe "when one is NOT named" do
it "returns an error" do
expected = {
"errors" => [
{"message" => "An operation name is required"}
]
}
assert_equal(expected, result)
end
end
describe "when the named operation is not present" do
let(:operation_name) { "nonsenseOperation" }
it "returns an error" do
expected = {
"errors" => [
{"message" => 'No operation named "nonsenseOperation"'}
]
}
assert_equal(expected, result)
end
end
end
describe "operation and fragment definitions of the same name" do
let(:query_string) { %|
query Cheese { cheese(id: 1) { ...Cheese } }
query MoreCheese { cheese(id: 2) { ...Cheese } }
fragment Cheese on Cheese { flavor }
|}
let(:operation_name) { "Cheese" }
it "runs the named operation" do
expected = {
"data" => {
"cheese" => {
"flavor" => "Brie"
}
}
}
assert_equal(expected, result)
end
end
describe "execution order" do
let(:query_string) {%|
mutation setInOrder {
first: pushValue(value: 1)
second: pushValue(value: 5)
third: pushValue(value: 2)
fourth: replaceValues(input: {values: [6,5,4]})
}
|}
it "executes mutations in order" do
expected = {"data"=>{
"first"=> [1],
"second"=>[1, 5],
"third"=> [1, 5, 2],
"fourth"=> [6, 5 ,4],
}}
assert_equal(expected, result)
end
end
describe "fragment resolution" do
let(:schema) { Dummy::Schema }
let(:variables) { nil }
let(:query_string) { %|
query getDairy {
dairy {
id
... on Dairy {
id
}
...repetitiveFragment
}
}
fragment repetitiveFragment on Dairy {
id
}
|}
it "resolves each field only one time, even when present in multiple fragments" do
ctx = { resolved_count: 0 }
result = Dummy::Schema.execute(query_string, context: ctx)
expected = {"data" => {
"dairy" => { "id" => "1" }
}}
assert_equal(expected, result)
assert_equal 1, ctx[:resolved_count]
end
end
describe "runtime errors" do
let(:query_string) {%| query noMilk { error }|}
it "raises error" do
assert_raises(RuntimeError) { result }
end
describe "if nil is given for a non-null field" do
let(:query_string) {%| query noMilk { cow { name cantBeNullButIs } }|}
it "turns into error message and nulls the entire selection" do
expected = {
"data" => { "cow" => nil },
"errors" => [
{
"message" => "Cannot return null for non-nullable field Cow.cantBeNullButIs",
"path" => ["cow", "cantBeNullButIs"],
"locations" => [{ "line" => 1, "column" => 28 }]
}
]
}
assert_equal(expected, result)
end
end
describe "if an execution error is raised for a non-null field" do
let(:query_string) {%| query noMilk { cow { name cantBeNullButRaisesExecutionError } }|}
it "uses provided error message and nulls the entire selection" do
expected = {
"data" => { "cow" => nil },
"errors" => [
{
"message" => "BOOM",
"locations" => [ { "line" => 1, "column" => 28 } ],
"path" => ["cow", "cantBeNullButRaisesExecutionError"]
}
]
}
assert_equal(expected, result)
end
end
describe "if the schema has a rescue handler" do
let(:schema) {
Class.new(Dummy::Schema) do
rescue_from(RuntimeError) { raise GraphQL::ExecutionError, "Error was handled!" }
end
}
it "adds to the errors key" do
expected = {
"data" => {"error" => nil},
"errors"=>[
{
"message"=>"Error was handled!",
"locations" => [{"line"=>1, "column"=>17}],
"path"=>["error"],
}
]
}
assert_equal(expected, result)
end
end
describe "if the schema has a rescue handler with an instance of GraphQL::ExecutionError as an argument" do
let(:schema) {
Class.new(Dummy::Schema) do
rescue_from(RuntimeError) { GraphQL::ExecutionError.new("Error was handled!", extensions: { code: "DUMMY_ERROR" }) }
end
}
it "adds to the errors key" do
expected = {
"data" => {"error" => nil},
"errors"=>[
{
"message"=>"Error was handled!",
"locations" => [{"line"=>1, "column"=>17}],
"path"=>["error"],
"extensions"=>{ "code" => "DUMMY_ERROR"}
}
]
}
assert_equal(expected, result)
end
end
end
describe "variable coercion" do
describe "for unspecified with default" do
let(:query_string) {%| query Q($limit: Int = 2) { milk(id: 1) { flavors(limit: $limit) } } |}
it "uses the default value" do
expected = {
"data" => {
"milk" => {
"flavors" => ["Natural", "Chocolate"],
}
}
}
assert_equal(expected, result)
end
end
describe "for input object type" do
let(:variables) { {"input" => [{ "source" => "SHEEP" }]} }
let(:query_string) {%| query Q($input: [DairyProductInput]) { searchDairy(product: $input) { __typename, ... on Cheese { id, source } } } |}
it "uses the default value" do
expected = {
"data" => {
"searchDairy" => {
"__typename" => "Cheese",
"id" => 3,
"source" => "SHEEP"
}
}
}
assert_equal(expected, result)
end
end
describe "for required input objects" do
let(:variables) { { } }
let(:query_string) {%| mutation M($input: ReplaceValuesInput!) { replaceValues(input: $input) } |}
it "returns a variable validation error" do
expected = {
"errors"=>[
{
"message" => "Variable $input of type ReplaceValuesInput! was provided invalid value",
"locations" => [{ "line" => 1, "column" => 13 }],
"extensions" => {
"value" => nil,
"problems" => [{ "path" => [], "explanation" => "Expected value to not be null" }]
}
}
]
}
assert_equal(expected, result)
end
end
describe "for required input object fields" do
let(:variables) { {"input" => {} } }
let(:query_string) {%| mutation M($input: ReplaceValuesInput!) { replaceValues(input: $input) } |}
it "returns a variable validation error" do
expected = {
"errors"=>[
{
"message" => "Variable $input of type ReplaceValuesInput! was provided invalid value for values (Expected value to not be null)",
"locations" => [{ "line" => 1, "column" => 13 }],
"extensions" => {
"value" => {},
"problems" => [{ "path" => ["values"], "explanation" => "Expected value to not be null" }]
}
}
]
}
assert_equal(expected, result)
end
end
describe "for input objects with unknown keys in value" do
let(:variables) { {"input" => [{ "foo" => "bar" }]} }
let(:query_string) {%| query Q($input: [DairyProductInput]) { searchDairy(product: $input) { __typename, ... on Cheese { id, source } } } |}
it "returns a variable validation error" do
expected = {
"errors"=>[
{
"message" => "Variable $input of type [DairyProductInput] was provided invalid value for 0.foo (Field is not defined on DairyProductInput), 0.source (Expected value to not be null)",
"locations" => [{ "line" => 1, "column" => 10 }],
"extensions" => {
"value" => [{ "foo" => "bar" }],
"problems" => [
{ "path" => [0, "foo"], "explanation" => "Field is not defined on DairyProductInput" },
{ "path" => [0, "source"], "explanation" => "Expected value to not be null" }
]
}
}
]
}
assert_equal(expected, result.to_h)
end
end
describe "for input objects with nil value for a required input" do
let(:variables) { {"input" => [{ "source" => nil }]} }
let(:query_string) {%| query Q($input: [DairyProductInput]) { searchDairy(product: $input) { __typename, ... on Cheese { id, source } } } |}
it "returns a variable validation error" do
expected = {
"errors"=>[
{
"message" => "Variable $input of type [DairyProductInput] was provided invalid value for 0.source (Expected value to not be null)",
"locations" => [{ "line" => 1, "column" => 10 }],
"extensions" => {
"value" => [{ "source" => nil }],
"problems" => [
{ "path" => [0, "source"], "explanation" => "Expected value to not be null" }
]
}
}
]
}
assert_equal(expected, result.to_h)
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/query/fingerprint_spec.rb | spec/graphql/query/fingerprint_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::Fingerprint do
def build_query(str, var)
GraphQL::Query.new(Dummy::Schema, str, variables: var)
end
it "makes stable variable fingerprints" do
var1a = { "a" => 1, "b" => 2 }
var1b = { "a" => 1, "b" => 2 }
# These keys are in a different order -- they'll be hashed differently.
var2 = { "b" => 2, "a" => 1 }
str = "{ __typename }"
expected_fingerprint = "2/QyWM_3g_5wNtikMDP4MK38YOwDc4JHNUisdCuIgpJ3c="
assert_equal expected_fingerprint, build_query(str, var1a).variables_fingerprint
assert_equal expected_fingerprint, build_query(str, var1b).variables_fingerprint
other_expected_fingerprint = "2/P7dUUyJccyp2t4meoglt2hRVGJyJgXI5cyGC9z_loJ8="
assert_equal other_expected_fingerprint, build_query(str, var2).variables_fingerprint
# `nil` is treated like {}
empty_fingerprint = "0/RBNvo1WzZ4oRRq0W9-hknpT7T8If536DEMBg9hyq_4o="
assert_equal empty_fingerprint, build_query(str, nil).variables_fingerprint
assert_equal empty_fingerprint, build_query(str, {}).variables_fingerprint
end
it "makes stable query fingerprints" do
str1a = "{ __typename }"
str1b = "{ __typename }"
# Different whitespace is a different query
str2 = "{\n __typename\n}\n"
str3 = "query GetTypename { __typename }"
expected_fingerprint = "anonymous/f1bmfdIas_MNH_i3vtCIk_Cg24ZEmDYYmzYd0eVt20s="
assert_equal expected_fingerprint, build_query(str1a, {}).operation_fingerprint
assert_equal expected_fingerprint, build_query(str1b, {}).operation_fingerprint
other_expected_fingerprint = "anonymous/jY9zZenob6jjMT_K8hMbgB6v6VSd4iNzCJzydRGFizk="
assert_equal other_expected_fingerprint, build_query(str2, {}).operation_fingerprint
op_name_expected_fingerprint = "GetTypename/eKSJYYymUg0JV-FrtUF5idy4Ydt1IE4lZoHzxtzWog0="
assert_equal op_name_expected_fingerprint, build_query(str3, {}).operation_fingerprint
end
it "returns a fingerprint when the query string is blank or nil" do
nil_query = build_query(nil, {})
blank_query = build_query("", {})
assert_equal "anonymous/47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU=", blank_query.operation_fingerprint
assert_equal "anonymous/47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU=", nil_query.operation_fingerprint
end
it "makes combined fingerprints" do
str1a = "{ __typename }"
str1b = "{ __typename }"
str1_fingerprint = "f1bmfdIas_MNH_i3vtCIk_Cg24ZEmDYYmzYd0eVt20s="
str2 = "query getTypename {\n __typename\n}\n"
str2_fingerprint = "PZ4sJYI9Dkw_SxWdh_VdxKEuktK_nIoSvev_0QrEHL8="
var1a = { "a" => 1, "b" => 2 }
var1b = { "a" => 1, "b" => 2 }
var1_fingerprint = "QyWM_3g_5wNtikMDP4MK38YOwDc4JHNUisdCuIgpJ3c="
# These keys are in a different order -- they'll be hashed differently.
var2 = { "b" => 2, "a" => 1 }
var2_fingerprint = "P7dUUyJccyp2t4meoglt2hRVGJyJgXI5cyGC9z_loJ8="
nil_var_fingerprint = "RBNvo1WzZ4oRRq0W9-hknpT7T8If536DEMBg9hyq_4o="
assert_equal "anonymous/#{str1_fingerprint}/2/#{var1_fingerprint}", build_query(str1a, var1a).fingerprint
assert_equal "anonymous/#{str1_fingerprint}/2/#{var1_fingerprint}", build_query(str1b, var1b).fingerprint
assert_equal "getTypename/#{str2_fingerprint}/0/#{nil_var_fingerprint}", build_query(str2, nil).fingerprint
assert_equal "anonymous/#{str1_fingerprint}/2/#{var2_fingerprint}", build_query(str1a, var2).fingerprint
assert_equal "getTypename/#{str2_fingerprint}/2/#{var1_fingerprint}", build_query(str2, var1b).fingerprint
example_query = build_query(str2, var1b)
assert_equal example_query.fingerprint, "#{example_query.operation_fingerprint}/#{example_query.variables_fingerprint}"
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/query/partial_spec.rb | spec/graphql/query/partial_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::Partial do
class PartialSchema < GraphQL::Schema
module Database
FARMS = {
"1" => OpenStruct.new(name: "Bellair Farm", products: ["VEGETABLES", "MEAT", "EGGS"], neighboring_farm_id: "2"),
"2" => OpenStruct.new(name: "Henley's Orchard", products: ["FRUIT", "MEAT", "EGGS"], neighboring_farm_id: "3"),
"3" => OpenStruct.new(name: "Wenger Grapes", products: ["FRUIT"], neighboring_farm_id: "1"),
}
class << self
def get(id)
@log << [:get, id]
FARMS[id]
end
def mget(ids)
@log << [:mget, ids]
ids.map { |id| FARMS[id] }
end
attr_reader :log
def clear
@log = []
end
end
end
class FarmSource < GraphQL::Dataloader::Source
def fetch(farm_ids)
Database.mget(farm_ids)
end
end
class FarmProduct < GraphQL::Schema::Enum
value :FRUIT
value :VEGETABLES
value :MEAT, value: :__MEAT__
value :EGGS
value :DAIRY
end
module Entity
include GraphQL::Schema::Interface
field :name, String
end
class Farm < GraphQL::Schema::Object
implements Entity
field :name, String
field :products, [FarmProduct]
field :error, Int
def error
raise GraphQL::ExecutionError, "This is a field error"
end
field :neighboring_farm, Farm
def neighboring_farm
dataloader.with(FarmSource).load(object.neighboring_farm_id)
end
end
class UpcasedFarm < GraphQL::Schema::Object
field :name, String
def name
object[:name].upcase
end
end
class Market < GraphQL::Schema::Object
implements Entity
field :is_year_round, Boolean
end
class Thing < GraphQL::Schema::Union
possible_types(Farm, Market)
end
class Query < GraphQL::Schema::Object
field :farms, [Farm], fallback_value: Database::FARMS.values
field :farm, Farm do
argument :id, ID, loads: Farm, as: :farm
end
def farm(farm:)
farm
end
field :farm_names, [String], fallback_value: Database::FARMS.each_value.map(&:name)
field :query, Query, fallback_value: true
field :thing, Thing
def thing
Database.get("1")
end
field :entity, Entity
def entity; Database.get("1"); end
field :read_context, String do
argument :key, String
end
def read_context(key:)
-> { context[key].to_s }
end
field :current_path, [String]
def current_path
context.current_path
end
field :current_values, [String]
def current_values
[
GraphQL::Current.operation_name,
GraphQL::Current.field.path,
GraphQL::Current.dataloader_source_class.inspect,
]
end
end
class Mutation < GraphQL::Schema::Object
field :update_farm, Farm do
argument :name, String
end
def update_farm(name:)
{ name: name }
end
end
query(Query)
mutation(Mutation)
def self.object_from_id(id, ctx)
ctx.dataloader.with(FarmSource).load(id)
end
def self.resolve_type(abs_type, object, ctx)
object[:is_market] ? Market : Farm
end
use GraphQL::Dataloader
lazy_resolve Proc, :call
end
before do
PartialSchema::Database.clear
end
def run_partials(string, partial_configs, **query_kwargs)
query = GraphQL::Query.new(PartialSchema, string, **query_kwargs)
query.run_partials(partial_configs)
end
it "returns results for the named parts" do
str = "{
farms { name, products }
farm1: farm(id: \"1\") { name }
farm2: farm(id: \"2\") { name }
}"
results = run_partials(str, [
{ path: ["farm1"], object: PartialSchema::Database::FARMS["1"] },
{ path: ["farm2"], object: OpenStruct.new(name: "Injected Farm") },
{ path: ["farms", 0], object: { name: "Kestrel Hollow", products: [:__MEAT__, "EGGS"]} },
])
assert_equal [
{ "data" => { "name" => "Bellair Farm" } },
{ "data" => { "name" => "Injected Farm" } },
{"data" => {"name" => "Kestrel Hollow", "products" => ["MEAT", "EGGS"]} },
], results
end
it "runs inline fragments" do
str = "{
farm(id: \"1\") {
... on Farm {
name
... {
n2: name
}
}
}
}"
document = GraphQL.parse(str)
fragment_node = document.definitions.first.selections.first.selections.first
other_fragment_node = fragment_node.selections[1]
results = run_partials(str, [
{ fragment_node: fragment_node, type: PartialSchema::Farm, object: { name: "Belair Farm" } },
{ fragment_node: other_fragment_node, type: PartialSchema::UpcasedFarm, object: { name: "Free Union Grass Farm" } }
])
assert_equal({ "name" => "Belair Farm", "n2" => "Belair Farm" }, results[0]["data"])
assert_equal({ "n2" => "FREE UNION GRASS FARM" }, results[1]["data"])
end
it "runs fragment definitions" do
str = "{
farm(id: \"1\") { ... farmFields }
}
fragment farmFields on Farm {
farmName: name
}"
node = GraphQL.parse(str).definitions.last
results = run_partials(str, [{ fragment_node: node, type: PartialSchema::Farm, object: { name: "Clovertop Creamery" } }])
assert_equal({ "farmName" => "Clovertop Creamery" }, results[0]["data"])
end
it "works with GraphQL::Current" do
res = run_partials("query CheckCurrentValues { query { currentValues } }", [path: ["query"], object: nil])
assert_equal ["CheckCurrentValues", "Query.currentValues", "nil"], res[0]["data"]["currentValues"]
end
it "returns errors if they occur" do
str = "{
farm1: farm(id: \"1\") { error }
farm2: farm(id: \"1\") { name }
farm3: farm(id: \"1\") { name fieldError: error }
farm4: farm(id: \"1\") {
neighboringFarm {
error
}
}
}"
results = run_partials(str, [
{ path: ["farm1"], object: PartialSchema::Database::FARMS["1"] },
{ path: ["farm2"], object: PartialSchema::Database::FARMS["2"] },
{ path: ["farm3"], object: PartialSchema::Database::FARMS["3"] },
{ path: ["farm4"], object: PartialSchema::Database::FARMS["3"] },
])
assert_equal [{"message"=>"This is a field error", "locations"=>[{"line"=>2, "column"=>30}], "path"=>["farm1", "error"]}], results[0]["errors"]
refute results[1].key?("errors")
assert_equal [{"message"=>"This is a field error", "locations"=>[{"line"=>4, "column"=>35}], "path"=>["farm3", "fieldError"]}], results[2]["errors"]
assert_equal [{"message"=>"This is a field error", "locations"=>[{"line"=>7, "column"=>11}], "path"=>["farm4", "neighboringFarm", "error"]}], results[3]["errors"]
assert_equal({ "error" => nil }, results[0]["data"])
assert_equal({ "name" => "Henley's Orchard" }, results[1]["data"])
assert_equal({ "name" => "Wenger Grapes", "fieldError" => nil }, results[2]["data"])
assert_equal({ "neighboringFarm" => { "error" => nil } }, results[3]["data"])
end
it "raises errors when given nonexistent paths" do
str = "{ farm1: farm(id: \"1\") { error neighboringFarm { name } } }"
query = GraphQL::Query.new(PartialSchema, str)
err = assert_raises ArgumentError do
query.run_partials([{ path: ["farm500"], object: PartialSchema::Database::FARMS["1"] }])
end
assert_equal "Path `[\"farm500\"]` is not present in this query. `\"farm500\"` was not found. Try a different path or rewrite the query to include it.", err.message
err = assert_raises ArgumentError do
query.run_partials([{ path: ["farm1", "neighboringFarm", "blah"], object: PartialSchema::Database::FARMS["1"] }])
end
assert_equal "Path `[\"farm1\", \"neighboringFarm\", \"blah\"]` is not present in this query. `\"blah\"` was not found. Try a different path or rewrite the query to include it.", err.message
end
it "can run partials with the same path" do
str = "{
farm(id: \"1\") { name }
}"
results = run_partials(str, [
{ path: ["farm"], object: PartialSchema::Database::FARMS["1"] },
{ path: ["farm"], object: -> { OpenStruct.new(name: "Injected Farm") } }
])
assert_equal [
{ "data" => { "name" => "Bellair Farm" } },
{ "data" => { "name" => "Injected Farm" } },
], results
end
it "runs multiple partials concurrently" do
str = <<~GRAPHQL
query {
query1: query { farm(id: "1") { name neighboringFarm { name } } }
query2: query { farm(id: "2") { name neighboringFarm { name } } }
}
GRAPHQL
results = run_partials(str, [{ path: ["query1"], object: true }, { path: ["query2"], object: true }])
assert_equal "Henley's Orchard", results.first["data"]["farm"]["neighboringFarm"]["name"]
assert_equal "Wenger Grapes", results.last["data"]["farm"]["neighboringFarm"]["name"]
assert_equal [[:mget, ["1", "2"]], [:mget, ["3"]]], PartialSchema::Database.log
end
it "runs arrays and returns useful metadata in the result" do
str = "{ farms { name } }"
results = run_partials(str, [{ path: ["farms"], object: [{ name: "Twenty Paces" }, { name: "Spring Creek Blooms" }]}])
result = results.first
assert_equal [{ "name" => "Twenty Paces" }, { "name" => "Spring Creek Blooms" }], result["data"]
assert_equal ["farms"], result.path
assert_instance_of GraphQL::Query::Context, result.context
assert_instance_of GraphQL::Query::Partial, result.partial
assert_instance_of GraphQL::Query::Partial, result.context.query
refute result.partial.leaf?
end
it "works on lists of scalars" do
str = "{ query { farmNames } }"
results = run_partials(str, [
{ path: ["query", "farmNames", 0], object: "Twenty Paces" },
{ path: ["query", "farmNames", 1], object: "Caromont" },
{ path: ["query", "farmNames", 2], object: GraphQL::ExecutionError.new("Boom!") },
])
assert_equal "Twenty Paces", results[0]["data"]
assert_equal "Caromont", results[1]["data"]
assert_equal({
"errors" => [{"message" => "Boom!", "locations" => [{"line" => 1, "column" => 11}], "path" => ["query", "farmNames", 2, "farmNames"]}],
"data" => nil
}, results[2])
end
it "merges selections when path steps are duplicated" do
str = <<-GRAPHQL
{
farm(id: 5) { neighboringFarm { name } }
farm(id: 5) { neighboringFarm { name2: name } }
}
GRAPHQL
results = run_partials(str, [{ path: ["farm", "neighboringFarm"], object: OpenStruct.new(name: "Dawnbreak") }])
assert_equal({"name" => "Dawnbreak", "name2" => "Dawnbreak" }, results.first["data"])
end
it "works when there are inline fragments in the path" do
str = <<-GRAPHQL
{
farm(id: "BLAH") {
... on Farm {
neighboringFarm {
name
}
}
neighboringFarm {
__typename
}
...FarmFields
}
}
fragment FarmFields on Farm {
neighboringFarm {
n2: name
}
}
GRAPHQL
results = run_partials(str, [{ path: ["farm", "neighboringFarm"], object: OpenStruct.new(name: "Dawnbreak") }])
assert_equal({"name" => "Dawnbreak", "__typename" => "Farm", "n2" => "Dawnbreak"}, results.first["data"])
end
it "runs partials on scalars and enums" do
str = "{ farm(id: \"BLAH\") { name products } }"
results = run_partials(str, [
{ path: ["farm", "name"], object: "Polyface" },
{ path: ["farm", "products"], object: [:__MEAT__] },
{ path: ["farm", "products"], object: -> { ["EGGS"] } },
])
assert_equal ["Polyface", ["MEAT"], ["EGGS"]], results.map { |r| r["data"] }
assert results[0].partial.leaf?
assert results[1].partial.leaf?
assert results[2].partial.leaf?
end
it "runs on union selections" do
str = "{
thing {
...on Farm { name }
...on Market { name isYearRound }
}
}"
results = run_partials(str, [
{ path: ["thing"], object: { name: "Whisper Hill" } },
{ path: ["thing"], object: { is_market: true, name: "Crozet Farmers Market", is_year_round: false } },
])
assert_equal({ "name" => "Whisper Hill" }, results[0]["data"])
assert_equal({ "name" => "Crozet Farmers Market", "isYearRound" => false }, results[1]["data"])
end
it "runs on interface selections" do
str = "{
entity {
name
__typename
}
}"
results = run_partials(str, [
{ path: ["entity"], object: { name: "Whisper Hill" } },
{ path: ["entity"], object: { is_market: true, name: "Crozet Farmers Market" } },
])
assert_equal({ "name" => "Whisper Hill", "__typename" => "Farm" }, results[0]["data"])
assert_equal({ "name" => "Crozet Farmers Market", "__typename" => "Market" }, results[1]["data"])
end
it "runs scalars on abstract types" do
str = "{
entity {
name
__typename
}
}"
results = run_partials(str, [
{ path: ["entity", "name"], object: "Whisper Hill" },
{ path: ["entity", "__typename"], object: "Farm" },
{ path: ["entity", "name"], object: "Crozet Farmers Market" },
])
assert_equal("Whisper Hill", results[0]["data"])
assert_equal("Farm", results[1]["data"])
assert_equal("Crozet Farmers Market", results[2]["data"])
end
it "accepts custom context" do
str = "{ readContext(key: \"custom\") }"
results = run_partials(str, [
{ path: [], object: nil, context: { "custom" => "one" } },
{ path: [], object: nil, context: { "custom" => "two" } },
{ path: [], object: nil },
], context: { "custom" => "three"} )
assert_equal "one", results[0]["data"]["readContext"]
assert_equal "two", results[1]["data"]["readContext"]
assert_equal "three", results[2]["data"]["readContext"]
end
it "uses a full path relative to the parent query" do
str = "{ q1: query { q2: query { query { currentPath } } } }"
results = run_partials(str, [
{ path: [], object: nil },
{ path: ["q1", "q2"], object: nil },
{ path: ["q1", "q2", "query"], object: nil },
{ path: ["q1", "q2", "query", "currentPath"], object: ["injected", "path"] },
])
assert_equal({"q1" => { "q2" => { "query" => { "currentPath" => ["q1", "q2", "query", "currentPath"] } } } }, results[0]["data"])
assert_equal [], results[0].partial.path
assert_equal({"query" => {"currentPath" => ["q1", "q2", "query", "currentPath"]}}, results[1]["data"])
assert_equal ["q1", "q2"], results[1].partial.path
assert_equal({ "currentPath" => ["q1", "q2", "query", "currentPath"] }, results[2]["data"])
assert_equal ["q1", "q2", "query"], results[2].partial.path
assert_equal(["injected", "path"], results[3]["data"])
assert_equal ["q1", "q2", "query", "currentPath"], results[3].partial.path
end
it "runs partials on mutation root" do
str = "mutation { updateFarm(name: \"Brawndo Acres\") { name } }"
results = run_partials(str, [
{ path: [], object: nil },
{ path: ["updateFarm"], object: { name: "Georgetown Farm" } },
{ path: ["updateFarm", "name"], object: "Notta Farm" },
])
assert_equal({ "updateFarm" => { "name" => "Brawndo Acres" } }, results[0]["data"])
assert_equal({ "name" => "Georgetown Farm" }, results[1]["data"])
assert_equal("Notta Farm", results[2]["data"])
end
it "handles errors on scalars" do
str = "{
entity {
name
__typename
}
}"
results = run_partials(str, [
{ path: ["entity"], object: { name: GraphQL::ExecutionError.new("Boom!") } },
{ path: ["entity", "name"], object: GraphQL::ExecutionError.new("Bang!") },
{ path: ["entity", "name"], object: -> { GraphQL::ExecutionError.new("Blorp!") } },
])
assert_equal({
"errors" => [{"message" => "Boom!", "locations" => [{"line" => 3, "column" => 9}], "path" => ["entity", "name"]}],
"data" => { "name" => nil, "__typename" => "Farm" }
}, results[0])
assert_equal({
"errors" => [{"message" => "Bang!", "locations" => [{"line" => 3, "column" => 9}], "path" => ["entity", "name", "name"]}],
"data" => nil
}, results[1])
assert_equal({
"errors" => [{"message" => "Blorp!", "locations" => [{"line" => 3, "column" => 9}], "path" => ["entity", "name", "name"]}],
"data" => nil
}, results[2])
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/query/context/scoped_context_spec.rb | spec/graphql/query/context/scoped_context_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Query::Context::ScopedContext do
class ScopedContextSchema < GraphQL::Schema
class Promise
def initialize(parent = nil, &block)
@parent = parent
@block = block
@value = nil
@children = []
end
def value
@value ||= begin
if @parent
@parent.value
else
v = @block.call
@children.each { |ch| ch.resolve_with(v) }
v
end
end
end
def resolve_with(v)
@value = @block.call(v)
end
def then(&block)
prm = Promise.new(self, &block)
@children << prm
prm
end
end
class Thing < GraphQL::Schema::Object
field :name, String
def name
context[:thing_name]
end
field :name_2, String
def name_2
context[:thing_name_2]
end
end
class ThingEdgeType < GraphQL::Schema::Object
field :node, Thing
def node
scoped_ctx = context.scoped
# Create a tree of promises, where many depend on one parent:
prm = context[:main_promise] ||= Promise.new { :noop }
prm.then {
scoped_ctx.set!(:thing_name, object)
scoped_ctx.merge!({ thing_name_2: object.to_s.upcase })
:thing
}
end
end
class ThingConnectionType < GraphQL::Schema::Object
field :edges, [ThingEdgeType]
def edges
object
end
end
class Query < GraphQL::Schema::Object
field :things, ThingConnectionType, connection: false
def things
[:one, :two, :three]
end
end
query(Query)
lazy_resolve(Promise, :value)
end
it "works with promise tree resolution and .scoped" do
query_str = "{ things { edges { node { name name2 } } } }"
res = ScopedContextSchema.execute(query_str)
assert_equal "one", res["data"]["things"]["edges"][0]["node"]["name"]
assert_equal "ONE", res["data"]["things"]["edges"][0]["node"]["name2"]
assert_equal "two", res["data"]["things"]["edges"][1]["node"]["name"]
assert_equal "TWO", res["data"]["things"]["edges"][1]["node"]["name2"]
assert_equal "three", res["data"]["things"]["edges"][2]["node"]["name"]
assert_equal "THREE", res["data"]["things"]["edges"][2]["node"]["name2"]
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/subscriptions/broadcast_analyzer_spec.rb | spec/graphql/subscriptions/broadcast_analyzer_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Subscriptions::BroadcastAnalyzer do
class BroadcastTestSchema < GraphQL::Schema
LOG_OUTPUT = StringIO.new
LOGGER = Logger.new(LOG_OUTPUT)
LOGGER.formatter = ->(severity, time, progname, msg) { "#{severity}: #{msg}\n"}
module Throwable
include GraphQL::Schema::Interface
field :weight, Integer, null: false
field :too_heavy_for_viewer, Boolean, null: false, broadcastable: false
field :split_broadcastable_test, Boolean, null: false
end
class BroadcastableConnection < GraphQL::Types::Relay::BaseConnection
default_broadcastable(true)
end
class BroadcastableEdge < GraphQL::Types::Relay::BaseEdge
default_broadcastable(true)
end
class Javelin < GraphQL::Schema::Object
implements Throwable
edge_type_class(BroadcastableEdge)
connection_type_class(BroadcastableConnection)
field :split_broadcastable_test, Boolean, null: false, broadcastable: false
field :length, Integer, broadcastable: true
end
class Shot < GraphQL::Schema::Object
implements Throwable
field :viewer_can_put, Boolean, null: false, broadcastable: false
field :diameter, Integer, broadcastable: true
end
class Query < GraphQL::Schema::Object
field :throwable, Throwable
end
class Mutation < GraphQL::Schema::Object
field :noop, String
end
class Subscription < GraphQL::Schema::Object
class ThrowableWasThrown < GraphQL::Schema::Subscription
field :throwable, Throwable, null: false
field :viewer, String, null: false, broadcastable: false
end
field :throwable_was_thrown, subscription: ThrowableWasThrown
class NewMaxThrowRecord < GraphQL::Schema::Subscription
field :distance, Integer, null: false, broadcastable: true
end
field :new_max_throw_record, subscription: NewMaxThrowRecord, broadcastable: true
class NewJavelin < GraphQL::Schema::Subscription
field :javelins, Javelin.connection_type, broadcastable: true
field :shots, Shot.connection_type, broadcastable: true
end
field :new_javelin, subscription: NewJavelin, broadcastable: true
end
query(Query)
mutation(Mutation)
subscription(Subscription)
orphan_types(Shot, Javelin)
use GraphQL::Subscriptions, broadcast: true, default_broadcastable: true
default_logger(LOGGER)
end
# Inheritance doesn't quite work, because the query analyzer is carried over.
class BroadcastTestDefaultFalseSchema < GraphQL::Schema
query(BroadcastTestSchema::Query)
mutation(BroadcastTestSchema::Mutation)
subscription(BroadcastTestSchema::Subscription)
orphan_types(BroadcastTestSchema::Shot, BroadcastTestSchema::Javelin)
use GraphQL::Subscriptions, broadcast: true, default_broadcastable: false
default_logger(BroadcastTestSchema::LOGGER)
end
def broadcastable?(query_str, schema: BroadcastTestSchema)
schema.subscriptions.broadcastable?(query_str)
end
before do
BroadcastTestSchema::LOG_OUTPUT.rewind
BroadcastTestSchema::LOG_OUTPUT.string.clear
end
it "doesn't run for non-subscriptions" do
assert_nil broadcastable?("{ __typename }")
assert_nil broadcastable?("mutation { __typename }")
assert_equal true, broadcastable?("subscription { __typename }")
end
describe "when the default is false" do
it "applies default false when any field is not tagged" do
assert_equal false, broadcastable?("subscription { throwableWasThrown { throwable { weight } } }", schema: BroadcastTestDefaultFalseSchema)
end
it "returns true when all fields are tagged true" do
assert_equal true, broadcastable?("subscription { newMaxThrowRecord { distance } }", schema: BroadcastTestDefaultFalseSchema)
end
it "treats introspection fields as broadcastable" do
assert_equal true, broadcastable?("subscription { __typename }", schema: BroadcastTestDefaultFalseSchema)
end
end
describe "when the default is true" do
it "returns false when any field is tagged false" do
assert_equal false, broadcastable?("subscription { throwableWasThrown { viewer } }")
assert_equal false, broadcastable?("subscription { throwableWasThrown { throwable { ... on Shot { viewerCanPut } } } }")
end
it "returns true no field is tagged false" do
assert_equal true, broadcastable?("subscription { throwableWasThrown { throwable { weight } } }")
end
end
describe "nodes field" do
it "can be broadcastable" do
query_str = "subscription { newJavelin { javelins { nodes { length } edges { node { length } } pageInfo { hasNextPage } } } }"
assert broadcastable?(query_str)
assert broadcastable?(query_str, schema: BroadcastTestDefaultFalseSchema)
end
it "follows the default schema setting" do
query_str = "subscription { newJavelin { shots { nodes { diameter } edges { node { diameter } } pageInfo { hasNextPage } } } }"
assert broadcastable?(query_str)
assert_equal BroadcastTestSchema.default_logger, BroadcastTestDefaultFalseSchema.default_logger
BroadcastTestSchema::LOG_OUTPUT.string.clear
BroadcastTestSchema::LOG_OUTPUT.rewind
refute broadcastable?(query_str, schema: BroadcastTestDefaultFalseSchema)
assert_equal "DEBUG: `broadcastable: nil` for field: ShotConnection.nodes\n", BroadcastTestSchema::LOG_OUTPUT.string
end
end
describe "abstract types" do
describe "when a field returns an interface" do
it "observes the interface-defined configuration" do
assert_equal false, broadcastable?("subscription { throwableWasThrown { throwable { tooHeavyForViewer } } }")
end
it "requires all object type fields to be broadcastable" do
query_str = <<-GRAPHQL
subscription {
throwableWasThrown {
throwable {
# this is configured `false` for Javelin
splitBroadcastableTest
}
}
}
GRAPHQL
assert_equal false, broadcastable?(query_str)
end
it "is ok if all explicitly-named object fields are broadcastable" do
query_str = <<-GRAPHQL
subscription {
throwableWasThrown {
throwable {
# Although this is false on Javelin, it's not overridden on Shot,
# so it should use the default of `true`
...on Shot {
splitBroadcastableTest
}
}
}
}
GRAPHQL
assert_equal true, broadcastable?(query_str)
end
it "is false if any explicitly-named object fields are broadcastable" do
query_str = <<-GRAPHQL
subscription {
throwableWasThrown {
throwable {
...on Shot {
splitBroadcastableTest
}
... on Javelin {
# Explicitly-named Javelin has it configured `false`
splitBroadcastableTest
}
}
}
}
GRAPHQL
assert_equal false, broadcastable?(query_str)
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/subscriptions/serialize_spec.rb | spec/graphql/subscriptions/serialize_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Subscriptions::Serialize do
def serialize_dump(v)
GraphQL::Subscriptions::Serialize.dump(v)
end
def serialize_load(v)
GraphQL::Subscriptions::Serialize.load(v)
end
if defined?(GlobalID)
it "should serialize GlobalID::Identification in Array/Hash" do
user_a = GlobalIDUser.new("a")
user_b = GlobalIDUser.new("b")
str_a = serialize_dump(["first", 2, user_a])
str_b = serialize_dump({"first" => 'first', "second" => 2, "user" => user_b})
assert_equal str_a, '["first",2,{"__gid__":"Z2lkOi8vZ3JhcGhxbC1ydWJ5LXRlc3QvR2xvYmFsSURVc2VyL2E"}]'
assert_equal str_b, '{"first":"first","second":2,"user":{"__gid__":"Z2lkOi8vZ3JhcGhxbC1ydWJ5LXRlc3QvR2xvYmFsSURVc2VyL2I"}}'
end
it "should deserialize GlobalID::Identification in Array/Hash" do
user_a = GlobalIDUser.new("a")
user_b = GlobalIDUser.new("b")
str_a = '["first",2,{"__gid__":"Z2lkOi8vZ3JhcGhxbC1ydWJ5LXRlc3QvR2xvYmFsSURVc2VyL2E"}]'
str_b = '{"first":"first","second":2,"user":{"__gid__":"Z2lkOi8vZ3JhcGhxbC1ydWJ5LXRlc3QvR2xvYmFsSURVc2VyL2I"}}'
parsed_obj_a = serialize_load(str_a)
parsed_obj_b = serialize_load(str_b)
assert_equal parsed_obj_a, ["first", 2, user_a]
assert_equal parsed_obj_b, {'first' => 'first', 'second' => 2, 'user' => user_b}
end
it "uses locate_many for arrays of global ids" do
user_a = GlobalIDUser.new("a")
user_b = GlobalIDUser.new("b")
str = serialize_dump({ "users" => [user_a, user_b] })
loaded = serialize_load(str)
assert_equal [user_a, user_b], loaded["users"]
# It went through the plural load codepath:
assert_equal false, user_a.located_many?
assert_equal [true, true], loaded["users"].map(&:located_many?)
end
end
it "can deserialize symbols" do
value = { a: :a, "b" => 2 }
dumped = serialize_dump(value)
expected_dumped = '{"a":{"__sym__":"a"},"b":2,"__sym_keys__":["a"]}'
assert_equal expected_dumped, dumped
loaded = serialize_load(dumped)
assert_equal value, loaded
end
it "can deserialize date/times" do
datetime = DateTime.parse("2020-01-03 10:11:12")
time = Time.new
date = Date.today
[datetime, time, date].each do |timestamp|
serialized = serialize_dump(timestamp)
reloaded = serialize_load(serialized)
assert_equal timestamp, reloaded, "#{timestamp.inspect} is serialized to #{serialized.inspect} and reloaded"
end
end
if defined?(ActiveSupport::TimeWithZone) && defined?(Rails) && Rails.version.split(".").first.to_i >= 7
it "can deserialize ActiveSupport::TimeWithZone into the right zone" do
klass = Class.new(ActiveSupport::TimeWithZone) do
# Forcing the name here for simulating the case where
# config.active_support.remove_deprecated_time_with_zone_name = true
# in a Rails 7+ installation
def self.name
"ActiveSupport::TimeWithZone"
end
end
time_utc = klass.new(Time.at(1), ActiveSupport::TimeZone["UTC"])
time_est = klass.new(Time.at(1), ActiveSupport::TimeZone["EST"])
serialized_utc = serialize_dump(time_utc)
reloaded_utc = serialize_load(serialized_utc)
serialized_est = serialize_dump(time_est)
reloaded_est = serialize_load(serialized_est)
assert_equal time_utc, reloaded_utc, "#{time_utc.inspect} is serialized to #{serialized_utc.inspect} and reloaded"
assert_equal time_est, reloaded_est, "#{time_est.inspect} is serialized to #{serialized_est.inspect} and reloaded"
assert_equal "UTC", time_utc.time_zone.name, "#{time_utc.inspect} is parsed within the UTC time zone"
assert_equal "EST", time_est.time_zone.name, "#{time_est.inspect} is parsed within the EST time zone"
end
end
if testing_rails?
describe "ActiveRecord::Relations" do
before do
Food.destroy_all
Food.create!(name: "Peanut Butter")
Food.create!(name: "Jelly")
end
after do
Food.destroy_all
end
it "turns them into Arrays and can reload them with GlobalID" do
assert_equal 2, Food.count
serialized = serialize_dump(Food.all)
reloaded = serialize_load(serialized)
assert_equal reloaded, Food.all.to_a
end
end
end
it "can deserialize openstructs" do
os = OpenStruct.new(a: 1.2, b: :c, d: Time.new, e: OpenStruct.new(f: [1, 2, 3]))
serialized = serialize_dump(os)
reloaded = serialize_load(serialized)
assert_equal os, reloaded, "It reloads #{os.inspect} from #{serialized.inspect}"
end
it "can deserialize single key hash" do
os = { 'a' => 1 }
serialized = os.to_json
reloaded = serialize_load(serialized)
assert_equal os, reloaded
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/subscriptions/action_cable_subscriptions_spec.rb | spec/graphql/subscriptions/action_cable_subscriptions_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Subscriptions::ActionCableSubscriptions" do
class ActionCableTestSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :int, Integer
end
class Filter < GraphQL::Schema::InputObject
argument :trending , Boolean, required: false
end
class Keyword < GraphQL::Schema::InputObject
argument :value, String
argument :fuzzy, Boolean, required: false
end
class NewsFlash < GraphQL::Schema::Subscription
argument :max_per_hour, Integer, required: false
argument :filter, Filter, required: false
argument :keywords, [Keyword], required: false
field :text, String, null: false
end
class EvenCounter < GraphQL::Schema::Subscription
field :count, Integer, null: false
def update
if object[:count].even?
object
else
NO_UPDATE
end
end
end
class Subscription < GraphQL::Schema::Object
field :news_flash, subscription: NewsFlash
field :even_counter, subscription: EvenCounter
end
query(Query)
subscription(Subscription)
use GraphQL::Subscriptions::ActionCableSubscriptions,
action_cable: GraphQL::Testing::MockActionCable,
action_cable_coder: JSON
end
class NamespacedActionCableTestSchema < GraphQL::Schema
query(ActionCableTestSchema::Query)
subscription(ActionCableTestSchema::Subscription)
use GraphQL::Subscriptions::ActionCableSubscriptions,
namespace: "other:",
action_cable: GraphQL::Testing::MockActionCable,
action_cable_coder: JSON
end
before do
GraphQL::Testing::MockActionCable.clear_mocks
end
def subscription_update(data)
{ result: { "data" => data }, more: true }
end
it "sends updates over the given `action_cable:`" do
mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: { channel: mock_channel })
ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"})
expected_msg = subscription_update({
"newsFlash" => {
"text" => "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"
}
})
assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
end
it "uses arguments to divide traffic" do
mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
ActionCableTestSchema.execute("subscription { newsFlash(maxPerHour: 3) { text } }", context: { channel: mock_channel })
ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Sunrise enjoyed over a cup of coffee"})
ActionCableTestSchema.subscriptions.trigger(:news_flash, {max_per_hour: 3}, {text: "Neighbor shares bumper crop of summer squash with widow next door"})
ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Sunset enjoyed over a cup of tea"})
expected_msg = subscription_update({
"newsFlash" => {
"text" => "Neighbor shares bumper crop of summer squash with widow next door"
}
})
assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
end
it "handles custom argument correctly" do
mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
ActionCableTestSchema.execute("subscription { newsFlash(filter: { trending: true }) { text } }", context: { channel: mock_channel })
ActionCableTestSchema.subscriptions.trigger(:news_flash, {filter: {trending: true}}, {text: "Neighbor shares bumper crop of summer squash with widow next door"})
expected_msg = subscription_update({
"newsFlash" => {
"text" => "Neighbor shares bumper crop of summer squash with widow next door"
}
})
assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
end
it "handles nested custom argument correctly" do
mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
ActionCableTestSchema.execute("subscription { newsFlash(keywords: [{ value: \"rain\", fuzzy: true }]) { text } }", context: { channel: mock_channel })
ActionCableTestSchema.subscriptions.trigger(:news_flash, {keywords: [{value: "rain", fuzzy: true}]}, {text: "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"})
expected_msg = subscription_update({
"newsFlash" => {
"text" => "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"
}
})
assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
end
it "uses namespace to divide traffic" do
mock_channel_1 = GraphQL::Testing::MockActionCable.get_mock_channel
ctx_1 = { channel: mock_channel_1 }
ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: ctx_1)
mock_channel_2 = GraphQL::Testing::MockActionCable.get_mock_channel
ctx_2 = { channel: mock_channel_2 }
NamespacedActionCableTestSchema.execute("subscription { newsFlash { text } }", context: ctx_2)
ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Neighbor shares bumper crop of summer squash with widow next door"})
NamespacedActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "Sunrise enjoyed over a cup of coffee"})
expected_msg_1 = subscription_update({
"newsFlash" => {
"text" => "Neighbor shares bumper crop of summer squash with widow next door"
}
})
expected_msg_2 = subscription_update({
"newsFlash" => {
"text" => "Sunrise enjoyed over a cup of coffee"
}
})
assert_equal [expected_msg_1], mock_channel_1.mock_broadcasted_messages
assert_equal [expected_msg_2], mock_channel_2.mock_broadcasted_messages
expected_streams = [
# No namespace
"graphql-subscription:#{ctx_1[:subscription_id]}",
"graphql-event::newsFlash:",
# Namespaced with `other:`
"graphql-subscription:other:#{ctx_2[:subscription_id]}",
"graphql-event:other::newsFlash:",
]
assert_equal expected_streams, GraphQL::Testing::MockActionCable.mock_stream_names
end
it "supports no_update" do
mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
ctx = { channel: mock_channel }
ActionCableTestSchema.execute("subscription { evenCounter { count } }", context: ctx)
1.upto(4) do |c|
ActionCableTestSchema.subscriptions.trigger(:even_counter, {}, {count: c})
end
expected_messages = [
subscription_update("evenCounter" => { "count" => 2 }),
subscription_update("evenCounter" => { "count" => 4 }),
]
assert_equal expected_messages, mock_channel.mock_broadcasted_messages
end
it "handles `execute_update` for a missing subscription ID" do
res = ActionCableTestSchema.subscriptions.execute_update("nonsense-id", {}, {})
assert_nil res
end
it "raise ExecutionError for a missing context.channel" do
error = assert_raises GraphQL::Error do
ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: {})
end
assert_includes error.message, "This GraphQL Subscription client does not support the transport protocol expected"
end
if defined?(GlobalID)
class MultiTenantSchema < GraphQL::Schema
module Data
class Player
include GlobalID::Identification
attr_reader :name, :id
def initialize(id, name)
@id = id
@name = name
end
def self.find(id)
Data.find(id)
end
end
OBJECTS_BY_TENANT = {
"tenant-1" => { 1 => Player.new(1, "player-1") },
"tenant-2" => { 2 => Player.new(2, "player-2") },
}
def self.find(id)
if @current_tenant
id = id.to_i # It's stringified by GlobalId
@current_tenant[id] || raise("Didn't find `#{id.inspect}` in #{@current_tenant}")
else
raise("Use .switch to pick a tenant first")
end
end
def self.switch(tenant)
@current_tenant = OBJECTS_BY_TENANT.fetch(tenant)
yield
ensure
@current_tenant = nil
end
end
class Player < GraphQL::Schema::Object
field :name, String, null: false
end
class PointScored < GraphQL::Schema::Subscription
field :score, Int, null: false
field :player, Player, null: false
subscription_scope :tenant
def update
{
score: object[:score],
player: object[:player] || Data.find(object[:player_id])
}
end
end
class Subscription < GraphQL::Schema::Object
field :point_scored, subscription: PointScored
end
module TenantTrace
def execute_multiplex(multiplex:)
tenant = multiplex.queries.first.context[:tenant]
Data.switch(tenant) do
super
end
end
end
query(Player)
subscription(Subscription)
trace_with(TenantTrace)
module Serialize
def self.load(message, ctx)
Data.switch(ctx[:tenant]) do
GraphQL::Subscriptions::Serialize.load(message)
end
end
def self.dump(obj)
GraphQL::Subscriptions::Serialize.dump(obj)
end
end
use GraphQL::Subscriptions::ActionCableSubscriptions,
action_cable: GraphQL::Testing::MockActionCable,
action_cable_coder: JSON,
serializer: Serialize
end
it "works with multi-tenant architecture" do
mock_channel_1 = GraphQL::Testing::MockActionCable.get_mock_channel
ctx_1 = { channel: mock_channel_1, tenant: "tenant-1" }
MultiTenantSchema.execute("subscription { pointScored { score player { name } } }", context: ctx_1)
mock_channel_2 = GraphQL::Testing::MockActionCable.get_mock_channel
ctx_2 = { channel: mock_channel_2, tenant: "tenant-2" }
MultiTenantSchema.execute("subscription { pointScored { score player { name } } }", context: ctx_2)
# This will use the `.find` in `def update`:
MultiTenantSchema.subscriptions.trigger(:point_scored, {}, { score: 5, player_id: 1 }, scope: "tenant-1")
# This will use GlobalId in `Serialize`:
MultiTenantSchema.subscriptions.trigger(:point_scored, {}, { score: 3, player: MultiTenantSchema::Data::Player.new(2, nil) }, scope: "tenant-2")
expected_msg_1 = subscription_update({
"pointScored" => {
"score" => 5,
"player" => { "name" => "player-1" },
}
})
expected_msg_2 = subscription_update({
"pointScored" => {
"score" => 3,
"player" => { "name" => "player-2" }
},
})
assert_equal [expected_msg_1], mock_channel_1.mock_broadcasted_messages
assert_equal [expected_msg_2], mock_channel_2.mock_broadcasted_messages
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/subscriptions/event_spec.rb | spec/graphql/subscriptions/event_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Subscriptions::Event do
class EventSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
end
class JsonSubscription < GraphQL::Schema::Subscription
argument :some_json, GraphQL::Types::JSON, required: false
field :text, String, null: false
end
class Subscription < GraphQL::Schema::Object
field :json_subscription, subscription: JsonSubscription
end
query(Query)
subscription(Subscription)
end
def build_dummy_context(context = {})
GraphQL::Query.new(EventSchema, "{ __typename }", context: context).context
end
it "should serialize a JSON argument into the topic name" do
field = EventSchema.subscription.fields["jsonSubscription"]
event = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => { "b" => 1, "a" => 0 } }, field: field, context: build_dummy_context, scope: nil)
assert_equal %Q{:jsonSubscription:someJson:{"a":0,"b":1}}, event.topic
end
it "should not serialize the context into the topic name" do
field = EventSchema.subscription.fields["jsonSubscription"]
context = build_dummy_context({ my_id: "abc" })
event = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => { "b" => 1, "a" => 0 } }, field: field, context: context, scope: nil)
assert_equal %Q{:jsonSubscription:someJson:{"a":0,"b":1}}, event.topic
assert_equal event.context[:my_id], "abc"
end
it "should serialize two equivalent JSON hashes with different key orderings into equivalent topic names" do
field = EventSchema.subscription.fields["jsonSubscription"]
event_a = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => { "b" => 1, "a" => 0 } }, field: field, context: build_dummy_context, scope: nil)
event_b = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => { "a" => 0, "b" => 1 } }, field: field, context: build_dummy_context, scope: nil)
assert_equal event_a.topic, event_b.topic
end
it "should serialize nested hashes into their sorted key forms" do
field = EventSchema.subscription.fields["jsonSubscription"]
nested_hash = {
"b" => 1,
"c" => {
"z" => 100,
"y" => 99
},
"a" => 0
}
event = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => nested_hash }, field: field, context: build_dummy_context, scope: nil)
assert_equal %Q{:jsonSubscription:someJson:{"a":0,"b":1,"c":{"y":99,"z":100}}}, event.topic
end
it "should serialize a hash inside an array as a sorted hash" do
field = EventSchema.subscription.fields["jsonSubscription"]
event = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => [{ "b" => 1, "a" => 0 }] }, field: field, context: build_dummy_context, scope: nil)
assert_equal %Q{:jsonSubscription:someJson:[{"a":0,"b":1}]}, event.topic
end
it "should serialize a hash inside an array of an array as a sorted hash" do
field = EventSchema.subscription.fields["jsonSubscription"]
event = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => [[{ "b" => 1, "a" => 0 }]] }, field: field, context: build_dummy_context, scope: nil)
assert_equal %Q{:jsonSubscription:someJson:[[{"a":0,"b":1}]]}, event.topic
end
it "should serialize a hash inside an array inside of a hash" do
field = EventSchema.subscription.fields["jsonSubscription"]
event = GraphQL::Subscriptions::Event.new(name: "test", arguments: { "someJson" => { "key" => [{ "b" => 1, "a" => 0}]} }, field: field, context: build_dummy_context, scope: nil)
assert_equal %Q{:jsonSubscription:someJson:{"key":[{"a":0,"b":1}]}}, event.topic
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/type_type_spec.rb | spec/graphql/introspection/type_type_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Introspection::TypeType do
let(:query_string) {%|
query introspectionQuery {
cheeseType: __type(name: "Cheese") { name, kind, fields { name, isDeprecated, type { kind, name, ofType { name } } } }
milkType: __type(name: "Milk") { interfaces { name }, fields { type { kind, name, ofType { name } } } }
dairyAnimal: __type(name: "DairyAnimal") { name, kind, enumValues(includeDeprecated: false) { name, isDeprecated } }
dairyProduct: __type(name: "DairyProduct") { name, kind, possibleTypes { name } }
animalProduct: __type(name: "AnimalProduct") { name, kind, specifiedByURL, possibleTypes { name }, fields { name } }
missingType: __type(name: "NotAType") { name }
timeType: __type(name: "Time") { specifiedByURL }
}
|}
let(:result) { Dummy::Schema.execute(query_string, context: {}, variables: {"cheeseId" => 2}) }
let(:cheese_fields) {[
{"name"=>"dairyProduct", "isDeprecated" => false, "type"=>{"kind"=>"UNION", "name"=>"DairyProduct", "ofType"=>nil}},
{"name"=>"deeplyNullableCheese", "isDeprecated" => false, "type"=>{ "kind" => "OBJECT", "name" => "Cheese", "ofType" => nil}},
{"name"=>"flavor", "isDeprecated" => false, "type" => { "kind" => "NON_NULL", "name" => nil, "ofType" => { "name" => "String"}}},
{"name"=>"id", "isDeprecated" => false, "type" => { "kind" => "NON_NULL", "name" => nil, "ofType" => { "name" => "Int"}}},
{"name"=>"nullableCheese", "isDeprecated"=>false, "type"=>{ "kind" => "OBJECT", "name" => "Cheese", "ofType"=>nil}},
{"name"=>"origin", "isDeprecated" => false, "type" => { "kind" => "NON_NULL", "name" => nil, "ofType" => { "name" => "String"}}},
{"name"=>"selfAsEdible", "isDeprecated"=>false, "type"=>{"kind"=>"INTERFACE", "name"=>"Edible", "ofType"=>nil}},
{"name"=>"similarCheese", "isDeprecated"=>false, "type"=>{ "kind" => "OBJECT", "name"=>"Cheese", "ofType"=>nil}},
{"name"=>"source", "isDeprecated" => false, "type" => { "kind" => "NON_NULL", "name" => nil, "ofType" => { "name" => "DairyAnimal"}}},
]}
let(:dairy_animals) {[
{"name"=>"NONE", "isDeprecated"=> false },
{"name"=>"COW", "isDeprecated"=> false },
{"name"=>"DONKEY", "isDeprecated"=> false },
{"name"=>"GOAT", "isDeprecated"=> false },
{"name"=>"REINDEER", "isDeprecated"=> false },
{"name"=>"SHEEP", "isDeprecated"=> false },
]}
it "exposes metadata about types" do
expected = {"data"=> {
"cheeseType" => {
"name"=> "Cheese",
"kind" => "OBJECT",
"fields"=> cheese_fields
},
"milkType"=>{
"interfaces"=>[
{"name"=>"AnimalProduct"},
{"name"=>"Edible"},
{"name"=>"EdibleAsMilk"},
{"name"=>"LocalProduct"},
],
"fields"=>[
{"type"=>{"kind"=>"LIST","name"=>nil, "ofType"=>{"name"=>"DairyProduct"}}},
{"type"=>{"kind"=>"SCALAR","name"=>"String", "ofType"=>nil}},
{"type"=>{"kind"=>"NON_NULL","name"=>nil, "ofType"=>{"name"=>"Float"}}},
{"type"=>{"kind"=>"LIST","name"=>nil, "ofType"=>{"name"=>"String"}}},
{"type"=>{"kind"=>"NON_NULL","name"=>nil, "ofType"=>{"name"=>"ID"}}},
{"type"=>{"kind"=>"NON_NULL","name"=>nil, "ofType"=>{"name"=>"String"}}},
{"type"=>{"kind"=>"INTERFACE", "name"=>"Edible", "ofType"=>nil}},
{"type"=>{"kind"=>"NON_NULL","name"=>nil,"ofType"=>{"name"=>"DairyAnimal"}}},
]
},
"dairyAnimal"=>{
"name"=>"DairyAnimal",
"kind"=>"ENUM",
"enumValues"=> dairy_animals,
},
"dairyProduct"=>{
"name"=>"DairyProduct",
"kind"=>"UNION",
"possibleTypes"=>[{"name"=>"Cheese"}, {"name"=>"Milk"}],
},
"animalProduct" => {
"name"=>"AnimalProduct",
"kind"=>"INTERFACE",
"specifiedByURL" => nil,
"possibleTypes"=>[{"name"=>"Cheese"}, {"name"=>"Honey"}, {"name"=>"Milk"}],
"fields"=>[
{"name"=>"source"},
]
},
"missingType" => nil,
"timeType" => { "specifiedByURL" => "https://time.graphql"}
}}
assert_equal(expected, result.to_h)
end
describe "deprecated fields" do
let(:query_string) {%|
query introspectionQuery {
cheeseType: __type(name: "Cheese") { name, kind, fields(includeDeprecated: true) { name, isDeprecated, type { kind, name, ofType { name } } } }
dairyAnimal: __type(name: "DairyAnimal") { name, kind, enumValues(includeDeprecated: true) { name, isDeprecated } }
}
|}
let(:deprecated_fields) { {"name"=>"fatContent", "isDeprecated"=>true, "type"=>{"kind"=>"NON_NULL","name"=>nil, "ofType"=>{"name"=>"Float"}}} }
it "can expose deprecated fields" do
new_cheese_fields = ([deprecated_fields] + cheese_fields).sort_by { |f| f["name"] }
expected = { "data" => {
"cheeseType" => {
"name"=> "Cheese",
"kind" => "OBJECT",
"fields"=> new_cheese_fields
},
"dairyAnimal"=>{
"name"=>"DairyAnimal",
"kind"=>"ENUM",
"enumValues"=> dairy_animals + [{"name" => "YAK", "isDeprecated" => true}],
},
}}
assert_equal(expected, result)
end
it "hides deprecated field arguments by default" do
result = Dummy::Schema.execute <<-GRAPHQL
{
__type(name: "Query") {
fields {
name
args {
name
}
}
}
}
GRAPHQL
from_source_field = result['data']['__type']['fields'].find { |f| f['name'] == 'fromSource' }
expected = [
{"name" => "source"}
]
assert_equal(expected, from_source_field['args'])
end
it "can expose deprecated field arguments" do
result = Dummy::Schema.execute <<-GRAPHQL
{
__type(name: "Query") {
fields {
name
args(includeDeprecated: true) {
name
isDeprecated
deprecationReason
}
}
}
}
GRAPHQL
from_source_field = result['data']['__type']['fields'].find { |f| f['name'] == 'fromSource' }
expected = [
{"name" => "source", "isDeprecated" => false, "deprecationReason" => nil},
{"name" => "oldSource", "isDeprecated" => true, "deprecationReason" => "No longer supported"}
]
assert_equal(expected, from_source_field['args'])
end
end
describe "input objects" do
let(:query_string) {%|
query introspectionQuery {
__type(name: "DairyProductInput") { name, description, kind, inputFields { name, type { kind, name }, defaultValue } }
}
|}
it "exposes metadata about input objects" 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},
{"name"=>"originDairy", "type"=>{"kind"=>"SCALAR","name"=>"String"}, "defaultValue"=>"\"Sugar Hollow Dairy\""},
{"name"=>"fatContent", "type"=>{"kind"=>"SCALAR","name" => "Float"}, "defaultValue"=>"0.3"},
{"name"=>"organic", "type"=>{"kind"=>"SCALAR","name" => "Boolean"}, "defaultValue"=>"false"},
{"name"=>"order_by", "type"=>{"kind"=>"INPUT_OBJECT", "name"=>"ResourceOrderType"}, "defaultValue"=>"{direction: \"ASC\"}"},
]
}
}}
assert_equal(expected, result)
end
it "can expose deprecated input fields" do
result = Dummy::Schema.execute <<-GRAPHQL
{
__type(name: "DairyProductInput") {
inputFields(includeDeprecated: true) {
name
isDeprecated
deprecationReason
}
}
}
GRAPHQL
expected = {
"data" => {
"__type" => {
"inputFields" => [
{"name" => "source", "isDeprecated" => false, "deprecationReason" => nil},
{"name" => "originDairy", "isDeprecated" => false, "deprecationReason" => nil},
{"name" => "fatContent", "isDeprecated" => false, "deprecationReason" => nil},
{"name" => "organic", "isDeprecated" => false, "deprecationReason" => nil},
{"name" => "order_by", "isDeprecated" => false, "deprecationReason" => nil},
{"name" => "oldSource", "isDeprecated" => true, "deprecationReason" => "No longer supported"},
]
}
}
}
assert_equal(expected, result)
end
it "includes Relay fields" do
res = StarWars::Schema.execute <<-GRAPHQL
{
__schema {
types {
name
fields {
name
args { name }
}
}
}
}
GRAPHQL
type_result = res["data"]["__schema"]["types"].find { |t| t["name"] == "Faction" }
field_result = type_result["fields"].find { |f| f["name"] == "bases" }
all_arg_names = ["after", "before", "first", "last", "nameIncludes", "complexOrder"]
returned_arg_names = field_result["args"].map { |a| a["name"] }
assert_equal all_arg_names.sort, returned_arg_names.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/introspection/introspection_query_spec.rb | spec/graphql/introspection/introspection_query_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe "GraphQL::Introspection::INTROSPECTION_QUERY" do
let(:schema) {
Class.new(Dummy::Schema) do
max_depth(15)
end
}
let(:query_string) { GraphQL::Introspection::INTROSPECTION_QUERY }
let(:result) { schema.execute(query_string) }
it "runs" do
assert(result["data"])
end
it "is limited to the max query depth" do
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "DeepQuery"
field :foo, [[[Float]]], null: false
end
deep_schema = Class.new(GraphQL::Schema) do
query query_type
end
result = deep_schema.execute(query_string)
assert(GraphQL::Schema::Loader.load(result))
end
it "doesn't handle too deeply nested (< 8) schemas" do
query_type = Class.new(GraphQL::Schema::Object) do
graphql_name "DeepQuery"
field :foo, [[[[Float]]]], null: false
end
deep_schema = Class.new(GraphQL::Schema) do
query query_type
end
result = deep_schema.execute(query_string)
assert_raises(KeyError) {
GraphQL::Schema::Loader.load(result)
}
end
it "doesn't contain blank lines" do
int_query = GraphQL::Introspection.query
refute_includes int_query, "\n\n"
int_query_with_options = GraphQL::Introspection.query(
include_deprecated_args: true,
include_schema_description: true,
include_is_repeatable: true,
include_specified_by_url: true,
include_is_one_of: true
)
refute_includes int_query_with_options, "\n\n"
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/directive_type_spec.rb | spec/graphql/introspection/directive_type_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GraphQL::Introspection::DirectiveType do
let(:query_string) {%|
query getDirectives {
__schema {
directives {
name,
args { name, type { kind, name, ofType { name } } },
locations
isRepeatable
# Deprecated fields:
onField
onFragment
onOperation
}
}
}
|}
let(:directive_with_deprecated_arg) do
Class.new(GraphQL::Schema::Directive) do
graphql_name "customTransform"
locations GraphQL::Schema::Directive::FIELD
argument :old_way, String, required: false, deprecation_reason: "Use the newWay"
argument :new_way, String, required: false
end
end
let(:schema) { Class.new(Dummy::Schema) { directive(Class.new(GraphQL::Schema::Directive) { graphql_name("doStuff"); repeatable(true) })}}
let(:result) { schema.execute(query_string) }
before do
schema.max_depth(100)
end
it "shows directive info " do
expected = { "data" => {
"__schema" => {
"directives" => [
{
"name" => "deprecated",
"args" => [
{"name"=>"reason", "type"=>{"kind"=>"SCALAR", "name"=>"String", "ofType"=>nil}}
],
"locations"=>["FIELD_DEFINITION", "ENUM_VALUE", "ARGUMENT_DEFINITION", "INPUT_FIELD_DEFINITION"],
"isRepeatable" => false,
"onField" => false,
"onFragment" => false,
"onOperation" => false,
},
{
"name"=>"directiveForVariableDefinition",
"args"=>[],
"locations"=>["VARIABLE_DEFINITION"],
"isRepeatable"=>false,
"onField"=>false,
"onFragment"=>false,
"onOperation"=>false,
},
{
"name"=>"doStuff",
"args"=>[],
"locations"=>[],
"isRepeatable"=>true,
"onField"=>false,
"onFragment"=>false,
"onOperation"=>false,
},
{
"name" => "include",
"args" => [
{"name"=>"if", "type"=>{"kind"=>"NON_NULL", "name"=>nil, "ofType"=>{"name"=>"Boolean"}}}
],
"locations"=>["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"],
"isRepeatable" => false,
"onField" => true,
"onFragment" => true,
"onOperation" => false,
},
{
"name" => "oneOf",
"args" => [],
"locations"=>["INPUT_OBJECT"],
"isRepeatable" => false,
"onField" => false,
"onFragment" => false,
"onOperation" => false,
},
{
"name" => "skip",
"args" => [
{"name"=>"if", "type"=>{"kind"=>"NON_NULL", "name"=>nil, "ofType"=>{"name"=>"Boolean"}}}
],
"locations"=>["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"],
"isRepeatable" => false,
"onField" => true,
"onFragment" => true,
"onOperation" => false,
},
{
"name" => "specifiedBy",
"args" => [
{"name"=>"url", "type"=>{"kind"=>"NON_NULL", "name"=>nil, "ofType"=>{"name"=>"String"}}}
],
"locations"=>["SCALAR"],
"isRepeatable" => false,
"onField" => false,
"onFragment" => false,
"onOperation" => false,
},
]
}
}}
assert_equal(expected, result.to_h)
end
it "hides deprecated arguments by default" do
schema.directive(directive_with_deprecated_arg)
result = schema.execute <<-GRAPHQL
{
__schema {
directives {
name
args {
name
}
}
}
}
GRAPHQL
directive_result = result["data"]["__schema"]["directives"].find { |d| d["name"] == "customTransform" }
expected = [
{"name" => "newWay"}
]
assert_equal(expected, directive_result["args"])
end
it "can expose deprecated arguments" do
schema.directive(directive_with_deprecated_arg)
result = schema.execute <<-GRAPHQL
{
__schema {
directives {
name
args(includeDeprecated: true) {
name
isDeprecated
deprecationReason
}
}
}
}
GRAPHQL
directive_result = result["data"]["__schema"]["directives"].find { |d| d["name"] == "customTransform" }
expected = [
{"name" => "oldWay", "isDeprecated" => true, "deprecationReason" => "Use the newWay"},
{"name" => "newWay", "isDeprecated" => false, "deprecationReason" => nil}
]
assert_equal(expected, directive_result["args"])
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.