1 Star 0 Fork 0

麦冬果果/graphql-go

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
executor_test.go 47.29 KB
一键复制 编辑 原始数据 按行查看 历史
D8DCA782 提交于 2018-07-20 11:47 +08:00 . removes extra error suffix
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
package graphql_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"testing"
"time"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/gqlerrors"
"github.com/graphql-go/graphql/language/location"
"github.com/graphql-go/graphql/testutil"
)
func TestExecutesArbitraryCode(t *testing.T) {
deepData := map[string]interface{}{}
data := map[string]interface{}{
"a": func() interface{} { return "Apple" },
"b": func() interface{} { return "Banana" },
"c": func() interface{} { return "Cookie" },
"d": func() interface{} { return "Donut" },
"e": func() interface{} { return "Egg" },
"f": "Fish",
"pic": func(size int) string {
return fmt.Sprintf("Pic of size: %v", size)
},
"deep": func() interface{} { return deepData },
}
data["promise"] = func() interface{} {
return data
}
deepData = map[string]interface{}{
"a": func() interface{} { return "Already Been Done" },
"b": func() interface{} { return "Boring" },
"c": func() interface{} { return []string{"Contrived", "", "Confusing"} },
"deeper": func() interface{} { return []interface{}{data, nil, data} },
}
query := `
query Example($size: Int) {
a,
b,
x: c
...c
f
...on DataType {
pic(size: $size)
promise {
a
}
}
deep {
a
b
c
deeper {
a
b
}
}
}
fragment c on DataType {
d
e
}
`
expected := &graphql.Result{
Data: map[string]interface{}{
"b": "Banana",
"x": "Cookie",
"d": "Donut",
"e": "Egg",
"promise": map[string]interface{}{
"a": "Apple",
},
"a": "Apple",
"deep": map[string]interface{}{
"a": "Already Been Done",
"b": "Boring",
"c": []interface{}{
"Contrived",
"",
"Confusing",
},
"deeper": []interface{}{
map[string]interface{}{
"a": "Apple",
"b": "Banana",
},
nil,
map[string]interface{}{
"a": "Apple",
"b": "Banana",
},
},
},
"f": "Fish",
"pic": "Pic of size: 100",
},
}
// Schema Definitions
picResolverFn := func(p graphql.ResolveParams) (interface{}, error) {
// get and type assert ResolveFn for this field
picResolver, ok := p.Source.(map[string]interface{})["pic"].(func(size int) string)
if !ok {
return nil, nil
}
// get and type assert argument
sizeArg, ok := p.Args["size"].(int)
if !ok {
return nil, nil
}
return picResolver(sizeArg), nil
}
dataType := graphql.NewObject(graphql.ObjectConfig{
Name: "DataType",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
"b": &graphql.Field{
Type: graphql.String,
},
"c": &graphql.Field{
Type: graphql.String,
},
"d": &graphql.Field{
Type: graphql.String,
},
"e": &graphql.Field{
Type: graphql.String,
},
"f": &graphql.Field{
Type: graphql.String,
},
"pic": &graphql.Field{
Args: graphql.FieldConfigArgument{
"size": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Type: graphql.String,
Resolve: picResolverFn,
},
},
})
deepDataType := graphql.NewObject(graphql.ObjectConfig{
Name: "DeepDataType",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
"b": &graphql.Field{
Type: graphql.String,
},
"c": &graphql.Field{
Type: graphql.NewList(graphql.String),
},
"deeper": &graphql.Field{
Type: graphql.NewList(dataType),
},
},
})
// Exploring a way to have a Object within itself
// in this case DataType has DeepDataType has DataType
dataType.AddFieldConfig("deep", &graphql.Field{
Type: deepDataType,
})
// in this case DataType has DataType
dataType.AddFieldConfig("promise", &graphql.Field{
Type: dataType,
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: dataType,
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
astDoc := testutil.TestParse(t, query)
// execute
args := map[string]interface{}{
"size": 100,
}
operationName := "Example"
ep := graphql.ExecuteParams{
Schema: schema,
Root: data,
AST: astDoc,
OperationName: operationName,
Args: args,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestMergesParallelFragments(t *testing.T) {
query := `
{ a, ...FragOne, ...FragTwo }
fragment FragOne on Type {
b
deep { b, deeper: deep { b } }
}
fragment FragTwo on Type {
c
deep { c, deeper: deep { c } }
}
`
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "Apple",
"b": "Banana",
"deep": map[string]interface{}{
"c": "Cherry",
"b": "Banana",
"deeper": map[string]interface{}{
"b": "Banana",
"c": "Cherry",
},
},
"c": "Cherry",
},
}
typeObjectType := graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "Apple", nil
},
},
"b": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "Banana", nil
},
},
"c": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "Cherry", nil
},
},
},
})
deepTypeFieldConfig := &graphql.Field{
Type: typeObjectType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source, nil
},
}
typeObjectType.AddFieldConfig("deep", deepTypeFieldConfig)
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: typeObjectType,
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestThreadsSourceCorrectly(t *testing.T) {
query := `
query Example { a }
`
data := map[string]interface{}{
"key": "value",
}
var resolvedSource map[string]interface{}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
resolvedSource = p.Source.(map[string]interface{})
return resolvedSource, nil
},
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
Root: data,
AST: ast,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
expected := "value"
if resolvedSource["key"] != expected {
t.Fatalf("Expected context.key to equal %v, got %v", expected, resolvedSource["key"])
}
}
func TestCorrectlyThreadsArguments(t *testing.T) {
query := `
query Example {
b(numArg: 123, stringArg: "foo")
}
`
var resolvedArgs map[string]interface{}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"b": &graphql.Field{
Args: graphql.FieldConfigArgument{
"numArg": &graphql.ArgumentConfig{
Type: graphql.Int,
},
"stringArg": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
resolvedArgs = p.Args
return resolvedArgs, nil
},
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
expectedNum := 123
expectedString := "foo"
if resolvedArgs["numArg"] != expectedNum {
t.Fatalf("Expected args.numArg to equal `%v`, got `%v`", expectedNum, resolvedArgs["numArg"])
}
if resolvedArgs["stringArg"] != expectedString {
t.Fatalf("Expected args.stringArg to equal `%v`, got `%v`", expectedNum, resolvedArgs["stringArg"])
}
}
func TestThreadsRootValueContextCorrectly(t *testing.T) {
query := `
query Example { a }
`
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
val, _ := p.Info.RootValue.(map[string]interface{})["stringKey"].(string)
return val, nil
},
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: map[string]interface{}{
"stringKey": "stringValue",
},
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "stringValue",
},
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestThreadsContextCorrectly(t *testing.T) {
query := `
query Example { a }
`
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Context.Value("foo"), nil
},
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Context: context.WithValue(context.Background(), "foo", "bar"),
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "bar",
},
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestNullsOutErrorSubtrees(t *testing.T) {
// TODO: TestNullsOutErrorSubtrees test for go-routines if implemented
query := `{
sync,
syncError,
}`
expectedData := map[string]interface{}{
"sync": "sync",
"syncError": nil,
}
expectedErrors := []gqlerrors.FormattedError{
{
Message: "Error getting syncError",
Locations: []location.SourceLocation{
{
Line: 3, Column: 7,
},
},
Path: []interface{}{
"syncError",
},
},
}
data := map[string]interface{}{
"sync": func() interface{} {
return "sync"
},
"syncError": func() interface{} {
panic("Error getting syncError")
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"sync": &graphql.Field{
Type: graphql.String,
},
"syncError": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) == 0 {
t.Fatalf("wrong result, expected errors, got %v", len(result.Errors))
}
if !reflect.DeepEqual(expectedData, result.Data) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedData, result.Data))
}
if !reflect.DeepEqual(expectedErrors, result.Errors) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
}
}
func TestUsesTheInlineOperationIfNoOperationNameIsProvided(t *testing.T) {
doc := `{ a }`
data := map[string]interface{}{
"a": "b",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "b",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestUsesTheOnlyOperationIfNoOperationNameIsProvided(t *testing.T) {
doc := `query Example { a }`
data := map[string]interface{}{
"a": "b",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "b",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestUsesTheNamedOperationIfOperationNameIsProvided(t *testing.T) {
doc := `query Example { first: a } query OtherExample { second: a }`
data := map[string]interface{}{
"a": "b",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"second": "b",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
OperationName: "OtherExample",
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestThrowsIfNoOperationIsProvided(t *testing.T) {
doc := `fragment Example on Type { a }`
data := map[string]interface{}{
"a": "b",
}
expectedErrors := []gqlerrors.FormattedError{
{
Message: "Must provide an operation.",
Locations: []location.SourceLocation{},
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) != 1 {
t.Fatalf("wrong result, expected len(1) unexpected len: %v", len(result.Errors))
}
if result.Data != nil {
t.Fatalf("wrong result, expected nil result.Data, got %v", result.Data)
}
if !reflect.DeepEqual(expectedErrors, result.Errors) {
t.Fatalf("unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
}
}
func TestThrowsIfNoOperationNameIsProvidedWithMultipleOperations(t *testing.T) {
doc := `query Example { a } query OtherExample { a }`
data := map[string]interface{}{
"a": "b",
}
expectedErrors := []gqlerrors.FormattedError{
{
Message: "Must provide operation name if query contains multiple operations.",
Locations: []location.SourceLocation{},
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) != 1 {
t.Fatalf("wrong result, expected len(1) unexpected len: %v", len(result.Errors))
}
if result.Data != nil {
t.Fatalf("wrong result, expected nil result.Data, got %v", result.Data)
}
if !reflect.DeepEqual(expectedErrors, result.Errors) {
t.Fatalf("unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
}
}
func TestThrowsIfUnknownOperationNameIsProvided(t *testing.T) {
doc := `query Example { a } query OtherExample { a }`
data := map[string]interface{}{
"a": "b",
}
expectedErrors := []gqlerrors.FormattedError{
{
Message: `Unknown operation named "UnknownExample".`,
Locations: []location.SourceLocation{},
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
OperationName: "UnknownExample",
}
result := testutil.TestExecute(t, ep)
if result.Data != nil {
t.Fatalf("wrong result, expected nil result.Data, got %v", result.Data)
}
if !reflect.DeepEqual(expectedErrors, result.Errors) {
t.Fatalf("unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
}
}
func TestUsesTheQuerySchemaForQueries(t *testing.T) {
doc := `query Q { a } mutation M { c } subscription S { a }`
data := map[string]interface{}{
"a": "b",
"c": "d",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "b",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Q",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
Mutation: graphql.NewObject(graphql.ObjectConfig{
Name: "M",
Fields: graphql.Fields{
"c": &graphql.Field{
Type: graphql.String,
},
},
}),
Subscription: graphql.NewObject(graphql.ObjectConfig{
Name: "S",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
OperationName: "Q",
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestUsesTheMutationSchemaForMutations(t *testing.T) {
doc := `query Q { a } mutation M { c }`
data := map[string]interface{}{
"a": "b",
"c": "d",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"c": "d",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Q",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
Mutation: graphql.NewObject(graphql.ObjectConfig{
Name: "M",
Fields: graphql.Fields{
"c": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
OperationName: "M",
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestUsesTheSubscriptionSchemaForSubscriptions(t *testing.T) {
doc := `query Q { a } subscription S { a }`
data := map[string]interface{}{
"a": "b",
"c": "d",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "b",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Q",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
Subscription: graphql.NewObject(graphql.ObjectConfig{
Name: "S",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
OperationName: "S",
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestCorrectFieldOrderingDespiteExecutionOrder(t *testing.T) {
doc := `
{
b,
a,
c,
d,
e
}
`
data := map[string]interface{}{
"a": func() interface{} { return "a" },
"b": func() interface{} { return "b" },
"c": func() interface{} { return "c" },
"d": func() interface{} { return "d" },
"e": func() interface{} { return "e" },
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "a",
"b": "b",
"c": "c",
"d": "d",
"e": "e",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
"b": &graphql.Field{
Type: graphql.String,
},
"c": &graphql.Field{
Type: graphql.String,
},
"d": &graphql.Field{
Type: graphql.String,
},
"e": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
// TODO: test to ensure key ordering
// The following does not work
// - iterating over result.Data map
// Note that golang's map iteration order is randomized
// So, iterating over result.Data won't do it for a test
// - Marshal the result.Data to json string and assert it
// json.Marshal seems to re-sort the keys automatically
//
t.Skipf("TODO: Ensure key ordering")
}
func TestAvoidsRecursion(t *testing.T) {
doc := `
query Q {
a
...Frag
...Frag
}
fragment Frag on Type {
a,
...Frag
}
`
data := map[string]interface{}{
"a": "b",
}
expected := &graphql.Result{
Data: map[string]interface{}{
"a": "b",
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
OperationName: "Q",
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestDoesNotIncludeIllegalFieldsInOutput(t *testing.T) {
doc := `mutation M {
thisIsIllegalDontIncludeMe
}`
expected := &graphql.Result{
Data: map[string]interface{}{},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Q",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
}),
Mutation: graphql.NewObject(graphql.ObjectConfig{
Name: "M",
Fields: graphql.Fields{
"c": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) != 0 {
t.Fatalf("wrong result, expected len(%v) errors, got len(%v)", len(expected.Errors), len(result.Errors))
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestDoesNotIncludeArgumentsThatWereNotSet(t *testing.T) {
doc := `{ field(a: true, c: false, e: 0) }`
expected := &graphql.Result{
Data: map[string]interface{}{
"field": `{"a":true,"c":false,"e":0}`,
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"field": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"a": &graphql.ArgumentConfig{
Type: graphql.Boolean,
},
"b": &graphql.ArgumentConfig{
Type: graphql.Boolean,
},
"c": &graphql.ArgumentConfig{
Type: graphql.Boolean,
},
"d": &graphql.ArgumentConfig{
Type: graphql.Int,
},
"e": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
args, _ := json.Marshal(p.Args)
return string(args), nil
},
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, doc)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) > 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
type testSpecialType struct {
Value string
}
type testNotSpecialType struct {
Value string
}
func TestFailsWhenAnIsTypeOfCheckIsNotMet(t *testing.T) {
query := `{ specials { value } }`
data := map[string]interface{}{
"specials": []interface{}{
testSpecialType{"foo"},
testNotSpecialType{"bar"},
},
}
expected := &graphql.Result{
Data: map[string]interface{}{
"specials": []interface{}{
map[string]interface{}{
"value": "foo",
},
nil,
},
},
Errors: []gqlerrors.FormattedError{
{
Message: `Expected value of type "SpecialType" but got: graphql_test.testNotSpecialType.`,
Locations: []location.SourceLocation{
{
Line: 1,
Column: 3,
},
},
Path: []interface{}{
"specials",
1,
},
},
},
}
specialType := graphql.NewObject(graphql.ObjectConfig{
Name: "SpecialType",
IsTypeOf: func(p graphql.IsTypeOfParams) bool {
if _, ok := p.Value.(testSpecialType); ok {
return true
}
return false
},
Fields: graphql.Fields{
"value": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source.(testSpecialType).Value, nil
},
},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"specials": &graphql.Field{
Type: graphql.NewList(specialType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Source.(map[string]interface{})["specials"], nil
},
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
Root: data,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) == 0 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestFailsToExecuteQueryContainingATypeDefinition(t *testing.T) {
query := `
{ foo }
type Query { foo: String }
`
expected := &graphql.Result{
Data: nil,
Errors: []gqlerrors.FormattedError{
{
Message: "GraphQL cannot execute a request containing a ObjectDefinition",
Locations: []location.SourceLocation{},
},
},
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"foo": &graphql.Field{
Type: graphql.String,
},
},
}),
})
if err != nil {
t.Fatalf("Error in schema %v", err.Error())
}
// parse query
ast := testutil.TestParse(t, query)
// execute
ep := graphql.ExecuteParams{
Schema: schema,
AST: ast,
}
result := testutil.TestExecute(t, ep)
if len(result.Errors) != 1 {
t.Fatalf("wrong result, unexpected errors: %v", result.Errors)
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expected, result))
}
}
func TestQuery_ExecutionAddsErrorsFromFieldResolveFn(t *testing.T) {
qError := errors.New("queryError")
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, qError
},
},
"b": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "ok", nil
},
},
},
})
blogSchema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "{ a }"
result := graphql.Do(graphql.Params{
Schema: blogSchema,
RequestString: query,
})
if len(result.Errors) == 0 {
t.Fatal("wrong result, expected errors, got no errors")
}
if result.Errors[0].Error() != qError.Error() {
t.Fatalf("wrong result, unexpected error, got: %v, expected: %v", result.Errors[0], qError)
}
}
func TestQuery_ExecutionDoesNotAddErrorsFromFieldResolveFn(t *testing.T) {
qError := errors.New("queryError")
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, qError
},
},
"b": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "ok", nil
},
},
},
})
blogSchema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "{ b }"
result := graphql.Do(graphql.Params{
Schema: blogSchema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
}
}
func TestQuery_InputObjectUsesFieldDefaultValueFn(t *testing.T) {
inputType := graphql.NewInputObject(graphql.InputObjectConfig{
Name: "Input",
Fields: graphql.InputObjectConfigFieldMap{
"default": &graphql.InputObjectFieldConfig{
Type: graphql.String,
DefaultValue: "bar",
},
},
})
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"foo": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(inputType),
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
val := p.Args["foo"].(map[string]interface{})
def, ok := val["default"]
if !ok || def == nil {
return nil, errors.New("queryError: No 'default' param")
}
if def.(string) != "bar" {
return nil, errors.New("queryError: 'default' param has wrong value")
}
return "ok", nil
},
},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := `{ a(foo: {}) }`
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
}
}
func TestMutation_ExecutionAddsErrorsFromFieldResolveFn(t *testing.T) {
mError := errors.New("mutationError")
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
})
m := graphql.NewObject(graphql.ObjectConfig{
Name: "Mutation",
Fields: graphql.Fields{
"foo": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"f": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, mError
},
},
"bar": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"b": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "ok", nil
},
},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
Mutation: m,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "mutation _ { newFoo: foo(f:\"title\") }"
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) == 0 {
t.Fatal("wrong result, expected errors, got no errors")
}
if result.Errors[0].Error() != mError.Error() {
t.Fatalf("wrong result, unexpected error, got: %v, expected: %v", result.Errors[0], mError)
}
}
func TestMutation_ExecutionDoesNotAddErrorsFromFieldResolveFn(t *testing.T) {
mError := errors.New("mutationError")
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"a": &graphql.Field{
Type: graphql.String,
},
},
})
m := graphql.NewObject(graphql.ObjectConfig{
Name: "Mutation",
Fields: graphql.Fields{
"foo": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"f": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, mError
},
},
"bar": &graphql.Field{
Type: graphql.String,
Args: graphql.FieldConfigArgument{
"b": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return "ok", nil
},
},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
Mutation: m,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "mutation _ { newBar: bar(b:\"title\") }"
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
}
}
func TestGraphqlTag(t *testing.T) {
typeObjectType := graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"fooBar": &graphql.Field{Type: graphql.String},
},
})
var baz = &graphql.Field{
Type: typeObjectType,
Description: "typeObjectType",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
t := struct {
FooBar string `graphql:"fooBar"`
}{"foo bar value"}
return t, nil
},
}
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"baz": baz,
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "{ baz { fooBar } }"
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
}
expectedData := map[string]interface{}{
"baz": map[string]interface{}{
"fooBar": "foo bar value",
},
}
if !reflect.DeepEqual(result.Data, expectedData) {
t.Fatalf("unexpected result, got: %+v, expected: %+v", expectedData, result.Data)
}
}
func TestFieldResolver(t *testing.T) {
typeObjectType := graphql.NewObject(graphql.ObjectConfig{
Name: "Type",
Fields: graphql.Fields{
"fooBar": &graphql.Field{Type: graphql.String},
},
})
var baz = &graphql.Field{
Type: typeObjectType,
Description: "typeObjectType",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return testCustomResolver{}, nil
},
}
var bazPtr = &graphql.Field{
Type: typeObjectType,
Description: "typeObjectType",
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return &testCustomResolver{}, nil
},
}
q := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"baz": baz,
"bazPtr": bazPtr,
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: q,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
query := "{ baz { fooBar }, bazPtr { fooBar } }"
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("wrong result, unexpected errors: %+v", result.Errors)
}
expectedData := map[string]interface{}{
"baz": map[string]interface{}{
"fooBar": "foo bar value",
},
"bazPtr": map[string]interface{}{
"fooBar": "foo bar value",
},
}
if !reflect.DeepEqual(result.Data, expectedData) {
t.Fatalf("unexpected result, got: %+v, expected: %+v", result.Data, expectedData)
}
}
type testCustomResolver struct{}
func (r testCustomResolver) Resolve(p graphql.ResolveParams) (interface{}, error) {
if p.Info.FieldName == "fooBar" {
return "foo bar value", nil
}
return "", errors.New("invalid field " + p.Info.FieldName)
}
func TestContextDeadline(t *testing.T) {
timeout := time.Millisecond * time.Duration(100)
acceptableDelay := time.Millisecond * time.Duration(10)
expectedErrors := []gqlerrors.FormattedError{
{
Message: context.DeadlineExceeded.Error(),
Locations: []location.SourceLocation{},
},
}
// Query type includes a field that won't resolve within the deadline
var queryType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"hello": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
time.Sleep(2 * time.Second)
return "world", nil
},
},
},
})
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
})
if err != nil {
t.Fatalf("unexpected error, got: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
startTime := time.Now()
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: "{hello}",
Context: ctx,
})
duration := time.Since(startTime)
if duration > timeout+acceptableDelay {
t.Fatalf("graphql.Do completed in %s, should have completed in %s", duration, timeout)
}
if !result.HasErrors() || len(result.Errors) == 0 {
t.Fatalf("Result should include errors when deadline is exceeded")
}
if !reflect.DeepEqual(expectedErrors, result.Errors) {
t.Fatalf("Unexpected result, Diff: %v", testutil.Diff(expectedErrors, result.Errors))
}
}
func TestThunkResultsProcessedCorrectly(t *testing.T) {
barType := graphql.NewObject(graphql.ObjectConfig{
Name: "Bar",
Fields: graphql.Fields{
"bazA": &graphql.Field{
Type: graphql.String,
},
"bazB": &graphql.Field{
Type: graphql.String,
},
},
})
fooType := graphql.NewObject(graphql.ObjectConfig{
Name: "Foo",
Fields: graphql.Fields{
"bar": &graphql.Field{
Type: barType,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
var bar struct {
BazA string
BazB string
}
bar.BazA = "A"
bar.BazB = "B"
thunk := func() interface{} { return &bar }
return thunk, nil
},
},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"foo": &graphql.Field{
Type: fooType,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
var foo struct{}
return foo, nil
},
},
},
})
expectNoError := func(err error) {
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
})
expectNoError(err)
query := "{ foo { bar { bazA bazB } } }"
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) != 0 {
t.Fatalf("expected no errors, got %v", result.Errors)
}
foo := result.Data.(map[string]interface{})["foo"].(map[string]interface{})
bar, ok := foo["bar"].(map[string]interface{})
if !ok {
t.Errorf("expected bar to be a map[string]interface{}: actual = %v", reflect.TypeOf(foo["bar"]))
} else {
if got, want := bar["bazA"], "A"; got != want {
t.Errorf("foo.bar.bazA: got=%v, want=%v", got, want)
}
if got, want := bar["bazB"], "B"; got != want {
t.Errorf("foo.bar.bazB: got=%v, want=%v", got, want)
}
}
if t.Failed() {
b, err := json.Marshal(result.Data)
expectNoError(err)
t.Log(string(b))
}
}
func assertJSON(t *testing.T, expected string, actual interface{}) {
var e interface{}
if err := json.Unmarshal([]byte(expected), &e); err != nil {
t.Fatalf(err.Error())
}
aJSON, err := json.MarshalIndent(actual, "", " ")
if err != nil {
t.Fatalf(err.Error())
}
var a interface{}
if err := json.Unmarshal(aJSON, &a); err != nil {
t.Fatalf(err.Error())
}
if !reflect.DeepEqual(e, a) {
eNormalizedJSON, err := json.MarshalIndent(e, "", " ")
if err != nil {
t.Fatalf(err.Error())
}
t.Fatalf("Expected JSON:\n\n%v\n\nActual JSON:\n\n%v", string(eNormalizedJSON), string(aJSON))
}
}
type extendedError struct {
error
extensions map[string]interface{}
}
func (err extendedError) Extensions() map[string]interface{} {
return err.extensions
}
var _ gqlerrors.ExtendedError = &extendedError{}
func testErrors(t *testing.T, nameType graphql.Output, extensions map[string]interface{}) *graphql.Result {
type Hero struct {
Id string `graphql:"id"`
Name string
Friends []Hero `graphql:"friends"`
}
var heroFields graphql.Fields
heroType := graphql.NewObject(graphql.ObjectConfig{
Name: "Hero",
Fields: graphql.FieldsThunk(func() graphql.Fields {
return heroFields
}),
})
heroFields = graphql.Fields{
"id": &graphql.Field{
Type: graphql.ID,
},
"name": &graphql.Field{
Type: nameType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
hero := p.Source.(Hero)
if hero.Name != "" {
return hero.Name, nil
}
err := fmt.Errorf("Name for character with ID %v could not be fetched.", hero.Id)
if extensions != nil {
return nil, &extendedError{
error: err,
extensions: extensions,
}
}
return nil, err
},
},
"friends": &graphql.Field{
Type: graphql.NewList(heroType),
},
}
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"hero": &graphql.Field{
Type: heroType,
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
return Hero{
Name: "R2-D2",
Friends: []Hero{
{Id: "1000", Name: "Luke Skywalker"},
{Id: "1002"},
{Id: "1003", Name: "Leia Organa"},
},
}, nil
},
},
},
})
expectNoError := func(err error) {
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
}
schema, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
})
expectNoError(err)
return graphql.Do(graphql.Params{
Schema: schema,
RequestString: `{
hero {
name
heroFriends: friends {
id
name
}
}
}`,
})
}
// http://facebook.github.io/graphql/June2018/#example-bc485
func TestQuery_ErrorPath(t *testing.T) {
result := testErrors(t, graphql.String, nil)
assertJSON(t, `{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ]
}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
{
"id": "1002",
"name": null
},
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}
}`, result)
}
// http://facebook.github.io/graphql/June2018/#example-08b62
func TestQuery_ErrorPathForNonNullField(t *testing.T) {
result := testErrors(t, graphql.NewNonNull(graphql.String), nil)
assertJSON(t, `{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ]
}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
null,
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}
}`, result)
}
// http://facebook.github.io/graphql/June2018/#example-fce18
func TestQuery_ErrorExtensions(t *testing.T) {
result := testErrors(t, graphql.NewNonNull(graphql.String), map[string]interface{}{
"code": "CAN_NOT_FETCH_BY_ID",
"timestamp": "Fri Feb 9 14:33:09 UTC 2018",
})
assertJSON(t, `{
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ],
"extensions": {
"code": "CAN_NOT_FETCH_BY_ID",
"timestamp": "Fri Feb 9 14:33:09 UTC 2018"
}}
],
"data": {
"hero": {
"name": "R2-D2",
"heroFriends": [
{
"id": "1000",
"name": "Luke Skywalker"
},
null,
{
"id": "1003",
"name": "Leia Organa"
}
]
}
}
}`, result)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/mdgg0816/graphql-go.git
git@gitee.com:mdgg0816/graphql-go.git
mdgg0816
graphql-go
graphql-go
v0.7.6

搜索帮助