From 67f1ddd06bed22f12b006395332feb19bef89113 Mon Sep 17 00:00:00 2001 From: Daniel Gallagher Date: Fri, 6 Jul 2018 12:13:20 -0700 Subject: [PATCH] Run black formatter via pre-commit on all files --- conftest.py | 5 + docs/conf.py | 165 +++++---- graphql/backend/base.py | 2 + graphql/backend/compiled.py | 1 + graphql/backend/quiver_cloud.py | 1 + graphql/backend/tests/test_decider.py | 1 + graphql/error/located_error.py | 1 + graphql/error/syntax_error.py | 1 + graphql/execution/executors/asyncio.py | 1 + graphql/execution/executors/asyncio_utils.py | 2 + graphql/execution/executors/gevent.py | 1 + graphql/execution/executors/process.py | 1 + graphql/execution/executors/sync.py | 1 + graphql/execution/tests/test_abstract.py | 3 + graphql/execution/tests/test_dataloader.py | 3 + .../execution/tests/test_execute_schema.py | 2 + graphql/execution/tests/test_executor.py | 12 + .../execution/tests/test_executor_gevent.py | 1 + .../execution/tests/test_executor_thread.py | 1 + graphql/execution/tests/test_lists.py | 1 + graphql/execution/tests/test_located_error.py | 10 +- graphql/execution/tests/test_mutations.py | 2 + graphql/execution/tests/test_nonnull.py | 2 + graphql/execution/tests/test_resolve.py | 1 + graphql/execution/tests/test_subscribe.py | 2 + .../execution/tests/test_union_interface.py | 3 + graphql/execution/tests/test_variables.py | 1 + graphql/language/lexer.py | 4 +- graphql/language/tests/test_visitor.py | 19 + graphql/language/tests/test_visitor_meta.py | 3 + graphql/language/visitor.py | 1 + graphql/language/visitor_meta.py | 1 + graphql/pyutils/compat.py | 1 + graphql/type/definition.py | 13 +- graphql/type/tests/test_validation.py | 23 ++ graphql/type/typemap.py | 1 + .../rules/arguments_of_correct_type.py | 1 + .../rules/default_values_of_correct_type.py | 1 + .../rules/fragments_on_composite_types.py | 1 + .../validation/rules/known_argument_names.py | 1 + graphql/validation/rules/known_directives.py | 1 + .../validation/rules/known_fragment_names.py | 1 + graphql/validation/rules/known_type_names.py | 1 + .../rules/overlapping_fields_can_be_merged.py | 4 +- .../rules/possible_fragment_spreads.py | 1 + .../rules/provided_non_null_arguments.py | 1 + graphql/validation/rules/scalar_leafs.py | 1 + .../rules/variables_are_input_types.py | 1 + .../tests/test_arguments_of_correct_type.py | 14 + scripts/ast.ast | 2 +- scripts/casing.py | 8 +- scripts/fb_ast.py | 24 +- scripts/generate_ast.py | 143 +++++--- setup.py | 92 +++-- tests/starwars/starwars_fixtures.py | 69 ++-- tests/starwars/starwars_schema.py | 159 ++++----- tests/starwars/test_introspection.py | 328 ++++++------------ tests/starwars/test_query.py | 244 +++++-------- tests/starwars/test_validation.py | 30 +- tests_py35/core_execution/__init__.py | 2 +- .../core_execution/test_asyncio_executor.py | 91 ++--- 61 files changed, 743 insertions(+), 771 deletions(-) diff --git a/conftest.py b/conftest.py index a36e6ba1..6b916378 100644 --- a/conftest.py +++ b/conftest.py @@ -4,11 +4,13 @@ try: import pyannotate_runtime + PYANOTATE_PRESENT = True except ImportError: PYANOTATE_PRESENT = False if PYANOTATE_PRESENT: + def pytest_collection_finish(session): """Handle the pytest collection finish hook: configure pyannotate. Explicitly delay importing `collect_types` until all tests have @@ -16,15 +18,18 @@ def pytest_collection_finish(session): world before importing pyannotate. """ from pyannotate_runtime import collect_types + collect_types.init_types_collection() @pytest.fixture(autouse=True) def collect_types_fixture(): from pyannotate_runtime import collect_types + collect_types.resume() yield collect_types.pause() def pytest_sessionfinish(session, exitstatus): from pyannotate_runtime import collect_types + collect_types.dump_stats("type_info.json") diff --git a/docs/conf.py b/docs/conf.py index dab2d99b..d5c9947c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,51 +19,51 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.todo', - 'sphinx.ext.coverage', - 'sphinx.ext.viewcode', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.viewcode", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'graphqllib' -copyright = u'2015, Taeho Kim' -author = u'Taeho Kim' +project = u"graphqllib" +copyright = u"2015, Taeho Kim" +author = u"Taeho Kim" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '0.1' +version = "0.1" # The full version, including alpha/beta/rc tags. -release = '0.1a0' +release = "0.1a0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -74,37 +74,37 @@ # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. -#keep_warnings = False +# keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True @@ -114,156 +114,149 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'alabaster' +html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -#html_static_path = ['_static'] +# html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. -#html_extra_path = [] +# html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -#html_search_language = 'en' +# html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value -#html_search_options = {'type': 'default'} +# html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. -#html_search_scorer = 'scorer.js' +# html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. -htmlhelp_basename = 'graphqllibdoc' +htmlhelp_basename = "graphqllibdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { -# The paper size ('letterpaper' or 'a4paper'). -#'papersize': 'letterpaper', - -# The font size ('10pt', '11pt' or '12pt'). -#'pointsize': '10pt', - -# Additional stuff for the LaTeX preamble. -#'preamble': '', - -# Latex figure (float) alignment -#'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'graphqllib.tex', u'graphqllib Documentation', - u'Taeho Kim', 'manual'), + (master_doc, "graphqllib.tex", u"graphqllib Documentation", u"Taeho Kim", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'graphqllib', u'graphqllib Documentation', - [author], 1) -] +man_pages = [(master_doc, "graphqllib", u"graphqllib Documentation", [author], 1)] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------- @@ -272,23 +265,29 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'graphqllib', u'graphqllib Documentation', - author, 'graphqllib', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "graphqllib", + u"graphqllib Documentation", + author, + "graphqllib", + "One line description of project.", + "Miscellaneous", + ) ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. -#texinfo_no_detailmenu = False +# texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'https://docs.python.org/': None} +intersphinx_mapping = {"https://docs.python.org/": None} diff --git a/graphql/backend/base.py b/graphql/backend/base.py index 6573d3a7..3d34d16a 100644 --- a/graphql/backend/base.py +++ b/graphql/backend/base.py @@ -13,6 +13,7 @@ class GraphQLBackend(six.with_metaclass(ABCMeta)): + @abstractmethod def document_from_string(self, schema, request_string): raise NotImplementedError( @@ -21,6 +22,7 @@ def document_from_string(self, schema, request_string): class GraphQLDocument(object): + def __init__(self, schema, document_string, document_ast, execute): # type: (GraphQLSchema, str, Document, Callable) -> None self.schema = schema diff --git a/graphql/backend/compiled.py b/graphql/backend/compiled.py index e3805cd1..df073c93 100644 --- a/graphql/backend/compiled.py +++ b/graphql/backend/compiled.py @@ -8,6 +8,7 @@ class GraphQLCompiledDocument(GraphQLDocument): + @classmethod def from_code( cls, diff --git a/graphql/backend/quiver_cloud.py b/graphql/backend/quiver_cloud.py index 280f23d9..1b004ba5 100644 --- a/graphql/backend/quiver_cloud.py +++ b/graphql/backend/quiver_cloud.py @@ -32,6 +32,7 @@ class GraphQLQuiverCloudBackend(GraphQLBackend): + def __init__(self, dsn, python_options=None, **options): super(GraphQLQuiverCloudBackend, self).__init__(**options) try: diff --git a/graphql/backend/tests/test_decider.py b/graphql/backend/tests/test_decider.py index 32dccaee..32ca8acd 100644 --- a/graphql/backend/tests/test_decider.py +++ b/graphql/backend/tests/test_decider.py @@ -17,6 +17,7 @@ class FakeBackend(GraphQLBackend): + def __init__(self, name, raises=False): # type: (str, bool) -> None self.raises = raises diff --git a/graphql/error/located_error.py b/graphql/error/located_error.py index fe84e495..16e865c8 100644 --- a/graphql/error/located_error.py +++ b/graphql/error/located_error.py @@ -11,6 +11,7 @@ class GraphQLLocatedError(GraphQLError): + def __init__( self, nodes, # type: List[Field] diff --git a/graphql/error/syntax_error.py b/graphql/error/syntax_error.py index d38adc1f..0eadbd0d 100644 --- a/graphql/error/syntax_error.py +++ b/graphql/error/syntax_error.py @@ -10,6 +10,7 @@ class GraphQLSyntaxError(GraphQLError): + def __init__(self, source, position, description): # type: (Source, int, str) -> None location = get_location(source, position) diff --git a/graphql/execution/executors/asyncio.py b/graphql/execution/executors/asyncio.py index bafa492b..8640b9cd 100644 --- a/graphql/execution/executors/asyncio.py +++ b/graphql/execution/executors/asyncio.py @@ -45,6 +45,7 @@ def asyncgen_to_observable(asyncgen, loop=None): class AsyncioExecutor(object): + def __init__(self, loop=None): # type: (Optional[_UnixSelectorEventLoop]) -> None if loop is None: diff --git a/graphql/execution/executors/asyncio_utils.py b/graphql/execution/executors/asyncio_utils.py index 17ec5c79..9b201072 100644 --- a/graphql/execution/executors/asyncio_utils.py +++ b/graphql/execution/executors/asyncio_utils.py @@ -4,10 +4,12 @@ def asyncgen_to_observable(asyncgen, loop=None): + def emit(observer): task = ensure_future(iterate_asyncgen(asyncgen, observer), loop=loop) def dispose(): + async def await_task(): await task diff --git a/graphql/execution/executors/gevent.py b/graphql/execution/executors/gevent.py index 4bc5ac4e..cae187e1 100644 --- a/graphql/execution/executors/gevent.py +++ b/graphql/execution/executors/gevent.py @@ -7,6 +7,7 @@ class GeventExecutor(object): + def __init__(self): self.jobs = [] diff --git a/graphql/execution/executors/process.py b/graphql/execution/executors/process.py index 948279ae..36782b81 100644 --- a/graphql/execution/executors/process.py +++ b/graphql/execution/executors/process.py @@ -11,6 +11,7 @@ def queue_process(q): class ProcessExecutor(object): + def __init__(self): self.processes = [] self.q = Queue() diff --git a/graphql/execution/executors/sync.py b/graphql/execution/executors/sync.py index c45d8a8f..e18b0819 100644 --- a/graphql/execution/executors/sync.py +++ b/graphql/execution/executors/sync.py @@ -4,6 +4,7 @@ class SyncExecutor(object): + def wait_until_finished(self): # type: () -> None pass diff --git a/graphql/execution/tests/test_abstract.py b/graphql/execution/tests/test_abstract.py index ef3eacd3..2ad4e7f9 100644 --- a/graphql/execution/tests/test_abstract.py +++ b/graphql/execution/tests/test_abstract.py @@ -11,6 +11,7 @@ class Dog(object): + def __init__(self, name, woofs): # type: (str, bool) -> None self.name = name @@ -18,6 +19,7 @@ def __init__(self, name, woofs): class Cat(object): + def __init__(self, name, meows): # type: (str, bool) -> None self.name = name @@ -25,6 +27,7 @@ def __init__(self, name, meows): class Human(object): + def __init__(self, name): # type: (str) -> None self.name = name diff --git a/graphql/execution/tests/test_dataloader.py b/graphql/execution/tests/test_dataloader.py index 88f292d1..d23e384f 100644 --- a/graphql/execution/tests/test_dataloader.py +++ b/graphql/execution/tests/test_dataloader.py @@ -64,6 +64,7 @@ def test_batches_correctly(executor): load_calls = [] class BusinessDataLoader(DataLoader): + def batch_load_fn(self, keys): # type: (List[str]) -> Promise load_calls.append(keys) @@ -144,6 +145,7 @@ def test_batches_multiple_together(executor): business_load_calls = [] class BusinessDataLoader(DataLoader): + def batch_load_fn(self, keys): # type: (List[str]) -> Promise business_load_calls.append(keys) @@ -152,6 +154,7 @@ def batch_load_fn(self, keys): location_load_calls = [] class LocationDataLoader(DataLoader): + def batch_load_fn(self, keys): # type: (List[str]) -> Promise location_load_calls.append(keys) diff --git a/graphql/execution/tests/test_execute_schema.py b/graphql/execution/tests/test_execute_schema.py index 0c7e1033..c960af2e 100644 --- a/graphql/execution/tests/test_execute_schema.py +++ b/graphql/execution/tests/test_execute_schema.py @@ -76,6 +76,7 @@ def test_executes_using_a_schema(): BlogSchema = GraphQLSchema(BlogQuery) class Article(object): + def __init__(self, id): # type: (int) -> None self.id = id @@ -100,6 +101,7 @@ def recentArticle(self): return Article(1) class Pic(object): + def __init__(self, uid, width, height): # type: (int, int, int) -> None self.url = "cdn://{}".format(uid) diff --git a/graphql/execution/tests/test_executor.py b/graphql/execution/tests/test_executor.py index 88e5b693..9883d2c3 100644 --- a/graphql/execution/tests/test_executor.py +++ b/graphql/execution/tests/test_executor.py @@ -257,6 +257,7 @@ def test_nulls_out_error_subtrees(): }""" class Data(object): + def ok(self): # type: () -> str return "ok" @@ -498,11 +499,13 @@ def test_does_not_include_arguments_that_were_not_set(): def test_fails_when_an_is_type_of_check_is_not_met(): # type: () -> None class Special(object): + def __init__(self, value): # type: (str) -> None self.value = value class NotSpecial(object): + def __init__(self, value): # type: (str) -> None self.value = value @@ -594,6 +597,7 @@ def test_middleware(): }""" class Data(object): + def ok(self): # type: () -> str return "ok" @@ -627,6 +631,7 @@ def test_middleware_class(): }""" class Data(object): + def ok(self): # type: () -> str return "ok" @@ -643,6 +648,7 @@ def not_ok(self): ) class MyMiddleware(object): + def resolve(self, next, *args, **kwargs): # type: (Callable, *Any, **Any) -> Promise p = next(*args, **kwargs) @@ -661,6 +667,7 @@ def test_middleware_skip_promise_wrap(): }""" class Data(object): + def ok(self): # type: () -> str return "ok" @@ -677,11 +684,13 @@ def not_ok(self): ) class MyPromiseMiddleware(object): + def resolve(self, next, *args, **kwargs): # type: (Callable, *Any, **Any) -> Promise return Promise.resolve(next(*args, **kwargs)) class MyEmptyMiddleware(object): + def resolve(self, next, *args, **kwargs): # type: (Callable, *Any, **Any) -> str return next(*args, **kwargs) @@ -768,6 +777,7 @@ def test_executor_properly_propogates_path_data(mocker): BlogSchema = GraphQLSchema(BlogQuery) class Article(object): + def __init__(self, id): # type: (int) -> None self.id = id @@ -790,12 +800,14 @@ def recentArticle(self): return Article(1) class Pic(object): + def __init__(self, uid, width, height): self.url = "cdn://{}".format(uid) self.width = str(width) self.height = str(height) class PathCollectorMiddleware(object): + def __init__(self): # type: () -> None self.paths = [] diff --git a/graphql/execution/tests/test_executor_gevent.py b/graphql/execution/tests/test_executor_gevent.py index 9256a018..fa22e5de 100644 --- a/graphql/execution/tests/test_executor_gevent.py +++ b/graphql/execution/tests/test_executor_gevent.py @@ -19,6 +19,7 @@ def test_gevent_executor(): + def resolver(context, *_): gevent.sleep(0.001) return "hey" diff --git a/graphql/execution/tests/test_executor_thread.py b/graphql/execution/tests/test_executor_thread.py index 6eaaf47e..5896e2f7 100644 --- a/graphql/execution/tests/test_executor_thread.py +++ b/graphql/execution/tests/test_executor_thread.py @@ -175,6 +175,7 @@ def test_synchronous_error_nulls_out_error_subtrees(): ) class Data: + def sync(self): # type: () -> str return "sync" diff --git a/graphql/execution/tests/test_lists.py b/graphql/execution/tests/test_lists.py index 3534a137..f58f34d2 100644 --- a/graphql/execution/tests/test_lists.py +++ b/graphql/execution/tests/test_lists.py @@ -20,6 +20,7 @@ def check(test_data, expected): + def run_check(self): # type: (Any) -> None test_type = self.type diff --git a/graphql/execution/tests/test_located_error.py b/graphql/execution/tests/test_located_error.py index 26773804..b5bec97f 100644 --- a/graphql/execution/tests/test_located_error.py +++ b/graphql/execution/tests/test_located_error.py @@ -1,8 +1,14 @@ # type: ignore # coding: utf-8 -from graphql import (GraphQLField, GraphQLObjectType, GraphQLSchema, - GraphQLString, execute, parse) +from graphql import ( + GraphQLField, + GraphQLObjectType, + GraphQLSchema, + GraphQLString, + execute, + parse, +) from graphql.error import GraphQLLocatedError diff --git a/graphql/execution/tests/test_mutations.py b/graphql/execution/tests/test_mutations.py index d7ec17bc..1a00cf35 100644 --- a/graphql/execution/tests/test_mutations.py +++ b/graphql/execution/tests/test_mutations.py @@ -17,12 +17,14 @@ class NumberHolder(object): + def __init__(self, n): # type: (int) -> None self.theNumber = n class Root(object): + def __init__(self, n): # type: (int) -> None self.numberHolder = NumberHolder(n) diff --git a/graphql/execution/tests/test_nonnull.py b/graphql/execution/tests/test_nonnull.py index 6f8a3725..8b4c7e0e 100644 --- a/graphql/execution/tests/test_nonnull.py +++ b/graphql/execution/tests/test_nonnull.py @@ -24,6 +24,7 @@ class ThrowingData(object): + def sync(self): # type: () -> None raise sync_error @@ -58,6 +59,7 @@ def nonNullPromiseNest(self): class NullingData(object): + def sync(self): # type: () -> Optional[Any] return None diff --git a/graphql/execution/tests/test_resolve.py b/graphql/execution/tests/test_resolve.py index d6788f38..6165b930 100644 --- a/graphql/execution/tests/test_resolve.py +++ b/graphql/execution/tests/test_resolve.py @@ -26,6 +26,7 @@ class CustomPromise(Promise): + @classmethod def fulfilled(cls, x): # type: (str) -> CustomPromise diff --git a/graphql/execution/tests/test_subscribe.py b/graphql/execution/tests/test_subscribe.py index 2fa039c3..d9c1cd32 100644 --- a/graphql/execution/tests/test_subscribe.py +++ b/graphql/execution/tests/test_subscribe.py @@ -114,6 +114,7 @@ def default_resolver(root, info): class MyObserver(Observer): + def on_next(self, value): self.has_on_next = value @@ -132,6 +133,7 @@ def create_subscription( ): # type: (...) -> Tuple[Callable, Union[ExecutionResult, Observable]] class Root(object): + class inbox(object): emails = [ Email( diff --git a/graphql/execution/tests/test_union_interface.py b/graphql/execution/tests/test_union_interface.py index bd61ba30..48b3bac9 100644 --- a/graphql/execution/tests/test_union_interface.py +++ b/graphql/execution/tests/test_union_interface.py @@ -19,18 +19,21 @@ class Dog(object): + def __init__(self, name, barks): self.name = name self.barks = barks class Cat(object): + def __init__(self, name, meows): self.name = name self.meows = meows class Person(object): + def __init__(self, name, pets, friends): # type: (str, List, List[Person]) -> None self.name = name diff --git a/graphql/execution/tests/test_variables.py b/graphql/execution/tests/test_variables.py index a4a1a8fe..232b408a 100644 --- a/graphql/execution/tests/test_variables.py +++ b/graphql/execution/tests/test_variables.py @@ -753,6 +753,7 @@ def test_does_not_allow_unknown_types_to_be_used_as_values(): # noinspection PyMethodMayBeStatic class TestUsesArgumentDefaultValues: + def test_when_no_argument_provided(self): # type: () -> None check( diff --git a/graphql/language/lexer.py b/graphql/language/lexer.py index a017dbce..a60bc6e2 100644 --- a/graphql/language/lexer.py +++ b/graphql/language/lexer.py @@ -372,7 +372,7 @@ def read_string(source, start): position += 1 if code == 92: # \ - append(body[chunk_start: position - 1]) + append(body[chunk_start : position - 1]) code = char_code_at(body, position) escaped = ESCAPED_CHAR_CODES.get(code) # type: ignore @@ -392,7 +392,7 @@ def read_string(source, start): source, position, u"Invalid character escape sequence: \\u{}.".format( - body[position + 1: position + 5] + body[position + 1 : position + 5] ), ) diff --git a/graphql/language/tests/test_visitor.py b/graphql/language/tests/test_visitor.py index 1392fe3e..f80dadbd 100644 --- a/graphql/language/tests/test_visitor.py +++ b/graphql/language/tests/test_visitor.py @@ -39,6 +39,7 @@ def test_allows_editing_a_node_both_on_enter_and_on_leave(): ast = parse("{ a, b, c { a, b, c } }", no_location=True) class TestVisitor(Visitor): + def __init__(self): # type: () -> None self.did_enter = False @@ -101,6 +102,7 @@ def test_allows_editing_the_root_node_on_enter_and_on_leave(): definitions = ast.definitions class TestVisitor(Visitor): + def __init__(self): # type: () -> None self.did_enter = False @@ -130,6 +132,7 @@ def test_allows_for_editing_on_enter(): ast = parse("{ a, b, c { a, b, c } }", no_location=True) class TestVisitor(Visitor): + def enter(self, node, *args): # type: (Any, *Any) -> Optional[Any] if isinstance(node, Field) and node.name.value == "b": @@ -146,6 +149,7 @@ def test_allows_for_editing_on_leave(): ast = parse("{ a, b, c { a, b, c } }", no_location=True) class TestVisitor(Visitor): + def leave(self, node, *args): # type: (Union[Field, Name], *Any) -> Optional[Falsey] if isinstance(node, Field) and node.name.value == "b": @@ -163,6 +167,7 @@ def test_visits_edited_node(): ast = parse("{ a { x } }") class TestVisitor(Visitor): + def __init__(self): # type: () -> None self.did_visit_added_field = False @@ -190,6 +195,7 @@ def test_allows_skipping_a_subtree(): ast = parse("{ a, b { x }, c }") class TestVisitor(Visitor): + def enter(self, node, *args): # type: (Any, *Any) -> Optional[Any] visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -227,6 +233,7 @@ def test_allows_early_exit_while_visiting(): ast = parse("{ a, b { x }, c }") class TestVisitor(Visitor): + def enter(self, node, *args): # type: (Any, *Any) -> Optional[Any] visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -262,6 +269,7 @@ def test_allows_a_named_functions_visitor_api(): ast = parse("{ a, b { x }, c }") class TestVisitor(Visitor): + def enter_Name(self, node, *args): # type: (Name, *Any) -> None visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -294,6 +302,7 @@ def test_visits_kitchen_sink(): ast = parse(KITCHEN_SINK) class TestVisitor(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> None kind = parent and type(parent).__name__ @@ -617,6 +626,7 @@ def test_visits_in_pararell_allows_skipping_a_subtree(): ast = parse("{ a, b { x }, c }") class TestVisitor(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> Optional[Any] visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -659,6 +669,7 @@ def test_visits_in_pararell_allows_skipping_different_subtrees(): ast = parse("{ a { x }, b { y} }") class TestVisitor(Visitor): + def __init__(self, name): # type: (str) -> None self.name = name @@ -744,6 +755,7 @@ def test_visits_in_pararell_allows_early_exit_while_visiting(): ast = parse("{ a, b { x }, c }") class TestVisitor(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> None visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -785,6 +797,7 @@ def test_visits_in_pararell_allows_early_exit_from_different_points(): ast = parse("{ a { y }, b { x } }") class TestVisitor(Visitor): + def __init__(self, name): # type: (str) -> None self.name = name @@ -872,12 +885,14 @@ def test_visits_in_pararell_allows_for_editing_on_enter(): ast = parse("{ a, b, c { a, b, c } }", no_location=True) class TestVisitor1(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> Optional[Any] if type(node).__name__ == "Field" and node.name.value == "b": return REMOVE class TestVisitor2(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> None visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -931,6 +946,7 @@ def test_visits_in_pararell_allows_for_editing_on_leave(): ast = parse("{ a, b, c { a, b, c } }", no_location=True) class TestVisitor1(Visitor): + def leave( self, node, # type: Union[Field, Name] @@ -943,6 +959,7 @@ def leave( return REMOVE class TestVisitor2(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> None visited.append(["enter", type(node).__name__, getattr(node, "value", None)]) @@ -1004,6 +1021,7 @@ def test_visits_with_typeinfo_maintains_type_info_during_visit(): type_info = TypeInfo(test_schema) class TestVisitor(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> None parent_type = type_info.get_parent_type() @@ -1091,6 +1109,7 @@ def test_visits_with_typeinfo_maintains_type_info_during_edit(): type_info = TypeInfo(test_schema) class TestVisitor(Visitor): + def enter(self, node, key, parent, *args): # type: (Any, Union[None, int, str], Any, *List[Any]) -> Optional[Any] parent_type = type_info.get_parent_type() diff --git a/graphql/language/tests/test_visitor_meta.py b/graphql/language/tests/test_visitor_meta.py index d40bb47a..19890ad3 100644 --- a/graphql/language/tests/test_visitor_meta.py +++ b/graphql/language/tests/test_visitor_meta.py @@ -5,6 +5,7 @@ def test_visitor_meta_creates_enter_and_leave_handlers(): # type: () -> None class MyVisitor(Visitor): + def enter_OperationDefinition(self): pass @@ -18,6 +19,7 @@ def leave_OperationDefinition(self): def test_visitor_inherits_parent_definitions(): # type: () -> None class MyVisitor(Visitor): + def enter_OperationDefinition(self): pass @@ -28,6 +30,7 @@ def leave_OperationDefinition(self): assert MyVisitor._get_leave_handler(ast.OperationDefinition) class MyVisitorSubclassed(MyVisitor): + def enter_FragmentDefinition(self): pass diff --git a/graphql/language/visitor.py b/graphql/language/visitor.py index 66dded46..c71bfc3b 100644 --- a/graphql/language/visitor.py +++ b/graphql/language/visitor.py @@ -15,6 +15,7 @@ class _Falsey(object): + def __nonzero__(self): return False diff --git a/graphql/language/visitor_meta.py b/graphql/language/visitor_meta.py index 37372c48..01c00c1f 100644 --- a/graphql/language/visitor_meta.py +++ b/graphql/language/visitor_meta.py @@ -48,6 +48,7 @@ class VisitorMeta(type): + def __new__(cls, name, bases, attrs): enter_handlers = {} leave_handlers = {} diff --git a/graphql/pyutils/compat.py b/graphql/pyutils/compat.py index 43613d74..7aa846bf 100644 --- a/graphql/pyutils/compat.py +++ b/graphql/pyutils/compat.py @@ -69,6 +69,7 @@ def callable(obj): else: class Iterator(object): + def next(self): return type(self).__next__(self) diff --git a/graphql/type/definition.py b/graphql/type/definition.py index ce9dffb5..b4e769ca 100644 --- a/graphql/type/definition.py +++ b/graphql/type/definition.py @@ -625,12 +625,13 @@ class GeoPoint(GraphQLInputObjectType): } """ - def __init__(self, - name, # type: str - fields, # type: Union[Callable[[], Dict[str, GraphQLInputObjectField]], Dict[str, GraphQLInputObjectField]] - description=None, # type: Optional[str] - container_type=None, # type: Type[Dict[str, Any]] - ): + def __init__( + self, + name, # type: str + fields, # type: Union[Callable[[], Dict[str, GraphQLInputObjectField]], Dict[str, GraphQLInputObjectField]] + description=None, # type: Optional[str] + container_type=None, # type: Type[Dict[str, Any]] + ): # type: (...) -> None assert name, "Type must be named." self.name = name diff --git a/graphql/type/tests/test_validation.py b/graphql/type/tests/test_validation.py index 4bead700..efd6392e 100644 --- a/graphql/type/tests/test_validation.py +++ b/graphql/type/tests/test_validation.py @@ -92,6 +92,7 @@ def schema_with_field_type(t): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ASchemaMustHaveObjectRootTypes: + def test_accepts_a_schema_whose_query_type_is_an_object_type(self): assert GraphQLSchema(query=SomeObjectType) @@ -155,6 +156,7 @@ def test_rejects_a_schema_whose_directives_are_incorrectly_typed(self): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ASchemaMustContainUniquelyNamedTypes: + def test_it_rejects_a_schema_which_defines_a_builtin_type(self): FakeString = GraphQLScalarType(name="String", serialize=_none) @@ -213,6 +215,7 @@ def test_it_rejects_a_schema_which_have_same_named_objects_implementing_an_inter # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ObjectsMustHaveFields: + def test_accepts_an_object_type_with_fields_object(self): assert schema_with_field_type( GraphQLObjectType( @@ -316,6 +319,7 @@ def test_rejects_an_object_type_with_a_field_function_with_an_invalid_value(self # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_FieldArgsMustBeProperlyNamed: + def test_accepts_field_args_with_valid_names(self): assert schema_with_field_type( GraphQLObjectType( @@ -352,6 +356,7 @@ def test_reject_field_args_with_invalid_names(self): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_FieldArgsMustBeObjects: + def test_accepts_an_object_with_field_args(self): assert schema_with_field_type( GraphQLObjectType( @@ -406,6 +411,7 @@ def test_rejects_an_object_with_incorrectly_typed_field_args_with_an_invalid_val # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ObjectInterfacesMustBeArray: + def test_accepts_an_object_type_with_array_interface(self): AnotherInterfaceType = GraphQLInterfaceType( name="AnotherInterface", @@ -475,6 +481,7 @@ def test_rejects_an_object_type_with_interfaces_as_a_function_returning_an_incor # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_UnionTypesMustBeArray: + def test_accepts_a_union_type_with_aray_types(self): assert schema_with_field_type( GraphQLUnionType( @@ -513,6 +520,7 @@ def test_rejects_a_union_type_with_incorrectly_typed_types(self): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_UnionTypesMustBeCallableThatReturnsArray: + def test_accepts_a_union_type_with_aray_types(self): assert schema_with_field_type( GraphQLUnionType( @@ -556,6 +564,7 @@ def schema_with_input_object(input_object_type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_InputObjectsMustHaveFields: + def test_accepts_an_input_object_type_with_fields(self): assert schema_with_input_object( GraphQLInputObjectType( @@ -671,6 +680,7 @@ def test_rejects_an_input_object_type_with_a_field_function_that_returns_empty( # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ObjectTypesMustBeAssertable: + def test_accepts_an_object_type_with_an_is_type_of_function(self): assert schema_with_field_type( GraphQLObjectType( @@ -698,6 +708,7 @@ def test_rejects_an_object_type_with_an_incorrect_type_for_is_type_of(self): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_InterfaceTypesMustBeResolvable: + def test_accepts_an_interface_type_defining_resolve_type(self): AnotherInterfaceType = GraphQLInterfaceType( name="AnotherInterface", @@ -783,6 +794,7 @@ def test_rejects_an_interface_type_not_defining_resolve_type_with_implementing_t # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_UnionTypesMustBeResolvable: + def test_accepts_a_union_type_defining_resolve_type(self): assert schema_with_field_type( GraphQLUnionType( @@ -834,6 +846,7 @@ def test_rejects_a_union_type_not_defining_resolve_type_of_object_types_not_defi # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ScalarTypesMustBeSerializable: + def test_accepts_a_scalar_type_defining_serialize(self): assert schema_with_field_type( GraphQLScalarType(name="SomeScalar", serialize=_none) @@ -913,6 +926,7 @@ def test_rejects_a_scalar_type_defining_parse_literal_and_parse_value_with_an_in # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_EnumTypesMustBeWellDefined: + def test_accepts_a_well_defined_enum_type_with_empty_value_definition(self): assert GraphQLEnumType( name="SomeEnum", @@ -988,6 +1002,7 @@ def repr_type_as_syntax_safe_fn(_type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ObjectFieldsMustHaveOutputTypes: + def accepts(self, type): assert schema_with_object_field_of_type(type) @@ -1042,6 +1057,7 @@ def schema_with_object_implementing_type(implemented_type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ObjectsCanOnlyImplementInterfaces: + def test_accepts_an_object_implementing_an_interface(self): AnotherInterfaceType = GraphQLInterfaceType( name="AnotherInterface", @@ -1089,6 +1105,7 @@ def schema_with_union_of_type(type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_UnionMustRepresentObjectTypes: + def test_accepts_a_union_of_an_object_type(self): assert schema_with_union_of_type(SomeObjectType) @@ -1121,6 +1138,7 @@ def schema_with_interface_field_of_type(field_type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_InterfaceFieldsMustHaveOutputTypes: + def accepts(self, type): assert schema_with_interface_field_of_type(type) @@ -1170,6 +1188,7 @@ def schema_with_arg_of_type(arg_type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_FieldArgumentsMustHaveInputTypes: + def accepts(self, type): assert schema_with_arg_of_type(type) @@ -1224,6 +1243,7 @@ def schema_with_input_field_of_type(input_field_type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_InputObjectFieldsMustHaveInputTypes: + def accepts(self, type): assert schema_with_input_field_of_type(type) @@ -1273,6 +1293,7 @@ def test_rejects_an_empty_input_field_type(self): class TestTypeSystem_ListMustAcceptGraphQLTypes: + def accepts(self, type): assert GraphQLList(type) @@ -1314,6 +1335,7 @@ def rejects(self, type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_NonNullMustAcceptGraphQLTypes: + def accepts(self, type): assert GraphQLNonNull(type) @@ -1346,6 +1368,7 @@ def rejects(self, type): # noinspection PyMethodMayBeStatic,PyPep8Naming class TestTypeSystem_ObjectsMustAdhereToInterfacesTheyImplement: + def test_accepts_an_object_which_implements_an_interface(self): AnotherInterface = GraphQLInterfaceType( name="AnotherInterface", diff --git a/graphql/type/typemap.py b/graphql/type/typemap.py index f492b7de..736200fa 100644 --- a/graphql/type/typemap.py +++ b/graphql/type/typemap.py @@ -22,6 +22,7 @@ class GraphQLTypeMap(OrderedDict): + def __init__(self, types): # type: (List[GraphQLNamedType]) -> None super(GraphQLTypeMap, self).__init__() diff --git a/graphql/validation/rules/arguments_of_correct_type.py b/graphql/validation/rules/arguments_of_correct_type.py index 7b9f87d3..d8ca36ae 100644 --- a/graphql/validation/rules/arguments_of_correct_type.py +++ b/graphql/validation/rules/arguments_of_correct_type.py @@ -10,6 +10,7 @@ class ArgumentsOfCorrectType(ValidationRule): + def enter_Argument( self, node, # type: Argument diff --git a/graphql/validation/rules/default_values_of_correct_type.py b/graphql/validation/rules/default_values_of_correct_type.py index d35c0872..dfd36e97 100644 --- a/graphql/validation/rules/default_values_of_correct_type.py +++ b/graphql/validation/rules/default_values_of_correct_type.py @@ -11,6 +11,7 @@ class DefaultValuesOfCorrectType(ValidationRule): + def enter_VariableDefinition(self, node, key, parent, path, ancestors): name = node.variable.name.value default_value = node.default_value diff --git a/graphql/validation/rules/fragments_on_composite_types.py b/graphql/validation/rules/fragments_on_composite_types.py index 33324b40..db3f1eaf 100644 --- a/graphql/validation/rules/fragments_on_composite_types.py +++ b/graphql/validation/rules/fragments_on_composite_types.py @@ -10,6 +10,7 @@ class FragmentsOnCompositeTypes(ValidationRule): + def enter_InlineFragment( self, node, # type: InlineFragment diff --git a/graphql/validation/rules/known_argument_names.py b/graphql/validation/rules/known_argument_names.py index 96966a8c..41d2b622 100644 --- a/graphql/validation/rules/known_argument_names.py +++ b/graphql/validation/rules/known_argument_names.py @@ -31,6 +31,7 @@ def _unknown_directive_arg_message(arg_name, directive_name, suggested_args): class KnownArgumentNames(ValidationRule): + def enter_Argument( self, node, # type: Argument diff --git a/graphql/validation/rules/known_directives.py b/graphql/validation/rules/known_directives.py index 86728355..66b6464f 100644 --- a/graphql/validation/rules/known_directives.py +++ b/graphql/validation/rules/known_directives.py @@ -5,6 +5,7 @@ class KnownDirectives(ValidationRule): + def enter_Directive(self, node, key, parent, path, ancestors): directive_def = next( ( diff --git a/graphql/validation/rules/known_fragment_names.py b/graphql/validation/rules/known_fragment_names.py index e572ce8e..418b0b0f 100644 --- a/graphql/validation/rules/known_fragment_names.py +++ b/graphql/validation/rules/known_fragment_names.py @@ -3,6 +3,7 @@ class KnownFragmentNames(ValidationRule): + def enter_FragmentSpread(self, node, key, parent, path, ancestors): fragment_name = node.name.value fragment = self.context.get_fragment(fragment_name) diff --git a/graphql/validation/rules/known_type_names.py b/graphql/validation/rules/known_type_names.py index 4c68c27b..e82a8a15 100644 --- a/graphql/validation/rules/known_type_names.py +++ b/graphql/validation/rules/known_type_names.py @@ -18,6 +18,7 @@ def _unknown_type_message(type, suggested_types): class KnownTypeNames(ValidationRule): + def enter_ObjectTypeDefinition(self, node, *args): return False diff --git a/graphql/validation/rules/overlapping_fields_can_be_merged.py b/graphql/validation/rules/overlapping_fields_can_be_merged.py index 4cba7ca2..8506e2cd 100644 --- a/graphql/validation/rules/overlapping_fields_can_be_merged.py +++ b/graphql/validation/rules/overlapping_fields_can_be_merged.py @@ -207,7 +207,7 @@ def _find_conflicts_within_selection_set( # selection set to collect conflicts within fragments spread together. # This compares each item in the list of fragment names to every other item # in that same list (except for itself). - for other_fragment_name in fragment_names[i + 1:]: + for other_fragment_name in fragment_names[i + 1 :]: _collect_conflicts_between_fragments( context, conflicts, @@ -444,7 +444,7 @@ def _collect_conflicts_within( # (except to itself). If the list only has one item, nothing needs to # be compared. for i, field in enumerate(fields): - for other_field in fields[i + 1:]: + for other_field in fields[i + 1 :]: # within one collection is never mutually exclusive conflict = _find_conflict( context, diff --git a/graphql/validation/rules/possible_fragment_spreads.py b/graphql/validation/rules/possible_fragment_spreads.py index 460d9191..c606d7a0 100644 --- a/graphql/validation/rules/possible_fragment_spreads.py +++ b/graphql/validation/rules/possible_fragment_spreads.py @@ -10,6 +10,7 @@ class PossibleFragmentSpreads(ValidationRule): + def enter_InlineFragment( self, node, # type: InlineFragment diff --git a/graphql/validation/rules/provided_non_null_arguments.py b/graphql/validation/rules/provided_non_null_arguments.py index bfdbabe8..55cde9af 100644 --- a/graphql/validation/rules/provided_non_null_arguments.py +++ b/graphql/validation/rules/provided_non_null_arguments.py @@ -9,6 +9,7 @@ class ProvidedNonNullArguments(ValidationRule): + def leave_Field( self, node, # type: Field diff --git a/graphql/validation/rules/scalar_leafs.py b/graphql/validation/rules/scalar_leafs.py index a36c4e8d..5bb75014 100644 --- a/graphql/validation/rules/scalar_leafs.py +++ b/graphql/validation/rules/scalar_leafs.py @@ -9,6 +9,7 @@ class ScalarLeafs(ValidationRule): + def enter_Field( self, node, # type: Field diff --git a/graphql/validation/rules/variables_are_input_types.py b/graphql/validation/rules/variables_are_input_types.py index 49397ad9..590e249a 100644 --- a/graphql/validation/rules/variables_are_input_types.py +++ b/graphql/validation/rules/variables_are_input_types.py @@ -6,6 +6,7 @@ class VariablesAreInputTypes(ValidationRule): + def enter_VariableDefinition(self, node, key, parent, path, ancestors): type = type_from_ast(self.context.get_schema(), node.type) diff --git a/graphql/validation/tests/test_arguments_of_correct_type.py b/graphql/validation/tests/test_arguments_of_correct_type.py index db165669..13c5a643 100644 --- a/graphql/validation/tests/test_arguments_of_correct_type.py +++ b/graphql/validation/tests/test_arguments_of_correct_type.py @@ -18,6 +18,7 @@ def bad_value(arg_name, type_name, value, line, column, errors=None): # noinspection PyMethodMayBeStatic class TestValidValues(object): + def test_good_int_value(self): expect_passes_rule( ArgumentsOfCorrectType, @@ -117,6 +118,7 @@ def test_good_enum_value(self): # noinspection PyMethodMayBeStatic class TestInvalidStringValues(object): + def test_int_into_string(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -172,6 +174,7 @@ def test_unquoted_string_into_string(self): # noinspection PyMethodMayBeStatic class TestInvalidIntValues(object): + def test_string_into_int(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -240,6 +243,7 @@ def test_float_into_int(self): # noinspection PyMethodMayBeStatic class TestInvalidFloatValues(object): + def test_string_into_float(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -282,6 +286,7 @@ def test_unquoted_into_float(self): # noinspection PyMethodMayBeStatic class TestInvalidBooleanValues(object): + def test_int_into_boolean(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -337,6 +342,7 @@ def test_unquoted_into_boolean(self): # noinspection PyMethodMayBeStatic class TestInvalidIDValues(object): + def test_float_into_id(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -379,6 +385,7 @@ def test_unquoted_into_id(self): # noinspection PyMethodMayBeStatic class TestInvalidEnumValues(object): + def test_int_into_enum(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -460,6 +467,7 @@ def test_different_case_enum_value_into_enum(self): # noinspection PyMethodMayBeStatic class TestValidListValues(object): + def test_good_list_value(self): expect_passes_rule( ArgumentsOfCorrectType, @@ -499,6 +507,7 @@ def test_single_value_into_list(self): # noinspection PyMethodMayBeStatic class TestInvalidListValues(object): + def test_incorrect_item_type(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -537,6 +546,7 @@ def test_single_value_of_incorrect_type(self): # noinspection PyMethodMayBeStatic class TestValidNonNullableValues(object): + def test_arg_on_optional_arg(self): expect_passes_rule( ArgumentsOfCorrectType, @@ -648,6 +658,7 @@ def test_all_reqs_and_opts_on_mixed_list(self): # noinspection PyMethodMayBeStatic class TestInvalidNonNullableValues(object): + def test_incorrect_value_type(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -680,6 +691,7 @@ def test_incorrect_value_and_missing_argument(self): # noinspection PyMethodMayBeStatic class TestValidInputObjectValue(object): + def test_optional_arg_despite_required_field_in_type(self): expect_passes_rule( ArgumentsOfCorrectType, @@ -767,6 +779,7 @@ def test_full_object_with_fields_in_different_order(self): # noinspection PyMethodMayBeStatic class TestInvalidInputObjectValue(object): + def test_partial_object_missing_required(self): expect_fails_rule( ArgumentsOfCorrectType, @@ -844,6 +857,7 @@ def test_partial_object_unknown_field_arg(self): # noinspection PyMethodMayBeStatic class TestDirectiveArguments(object): + def test_with_directives_of_valid_types(self): expect_passes_rule( ArgumentsOfCorrectType, diff --git a/scripts/ast.ast b/scripts/ast.ast index e4ff87ee..7b9aa677 100644 --- a/scripts/ast.ast +++ b/scripts/ast.ast @@ -117,7 +117,7 @@ S Type type T NonNullType # JS version prohibits nesting nonnull in nonnull, we can't because we # can't support multiple unions. Fix? -S Type type +S Type type T Name S string value diff --git a/scripts/casing.py b/scripts/casing.py index ff74030b..53c6040f 100644 --- a/scripts/casing.py +++ b/scripts/casing.py @@ -7,23 +7,23 @@ def title(s): - '''Capitalize the first character of s.''' + """Capitalize the first character of s.""" return s[0].capitalize() + s[1:] def camel(s): - '''Lowercase the first character of s.''' + """Lowercase the first character of s.""" return s[0].lower() + s[1:] def snake(s): - '''Convert from title or camelCase to snake_case.''' + """Convert from title or camelCase to snake_case.""" if len(s) < 2: return s.lower() out = s[0].lower() for c in s[1:]: if c.isupper(): - out += '_' + out += "_" c = c.lower() out += c return out diff --git a/scripts/fb_ast.py b/scripts/fb_ast.py index 4093f1eb..f91f2aed 100644 --- a/scripts/fb_ast.py +++ b/scripts/fb_ast.py @@ -19,44 +19,44 @@ def print_ast(lang_module, input_file): while line: line = line.strip() - if line.startswith('#') or not line: + if line.startswith("#") or not line: line = input_file.readline() continue code, rest = line.split(None, 1) - if code[0] == 'T': + if code[0] == "T": lang_module.start_type(rest) field_line = input_file.readline().strip() while field_line: - if field_line.startswith('#'): + if field_line.startswith("#"): field_line = input_file.readline().strip() continue field_kind, field_type, field_name = field_line.split() - nullable = len(field_kind) > 1 and field_kind[1] == '?' + nullable = len(field_kind) > 1 and field_kind[1] == "?" - if field_kind[0] == 'S': + if field_kind[0] == "S": plural = False - elif field_kind[0] == 'P': + elif field_kind[0] == "P": plural = True else: - raise Exception('Unknown field kind: ' + field_kind) + raise Exception("Unknown field kind: " + field_kind) lang_module.field(field_type, field_name, nullable, plural) field_line = input_file.readline().strip() lang_module.end_type(rest) - elif code[0] == 'U': + elif code[0] == "U": lang_module.start_union(rest) field_line = input_file.readline().strip() while field_line: option_code, option_type = field_line.split() - if option_code != 'O': - raise Exception('Unknown code in union: ' + option_code) + if option_code != "O": + raise Exception("Unknown code in union: " + option_code) lang_module.union_option(option_type) field_line = input_file.readline().strip() @@ -68,7 +68,7 @@ def print_ast(lang_module, input_file): lang_module.end_file() -if __name__ == '__main__': +if __name__ == "__main__": import sys lang = sys.argv[1] @@ -76,4 +76,4 @@ def print_ast(lang_module, input_file): lang_module = load_lang(lang) - print_ast(lang_module, open(filename, 'r')) + print_ast(lang_module, open(filename, "r")) diff --git a/scripts/generate_ast.py b/scripts/generate_ast.py index 9a23a15c..1546c07c 100644 --- a/scripts/generate_ast.py +++ b/scripts/generate_ast.py @@ -1,14 +1,15 @@ -if __name__ == '__main__': +if __name__ == "__main__": import os.path import sys import subprocess - project_root = os.path.join(os.path.dirname(__file__), '..') - with open(os.path.join(project_root, 'graphql/core/language/ast.py'), 'w') as fp: + + project_root = os.path.join(os.path.dirname(__file__), "..") + with open(os.path.join(project_root, "graphql/core/language/ast.py"), "w") as fp: process = subprocess.Popen( - ['python', './fb_ast.py', 'generate_ast', './ast.ast'], + ["python", "./fb_ast.py", "generate_ast", "./ast.ast"], stdout=fp, - cwd=os.path.join(project_root, 'scripts'), - env={'PYTHONPATH': '.'} + cwd=os.path.join(project_root, "scripts"), + env={"PYTHONPATH": "."}, ) sys.exit(process.wait()) @@ -16,9 +17,7 @@ from casing import snake # Fix inconsistencies between libgraphqlparser and graphql-js -REMAP_TYPES = { - 'ArrayValue': 'ListValue', -} +REMAP_TYPES = {"ArrayValue": "ListValue"} def remap_type(typename): @@ -26,28 +25,35 @@ def remap_type(typename): class Printer(object): + def __init__(self): self._current_union = None self._parent_types = {} self._fields = [] def start_file(self): - print('''# This is autogenerated code. DO NOT change this manually. + print( + """# This is autogenerated code. DO NOT change this manually. # Run scripts/generate_ast.py to generate this file. class Node(object): - __slots__ = ()''') + __slots__ = ()""" + ) def end_file(self): pass def start_type(self, name): name = remap_type(name) - parent_type = self._parent_types.get(name, 'Node') - print(''' + parent_type = self._parent_types.get(name, "Node") + print( + """ -class {name}({parent_type}):'''.format(name=name, parent_type=parent_type)) +class {name}({parent_type}):""".format( + name=name, parent_type=parent_type + ) + ) def field(self, type, name, nullable, plural): type = remap_type(type) @@ -65,74 +71,111 @@ def end_type(self, typename): self._fields = [] def _print_fields(self): - fields = ', '.join("'" + snake(name) + "'" for (type, name, nullable, plural) in self._fields) - print(''' _fields = ({},)'''.format(fields)) + fields = ", ".join( + "'" + snake(name) + "'" for (type, name, nullable, plural) in self._fields + ) + print(""" _fields = ({},)""".format(fields)) def _print_slots(self): - slots = ', '.join("'" + snake(name) + "'" for (type, name, nullable, plural) in self._fields) - print(''' __slots__ = ('loc', {slots},)'''.format(slots=slots)) + slots = ", ".join( + "'" + snake(name) + "'" for (type, name, nullable, plural) in self._fields + ) + print(""" __slots__ = ('loc', {slots},)""".format(slots=slots)) def _print_ctor(self): - fields = ( - [field for field in self._fields if not field[2]] + - [field for field in self._fields if field[2]]) - ctor_args = ', '.join(snake(name) + ('=None' if nullable else '') for (type, name, nullable, plural) in fields) - print(''' + fields = [field for field in self._fields if not field[2]] + [ + field for field in self._fields if field[2] + ] + ctor_args = ", ".join( + snake(name) + ("=None" if nullable else "") + for (type, name, nullable, plural) in fields + ) + print( + """ def __init__(self, {ctor_args}, loc=None): - self.loc = loc'''.format(ctor_args=ctor_args)) + self.loc = loc""".format( + ctor_args=ctor_args + ) + ) for type, name, nullable, plural in self._fields: - print(''' self.{name} = {name}'''.format(name=snake(name))) + print(""" self.{name} = {name}""".format(name=snake(name))) def _print_comparator(self, typename): - print(''' + print( + """ def __eq__(self, other): return ( self is other or ( isinstance(other, {typename}) and - self.loc == other.loc and'''.format(typename=typename)) - print(' and\n'.join( - ''' self.{name} == other.{name}'''.format(name=snake(name)) - for type, name, nullable, plural in self._fields - )) - print(' )') - print(' )') + self.loc == other.loc and""".format( + typename=typename + ) + ) + print( + " and\n".join( + """ self.{name} == other.{name}""".format( + name=snake(name) + ) + for type, name, nullable, plural in self._fields + ) + ) + print(" )") + print(" )") def _print_copy(self, typename): - fields = ( - [field for field in self._fields if not field[2]] + - [field for field in self._fields if field[2]]) - args = '\n'.join(''' self.{},'''.format(snake(name)) for (type, name, nullable, plural) in fields) - print(''' + fields = [field for field in self._fields if not field[2]] + [ + field for field in self._fields if field[2] + ] + args = "\n".join( + """ self.{},""".format(snake(name)) + for (type, name, nullable, plural) in fields + ) + print( + """ def __copy__(self): return type(self)( {} self.loc - )'''.format(args)) + )""".format( + args + ) + ) def _print_repr(self, typename): - print(''' + print( + """ def __repr__(self): - return ('{typename}(' '''.rstrip().format(typename=typename)) + return ('{typename}(' """.rstrip().format( + typename=typename + ) + ) first = True for type, name, nullable, plural in self._fields: - print(" '{comma}{name}={{self.{name}!r}}'".format( - comma=', ' if not first else '', - name=snake(name) - )) + print( + " '{comma}{name}={{self.{name}!r}}'".format( + comma=", " if not first else "", name=snake(name) + ) + ) first = False - print(''' ')').format(self=self)''') + print(""" ')').format(self=self)""") def _print_hash(self): - print(''' + print( + """ def __hash__(self): - return id(self)''') + return id(self)""" + ) def start_union(self, name): self._current_union = name - print(''' + print( + """ class {name}(Node): - __slots__ = ()'''.format(name=name)) + __slots__ = ()""".format( + name=name + ) + ) def union_option(self, option): option = remap_type(option) diff --git a/setup.py b/setup.py index 5edde148..a2b26b0a 100644 --- a/setup.py +++ b/setup.py @@ -4,89 +4,81 @@ import ast import re -_version_re = re.compile(r'VERSION\s+=\s+(.*)') +_version_re = re.compile(r"VERSION\s+=\s+(.*)") -with open('graphql/__init__.py', 'rb') as f: - version = ast.literal_eval(_version_re.search( - f.read().decode('utf-8')).group(1)) +with open("graphql/__init__.py", "rb") as f: + version = ast.literal_eval(_version_re.search(f.read().decode("utf-8")).group(1)) path_copy = sys.path[:] -sys.path.append('graphql') +sys.path.append("graphql") try: from pyutils.version import get_version + version = get_version(version) except Exception: version = ".".join([str(v) for v in version]) sys.path[:] = path_copy -install_requires = [ - 'six>=1.10.0', - 'promise>=2.1', - 'rx>=1.6.0', -] +install_requires = ["six>=1.10.0", "promise>=2.1", "rx>=1.6.0"] tests_requires = [ - 'pytest==3.0.2', - 'pytest-django==2.9.1', - 'pytest-cov==2.3.1', - 'coveralls', - 'gevent==1.1rc1', - 'six>=1.10.0', - 'pytest-benchmark==3.0.0', - 'pytest-mock==1.2', + "pytest==3.0.2", + "pytest-django==2.9.1", + "pytest-cov==2.3.1", + "coveralls", + "gevent==1.1rc1", + "six>=1.10.0", + "pytest-benchmark==3.0.0", + "pytest-mock==1.2", ] class PyTest(TestCommand): + def finalize_options(self): TestCommand.finalize_options(self) - self.test_args = ['graphql', '-vrsx'] + self.test_args = ["graphql", "-vrsx"] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest + errno = pytest.main(self.test_args) sys.exit(errno) setup( - name='graphql-core', + name="graphql-core", version=version, - description='GraphQL implementation for Python', - url='https://github.com/graphql-python/graphql-core', - download_url='https://github.com/graphql-python/graphql-core/releases', - author='Syrus Akbary, Jake Heinz, Taeho Kim', - author_email='me@syrusakbary.com', - license='MIT', + description="GraphQL implementation for Python", + url="https://github.com/graphql-python/graphql-core", + download_url="https://github.com/graphql-python/graphql-core/releases", + author="Syrus Akbary, Jake Heinz, Taeho Kim", + author_email="me@syrusakbary.com", + license="MIT", classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Libraries', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: Implementation :: PyPy', - 'License :: OSI Approved :: MIT License', - 'Topic :: Database :: Front-Ends', - 'Topic :: Internet :: WWW/HTTP', + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: Implementation :: PyPy", + "License :: OSI Approved :: MIT License", + "Topic :: Database :: Front-Ends", + "Topic :: Internet :: WWW/HTTP", ], - keywords='api graphql protocol rest', - packages=find_packages( - exclude=['tests', 'tests_py35', 'tests.*', 'tests_py35.*']), + keywords="api graphql protocol rest", + packages=find_packages(exclude=["tests", "tests_py35", "tests.*", "tests_py35.*"]), install_requires=install_requires, tests_require=tests_requires, - cmdclass={'test': PyTest}, - extras_require={ - 'gevent': [ - 'gevent==1.1rc1' - ], - 'test': tests_requires - } + cmdclass={"test": PyTest}, + extras_require={"gevent": ["gevent==1.1rc1"], "test": tests_requires}, ) diff --git a/tests/starwars/starwars_fixtures.py b/tests/starwars/starwars_fixtures.py index 51f29a59..9007b1a5 100644 --- a/tests/starwars/starwars_fixtures.py +++ b/tests/starwars/starwars_fixtures.py @@ -1,77 +1,64 @@ from collections import namedtuple -Human = namedtuple('Human', 'id name friends appearsIn homePlanet') +Human = namedtuple("Human", "id name friends appearsIn homePlanet") luke = Human( - id='1000', - name='Luke Skywalker', - friends=['1002', '1003', '2000', '2001'], + id="1000", + name="Luke Skywalker", + friends=["1002", "1003", "2000", "2001"], appearsIn=[4, 5, 6], - homePlanet='Tatooine', + homePlanet="Tatooine", ) vader = Human( - id='1001', - name='Darth Vader', - friends=['1004'], + id="1001", + name="Darth Vader", + friends=["1004"], appearsIn=[4, 5, 6], - homePlanet='Tatooine', + homePlanet="Tatooine", ) han = Human( - id='1002', - name='Han Solo', - friends=['1000', '1003', '2001'], + id="1002", + name="Han Solo", + friends=["1000", "1003", "2001"], appearsIn=[4, 5, 6], homePlanet=None, ) leia = Human( - id='1003', - name='Leia Organa', - friends=['1000', '1002', '2000', '2001'], + id="1003", + name="Leia Organa", + friends=["1000", "1002", "2000", "2001"], appearsIn=[4, 5, 6], - homePlanet='Alderaan', + homePlanet="Alderaan", ) tarkin = Human( - id='1004', - name='Wilhuff Tarkin', - friends=['1001'], - appearsIn=[4], - homePlanet=None, + id="1004", name="Wilhuff Tarkin", friends=["1001"], appearsIn=[4], homePlanet=None ) -humanData = { - '1000': luke, - '1001': vader, - '1002': han, - '1003': leia, - '1004': tarkin, -} +humanData = {"1000": luke, "1001": vader, "1002": han, "1003": leia, "1004": tarkin} -Droid = namedtuple('Droid', 'id name friends appearsIn primaryFunction') +Droid = namedtuple("Droid", "id name friends appearsIn primaryFunction") threepio = Droid( - id='2000', - name='C-3PO', - friends=['1000', '1002', '1003', '2001'], + id="2000", + name="C-3PO", + friends=["1000", "1002", "1003", "2001"], appearsIn=[4, 5, 6], - primaryFunction='Protocol', + primaryFunction="Protocol", ) artoo = Droid( - id='2001', - name='R2-D2', - friends=['1000', '1002', '1003'], + id="2001", + name="R2-D2", + friends=["1000", "1002", "1003"], appearsIn=[4, 5, 6], - primaryFunction='Astromech', + primaryFunction="Astromech", ) -droidData = { - '2000': threepio, - '2001': artoo, -} +droidData = {"2000": threepio, "2001": artoo} def getCharacter(id): diff --git a/tests/starwars/starwars_schema.py b/tests/starwars/starwars_schema.py index 74bf4364..a5c2a6f0 100644 --- a/tests/starwars/starwars_schema.py +++ b/tests/starwars/starwars_schema.py @@ -1,145 +1,128 @@ -from graphql.type import (GraphQLArgument, GraphQLEnumType, GraphQLEnumValue, - GraphQLField, GraphQLInterfaceType, GraphQLList, - GraphQLNonNull, GraphQLObjectType, GraphQLSchema, - GraphQLString) +from graphql.type import ( + GraphQLArgument, + GraphQLEnumType, + GraphQLEnumValue, + GraphQLField, + GraphQLInterfaceType, + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLSchema, + GraphQLString, +) from .starwars_fixtures import getDroid, getFriends, getHero, getHuman episodeEnum = GraphQLEnumType( - 'Episode', - description='One of the films in the Star Wars Trilogy', + "Episode", + description="One of the films in the Star Wars Trilogy", values={ - 'NEWHOPE': GraphQLEnumValue( - 4, - description='Released in 1977.', - ), - 'EMPIRE': GraphQLEnumValue( - 5, - description='Released in 1980.', - ), - 'JEDI': GraphQLEnumValue( - 6, - description='Released in 1983.', - ) - } + "NEWHOPE": GraphQLEnumValue(4, description="Released in 1977."), + "EMPIRE": GraphQLEnumValue(5, description="Released in 1980."), + "JEDI": GraphQLEnumValue(6, description="Released in 1983."), + }, ) characterInterface = GraphQLInterfaceType( - 'Character', - description='A character in the Star Wars Trilogy', + "Character", + description="A character in the Star Wars Trilogy", fields=lambda: { - 'id': GraphQLField( - GraphQLNonNull(GraphQLString), - description='The id of the character.' + "id": GraphQLField( + GraphQLNonNull(GraphQLString), description="The id of the character." ), - 'name': GraphQLField( - GraphQLString, - description='The name of the character.' - ), - 'friends': GraphQLField( + "name": GraphQLField(GraphQLString, description="The name of the character."), + "friends": GraphQLField( GraphQLList(characterInterface), - description='The friends of the character, or an empty list if they have none.' + description="The friends of the character, or an empty list if they have none.", ), - 'appearsIn': GraphQLField( - GraphQLList(episodeEnum), - description='Which movies they appear in.' + "appearsIn": GraphQLField( + GraphQLList(episodeEnum), description="Which movies they appear in." ), }, - resolve_type=lambda character, info: humanType if getHuman(character.id) else droidType, + resolve_type=lambda character, info: humanType + if getHuman(character.id) + else droidType, ) humanType = GraphQLObjectType( - 'Human', - description='A humanoid creature in the Star Wars universe.', + "Human", + description="A humanoid creature in the Star Wars universe.", fields=lambda: { - 'id': GraphQLField( - GraphQLNonNull(GraphQLString), - description='The id of the human.', - ), - 'name': GraphQLField( - GraphQLString, - description='The name of the human.', + "id": GraphQLField( + GraphQLNonNull(GraphQLString), description="The id of the human." ), - 'friends': GraphQLField( + "name": GraphQLField(GraphQLString, description="The name of the human."), + "friends": GraphQLField( GraphQLList(characterInterface), - description='The friends of the human, or an empty list if they have none.', + description="The friends of the human, or an empty list if they have none.", resolver=lambda human, *_: getFriends(human), ), - 'appearsIn': GraphQLField( - GraphQLList(episodeEnum), - description='Which movies they appear in.', + "appearsIn": GraphQLField( + GraphQLList(episodeEnum), description="Which movies they appear in." ), - 'homePlanet': GraphQLField( + "homePlanet": GraphQLField( GraphQLString, - description='The home planet of the human, or null if unknown.', - ) + description="The home planet of the human, or null if unknown.", + ), }, - interfaces=[characterInterface] + interfaces=[characterInterface], ) droidType = GraphQLObjectType( - 'Droid', - description='A mechanical creature in the Star Wars universe.', + "Droid", + description="A mechanical creature in the Star Wars universe.", fields=lambda: { - 'id': GraphQLField( - GraphQLNonNull(GraphQLString), - description='The id of the droid.', - ), - 'name': GraphQLField( - GraphQLString, - description='The name of the droid.', + "id": GraphQLField( + GraphQLNonNull(GraphQLString), description="The id of the droid." ), - 'friends': GraphQLField( + "name": GraphQLField(GraphQLString, description="The name of the droid."), + "friends": GraphQLField( GraphQLList(characterInterface), - description='The friends of the droid, or an empty list if they have none.', + description="The friends of the droid, or an empty list if they have none.", resolver=lambda droid, info, **args: getFriends(droid), ), - 'appearsIn': GraphQLField( - GraphQLList(episodeEnum), - description='Which movies they appear in.', + "appearsIn": GraphQLField( + GraphQLList(episodeEnum), description="Which movies they appear in." + ), + "primaryFunction": GraphQLField( + GraphQLString, description="The primary function of the droid." ), - 'primaryFunction': GraphQLField( - GraphQLString, - description='The primary function of the droid.', - ) }, - interfaces=[characterInterface] + interfaces=[characterInterface], ) queryType = GraphQLObjectType( - 'Query', + "Query", fields=lambda: { - 'hero': GraphQLField( + "hero": GraphQLField( characterInterface, args={ - 'episode': GraphQLArgument( - description='If omitted, returns the hero of the whole saga. If ' - 'provided, returns the hero of that particular episode.', + "episode": GraphQLArgument( + description="If omitted, returns the hero of the whole saga. If " + "provided, returns the hero of that particular episode.", type=episodeEnum, ) }, - resolver=lambda root, info, **args: getHero(args.get('episode')), + resolver=lambda root, info, **args: getHero(args.get("episode")), ), - 'human': GraphQLField( + "human": GraphQLField( humanType, args={ - 'id': GraphQLArgument( - description='id of the human', - type=GraphQLNonNull(GraphQLString), + "id": GraphQLArgument( + description="id of the human", type=GraphQLNonNull(GraphQLString) ) }, - resolver=lambda root, info, **args: getHuman(args['id']), + resolver=lambda root, info, **args: getHuman(args["id"]), ), - 'droid': GraphQLField( + "droid": GraphQLField( droidType, args={ - 'id': GraphQLArgument( - description='id of the droid', - type=GraphQLNonNull(GraphQLString), + "id": GraphQLArgument( + description="id of the droid", type=GraphQLNonNull(GraphQLString) ) }, - resolver=lambda root, info, **args: getDroid(args['id']), + resolver=lambda root, info, **args: getDroid(args["id"]), ), - } + }, ) StarWarsSchema = GraphQLSchema(query=queryType, types=[humanType, droidType]) diff --git a/tests/starwars/test_introspection.py b/tests/starwars/test_introspection.py index 7cac8a20..f3e07298 100644 --- a/tests/starwars/test_introspection.py +++ b/tests/starwars/test_introspection.py @@ -6,7 +6,7 @@ def test_allows_querying_the_schema_for_types(): - query = ''' + query = """ query IntrospectionTypeQuery { __schema { types { @@ -14,55 +14,25 @@ def test_allows_querying_the_schema_for_types(): } } } - ''' + """ expected = { "__schema": { "types": [ - { - "name": 'Query' - }, - { - "name": 'Episode' - }, - { - "name": 'Character' - }, - { - "name": 'String' - }, - { - "name": 'Human' - }, - { - "name": 'Droid' - }, - { - "name": '__Schema' - }, - { - "name": '__Type' - }, - { - "name": '__TypeKind' - }, - { - "name": 'Boolean' - }, - { - "name": '__Field' - }, - { - "name": '__InputValue' - }, - { - "name": '__EnumValue' - }, - { - "name": '__Directive' - }, - { - "name": '__DirectiveLocation' - } + {"name": "Query"}, + {"name": "Episode"}, + {"name": "Character"}, + {"name": "String"}, + {"name": "Human"}, + {"name": "Droid"}, + {"name": "__Schema"}, + {"name": "__Type"}, + {"name": "__TypeKind"}, + {"name": "Boolean"}, + {"name": "__Field"}, + {"name": "__InputValue"}, + {"name": "__EnumValue"}, + {"name": "__Directive"}, + {"name": "__DirectiveLocation"}, ] } } @@ -73,7 +43,7 @@ def test_allows_querying_the_schema_for_types(): def test_allows_querying_the_schema_for_query_type(): - query = ''' + query = """ query IntrospectionQueryTypeQuery { __schema { queryType { @@ -81,82 +51,62 @@ def test_allows_querying_the_schema_for_query_type(): } } } - ''' + """ - expected = { - '__schema': { - 'queryType': { - 'name': 'Query' - }, - } - } + expected = {"__schema": {"queryType": {"name": "Query"}}} result = graphql(StarWarsSchema, query) assert not result.errors assert contain_subset(result.data, expected) def test_allows_querying_the_schema_for_a_specific_type(): - query = ''' + query = """ query IntrospectionDroidTypeQuery { __type(name: "Droid") { name } } - ''' + """ - expected = { - '__type': { - 'name': 'Droid' - } - } + expected = {"__type": {"name": "Droid"}} result = graphql(StarWarsSchema, query) assert not result.errors assert contain_subset(result.data, expected) def test_allows_querying_the_schema_for_an_object_kind(): - query = ''' + query = """ query IntrospectionDroidKindQuery { __type(name: "Droid") { name kind } } - ''' + """ - expected = { - '__type': { - 'name': 'Droid', - 'kind': 'OBJECT' - } - } + expected = {"__type": {"name": "Droid", "kind": "OBJECT"}} result = graphql(StarWarsSchema, query) assert not result.errors assert contain_subset(result.data, expected) def test_allows_querying_the_schema_for_an_interface_kind(): - query = ''' + query = """ query IntrospectionCharacterKindQuery { __type(name: "Character") { name kind } } - ''' - expected = { - '__type': { - 'name': 'Character', - 'kind': 'INTERFACE' - } - } + """ + expected = {"__type": {"name": "Character", "kind": "INTERFACE"}} result = graphql(StarWarsSchema, query) assert not result.errors assert contain_subset(result.data, expected) def test_allows_querying_the_schema_for_object_fields(): - query = ''' + query = """ query IntrospectionDroidFieldsQuery { __type(name: "Droid") { name @@ -169,48 +119,21 @@ def test_allows_querying_the_schema_for_object_fields(): } } } - ''' + """ expected = { - '__type': { - 'name': 'Droid', - 'fields': [ - { - 'name': 'id', - 'type': { - 'name': None, - 'kind': 'NON_NULL' - } - }, - { - 'name': 'name', - 'type': { - 'name': 'String', - 'kind': 'SCALAR' - } - }, - { - 'name': 'friends', - 'type': { - 'name': None, - 'kind': 'LIST' - } - }, + "__type": { + "name": "Droid", + "fields": [ + {"name": "id", "type": {"name": None, "kind": "NON_NULL"}}, + {"name": "name", "type": {"name": "String", "kind": "SCALAR"}}, + {"name": "friends", "type": {"name": None, "kind": "LIST"}}, + {"name": "appearsIn", "type": {"name": None, "kind": "LIST"}}, { - 'name': 'appearsIn', - 'type': { - 'name': None, - 'kind': 'LIST' - } + "name": "primaryFunction", + "type": {"name": "String", "kind": "SCALAR"}, }, - { - 'name': 'primaryFunction', - 'type': { - 'name': 'String', - 'kind': 'SCALAR' - } - } - ] + ], } } @@ -220,7 +143,7 @@ def test_allows_querying_the_schema_for_object_fields(): def test_allows_querying_the_schema_for_nested_object_fields(): - query = ''' + query = """ query IntrospectionDroidNestedFieldsQuery { __type(name: "Droid") { name @@ -237,62 +160,45 @@ def test_allows_querying_the_schema_for_nested_object_fields(): } } } - ''' + """ expected = { - '__type': { - 'name': 'Droid', - 'fields': [ + "__type": { + "name": "Droid", + "fields": [ { - 'name': 'id', - 'type': { - 'name': None, - 'kind': 'NON_NULL', - 'ofType': { - 'name': 'String', - 'kind': 'SCALAR' - } - } + "name": "id", + "type": { + "name": None, + "kind": "NON_NULL", + "ofType": {"name": "String", "kind": "SCALAR"}, + }, }, { - 'name': 'name', - 'type': { - 'name': 'String', - 'kind': 'SCALAR', - 'ofType': None - } + "name": "name", + "type": {"name": "String", "kind": "SCALAR", "ofType": None}, }, { - 'name': 'friends', - 'type': { - 'name': None, - 'kind': 'LIST', - 'ofType': { - 'name': 'Character', - 'kind': 'INTERFACE' - } - } + "name": "friends", + "type": { + "name": None, + "kind": "LIST", + "ofType": {"name": "Character", "kind": "INTERFACE"}, + }, }, { - 'name': 'appearsIn', - 'type': { - 'name': None, - 'kind': 'LIST', - 'ofType': { - 'name': 'Episode', - 'kind': 'ENUM' - } - } + "name": "appearsIn", + "type": { + "name": None, + "kind": "LIST", + "ofType": {"name": "Episode", "kind": "ENUM"}, + }, }, { - 'name': 'primaryFunction', - 'type': { - 'name': 'String', - 'kind': 'SCALAR', - 'ofType': None - } - } - ] + "name": "primaryFunction", + "type": {"name": "String", "kind": "SCALAR", "ofType": None}, + }, + ], } } result = graphql(StarWarsSchema, query) @@ -301,7 +207,7 @@ def test_allows_querying_the_schema_for_nested_object_fields(): def test_allows_querying_the_schema_for_field_args(): - query = ''' + query = """ query IntrospectionQueryTypeQuery { __schema { queryType { @@ -324,65 +230,59 @@ def test_allows_querying_the_schema_for_field_args(): } } } - ''' + """ expected = { - '__schema': { - 'queryType': { - 'fields': [ + "__schema": { + "queryType": { + "fields": [ { - 'name': 'hero', - 'args': [ + "name": "hero", + "args": [ { - 'defaultValue': None, - 'description': 'If omitted, returns the hero of the whole ' + - 'saga. If provided, returns the hero of ' + - 'that particular episode.', - 'name': 'episode', - 'type': { - 'kind': 'ENUM', - 'name': 'Episode', - 'ofType': None - } + "defaultValue": None, + "description": "If omitted, returns the hero of the whole " + + "saga. If provided, returns the hero of " + + "that particular episode.", + "name": "episode", + "type": { + "kind": "ENUM", + "name": "Episode", + "ofType": None, + }, } - ] + ], }, { - 'name': 'human', - 'args': [ + "name": "human", + "args": [ { - 'name': 'id', - 'description': 'id of the human', - 'type': { - 'kind': 'NON_NULL', - 'name': None, - 'ofType': { - 'kind': 'SCALAR', - 'name': 'String' - } + "name": "id", + "description": "id of the human", + "type": { + "kind": "NON_NULL", + "name": None, + "ofType": {"kind": "SCALAR", "name": "String"}, }, - 'defaultValue': None + "defaultValue": None, } - ] + ], }, { - 'name': 'droid', - 'args': [ + "name": "droid", + "args": [ { - 'name': 'id', - 'description': 'id of the droid', - 'type': { - 'kind': 'NON_NULL', - 'name': None, - 'ofType': { - 'kind': 'SCALAR', - 'name': 'String' - } + "name": "id", + "description": "id of the droid", + "type": { + "kind": "NON_NULL", + "name": None, + "ofType": {"kind": "SCALAR", "name": "String"}, }, - 'defaultValue': None + "defaultValue": None, } - ] - } + ], + }, ] } } @@ -394,19 +294,19 @@ def test_allows_querying_the_schema_for_field_args(): def test_allows_querying_the_schema_for_documentation(): - query = ''' + query = """ query IntrospectionDroidDescriptionQuery { __type(name: "Droid") { name description } } - ''' + """ expected = { - '__type': { - 'name': 'Droid', - 'description': 'A mechanical creature in the Star Wars universe.' + "__type": { + "name": "Droid", + "description": "A mechanical creature in the Star Wars universe.", } } result = graphql(StarWarsSchema, query) diff --git a/tests/starwars/test_query.py b/tests/starwars/test_query.py index 81a20c99..5e3c2cd0 100644 --- a/tests/starwars/test_query.py +++ b/tests/starwars/test_query.py @@ -5,25 +5,21 @@ def test_hero_name_query(): - query = ''' + query = """ query HeroNameQuery { hero { name } } - ''' - expected = { - 'hero': { - 'name': 'R2-D2' - } - } + """ + expected = {"hero": {"name": "R2-D2"}} result = graphql(StarWarsSchema, query) assert not result.errors assert result.data == expected def test_hero_name_and_friends_query(): - query = ''' + query = """ query HeroNameAndFriendsQuery { hero { id @@ -33,16 +29,16 @@ def test_hero_name_and_friends_query(): } } } - ''' + """ expected = { - 'hero': { - 'id': '2001', - 'name': 'R2-D2', - 'friends': [ - {'name': 'Luke Skywalker'}, - {'name': 'Han Solo'}, - {'name': 'Leia Organa'}, - ] + "hero": { + "id": "2001", + "name": "R2-D2", + "friends": [ + {"name": "Luke Skywalker"}, + {"name": "Han Solo"}, + {"name": "Leia Organa"}, + ], } } result = graphql(StarWarsSchema, query) @@ -51,7 +47,7 @@ def test_hero_name_and_friends_query(): def test_nested_query(): - query = ''' + query = """ query NestedQuery { hero { name @@ -64,63 +60,41 @@ def test_nested_query(): } } } - ''' + """ expected = { - 'hero': { - 'name': 'R2-D2', - 'friends': [ + "hero": { + "name": "R2-D2", + "friends": [ { - 'name': 'Luke Skywalker', - 'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI'], - 'friends': [ - { - 'name': 'Han Solo', - }, - { - 'name': 'Leia Organa', - }, - { - 'name': 'C-3PO', - }, - { - 'name': 'R2-D2', - }, - ] + "name": "Luke Skywalker", + "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"], + "friends": [ + {"name": "Han Solo"}, + {"name": "Leia Organa"}, + {"name": "C-3PO"}, + {"name": "R2-D2"}, + ], }, { - 'name': 'Han Solo', - 'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI'], - 'friends': [ - { - 'name': 'Luke Skywalker', - }, - { - 'name': 'Leia Organa', - }, - { - 'name': 'R2-D2', - }, - ] + "name": "Han Solo", + "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"], + "friends": [ + {"name": "Luke Skywalker"}, + {"name": "Leia Organa"}, + {"name": "R2-D2"}, + ], }, { - 'name': 'Leia Organa', - 'appearsIn': ['NEWHOPE', 'EMPIRE', 'JEDI'], - 'friends': [ - { - 'name': 'Luke Skywalker', - }, - { - 'name': 'Han Solo', - }, - { - 'name': 'C-3PO', - }, - { - 'name': 'R2-D2', - }, - ] + "name": "Leia Organa", + "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"], + "friends": [ + {"name": "Luke Skywalker"}, + {"name": "Han Solo"}, + {"name": "C-3PO"}, + {"name": "R2-D2"}, + ], }, - ] + ], } } result = graphql(StarWarsSchema, query) @@ -129,104 +103,80 @@ def test_nested_query(): def test_fetch_luke_query(): - query = ''' + query = """ query FetchLukeQuery { human(id: "1000") { name } } - ''' - expected = { - 'human': { - 'name': 'Luke Skywalker', - } - } + """ + expected = {"human": {"name": "Luke Skywalker"}} result = graphql(StarWarsSchema, query) assert not result.errors assert result.data == expected def test_fetch_some_id_query(): - query = ''' + query = """ query FetchSomeIDQuery($someId: String!) { human(id: $someId) { name } } - ''' - params = { - 'someId': '1000', - } - expected = { - 'human': { - 'name': 'Luke Skywalker', - } - } + """ + params = {"someId": "1000"} + expected = {"human": {"name": "Luke Skywalker"}} result = graphql(StarWarsSchema, query, variable_values=params) assert not result.errors assert result.data == expected def test_fetch_some_id_query2(): - query = ''' + query = """ query FetchSomeIDQuery($someId: String!) { human(id: $someId) { name } } - ''' - params = { - 'someId': '1002', - } - expected = { - 'human': { - 'name': 'Han Solo', - } - } + """ + params = {"someId": "1002"} + expected = {"human": {"name": "Han Solo"}} result = graphql(StarWarsSchema, query, variable_values=params) assert not result.errors assert result.data == expected def test_invalid_id_query(): - query = ''' + query = """ query humanQuery($id: String!) { human(id: $id) { name } } - ''' - params = { - 'id': 'not a valid id', - } - expected = { - 'human': None - } + """ + params = {"id": "not a valid id"} + expected = {"human": None} result = graphql(StarWarsSchema, query, variable_values=params) assert not result.errors assert result.data == expected def test_fetch_luke_aliased(): - query = ''' + query = """ query FetchLukeAliased { luke: human(id: "1000") { name } } - ''' - expected = { - 'luke': { - 'name': 'Luke Skywalker', - } - } + """ + expected = {"luke": {"name": "Luke Skywalker"}} result = graphql(StarWarsSchema, query) assert not result.errors assert result.data == expected def test_fetch_luke_and_leia_aliased(): - query = ''' + query = """ query FetchLukeAndLeiaAliased { luke: human(id: "1000") { name @@ -235,22 +185,15 @@ def test_fetch_luke_and_leia_aliased(): name } } - ''' - expected = { - 'luke': { - 'name': 'Luke Skywalker', - }, - 'leia': { - 'name': 'Leia Organa', - } - } + """ + expected = {"luke": {"name": "Luke Skywalker"}, "leia": {"name": "Leia Organa"}} result = graphql(StarWarsSchema, query) assert not result.errors assert result.data == expected def test_duplicate_fields(): - query = ''' + query = """ query DuplicateFields { luke: human(id: "1000") { name @@ -261,16 +204,10 @@ def test_duplicate_fields(): homePlanet } } - ''' + """ expected = { - 'luke': { - 'name': 'Luke Skywalker', - 'homePlanet': 'Tatooine', - }, - 'leia': { - 'name': 'Leia Organa', - 'homePlanet': 'Alderaan', - } + "luke": {"name": "Luke Skywalker", "homePlanet": "Tatooine"}, + "leia": {"name": "Leia Organa", "homePlanet": "Alderaan"}, } result = graphql(StarWarsSchema, query) assert not result.errors @@ -278,7 +215,7 @@ def test_duplicate_fields(): def test_use_fragment(): - query = ''' + query = """ query UseFragment { luke: human(id: "1000") { ...HumanFragment @@ -291,16 +228,10 @@ def test_use_fragment(): name homePlanet } - ''' + """ expected = { - 'luke': { - 'name': 'Luke Skywalker', - 'homePlanet': 'Tatooine', - }, - 'leia': { - 'name': 'Leia Organa', - 'homePlanet': 'Alderaan', - } + "luke": {"name": "Luke Skywalker", "homePlanet": "Tatooine"}, + "leia": {"name": "Leia Organa", "homePlanet": "Alderaan"}, } result = graphql(StarWarsSchema, query) assert not result.errors @@ -308,52 +239,45 @@ def test_use_fragment(): def test_check_type_of_r2(): - query = ''' + query = """ query CheckTypeOfR2 { hero { __typename name } } - ''' - expected = { - 'hero': { - '__typename': 'Droid', - 'name': 'R2-D2', - } - } + """ + expected = {"hero": {"__typename": "Droid", "name": "R2-D2"}} result = graphql(StarWarsSchema, query) assert not result.errors assert result.data == expected def test_check_type_of_luke(): - query = ''' + query = """ query CheckTypeOfLuke { hero(episode: EMPIRE) { __typename name } } - ''' - expected = { - 'hero': { - '__typename': 'Human', - 'name': 'Luke Skywalker', - } - } + """ + expected = {"hero": {"__typename": "Human", "name": "Luke Skywalker"}} result = graphql(StarWarsSchema, query) assert not result.errors assert result.data == expected def test_parse_error(): - query = ''' + query = """ qeury - ''' + """ result = graphql(StarWarsSchema, query) assert result.invalid formatted_error = format_error(result.errors[0]) - assert formatted_error['locations'] == [{'column': 9, 'line': 2}] - assert 'Syntax Error GraphQL (2:9) Unexpected Name "qeury"' in formatted_error['message'] + assert formatted_error["locations"] == [{"column": 9, "line": 2}] + assert ( + 'Syntax Error GraphQL (2:9) Unexpected Name "qeury"' + in formatted_error["message"] + ) assert result.data is None diff --git a/tests/starwars/test_validation.py b/tests/starwars/test_validation.py index 538297cd..3e389d53 100644 --- a/tests/starwars/test_validation.py +++ b/tests/starwars/test_validation.py @@ -6,13 +6,13 @@ def validation_errors(query): - source = Source(query, 'StarWars.graphql') + source = Source(query, "StarWars.graphql") ast = parse(source) return validate(StarWarsSchema, ast) def test_nested_query_with_fragment(): - query = ''' + query = """ query NestedQueryWithFragment { hero { ...NameAndAppearances @@ -28,32 +28,32 @@ def test_nested_query_with_fragment(): name appearsIn } - ''' + """ assert not validation_errors(query) def test_non_existent_fields(): - query = ''' + query = """ query HeroSpaceshipQuery { hero { favoriteSpaceship } } - ''' + """ assert validation_errors(query) def test_require_fields_on_object(): - query = ''' + query = """ query HeroNoFieldsQuery { hero } - ''' + """ assert validation_errors(query) def test_disallows_fields_on_scalars(): - query = ''' + query = """ query HeroFieldsOnScalarQuery { hero { name { @@ -61,24 +61,24 @@ def test_disallows_fields_on_scalars(): } } } - ''' + """ assert validation_errors(query) def test_disallows_object_fields_on_interfaces(): - query = ''' + query = """ query DroidFieldOnCharacter { hero { name primaryFunction } } - ''' + """ assert validation_errors(query) def test_allows_object_fields_in_fragments(): - query = ''' + query = """ query DroidFieldInFragment { hero { name @@ -88,12 +88,12 @@ def test_allows_object_fields_in_fragments(): fragment DroidFields on Droid { primaryFunction } - ''' + """ assert not validation_errors(query) def test_allows_object_fields_in_inline_fragments(): - query = ''' + query = """ query DroidFieldInFragment { hero { name @@ -104,5 +104,5 @@ def test_allows_object_fields_in_inline_fragments(): fragment DroidFields on Droid { primaryFunction } - ''' + """ assert not validation_errors(query) diff --git a/tests_py35/core_execution/__init__.py b/tests_py35/core_execution/__init__.py index 9db7df9a..8d60ccb1 100644 --- a/tests_py35/core_execution/__init__.py +++ b/tests_py35/core_execution/__init__.py @@ -1 +1 @@ -__author__ = 'jake' +__author__ = "jake" diff --git a/tests_py35/core_execution/test_asyncio_executor.py b/tests_py35/core_execution/test_asyncio_executor.py index b89d2f35..8d5334d5 100644 --- a/tests_py35/core_execution/test_asyncio_executor.py +++ b/tests_py35/core_execution/test_asyncio_executor.py @@ -6,90 +6,101 @@ from graphql.execution import execute from graphql.language.parser import parse from graphql.execution.executors.asyncio import AsyncioExecutor -from graphql.type import ( - GraphQLSchema, - GraphQLObjectType, - GraphQLField, - GraphQLString -) +from graphql.type import GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString def test_asyncio_py35_executor(): - ast = parse('query Example { a, b, c }') + ast = parse("query Example { a, b, c }") async def resolver(context, *_): await asyncio.sleep(0.001) - return 'hey' + return "hey" async def resolver_2(context, *_): await asyncio.sleep(0.003) - return 'hey2' + return "hey2" def resolver_3(context, *_): - return 'hey3' + return "hey3" - Type = GraphQLObjectType('Type', { - 'a': GraphQLField(GraphQLString, resolver=resolver), - 'b': GraphQLField(GraphQLString, resolver=resolver_2), - 'c': GraphQLField(GraphQLString, resolver=resolver_3) - }) + Type = GraphQLObjectType( + "Type", + { + "a": GraphQLField(GraphQLString, resolver=resolver), + "b": GraphQLField(GraphQLString, resolver=resolver_2), + "c": GraphQLField(GraphQLString, resolver=resolver_3), + }, + ) result = execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor()) assert not result.errors - assert result.data == {'a': 'hey', 'b': 'hey2', 'c': 'hey3'} + assert result.data == {"a": "hey", "b": "hey2", "c": "hey3"} def test_asyncio_py35_executor_return_promise(): - ast = parse('query Example { a, b, c }') + ast = parse("query Example { a, b, c }") async def resolver(context, *_): await asyncio.sleep(0.001) - return 'hey' + return "hey" async def resolver_2(context, *_): await asyncio.sleep(0.003) - return 'hey2' + return "hey2" def resolver_3(context, *_): - return 'hey3' + return "hey3" - Type = GraphQLObjectType('Type', { - 'a': GraphQLField(GraphQLString, resolver=resolver), - 'b': GraphQLField(GraphQLString, resolver=resolver_2), - 'c': GraphQLField(GraphQLString, resolver=resolver_3) - }) + Type = GraphQLObjectType( + "Type", + { + "a": GraphQLField(GraphQLString, resolver=resolver), + "b": GraphQLField(GraphQLString, resolver=resolver_2), + "c": GraphQLField(GraphQLString, resolver=resolver_3), + }, + ) loop = asyncio.get_event_loop() async def do_exec(): - result = await execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor(loop), return_promise=True) + result = await execute( + GraphQLSchema(Type), + ast, + executor=AsyncioExecutor(loop), + return_promise=True, + ) assert not result.errors - assert result.data == {'a': 'hey', 'b': 'hey2', 'c': 'hey3'} + assert result.data == {"a": "hey", "b": "hey2", "c": "hey3"} loop.run_until_complete(do_exec()) def test_asyncio_py35_executor_with_error(): - ast = parse('query Example { a, b }') + ast = parse("query Example { a, b }") async def resolver(context, *_): await asyncio.sleep(0.001) - return 'hey' + return "hey" async def resolver_2(context, *_): await asyncio.sleep(0.003) - raise Exception('resolver_2 failed!') + raise Exception("resolver_2 failed!") - Type = GraphQLObjectType('Type', { - 'a': GraphQLField(GraphQLString, resolver=resolver), - 'b': GraphQLField(GraphQLString, resolver=resolver_2) - }) + Type = GraphQLObjectType( + "Type", + { + "a": GraphQLField(GraphQLString, resolver=resolver), + "b": GraphQLField(GraphQLString, resolver=resolver_2), + }, + ) result = execute(GraphQLSchema(Type), ast, executor=AsyncioExecutor()) formatted_errors = list(map(format_error, result.errors)) - assert formatted_errors == [{ - 'locations': [{'line': 1, 'column': 20}], - 'path': ['b'], - 'message': 'resolver_2 failed!' - }] - assert result.data == {'a': 'hey', 'b': None} + assert formatted_errors == [ + { + "locations": [{"line": 1, "column": 20}], + "path": ["b"], + "message": "resolver_2 failed!", + } + ] + assert result.data == {"a": "hey", "b": None}