1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
|
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema::BuildFromDefinition do
# Build a schema from `definition` and assert that it
# prints out the same string.
# Then return the built schema.
def assert_schema_and_compare_output(definition)
built_schema = GraphQL::Schema.from_definition(definition)
assert_equal definition, GraphQL::Schema::Printer.print_schema(built_schema)
built_schema
end
describe '.build' do
it 'can build a schema with a simple type' do
schema = <<-SCHEMA
schema {
query: HelloScalars
}
type EmptyType
type HelloScalars {
bool: Boolean
float: Float
id: ID
int: Int
str: String!
t: EmptyType
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'can build a schema with underscored names' do
schema = <<-SCHEMA
type A_Type {
f(argument_1: Int, argument_two: Int): Int
}
type Query {
some_field: A_Type
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'can build a schema with default input object values' do
schema = <<-SCHEMA
input InputObject {
a: Int
}
type Query {
a(input: InputObject = {a: 1}): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'can build a schema with directives' do
schema = <<-SCHEMA
schema {
query: Hello
}
directive @foo(arg: Int, nullDefault: Int = null) on FIELD
directive @greeting(pleasant: Boolean = true) on ARGUMENT_DEFINITION | ENUM | FIELD_DEFINITION | INPUT_OBJECT | INTERFACE | OBJECT | UNION
directive @greeting2 on INTERFACE
directive @hashed repeatable on FIELD_DEFINITION | INPUT_FIELD_DEFINITION
directive @language(is: String!) on ENUM_VALUE
type Hello implements Secret & Secret2 @greeting {
goodbye(saying: Parting @greeting): Parting
humbug: Int @greeting(pleasant: false)
password: Phrase @hashed
password2: String
str(in: Input): String
}
input Input @greeting {
value: String @hashed
}
enum Parting @greeting {
AU_REVOIR @language(is: "fr")
ZAI_JIAN @language(is: "zh")
}
union Phrase @greeting = Hello | Word
interface Secret implements Secret2 @greeting @greeting2 {
password: String
password2: String
}
interface Secret2 {
password2: String
}
type Word {
str: String
}
SCHEMA
parsed_schema = GraphQL::Schema.from_definition(schema)
hello_type = parsed_schema.get_type("Hello")
assert_equal ["deprecated", "foo", "greeting", "greeting2", "hashed", "include", "language", "oneOf", "skip", "specifiedBy"], parsed_schema.directives.keys.sort
parsed_schema.directives.values.each do |dir_class|
assert dir_class < GraphQL::Schema::Directive
end
assert_equal true, parsed_schema.directives["hashed"].repeatable?
assert_equal false, parsed_schema.directives["deprecated"].repeatable?
assert_equal 1, hello_type.directives.size
assert_instance_of parsed_schema.directives["greeting"], hello_type.directives.first
assert_equal({ pleasant: true }, hello_type.directives.first.arguments.keyword_arguments)
humbug_directives = hello_type.get_field("humbug").directives
assert_equal 1, humbug_directives.size
assert_instance_of parsed_schema.directives["greeting"], humbug_directives.first
assert_equal({ pleasant: false }, humbug_directives.first.arguments.keyword_arguments)
au_revoir_directives = parsed_schema.get_type("Parting").values["AU_REVOIR"].directives
assert_equal 1, au_revoir_directives.size
assert_instance_of parsed_schema.directives["language"], au_revoir_directives.first
assert_equal({ is: "fr" }, au_revoir_directives.first.arguments.keyword_arguments)
secret_type = parsed_schema.get_type("Secret")
assert_equal 2, secret_type.directives.size
assert_schema_and_compare_output(schema)
end
it 'supports descriptions and definition_line' do
schema = <<-SCHEMA
schema {
query: Hello
}
"""
This is a directive
"""
directive @foo(
"""
It has an argument
"""
arg: Int
) on FIELD
"""
With an enum
"""
enum Color {
BLUE
"""
Not a creative color
"""
GREEN
RED
}
"""
What a great type
"""
type Hello implements I {
anEnum(s: S): Color
"""
And a field to boot
"""
str(i: Input): String
u: U
}
"""
An interface
"""
interface I {
str(i: Input): String
}
"""
And an Input
"""
input Input {
s: String
}
"""
A scalar
"""
scalar S
"""
And a union
"""
union U = Hello
SCHEMA
assert_schema_and_compare_output(schema)
# TODO: GraphQL::CParser doesn't support definition_line yet.
built_schema = GraphQL::Schema.from_definition(schema, parser: GraphQL::Language::Parser)
# The schema's are the same since there's no description
assert_equal 1, built_schema.ast_node.line
assert_equal 1, built_schema.ast_node.definition_line
# These account for description:
assert_equal 5, built_schema.directives["foo"].ast_node.line, "The ast_node.line points to the description"
assert_equal 8, built_schema.directives["foo"].ast_node.definition_line, "The ast_node.definition_line points to the definition"
arg = built_schema.directives["foo"].arguments["arg"]
assert_equal 9, arg.ast_node.line
assert_equal 12, arg.ast_node.definition_line
enum_type = built_schema.types["Color"]
assert_equal 15, enum_type.ast_node.line, "The ast_node.line points to the description"
assert_equal 18, enum_type.ast_node.definition_line, "The ast_node.definition_line points to the definition"
enum_value = enum_type.values["GREEN"]
assert_equal 21, enum_value.ast_node.line
assert_equal 24, enum_value.ast_node.definition_line
obj_type = built_schema.types["Hello"]
assert_equal 28, obj_type.ast_node.line, "The ast_node.line points to the description"
assert_equal 31, obj_type.ast_node.definition_line, "The ast_node.definition_line points to the definition"
field = obj_type.fields["str"]
assert_equal 34, field.ast_node.line
assert_equal 37, field.ast_node.definition_line
assert_equal 41, built_schema.types["I"].ast_node.line
assert_equal 44, built_schema.types["I"].ast_node.definition_line
assert_equal 48, built_schema.types["Input"].ast_node.line
assert_equal 51, built_schema.types["Input"].ast_node.definition_line
assert_equal 55, built_schema.types["S"].ast_node.line
assert_equal 58, built_schema.types["S"].ast_node.definition_line
assert_equal 60, built_schema.types["U"].ast_node.line
assert_equal 63, built_schema.types["U"].ast_node.definition_line
end
it 'handles empty type descriptions' do
schema = <<-SCHEMA
"""
"""
type Query {
f1: Int
}
SCHEMA
refute_nil GraphQL::Schema.from_definition(schema)
end
it 'maintains built-in directives' do
schema = <<-SCHEMA
schema {
query: Hello
}
type Hello {
str: String
}
SCHEMA
built_schema = GraphQL::Schema.from_definition(schema)
assert_equal ['deprecated', 'include', 'oneOf', 'skip', 'specifiedBy'], built_schema.directives.keys.sort
end
it 'supports overriding built-in directives' do
schema = <<-SCHEMA
schema {
query: Hello
}
directive @skip on FIELD
directive @include on FIELD
directive @deprecated on FIELD_DEFINITION
type Hello {
str: String
}
SCHEMA
built_schema = GraphQL::Schema.from_definition(schema)
refute built_schema.directives['skip'] == GraphQL::Schema::Directive::Skip
refute built_schema.directives['include'] == GraphQL::Schema::Directive::Include
refute built_schema.directives['deprecated'] == GraphQL::Schema::Directive::Deprecated
end
it 'supports adding directives while maintaining built-in directives' do
schema = <<-SCHEMA
schema @custom(thing: true) {
query: Hello
}
directive @foo(arg: Int) on FIELD
directive @custom(thing: Boolean) on SCHEMA
type Hello {
str: String
}
SCHEMA
built_schema = GraphQL::Schema.from_definition(schema)
assert built_schema.directives.keys.include?('skip')
assert built_schema.directives.keys.include?('include')
assert built_schema.directives.keys.include?('deprecated')
assert built_schema.directives.keys.include?('foo')
end
it 'supports type modifiers' do
schema = <<-SCHEMA
schema {
query: HelloScalars
}
type HelloScalars {
listOfNonNullStrs: [String!]
listOfStrs: [String]
nonNullListOfNonNullStrs: [String!]!
nonNullListOfStrs: [String]!
nonNullStr: String!
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports recursive type' do
schema = <<-SCHEMA
schema {
query: Recurse
}
type Recurse {
recurse: Recurse
str: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports two types circular' do
schema = <<-SCHEMA
schema {
query: TypeOne
}
type TypeOne {
str: String
typeTwo: TypeTwo
}
type TypeTwo {
str: String
typeOne: TypeOne
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports single argument fields' do
schema = <<-SCHEMA
schema {
query: Hello
}
type Hello {
booleanToStr(bool: Boolean): String
floatToStr(float: Float): String
idToStr(id: ID): String
str(int: Int): String
strToStr(bool: String): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'properly understands connections' do
schema = <<-SCHEMA
schema {
query: Type
}
type Organization {
email: String
}
"""
The connection type for Organization.
"""
type OrganizationConnection {
"""
A list of edges.
"""
edges: [OrganizationEdge]
"""
A list of nodes.
"""
nodes: [Organization]
"""
Information to aid in pagination.
"""
pageInfo: PageInfo!
"""
Identifies the total count of items in the connection.
"""
totalCount: Int!
}
"""
An edge in a connection.
"""
type OrganizationEdge {
"""
A cursor for use in pagination.
"""
cursor: String!
"""
The item at the end of the edge.
"""
node: Organization
}
"""
Information about pagination in a connection.
"""
type PageInfo {
"""
When paginating forwards, the cursor to continue.
"""
endCursor: String
"""
When paginating forwards, are there more items?
"""
hasNextPage: Boolean!
"""
When paginating backwards, are there more items?
"""
hasPreviousPage: Boolean!
"""
When paginating backwards, the cursor to continue.
"""
startCursor: String
}
type Type {
name: String
organization(
"""
The login of the organization to find.
"""
login: String!
): Organization
"""
A list of organizations the user belongs to.
"""
organizations(
"""
Returns the elements in the list that come after the specified cursor.
"""
after: String
"""
Returns the elements in the list that come before the specified cursor.
"""
before: String
"""
Returns the first _n_ elements from the list.
"""
first: Int
"""
Returns the last _n_ elements from the list.
"""
last: Int
): OrganizationConnection!
}
SCHEMA
built_schema = assert_schema_and_compare_output(schema)
obj = built_schema.types["Type"]
refute obj.fields["organization"].connection?
assert obj.fields["organizations"].connection?
end
it 'supports simple type with multiple arguments' do
schema = <<-SCHEMA
schema {
query: Hello
}
type Hello {
str(bool: Boolean, int: Int): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple type with interface' do
schema = <<-SCHEMA
schema {
query: Hello
}
type Hello implements WorldInterface {
str: String
}
interface WorldInterface {
str: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it "supports interfaces that implement interfaces" do
schema = <<-SCHEMA
interface Named implements Node {
id: ID
name: String
}
interface Node {
id: ID
}
type Query {
thing: Thing
}
type Thing implements Named & Node {
id: ID
name: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it "only adds the interface to the type once" do
schema = <<-SCHEMA
interface Named implements Node {
id: ID
name: String
}
interface Node {
id: ID
}
type Query {
thing: Thing
}
type Thing implements Named & Node & Timestamped {
id: ID
name: String
timestamp: String
}
interface Timestamped implements Node {
id: ID
timestamp: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple output enum' do
schema = <<-SCHEMA
schema {
query: OutputEnumRoot
}
enum Hello {
WORLD
}
type OutputEnumRoot {
hello: Hello
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple input enum' do
schema = <<-SCHEMA
schema {
query: InputEnumRoot
}
enum Hello {
WORLD
}
type InputEnumRoot {
str(hello: Hello): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports multiple value enum' do
schema = <<-SCHEMA
schema {
query: OutputEnumRoot
}
enum Hello {
RLD
WO
}
type OutputEnumRoot {
hello: Hello
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple union' do
schema = <<-SCHEMA
schema {
query: Root
}
union Hello = World
type Root {
hello: Hello
}
type World {
str: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports multiple union' do
schema = <<-SCHEMA
schema {
query: Root
}
union Hello = WorldOne | WorldTwo
type Root {
hello: Hello
}
type WorldOne {
str: String
}
type WorldTwo {
str: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports redefining built-in scalars' do
schema = <<-SCHEMA
schema {
query: Root
}
scalar ID
type Root {
builtInScalar: ID
}
SCHEMA
built_schema = assert_schema_and_compare_output(schema)
id_scalar = built_schema.types["ID"]
assert_equal true, id_scalar.valid_isolated_input?("123")
end
it 'supports custom scalar' do
schema = <<-SCHEMA
schema {
query: Root
}
scalar CustomScalar
type Root {
customScalar: CustomScalar
}
SCHEMA
built_schema = assert_schema_and_compare_output(schema)
custom_scalar = built_schema.types["CustomScalar"]
assert_equal true, custom_scalar.valid_isolated_input?("anything")
assert_equal true, custom_scalar.valid_isolated_input?(12345)
end
it 'supports input object' do
schema = <<-SCHEMA
schema {
query: Root
}
input Input {
int: Int
nullDefault: Int = null
}
type Root {
field(in: Input): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple argument field with default value' do
schema = <<-SCHEMA
schema {
query: Hello
}
enum Color {
BLUE
RED
}
type Hello {
hello(color: Color = RED): String
nullable(color: Color = null): String
str(int: Int = 2): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple type with mutation' do
schema = <<-SCHEMA
schema {
query: HelloScalars
mutation: Mutation
}
type HelloScalars {
bool: Boolean
int: Int
str: String
}
type Mutation {
addHelloScalars(bool: Boolean, int: Int, str: String): HelloScalars
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple type with mutation and default values' do
schema = <<-SCHEMA
enum Color {
BLUE
RED
}
type Mutation {
hello(color: Color = RED, int: Int, nullDefault: Int = null, str: String): String
}
type Query {
str: String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports simple type with subscription' do
schema = <<-SCHEMA
schema {
query: HelloScalars
subscription: Subscription
}
type HelloScalars {
bool: Boolean
int: Int
str: String
}
type Subscription {
subscribeHelloScalars(bool: Boolean, int: Int, str: String): HelloScalars
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports unreferenced type implementing referenced interface' do
schema = <<-SCHEMA
type Concrete implements Iface {
key: String
}
interface Iface {
key: String
}
type Query {
iface: Iface
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports unreferenced type implementing referenced union' do
schema = <<-SCHEMA
type Concrete {
key: String
}
type Query {
union: Union
}
union Union = Concrete
SCHEMA
assert_schema_and_compare_output(schema)
end
it 'supports @deprecated' do
schema = <<-SCHEMA
directive @directiveWithDeprecatedArg(deprecatedArg: Boolean @deprecated(reason: "Don't use me!")) on OBJECT
enum MyEnum {
OLD_VALUE @deprecated
OTHER_VALUE @deprecated(reason: "Terrible reasons")
VALUE
}
input MyInput {
int: Int @deprecated(reason: "This is not the argument you're looking for")
string: String
}
type Query {
enum: MyEnum
field1: String @deprecated
field2: Int @deprecated(reason: "Because I said so")
field3(deprecatedArg: MyInput @deprecated(reason: "Use something else")): String
}
SCHEMA
assert_schema_and_compare_output(schema)
end
it "tracks original AST node" do
schema_definition = <<-GRAPHQL
schema @custom(thing: true) {
query: Query
}
enum Enum {
VALUE
}
type Query {
field(argument: String): String
deprecatedField(argument: String): String @deprecated(reason: "Test")
}
interface Interface {
field(argument: String): String
}
union Union = Query
scalar Scalar
input Input {
argument: String
}
directive @Directive (
# Argument
argument: String
) on SCHEMA
directive @custom(thing: Boolean) on SCHEMA
type Type implements Interface {
field(argument: String): String
}
GRAPHQL
schema = GraphQL::Schema.from_definition(schema_definition)
assert_equal [1, 1], schema.ast_node.position
assert_equal [1, 8], schema.ast_node.directives.first.position
assert_equal [5, 1], schema.types["Enum"].ast_node.position
assert_equal [6, 3], schema.types["Enum"].values["VALUE"].ast_node.position
assert_equal [9, 1], schema.types["Query"].ast_node.position
assert_equal [10, 3], schema.types["Query"].fields["field"].ast_node.position
assert_equal [10, 9], schema.types["Query"].fields["field"].arguments["argument"].ast_node.position
assert_equal [11, 45], schema.types["Query"].fields["deprecatedField"].ast_node.directives[0].position
assert_equal [11, 57], schema.types["Query"].fields["deprecatedField"].ast_node.directives[0].arguments[0].position
assert_equal [14, 1], schema.types["Interface"].ast_node.position
assert_equal [15, 3], schema.types["Interface"].fields["field"].ast_node.position
assert_equal [15, 9], schema.types["Interface"].fields["field"].arguments["argument"].ast_node.position
assert_equal [18, 1], schema.types["Union"].ast_node.position
assert_equal [20, 1], schema.types["Scalar"].ast_node.position
assert_equal [22, 1], schema.types["Input"].ast_node.position
assert_equal [23, 3], schema.types["Input"].arguments["argument"].ast_node.position
assert_equal [26, 1], schema.directives["Directive"].ast_node.position
assert_equal [28, 3], schema.directives["Directive"].arguments["argument"].ast_node.position
assert_equal [33, 22], schema.types["Type"].ast_node.interfaces[0].position
end
it 'can build a schema from a file path' do
schema = <<-SCHEMA
schema {
query: HelloScalars
}
type HelloScalars {
bool: Boolean
float: Float
id: ID
int: Int
str: String!
}
SCHEMA
Tempfile.create(['test', '.graphql']) do |file|
file.write(schema)
file.close
built_schema = GraphQL::Schema.from_definition(file.path)
assert_equal schema, GraphQL::Schema::Printer.print_schema(built_schema)
end
end
end
describe 'Failures' do
it 'Requires a schema definition or Query type' do
schema = <<-SCHEMA
type Hello {
bar: Bar
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Must provide schema definition with query type or a type named Query.', err.message
end
it 'Allows only a single schema definition' do
schema = <<-SCHEMA
schema {
query: Hello
}
schema {
query: Hello
}
type Hello {
bar: Bar
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Must provide only one schema definition.', err.message
end
it 'Requires a query type' do
schema = <<-SCHEMA
schema {
mutation: Hello
}
type Hello {
bar: Bar
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Must provide schema definition with query type or a type named Query.', err.message
end
it 'Unknown type referenced' do
schema = <<-SCHEMA
schema {
query: Hello
}
type Hello {
bar: Bar
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Type "Bar" not found in document.', err.message
end
it 'Unknown type in interface list' do
schema = <<-SCHEMA
schema {
query: Hello
}
type Hello implements Bar {
str: String
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Type "Bar" not found in document.', err.message
end
it 'Unknown type in union list' do
schema = <<-SCHEMA
schema {
query: Hello
}
union TestUnion = Bar
type Hello { testUnion: TestUnion }
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Type "Bar" not found in document.', err.message
end
it 'Unknown query type' do
schema = <<-SCHEMA
schema {
query: Wat
}
type Hello {
str: String
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Specified query type "Wat" not found in document.', err.message
end
it 'Unknown mutation type' do
schema = <<-SCHEMA
schema {
query: Hello
mutation: Wat
}
type Hello {
str: String
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Specified mutation type "Wat" not found in document.', err.message
end
it 'Unknown subscription type' do
schema = <<-SCHEMA
schema {
query: Hello
mutation: Wat
subscription: Awesome
}
type Hello {
str: String
}
type Wat {
str: String
}
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Specified subscription type "Awesome" not found in document.', err.message
end
it 'Does not consider operation names' do
schema = <<-SCHEMA
schema {
query: Foo
}
query Foo { field }
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Specified query type "Foo" not found in document.', err.message
end
it 'Does not consider fragment names' do
schema = <<-SCHEMA
schema {
query: Foo
}
fragment Foo on Type { field }
SCHEMA
err = assert_raises(GraphQL::Schema::InvalidDocumentError) do
GraphQL::Schema.from_definition(schema)
end
assert_equal 'Specified query type "Foo" not found in document.', err.message
end
end
describe "executable schema with resolver maps" do
class Something
def capitalize(args)
args[:word].upcase
end
end
let(:definition) {
<<-GRAPHQL
scalar Date
scalar UndefinedScalar
type Something { capitalize(word:String!): String }
type A { a: String }
type B { b: String }
union Thing = A | B
type Query {
hello: Something
thing: Thing
add_week(in: Date!): Date!
undefined_scalar(str: String, int: Int): UndefinedScalar
}
GRAPHQL
}
let(:resolvers) {
{
Date: {
coerce_input: ->(val, ctx) {
Time.at(Float(val))
},
coerce_result: ->(val, ctx) {
val.to_f
}
},
resolve_type: ->(type, obj, ctx) {
return ctx.schema.types['A']
},
Query: {
add_week: ->(o,a,c) {
raise "No Time" unless a[:in].is_a? Time
a[:in]
},
hello: ->(o,a,c) {
Something.new
},
thing: ->(o,a,c) {
OpenStruct.new({a: "a"})
},
undefined_scalar: ->(o,a,c) {
a.values.first
}
}
}
}
let(:schema) { GraphQL::Schema.from_definition(definition, default_resolve: resolvers) }
it "resolves unions" do
result = schema.execute("query { thing { ... on A { a } } }")
assert_equal(result.to_json,'{"data":{"thing":{"a":"a"}}}')
end
it "resolves scalars" do
result = schema.execute("query { add_week(in: 392277600.0) }")
assert_equal(result.to_json,'{"data":{"add_week":392277600.0}}')
end
it "passes args from graphql to the object" do
result = schema.execute("query { hello { capitalize(word: \"hello\") }}")
assert_equal(result.to_json,'{"data":{"hello":{"capitalize":"HELLO"}}}')
end
it "handles undefined scalar resolution with identity function" do
result = schema.execute <<-GRAPHQL
{
str: undefined_scalar(str: "abc")
int: undefined_scalar(int: 123)
}
GRAPHQL
assert_equal({ "str" => "abc", "int" => 123 }, result["data"])
end
it "doesn't warn about method conflicts" do
assert_output "", "" do
GraphQL::Schema.from_definition "
type Query {
int(method: Int): Int
}
"
end
end
end
describe "executable schemas from string" do
let(:schema_defn) {
<<-GRAPHQL
type Todo {text: String, from_context: String}
type Query { all_todos: [Todo]}
type Mutation { todo_add(text: String!): Todo}
GRAPHQL
}
Todo = Struct.new(:text, :from_context)
class RootResolver
attr_accessor :todos
def initialize
@todos = [Todo.new("Pay the bills.")]
end
def all_todos
@todos
end
def todo_add(args, ctx) # this is a method and accepting arguments
todo = Todo.new(args[:text], ctx[:context_value])
@todos << todo
todo
end
end
it "calls methods with args if args are defined" do
schema = GraphQL::Schema.from_definition(schema_defn)
root_values = RootResolver.new
schema.execute("mutation { todoAdd: todo_add(text: \"Buy Milk\") { text } }", root_value: root_values, context: {context_value: "bar"})
result = schema.execute("query { allTodos: all_todos { text, from_context } }", root_value: root_values)
assert_equal(result.to_json, '{"data":{"allTodos":[{"text":"Pay the bills.","from_context":null},{"text":"Buy Milk","from_context":"bar"}]}}')
end
describe "hash of resolvers with defaults" do
let(:todos) { [Todo.new("Pay the bills.")] }
let(:schema) { GraphQL::Schema.from_definition(schema_defn, default_resolve: resolve_hash) }
let(:resolve_hash) {
h = base_hash
h["Query"] ||= {}
h["Query"]["all_todos"] = ->(obj, args, ctx) { obj }
h["Mutation"] ||= {}
h["Mutation"]["todo_add"] = ->(obj, args, ctx) {
todo = Todo.new(args[:text], ctx[:context_value])
obj << todo
todo
}
h
}
let(:base_hash) {
# Fallback is to resolve by sending the field name
Hash.new { |h, k| h[k] = Hash.new { |h2, k2| ->(obj, args, ctx) { obj.public_send(k2) } } }
}
it "accepts a hash of resolve functions" do
schema.execute("mutation { todoAdd: todo_add(text: \"Buy Milk\") { text } }", context: {context_value: "bar"}, root_value: todos)
result = schema.execute("query { allTodos: all_todos { text, from_context } }", root_value: todos)
assert_equal(result.to_json, '{"data":{"allTodos":[{"text":"Pay the bills.","from_context":null},{"text":"Buy Milk","from_context":"bar"}]}}')
end
end
describe "custom resolve behavior" do
class AppResolver
def initialize
@todos = [Todo.new("Pay the bills.")]
@resolves = {
"Query" => {
"all_todos" => ->(obj, args, ctx) { @todos },
},
"Mutation" => {
"todo_add" => ->(obj, args, ctx) {
todo = Todo.new(args[:text], ctx[:context_value])
@todos << todo
todo
},
},
"Todo" => {
"text" => ->(obj, args, ctx) { obj.text },
"from_context" => ->(obj, args, ctx) { obj.from_context },
}
}
end
def call(type, field, obj, args, ctx)
@resolves
.fetch(type.graphql_name)
.fetch(field.graphql_name)
.call(obj, args, ctx)
end
end
it "accepts a default_resolve callable" do
schema = GraphQL::Schema.from_definition(schema_defn, default_resolve: AppResolver.new)
schema.execute("mutation { todoAdd: todo_add(text: \"Buy Milk\") { text } }", context: {context_value: "bar"})
result = schema.execute("query { allTodos: all_todos { text, from_context } }")
assert_equal('{"data":{"allTodos":[{"text":"Pay the bills.","from_context":null},{"text":"Buy Milk","from_context":"bar"}]}}', result.to_json)
end
end
describe "custom parser behavior" do
module BadParser
ParseError = Class.new(StandardError)
def self.parse(string)
raise ParseError
end
end
it 'accepts a parser callable' do
assert_raises(BadParser::ParseError) do
GraphQL::Schema.from_definition(schema_defn, parser: BadParser)
end
end
end
describe "relay behaviors" do
let(:schema_defn) { <<-GRAPHQL
interface Node {
id: ID!
}
type Query {
node(id: ID!): Node
}
type Thing implements Node {
id: ID!
name: String!
otherThings(after: String, first: Int): ThingConnection!
}
type ThingConnection {
edges: [ThingEdge!]!
}
type ThingEdge {
cursor: String!
node: Thing!
}
GRAPHQL
}
let(:query_string) {'
{
node(id: "taco") {
... on Thing {
name
otherThings {
edges {
node {
name
}
cursor
}
}
}
}
}
'}
it "doesn't try to add them" do
default_resolve = {
"Query" => {
"node" => ->(obj, args, ctx) {
OpenStruct.new(
name: "taco-thing",
otherThings: OpenStruct.new(
edges: [
OpenStruct.new(cursor: "a", node: OpenStruct.new(name: "other-thing-a")),
OpenStruct.new(cursor: "b", node: OpenStruct.new(name: "other-thing-b")),
]
)
)
}
},
"resolve_type" => ->(type, obj, ctx) {
ctx.query.get_type("Thing")
}
}
schema = GraphQL::Schema.from_definition(schema_defn, default_resolve: default_resolve)
result = schema.execute(query_string)
expected_data = {
"node" => {
"name" => "taco-thing",
"otherThings" => {
"edges" => [
{"node" => {"name" => "other-thing-a"}, "cursor" => "a"},
{"node" => {"name" => "other-thing-b"}, "cursor" => "b"},
]
}
}
}
assert_equal expected_data, result["data"]
end
it "doesn't add arguments that aren't in the IDL" do
schema = GraphQL::Schema.from_definition(schema_defn)
assert_equal schema_defn, schema.to_definition
end
end
end
it "works when a directive argument uses a redefined scalar" do
schema_str = <<-GRAPHQL
schema {
query: QueryRoot
}
directive @myDirective(id: ID) on MUTATION | QUERY
scalar ID
type QueryRoot {}
GRAPHQL
schema = GraphQL::Schema.from_definition(schema_str)
assert_equal schema.directives["myDirective"].get_argument("id").type, schema.find("ID")
end
describe "orphan types" do
it "only puts unreachable types in orphan types" do
schema = GraphQL::Schema.from_definition <<-GRAPHQL
type Query {
node(id: ID!): Node
t1: ReachableType
}
interface Node {
id: ID!
}
type ReachableType implements Node {
id: ID!
}
type ReachableThroughInterfaceType implements Node {
id: ID!
}
type UnreachableType {
id: ID!
}
GRAPHQL
assert_equal [], schema.orphan_types.map(&:graphql_name)
expected_definition = <<-GRAPHQL
interface Node {
id: ID!
}
type Query {
node(id: ID!): Node
t1: ReachableType
}
type ReachableThroughInterfaceType implements Node {
id: ID!
}
type ReachableType implements Node {
id: ID!
}
GRAPHQL
assert_equal expected_definition, schema.to_definition, "UnreachableType is excluded"
end
end
it "works with indirect interface implementation" do
schema_string = <<~GRAPHQL
type Query {
entities: [Entity!]!
person: Person
}
type Person implements NamedEntity {
id: ID!
name: String
nationality: String
}
type Product implements NamedEntity {
id: ID!
name: String
amount: Int
}
interface NamedEntity implements Entity {
id: ID!
name: String
}
type Payment implements Entity {
id: ID!
amount: Int
}
interface Entity {
id: ID!
}
GRAPHQL
schema = GraphQL::Schema.from_definition(schema_string)
assert_equal ["amount", "id"], schema.types.fetch("Payment").fields.keys.sort
assert_equal ["id", "name", "nationality"], schema.types.fetch("Person").fields.keys.sort
end
it "supports extending schemas with directives" do
schema_sdl = <<~EOS
extend schema
@link(import: ["@key", "@shareable"], url: "https://specs.apollo.dev/federation/v2.0")
directive @link(as: String, for: link__Purpose, import: [link__Import], url: String!) repeatable on SCHEMA
type Query {
something: Int
}
scalar link__Import
enum link__Purpose {
EXECUTION
SECURITY
}
EOS
schema = GraphQL::Schema.from_definition(schema_sdl)
assert_equal ["link"], schema.schema_directives.map(&:graphql_name)
assert_equal({ url: "https://specs.apollo.dev/federation/v2.0", import: ["@key", "@shareable"] },
schema.schema_directives.first.arguments.to_h)
assert_equal schema_sdl, schema.to_definition
end
it "supports extending schemas with directives" do
schema_sdl = <<~EOS
extend schema
@link(url: "https://specs.apollo.dev/federation/v2.0",
import: ["@key", "@shareable"])
type Query {
something: Int
}
EOS
class LinkSchema < GraphQL::Schema
class Import < GraphQL::Schema::Scalar
end
class Purpose < GraphQL::Schema::Scalar
end
class Link < GraphQL::Schema::Directive
argument :url, String
argument :as, String, required: false
argument :import, Import, required: false
argument :for, Purpose, required: false
repeatable(true)
locations SCHEMA
end
directive(Link)
end
assert_equal LinkSchema::Link, LinkSchema.directives["link"]
schema = LinkSchema.from_definition(schema_sdl)
assert_equal ["link"], schema.schema_directives.map(&:graphql_name)
assert_equal({ url: "https://specs.apollo.dev/federation/v2.0", import: ["@key", "@shareable"] },
schema.schema_directives.first.arguments.to_h)
expected_schema = <<~GRAPHQL
extend schema
@link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key", "@shareable"])
directive @link(as: String, for: Purpose, import: Import, url: String!) repeatable on SCHEMA
scalar Import
scalar Purpose
type Query {
something: Int
}
GRAPHQL
assert_equal expected_schema, schema.to_definition
end
describe "JSON type" do
class JsonTypeApplication
SCHEMA_STRING = <<~EOS
scalar JsonValue
type Query {
echoJsonValue(arg: JsonValue): JsonValue
}
EOS
def initialize
@schema = GraphQL::Schema.from_definition(SCHEMA_STRING, default_resolve: self)
end
def execute_query(query_string, **vars)
@schema.execute(query_string, variables: vars)
end
def call(parent_type, field, object, args, context)
args.fetch(:arg)
end
def coerce_input(type, value, ctx)
nils = ctx[:nils] ||= []
if value.is_a?(Array)
nils << value[2]
else
nils << value["abc"]
end
::JSON.generate(value)
end
def coerce_result(type, value, ctx)
::JSON.parse(value)
end
end
it "Sends normal ruby values to schema coercion" do
app = JsonTypeApplication.new
res_1 = app.execute_query(<<~EOS, arg: [3, "abc", nil, 7])
query WithArg($arg: JsonValue) {
echoJsonValue(arg: $arg)
}
EOS
assert_equal([3, "abc", nil, 7], res_1["data"]["echoJsonValue"])
assert_equal [nil, nil], res_1.context[:nils]
res_2 = app.execute_query(<<~EOS)
query {
echoJsonValue(arg: [3, "abc", null, 7])
}
EOS
assert_equal([3, "abc", nil, 7], res_2["data"]["echoJsonValue"])
assert_equal [nil, nil], res_2.context[:nils]
res_3 = app.execute_query(<<~EOS, arg: { "abc" => nil, "def" => 7 })
query WithArg($arg: JsonValue) {
echoJsonValue(arg: $arg)
}
EOS
assert_equal({ "abc" => nil, "def" => 7 }, res_3["data"]["echoJsonValue"])
assert_equal [nil, nil], res_3.context[:nils]
res_4 = app.execute_query(<<~EOS)
query {
echoJsonValue(arg: { abc: null, def: 7, ghi: { jkl: null } })
}
EOS
assert_equal({ "abc" => nil, "def" => 7, "ghi"=>{"jkl"=>nil} }, res_4["data"]["echoJsonValue"])
assert_equal [nil, nil], res_4.context[:nils]
end
end
it "reprints schema with extend when root types match" do
schema_str = <<~EOS
extend schema
@customDirective
directive @customDirective repeatable on SCHEMA
type Query {
foo: Int
}
EOS
schema = GraphQL::Schema.from_definition(schema_str)
assert_equal schema_str, schema.to_definition
end
end
|