|
1 |
| -from graphql.core.language.ast import Field, Name, SelectionSet |
| 1 | +from graphql.core.language.ast import Field, Name, SelectionSet, Document, OperationDefinition |
2 | 2 | from graphql.core.language.parser import parse
|
3 | 3 | from graphql.core.language.printer import print_ast
|
4 | 4 | from graphql.core.language.visitor import (
|
|
10 | 10 | from ...validation.tests.utils import test_schema
|
11 | 11 |
|
12 | 12 |
|
| 13 | +def test_allows_editing_a_node_both_on_enter_and_on_leave(): |
| 14 | + ast = parse('{ a, b, c { a, b, c } }', no_location=True) |
| 15 | + |
| 16 | + class TestVisitor(Visitor): |
| 17 | + def enter(self, node, *args): |
| 18 | + if isinstance(node, OperationDefinition): |
| 19 | + selection_set = node.selection_set |
| 20 | + self.selections = None |
| 21 | + if selection_set: |
| 22 | + self.selections = selection_set.selections |
| 23 | + new_selection_set = SelectionSet( |
| 24 | + selections=[]) |
| 25 | + return OperationDefinition( |
| 26 | + name=node.name, |
| 27 | + variable_definitions=node.variable_definitions, |
| 28 | + directives=node.directives, |
| 29 | + loc=node.loc, |
| 30 | + operation=node.operation, |
| 31 | + selection_set=new_selection_set) |
| 32 | + |
| 33 | + def leave(self, node, *args): |
| 34 | + if isinstance(node, OperationDefinition): |
| 35 | + new_selection_set = None |
| 36 | + if self.selections: |
| 37 | + new_selection_set = SelectionSet( |
| 38 | + selections=self.selections) |
| 39 | + return OperationDefinition( |
| 40 | + name=node.name, |
| 41 | + variable_definitions=node.variable_definitions, |
| 42 | + directives=node.directives, |
| 43 | + loc=node.loc, |
| 44 | + operation=node.operation, |
| 45 | + selection_set=new_selection_set) |
| 46 | + |
| 47 | + edited_ast = visit(ast, TestVisitor()) |
| 48 | + assert ast == parse('{ a, b, c { a, b, c } }', no_location=True) |
| 49 | + assert edited_ast == ast |
| 50 | + |
| 51 | + |
| 52 | +def test_allows_editing_the_root_node_on_enter_and_on_leave(): |
| 53 | + ast = parse('{ a, b, c { a, b, c } }', no_location=True) |
| 54 | + |
| 55 | + definitions = ast.definitions |
| 56 | + |
| 57 | + class TestVisitor(Visitor): |
| 58 | + def enter(self, node, *args): |
| 59 | + if isinstance(node, Document): |
| 60 | + return Document( |
| 61 | + loc=node.loc, |
| 62 | + definitions=[]) |
| 63 | + |
| 64 | + def leave(self, node, *args): |
| 65 | + if isinstance(node, Document): |
| 66 | + return Document( |
| 67 | + loc=node.loc, |
| 68 | + definitions=definitions) |
| 69 | + |
| 70 | + edited_ast = visit(ast, TestVisitor()) |
| 71 | + assert edited_ast == ast |
| 72 | + |
| 73 | + |
13 | 74 | def test_allows_for_editing_on_enter():
|
14 | 75 | ast = parse('{ a, b, c { a, b, c } }', no_location=True)
|
15 | 76 |
|
|
0 commit comments