back to Claude Sonnet 3.5 - Fill-in summary
Claude Sonnet 3.5 - Fill-in: graphene
Pytest Summary for test graphene
status | count |
---|---|
error | 5 |
total | 5 |
collected | 5 |
passed | 0 |
Failed pytests:
test_orderedtype.py::test_orderedtype
test_orderedtype.py::test_orderedtype
name = 'graphene', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ graphene/__init__.py:2: infrom .relay import ( graphene/relay/__init__.py:1: in from .node import Node, is_node, GlobalID graphene/relay/node.py:3: in from ..types import Field, Interface, ObjectType graphene/types/__init__.py:4: in from .argument import Argument graphene/types/argument.py:5: in from .structures import NonNull _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ from .unmountedtype import UnmountedType > from .utils import get_type E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) graphene/types/structures.py:2: ImportError The above exception was the direct cause of the following exception: cls = func = . at 0x7f9565cfc9a0> when = 'setup' reraise = ( , ) @classmethod def from_call( cls, func: Callable[[], TResult], when: Literal["collect", "setup", "call", "teardown"], reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, ) -> CallInfo[TResult]: """Call func, wrapping the result in a CallInfo. :param func: The function to call. Called without arguments. :type func: Callable[[], _pytest.runner.TResult] :param when: The phase in which the function is called. :param reraise: Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo. """ excinfo = None start = timing.time() precise_start = timing.perf_counter() try: > result: TResult | None = func() .venv/lib/python3.11/site-packages/_pytest/runner.py:341: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.11/site-packages/_pytest/runner.py:242: in lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise .venv/lib/python3.11/site-packages/pluggy/_hooks.py:513: in __call__ return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) .venv/lib/python3.11/site-packages/pluggy/_manager.py:120: in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:90: in pytest_runtest_setup yield from unraisable_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:70: in unraisable_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/logging.py:840: in pytest_runtest_setup yield from self._runtest_for(item, "setup") .venv/lib/python3.11/site-packages/_pytest/logging.py:829: in _runtest_for yield .venv/lib/python3.11/site-packages/_pytest/capture.py:875: in pytest_runtest_setup return (yield) .venv/lib/python3.11/site-packages/_pytest/threadexception.py:87: in pytest_runtest_setup yield from thread_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/threadexception.py:68: in thread_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/runner.py:160: in pytest_runtest_setup item.session._setupstate.setup(item) .venv/lib/python3.11/site-packages/_pytest/runner.py:514: in setup col.setup() .venv/lib/python3.11/site-packages/_pytest/python.py:663: in setup init_mod = importtestmodule(self.path / "__init__.py", self.config) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ path = PosixPath('/testbed/graphene/__init__.py') config = <_pytest.config.Config object at 0x7f95666cee50> def importtestmodule( path: Path, config: Config, ): # We assume we are only called once per module. importmode = config.getoption("--import-mode") try: mod = import_path( path, mode=importmode, root=config.rootpath, consider_namespace_packages=config.getini("consider_namespace_packages"), ) except SyntaxError as e: raise nodes.Collector.CollectError( ExceptionInfo.from_current().getrepr(style="short") ) from e except ImportPathMismatchError as e: raise nodes.Collector.CollectError( "import file mismatch:\n" "imported module {!r} has this __file__ attribute:\n" " {}\n" "which is not the same as the test file we want to collect:\n" " {}\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules".format(*e.args) ) from e except ImportError as e: exc_info = ExceptionInfo.from_current() if config.get_verbosity() < 2: exc_info.traceback = exc_info.traceback.filter(filter_traceback) exc_repr = ( exc_info.getrepr(style="short") if exc_info.traceback else exc_info.exconly() ) formatted_tb = str(exc_repr) > raise nodes.Collector.CollectError( f"ImportError while importing test module '{path}'.\n" "Hint: make sure your test modules/packages have valid Python names.\n" "Traceback:\n" f"{formatted_tb}" ) from e E _pytest.nodes.Collector.CollectError: ImportError while importing test module '/testbed/graphene/__init__.py'. E Hint: make sure your test modules/packages have valid Python names. E Traceback: E /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: in import_module E return _bootstrap._gcd_import(name[level:], package, level) E graphene/__init__.py:2: in E from .relay import ( E graphene/relay/__init__.py:1: in E from .node import Node, is_node, GlobalID E graphene/relay/node.py:3: in E from ..types import Field, Interface, ObjectType E graphene/types/__init__.py:4: in E from .argument import Argument E graphene/types/argument.py:5: in E from .structures import NonNull E graphene/types/structures.py:2: in E from .utils import get_type E E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) .venv/lib/python3.11/site-packages/_pytest/python.py:523: CollectError
test_orderedtype.py::test_orderedtype_eq
test_orderedtype.py::test_orderedtype_eq
name = 'graphene', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ graphene/__init__.py:2: infrom .relay import ( graphene/relay/__init__.py:1: in from .node import Node, is_node, GlobalID graphene/relay/node.py:3: in from ..types import Field, Interface, ObjectType graphene/types/__init__.py:4: in from .argument import Argument graphene/types/argument.py:5: in from .structures import NonNull _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ from .unmountedtype import UnmountedType > from .utils import get_type E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) graphene/types/structures.py:2: ImportError The above exception was the direct cause of the following exception: cls = func = . at 0x7f9565c61f80> when = 'setup' reraise = ( , ) @classmethod def from_call( cls, func: Callable[[], TResult], when: Literal["collect", "setup", "call", "teardown"], reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, ) -> CallInfo[TResult]: """Call func, wrapping the result in a CallInfo. :param func: The function to call. Called without arguments. :type func: Callable[[], _pytest.runner.TResult] :param when: The phase in which the function is called. :param reraise: Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo. """ excinfo = None start = timing.time() precise_start = timing.perf_counter() try: > result: TResult | None = func() .venv/lib/python3.11/site-packages/_pytest/runner.py:341: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.11/site-packages/_pytest/runner.py:242: in lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise .venv/lib/python3.11/site-packages/pluggy/_hooks.py:513: in __call__ return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) .venv/lib/python3.11/site-packages/pluggy/_manager.py:120: in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:90: in pytest_runtest_setup yield from unraisable_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:70: in unraisable_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/logging.py:840: in pytest_runtest_setup yield from self._runtest_for(item, "setup") .venv/lib/python3.11/site-packages/_pytest/logging.py:829: in _runtest_for yield .venv/lib/python3.11/site-packages/_pytest/capture.py:875: in pytest_runtest_setup return (yield) .venv/lib/python3.11/site-packages/_pytest/threadexception.py:87: in pytest_runtest_setup yield from thread_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/threadexception.py:68: in thread_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/runner.py:160: in pytest_runtest_setup item.session._setupstate.setup(item) .venv/lib/python3.11/site-packages/_pytest/runner.py:507: in setup raise exc[0].with_traceback(exc[1]) .venv/lib/python3.11/site-packages/_pytest/runner.py:514: in setup col.setup() .venv/lib/python3.11/site-packages/_pytest/python.py:663: in setup init_mod = importtestmodule(self.path / "__init__.py", self.config) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ path = PosixPath('/testbed/graphene/__init__.py') config = <_pytest.config.Config object at 0x7f95666cee50> def importtestmodule( path: Path, config: Config, ): # We assume we are only called once per module. importmode = config.getoption("--import-mode") try: mod = import_path( path, mode=importmode, root=config.rootpath, consider_namespace_packages=config.getini("consider_namespace_packages"), ) except SyntaxError as e: raise nodes.Collector.CollectError( ExceptionInfo.from_current().getrepr(style="short") ) from e except ImportPathMismatchError as e: raise nodes.Collector.CollectError( "import file mismatch:\n" "imported module {!r} has this __file__ attribute:\n" " {}\n" "which is not the same as the test file we want to collect:\n" " {}\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules".format(*e.args) ) from e except ImportError as e: exc_info = ExceptionInfo.from_current() if config.get_verbosity() < 2: exc_info.traceback = exc_info.traceback.filter(filter_traceback) exc_repr = ( exc_info.getrepr(style="short") if exc_info.traceback else exc_info.exconly() ) formatted_tb = str(exc_repr) > raise nodes.Collector.CollectError( f"ImportError while importing test module '{path}'.\n" "Hint: make sure your test modules/packages have valid Python names.\n" "Traceback:\n" f"{formatted_tb}" ) from e E _pytest.nodes.Collector.CollectError: ImportError while importing test module '/testbed/graphene/__init__.py'. E Hint: make sure your test modules/packages have valid Python names. E Traceback: E /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: in import_module E return _bootstrap._gcd_import(name[level:], package, level) E graphene/__init__.py:2: in E from .relay import ( E graphene/relay/__init__.py:1: in E from .node import Node, is_node, GlobalID E graphene/relay/node.py:3: in E from ..types import Field, Interface, ObjectType E graphene/types/__init__.py:4: in E from .argument import Argument E graphene/types/argument.py:5: in E from .structures import NonNull E graphene/types/structures.py:2: in E from .utils import get_type E E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) .venv/lib/python3.11/site-packages/_pytest/python.py:523: CollectError
test_orderedtype.py::test_orderedtype_hash
test_orderedtype.py::test_orderedtype_hash
name = 'graphene', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ graphene/__init__.py:2: infrom .relay import ( graphene/relay/__init__.py:1: in from .node import Node, is_node, GlobalID graphene/relay/node.py:3: in from ..types import Field, Interface, ObjectType graphene/types/__init__.py:4: in from .argument import Argument graphene/types/argument.py:5: in from .structures import NonNull _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ from .unmountedtype import UnmountedType > from .utils import get_type E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) graphene/types/structures.py:2: ImportError The above exception was the direct cause of the following exception: cls = func = . at 0x7f9565c63d80> when = 'setup' reraise = ( , ) @classmethod def from_call( cls, func: Callable[[], TResult], when: Literal["collect", "setup", "call", "teardown"], reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, ) -> CallInfo[TResult]: """Call func, wrapping the result in a CallInfo. :param func: The function to call. Called without arguments. :type func: Callable[[], _pytest.runner.TResult] :param when: The phase in which the function is called. :param reraise: Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo. """ excinfo = None start = timing.time() precise_start = timing.perf_counter() try: > result: TResult | None = func() .venv/lib/python3.11/site-packages/_pytest/runner.py:341: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.11/site-packages/_pytest/runner.py:242: in lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise .venv/lib/python3.11/site-packages/pluggy/_hooks.py:513: in __call__ return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) .venv/lib/python3.11/site-packages/pluggy/_manager.py:120: in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:90: in pytest_runtest_setup yield from unraisable_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:70: in unraisable_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/logging.py:840: in pytest_runtest_setup yield from self._runtest_for(item, "setup") .venv/lib/python3.11/site-packages/_pytest/logging.py:829: in _runtest_for yield .venv/lib/python3.11/site-packages/_pytest/capture.py:875: in pytest_runtest_setup return (yield) .venv/lib/python3.11/site-packages/_pytest/threadexception.py:87: in pytest_runtest_setup yield from thread_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/threadexception.py:68: in thread_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/runner.py:160: in pytest_runtest_setup item.session._setupstate.setup(item) .venv/lib/python3.11/site-packages/_pytest/runner.py:507: in setup raise exc[0].with_traceback(exc[1]) .venv/lib/python3.11/site-packages/_pytest/runner.py:514: in setup col.setup() .venv/lib/python3.11/site-packages/_pytest/python.py:663: in setup init_mod = importtestmodule(self.path / "__init__.py", self.config) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ path = PosixPath('/testbed/graphene/__init__.py') config = <_pytest.config.Config object at 0x7f95666cee50> def importtestmodule( path: Path, config: Config, ): # We assume we are only called once per module. importmode = config.getoption("--import-mode") try: mod = import_path( path, mode=importmode, root=config.rootpath, consider_namespace_packages=config.getini("consider_namespace_packages"), ) except SyntaxError as e: raise nodes.Collector.CollectError( ExceptionInfo.from_current().getrepr(style="short") ) from e except ImportPathMismatchError as e: raise nodes.Collector.CollectError( "import file mismatch:\n" "imported module {!r} has this __file__ attribute:\n" " {}\n" "which is not the same as the test file we want to collect:\n" " {}\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules".format(*e.args) ) from e except ImportError as e: exc_info = ExceptionInfo.from_current() if config.get_verbosity() < 2: exc_info.traceback = exc_info.traceback.filter(filter_traceback) exc_repr = ( exc_info.getrepr(style="short") if exc_info.traceback else exc_info.exconly() ) formatted_tb = str(exc_repr) > raise nodes.Collector.CollectError( f"ImportError while importing test module '{path}'.\n" "Hint: make sure your test modules/packages have valid Python names.\n" "Traceback:\n" f"{formatted_tb}" ) from e E _pytest.nodes.Collector.CollectError: ImportError while importing test module '/testbed/graphene/__init__.py'. E Hint: make sure your test modules/packages have valid Python names. E Traceback: E /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: in import_module E return _bootstrap._gcd_import(name[level:], package, level) E graphene/__init__.py:2: in E from .relay import ( E graphene/relay/__init__.py:1: in E from .node import Node, is_node, GlobalID E graphene/relay/node.py:3: in E from ..types import Field, Interface, ObjectType E graphene/types/__init__.py:4: in E from .argument import Argument E graphene/types/argument.py:5: in E from .structures import NonNull E graphene/types/structures.py:2: in E from .utils import get_type E E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) .venv/lib/python3.11/site-packages/_pytest/python.py:523: CollectError
test_orderedtype.py::test_orderedtype_resetcounter
test_orderedtype.py::test_orderedtype_resetcounter
name = 'graphene', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ graphene/__init__.py:2: infrom .relay import ( graphene/relay/__init__.py:1: in from .node import Node, is_node, GlobalID graphene/relay/node.py:3: in from ..types import Field, Interface, ObjectType graphene/types/__init__.py:4: in from .argument import Argument graphene/types/argument.py:5: in from .structures import NonNull _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ from .unmountedtype import UnmountedType > from .utils import get_type E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) graphene/types/structures.py:2: ImportError The above exception was the direct cause of the following exception: cls = func = . at 0x7f9565c63b00> when = 'setup' reraise = ( , ) @classmethod def from_call( cls, func: Callable[[], TResult], when: Literal["collect", "setup", "call", "teardown"], reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, ) -> CallInfo[TResult]: """Call func, wrapping the result in a CallInfo. :param func: The function to call. Called without arguments. :type func: Callable[[], _pytest.runner.TResult] :param when: The phase in which the function is called. :param reraise: Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo. """ excinfo = None start = timing.time() precise_start = timing.perf_counter() try: > result: TResult | None = func() .venv/lib/python3.11/site-packages/_pytest/runner.py:341: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.11/site-packages/_pytest/runner.py:242: in lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise .venv/lib/python3.11/site-packages/pluggy/_hooks.py:513: in __call__ return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) .venv/lib/python3.11/site-packages/pluggy/_manager.py:120: in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:90: in pytest_runtest_setup yield from unraisable_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:70: in unraisable_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/logging.py:840: in pytest_runtest_setup yield from self._runtest_for(item, "setup") .venv/lib/python3.11/site-packages/_pytest/logging.py:829: in _runtest_for yield .venv/lib/python3.11/site-packages/_pytest/capture.py:875: in pytest_runtest_setup return (yield) .venv/lib/python3.11/site-packages/_pytest/threadexception.py:87: in pytest_runtest_setup yield from thread_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/threadexception.py:68: in thread_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/runner.py:160: in pytest_runtest_setup item.session._setupstate.setup(item) .venv/lib/python3.11/site-packages/_pytest/runner.py:507: in setup raise exc[0].with_traceback(exc[1]) .venv/lib/python3.11/site-packages/_pytest/runner.py:514: in setup col.setup() .venv/lib/python3.11/site-packages/_pytest/python.py:663: in setup init_mod = importtestmodule(self.path / "__init__.py", self.config) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ path = PosixPath('/testbed/graphene/__init__.py') config = <_pytest.config.Config object at 0x7f95666cee50> def importtestmodule( path: Path, config: Config, ): # We assume we are only called once per module. importmode = config.getoption("--import-mode") try: mod = import_path( path, mode=importmode, root=config.rootpath, consider_namespace_packages=config.getini("consider_namespace_packages"), ) except SyntaxError as e: raise nodes.Collector.CollectError( ExceptionInfo.from_current().getrepr(style="short") ) from e except ImportPathMismatchError as e: raise nodes.Collector.CollectError( "import file mismatch:\n" "imported module {!r} has this __file__ attribute:\n" " {}\n" "which is not the same as the test file we want to collect:\n" " {}\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules".format(*e.args) ) from e except ImportError as e: exc_info = ExceptionInfo.from_current() if config.get_verbosity() < 2: exc_info.traceback = exc_info.traceback.filter(filter_traceback) exc_repr = ( exc_info.getrepr(style="short") if exc_info.traceback else exc_info.exconly() ) formatted_tb = str(exc_repr) > raise nodes.Collector.CollectError( f"ImportError while importing test module '{path}'.\n" "Hint: make sure your test modules/packages have valid Python names.\n" "Traceback:\n" f"{formatted_tb}" ) from e E _pytest.nodes.Collector.CollectError: ImportError while importing test module '/testbed/graphene/__init__.py'. E Hint: make sure your test modules/packages have valid Python names. E Traceback: E /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: in import_module E return _bootstrap._gcd_import(name[level:], package, level) E graphene/__init__.py:2: in E from .relay import ( E graphene/relay/__init__.py:1: in E from .node import Node, is_node, GlobalID E graphene/relay/node.py:3: in E from ..types import Field, Interface, ObjectType E graphene/types/__init__.py:4: in E from .argument import Argument E graphene/types/argument.py:5: in E from .structures import NonNull E graphene/types/structures.py:2: in E from .utils import get_type E E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) .venv/lib/python3.11/site-packages/_pytest/python.py:523: CollectError
test_orderedtype.py::test_orderedtype_non_orderabletypes
test_orderedtype.py::test_orderedtype_non_orderabletypes
name = 'graphene', package = None def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ level = 0 if name.startswith('.'): if not package: msg = ("the 'package' argument is required to perform a relative " "import for {!r}") raise TypeError(msg.format(name)) for character in name: if character != '.': break level += 1 > return _bootstrap._gcd_import(name[level:], package, level) /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ graphene/__init__.py:2: infrom .relay import ( graphene/relay/__init__.py:1: in from .node import Node, is_node, GlobalID graphene/relay/node.py:3: in from ..types import Field, Interface, ObjectType graphene/types/__init__.py:4: in from .argument import Argument graphene/types/argument.py:5: in from .structures import NonNull _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ from .unmountedtype import UnmountedType > from .utils import get_type E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) graphene/types/structures.py:2: ImportError The above exception was the direct cause of the following exception: cls = func = . at 0x7f9565c60f40> when = 'setup' reraise = ( , ) @classmethod def from_call( cls, func: Callable[[], TResult], when: Literal["collect", "setup", "call", "teardown"], reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None, ) -> CallInfo[TResult]: """Call func, wrapping the result in a CallInfo. :param func: The function to call. Called without arguments. :type func: Callable[[], _pytest.runner.TResult] :param when: The phase in which the function is called. :param reraise: Exception or exceptions that shall propagate if raised by the function, instead of being wrapped in the CallInfo. """ excinfo = None start = timing.time() precise_start = timing.perf_counter() try: > result: TResult | None = func() .venv/lib/python3.11/site-packages/_pytest/runner.py:341: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ .venv/lib/python3.11/site-packages/_pytest/runner.py:242: in lambda: runtest_hook(item=item, **kwds), when=when, reraise=reraise .venv/lib/python3.11/site-packages/pluggy/_hooks.py:513: in __call__ return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult) .venv/lib/python3.11/site-packages/pluggy/_manager.py:120: in _hookexec return self._inner_hookexec(hook_name, methods, kwargs, firstresult) .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:90: in pytest_runtest_setup yield from unraisable_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/unraisableexception.py:70: in unraisable_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/logging.py:840: in pytest_runtest_setup yield from self._runtest_for(item, "setup") .venv/lib/python3.11/site-packages/_pytest/logging.py:829: in _runtest_for yield .venv/lib/python3.11/site-packages/_pytest/capture.py:875: in pytest_runtest_setup return (yield) .venv/lib/python3.11/site-packages/_pytest/threadexception.py:87: in pytest_runtest_setup yield from thread_exception_runtest_hook() .venv/lib/python3.11/site-packages/_pytest/threadexception.py:68: in thread_exception_runtest_hook yield .venv/lib/python3.11/site-packages/_pytest/runner.py:160: in pytest_runtest_setup item.session._setupstate.setup(item) .venv/lib/python3.11/site-packages/_pytest/runner.py:507: in setup raise exc[0].with_traceback(exc[1]) .venv/lib/python3.11/site-packages/_pytest/runner.py:514: in setup col.setup() .venv/lib/python3.11/site-packages/_pytest/python.py:663: in setup init_mod = importtestmodule(self.path / "__init__.py", self.config) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ path = PosixPath('/testbed/graphene/__init__.py') config = <_pytest.config.Config object at 0x7f95666cee50> def importtestmodule( path: Path, config: Config, ): # We assume we are only called once per module. importmode = config.getoption("--import-mode") try: mod = import_path( path, mode=importmode, root=config.rootpath, consider_namespace_packages=config.getini("consider_namespace_packages"), ) except SyntaxError as e: raise nodes.Collector.CollectError( ExceptionInfo.from_current().getrepr(style="short") ) from e except ImportPathMismatchError as e: raise nodes.Collector.CollectError( "import file mismatch:\n" "imported module {!r} has this __file__ attribute:\n" " {}\n" "which is not the same as the test file we want to collect:\n" " {}\n" "HINT: remove __pycache__ / .pyc files and/or use a " "unique basename for your test file modules".format(*e.args) ) from e except ImportError as e: exc_info = ExceptionInfo.from_current() if config.get_verbosity() < 2: exc_info.traceback = exc_info.traceback.filter(filter_traceback) exc_repr = ( exc_info.getrepr(style="short") if exc_info.traceback else exc_info.exconly() ) formatted_tb = str(exc_repr) > raise nodes.Collector.CollectError( f"ImportError while importing test module '{path}'.\n" "Hint: make sure your test modules/packages have valid Python names.\n" "Traceback:\n" f"{formatted_tb}" ) from e E _pytest.nodes.Collector.CollectError: ImportError while importing test module '/testbed/graphene/__init__.py'. E Hint: make sure your test modules/packages have valid Python names. E Traceback: E /root/.local/share/uv/python/cpython-3.11.10-linux-x86_64-gnu/lib/python3.11/importlib/__init__.py:126: in import_module E return _bootstrap._gcd_import(name[level:], package, level) E graphene/__init__.py:2: in E from .relay import ( E graphene/relay/__init__.py:1: in E from .node import Node, is_node, GlobalID E graphene/relay/node.py:3: in E from ..types import Field, Interface, ObjectType E graphene/types/__init__.py:4: in E from .argument import Argument E graphene/types/argument.py:5: in E from .structures import NonNull E graphene/types/structures.py:2: in E from .utils import get_type E E ImportError: cannot import name 'get_type' from 'graphene.types.utils' (/testbed/graphene/types/utils.py) .venv/lib/python3.11/site-packages/_pytest/python.py:523: CollectError
Patch diff
diff --git a/graphene/pyutils/dataclasses.py b/graphene/pyutils/dataclasses.py
index f1ec952..9db800a 100644
--- a/graphene/pyutils/dataclasses.py
+++ b/graphene/pyutils/dataclasses.py
@@ -119,7 +119,9 @@ def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
It is an error to specify both default and default_factory.
"""
- pass
+ if default is not MISSING and default_factory is not MISSING:
+ raise ValueError('cannot specify both default and default_factory')
+ return Field(default, default_factory, init, repr, hash, compare, metadata)
_hash_action = {(False, False, False, False): None, (False, False, False,
@@ -146,7 +148,13 @@ def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
__hash__() method function is added. If frozen is true, fields may
not be assigned to after instance creation.
"""
- pass
+ def wrap(cls):
+ return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
+
+ if _cls is None:
+ return wrap
+
+ return wrap(_cls)
def fields(class_or_instance):
@@ -155,18 +163,23 @@ def fields(class_or_instance):
Accepts a dataclass or an instance of one. Tuple elements are of
type Field.
"""
- pass
+ if isinstance(class_or_instance, type):
+ return getattr(class_or_instance, _FIELDS).values()
+ elif isinstance(class_or_instance, object):
+ return fields(class_or_instance.__class__)
+ else:
+ raise TypeError('Argument must be a dataclass type or instance')
def _is_dataclass_instance(obj):
"""Returns True if obj is an instance of a dataclass."""
- pass
+ return hasattr(obj, _FIELDS)
def is_dataclass(obj):
"""Returns True if obj is a dataclass or an instance of a
dataclass."""
- pass
+ return isinstance(obj, type) and hasattr(obj, _FIELDS) or _is_dataclass_instance(obj)
def asdict(obj, *, dict_factory=dict):
@@ -188,7 +201,23 @@ def asdict(obj, *, dict_factory=dict):
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
- pass
+ def _asdict_inner(obj):
+ if _is_dataclass_instance(obj):
+ result = []
+ for f in fields(obj):
+ value = _asdict_inner(getattr(obj, f.name))
+ result.append((f.name, value))
+ return dict_factory(result)
+ elif isinstance(obj, (list, tuple)):
+ return type(obj)(_asdict_inner(v) for v in obj)
+ elif isinstance(obj, dict):
+ return type(obj)((_asdict_inner(k), _asdict_inner(v)) for k, v in obj.items())
+ else:
+ return copy.deepcopy(obj)
+
+ if not _is_dataclass_instance(obj):
+ raise TypeError("asdict() should be called on dataclass instances")
+ return _asdict_inner(obj)
def astuple(obj, *, tuple_factory=tuple):
@@ -209,7 +238,23 @@ def astuple(obj, *, tuple_factory=tuple):
dataclass instances. This will also look into built-in containers:
tuples, lists, and dicts.
"""
- pass
+ def _astuple_inner(obj):
+ if _is_dataclass_instance(obj):
+ result = []
+ for f in fields(obj):
+ value = _astuple_inner(getattr(obj, f.name))
+ result.append(value)
+ return tuple_factory(result)
+ elif isinstance(obj, (list, tuple)):
+ return type(obj)(_astuple_inner(v) for v in obj)
+ elif isinstance(obj, dict):
+ return type(obj)((_astuple_inner(k), _astuple_inner(v)) for k, v in obj.items())
+ else:
+ return copy.deepcopy(obj)
+
+ if not _is_dataclass_instance(obj):
+ raise TypeError("astuple() should be called on dataclass instances")
+ return _astuple_inner(obj)
def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
@@ -236,7 +281,29 @@ def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
dataclass().
"""
- pass
+ if namespace is None:
+ namespace = {}
+ else:
+ namespace = namespace.copy()
+
+ anns = {}
+ for item in fields:
+ if isinstance(item, str):
+ anns[item] = 'typing.Any'
+ elif len(item) == 2:
+ name, tp = item
+ anns[name] = tp
+ elif len(item) == 3:
+ name, tp, spec = item
+ anns[name] = tp
+ namespace[name] = spec
+ else:
+ raise TypeError(f'Invalid field specification: {item}')
+
+ namespace['__annotations__'] = anns
+ cls = type(cls_name, bases, namespace)
+ return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
+ unsafe_hash=unsafe_hash, frozen=frozen)
def replace(obj, **changes):
@@ -253,4 +320,14 @@ def replace(obj, **changes):
c1 = replace(c, x=3)
assert c1.x == 3 and c1.y == 2
"""
- pass
+ if not _is_dataclass_instance(obj):
+ raise TypeError("replace() should be called on dataclass instances")
+
+ # Create a dict of the original values
+ original_dict = asdict(obj)
+
+ # Update with the new values
+ original_dict.update(changes)
+
+ # Create a new instance with the updated values
+ return obj.__class__(**original_dict)
diff --git a/graphene/pyutils/version.py b/graphene/pyutils/version.py
index 7f16d40..715025c 100644
--- a/graphene/pyutils/version.py
+++ b/graphene/pyutils/version.py
@@ -6,19 +6,35 @@ import subprocess
def get_version(version=None):
"""Returns a PEP 440-compliant version number from VERSION."""
- pass
+ version = get_complete_version(version)
+ main = get_main_version(version)
+
+ sub = ''
+ if version[3] != 'final':
+ mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
+ sub = mapping[version[3]] + str(version[4])
+
+ return main + sub
def get_main_version(version=None):
"""Returns main version (X.Y[.Z]) from VERSION."""
- pass
+ version = get_complete_version(version)
+ parts = 2 if version[2] == 0 else 3
+ return '.'.join(str(x) for x in version[:parts])
def get_complete_version(version=None):
"""Returns a tuple of the graphene version. If version argument is non-empty,
then checks for correctness of the tuple provided.
"""
- pass
+ if version is None:
+ from graphene import VERSION as version
+ else:
+ assert len(version) == 5
+ assert version[3] in ('alpha', 'beta', 'rc', 'final')
+
+ return version
def get_git_changeset():
@@ -27,4 +43,15 @@ def get_git_changeset():
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
- pass
+ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ git_log = subprocess.Popen(
+ 'git log --pretty=format:%ct --quiet -1 HEAD',
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ shell=True, cwd=repo_dir, universal_newlines=True,
+ )
+ timestamp = git_log.communicate()[0]
+ try:
+ timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
+ except ValueError:
+ return None
+ return timestamp.strftime('%Y%m%d%H%M%S')
diff --git a/graphene/relay/connection.py b/graphene/relay/connection.py
index b1ab0bf..7cdc476 100644
--- a/graphene/relay/connection.py
+++ b/graphene/relay/connection.py
@@ -29,7 +29,12 @@ class PageInfo(ObjectType):
def page_info_adapter(startCursor, endCursor, hasPreviousPage, hasNextPage):
"""Adapter for creating PageInfo instances"""
- pass
+ return PageInfo(
+ start_cursor=startCursor,
+ end_cursor=endCursor,
+ has_previous_page=hasPreviousPage,
+ has_next_page=hasNextPage
+ )
class ConnectionOptions(ObjectTypeOptions):
@@ -75,7 +80,10 @@ class Connection(ObjectType):
def connection_adapter(cls, edges, pageInfo):
"""Adapter for creating Connection instances"""
- pass
+ return cls(
+ edges=edges,
+ page_info=pageInfo
+ )
class IterableConnectionField(Field):
diff --git a/graphene/relay/node.py b/graphene/relay/node.py
index 138a893..3093ed9 100644
--- a/graphene/relay/node.py
+++ b/graphene/relay/node.py
@@ -10,7 +10,11 @@ def is_node(objecttype):
"""
Check if the given objecttype has Node as an interface
"""
- pass
+ return issubclass(objecttype, Node) or (
+ isclass(objecttype)
+ and issubclass(objecttype, ObjectType)
+ and any(issubclass(i, Node) for i in objecttype._meta.interfaces)
+ )
class GlobalID(Field):
@@ -34,6 +38,9 @@ class NodeField(Field):
graphene_type(required=True, description='The ID of the object'
), **kwargs)
+ def get_resolver(self, parent_resolver):
+ return partial(self.node_type.node_resolver, get_node=self.node_type.get_node_from_global_id)
+
class AbstractNode(Interface):
diff --git a/graphene/types/definitions.py b/graphene/types/definitions.py
index 12b2a86..b0e53cb 100644
--- a/graphene/types/definitions.py
+++ b/graphene/types/definitions.py
@@ -19,24 +19,42 @@ class GrapheneGraphQLType:
class GrapheneInterfaceType(GrapheneGraphQLType, GraphQLInterfaceType):
- pass
+ def __copy__(self):
+ result = GrapheneInterfaceType(graphene_type=self.graphene_type)
+ result.__dict__.update(self.__dict__)
+ return result
class GrapheneUnionType(GrapheneGraphQLType, GraphQLUnionType):
- pass
+ def __copy__(self):
+ result = GrapheneUnionType(graphene_type=self.graphene_type)
+ result.__dict__.update(self.__dict__)
+ return result
class GrapheneObjectType(GrapheneGraphQLType, GraphQLObjectType):
- pass
+ def __copy__(self):
+ result = GrapheneObjectType(graphene_type=self.graphene_type)
+ result.__dict__.update(self.__dict__)
+ return result
class GrapheneScalarType(GrapheneGraphQLType, GraphQLScalarType):
- pass
+ def __copy__(self):
+ result = GrapheneScalarType(graphene_type=self.graphene_type)
+ result.__dict__.update(self.__dict__)
+ return result
class GrapheneEnumType(GrapheneGraphQLType, GraphQLEnumType):
- pass
+ def __copy__(self):
+ result = GrapheneEnumType(graphene_type=self.graphene_type)
+ result.__dict__.update(self.__dict__)
+ return result
class GrapheneInputObjectType(GrapheneGraphQLType, GraphQLInputObjectType):
- pass
+ def __copy__(self):
+ result = GrapheneInputObjectType(graphene_type=self.graphene_type)
+ result.__dict__.update(self.__dict__)
+ return result
diff --git a/graphene/types/enum.py b/graphene/types/enum.py
index cce1873..db44070 100644
--- a/graphene/types/enum.py
+++ b/graphene/types/enum.py
@@ -80,4 +80,4 @@ class Enum(UnmountedType, BaseType, metaclass=EnumMeta):
This function is called when the unmounted type (Enum instance)
is mounted (as a Field, InputField or Argument)
"""
- pass
+ return cls
diff --git a/graphene/types/field.py b/graphene/types/field.py
index a23e927..bde1cbf 100644
--- a/graphene/types/field.py
+++ b/graphene/types/field.py
@@ -88,11 +88,23 @@ class Field(MountedType):
Wraps a function resolver, using the ObjectType resolve_{FIELD_NAME}
(parent_resolver) if the Field definition has no resolver.
"""
- pass
+ def resolver(obj, info, **args):
+ if self.resolver:
+ return self.resolver(obj, info, **args)
+ elif parent_resolver:
+ return parent_resolver(obj, info, **args)
+ return default_resolver(obj, info, **args)
+ return resolver
def wrap_subscribe(self, parent_subscribe):
"""
Wraps a function subscribe, using the ObjectType subscribe_{FIELD_NAME}
(parent_subscribe) if the Field definition has no subscribe.
"""
- pass
+ def subscriber(obj, info, **args):
+ if hasattr(self, 'subscribe'):
+ return self.subscribe(obj, info, **args)
+ elif parent_subscribe:
+ return parent_subscribe(obj, info, **args)
+ return None
+ return subscriber
diff --git a/graphene/types/inputobjecttype.py b/graphene/types/inputobjecttype.py
index f99e2c1..c01bbac 100644
--- a/graphene/types/inputobjecttype.py
+++ b/graphene/types/inputobjecttype.py
@@ -24,7 +24,8 @@ def set_input_object_type_default_value(default_value):
This function should be called at the beginning of the app or in some other place where it is guaranteed to
be called before any InputObjectType is defined.
"""
- pass
+ global _INPUT_OBJECT_TYPE_DEFAULT_VALUE
+ _INPUT_OBJECT_TYPE_DEFAULT_VALUE = default_value
class InputObjectTypeContainer(dict, BaseType):
@@ -103,4 +104,4 @@ class InputObjectType(UnmountedType, BaseType):
This function is called when the unmounted type (InputObjectType instance)
is mounted (as a Field, InputField or Argument)
"""
- pass
+ return cls
diff --git a/graphene/types/mountedtype.py b/graphene/types/mountedtype.py
index ac4f6e7..91e4273 100644
--- a/graphene/types/mountedtype.py
+++ b/graphene/types/mountedtype.py
@@ -9,4 +9,6 @@ class MountedType(OrderedType):
"""
Mount the UnmountedType instance
"""
- pass
+ if isinstance(unmounted, UnmountedType):
+ return unmounted.get_type()
+ return unmounted
diff --git a/graphene/types/mutation.py b/graphene/types/mutation.py
index 1e5c548..9c42929 100644
--- a/graphene/types/mutation.py
+++ b/graphene/types/mutation.py
@@ -107,4 +107,12 @@ Read more: https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.m
def Field(cls, name=None, description=None, deprecation_reason=None,
required=False):
"""Mount instance of mutation Field."""
- pass
+ return Field(
+ cls._meta.output,
+ args=cls._meta.arguments,
+ resolver=cls._meta.resolver,
+ name=name,
+ description=description or cls._meta.description,
+ deprecation_reason=deprecation_reason,
+ required=required
+ )
diff --git a/graphene/types/scalars.py b/graphene/types/scalars.py
index b1a7427..adefc0b 100644
--- a/graphene/types/scalars.py
+++ b/graphene/types/scalars.py
@@ -32,23 +32,53 @@ class Scalar(UnmountedType, BaseType):
This function is called when the unmounted type (Scalar instance)
is mounted (as a Field, InputField or Argument)
"""
- pass
+ from graphql import GraphQLScalarType
+
+ return GraphQLScalarType(
+ name=cls._meta.name,
+ description=cls._meta.description,
+ serialize=cls.serialize,
+ parse_value=cls.parse_value,
+ parse_literal=cls.parse_literal,
+ )
MAX_INT = 2147483647
MIN_INT = -2147483648
+def coerce_int(value):
+ if isinstance(value, bool):
+ return 1 if value else 0
+ try:
+ int_value = int(value)
+ if MIN_INT <= int_value <= MAX_INT:
+ return int_value
+ except (TypeError, ValueError):
+ pass
+ raise ValueError(f"Int cannot represent non 32-bit signed integer value: {value}")
+
class Int(Scalar):
"""
The `Int` scalar type represents non-fractional signed whole numeric
- values. Int can represent values between -(2^53 - 1) and 2^53 - 1 since
+ values. Int can represent values between -(2^31) and 2^31 - 1 since
represented in JSON as double-precision floating point numbers specified
by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point).
"""
serialize = coerce_int
parse_value = coerce_int
+ @classmethod
+ def parse_literal(cls, node):
+ if isinstance(node, IntValueNode):
+ return coerce_int(node.value)
+
+
+def coerce_big_int(value):
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ raise ValueError(f"BigInt cannot represent non-integer value: {value}")
class BigInt(Scalar):
"""
@@ -56,9 +86,19 @@ class BigInt(Scalar):
`BigInt` is not constrained to 32-bit like the `Int` type and thus is a less
compatible type.
"""
- serialize = coerce_int
- parse_value = coerce_int
+ serialize = coerce_big_int
+ parse_value = coerce_big_int
+ @classmethod
+ def parse_literal(cls, node):
+ if isinstance(node, IntValueNode):
+ return coerce_big_int(node.value)
+
+def coerce_float(value):
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ raise ValueError(f"Float cannot represent non numeric value: {value}")
class Float(Scalar):
"""
@@ -69,6 +109,21 @@ class Float(Scalar):
serialize = coerce_float
parse_value = coerce_float
+ @classmethod
+ def parse_literal(cls, node):
+ if isinstance(node, (FloatValueNode, IntValueNode)):
+ return coerce_float(node.value)
+
+def coerce_string(value):
+ if isinstance(value, str):
+ return value
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, int) or isinstance(value, float):
+ return str(value)
+ if isinstance(value, dict) or isinstance(value, list):
+ raise ValueError(f"String cannot represent value: {value}")
+ return str(value)
class String(Scalar):
"""
@@ -79,6 +134,11 @@ class String(Scalar):
serialize = coerce_string
parse_value = coerce_string
+ @classmethod
+ def parse_literal(cls, node):
+ if isinstance(node, StringValueNode):
+ return node.value
+
class Boolean(Scalar):
"""
@@ -87,6 +147,10 @@ class Boolean(Scalar):
serialize = bool
parse_value = bool
+ @classmethod
+ def parse_literal(cls, node):
+ if isinstance(node, BooleanValueNode):
+ return node.value
class ID(Scalar):
"""
@@ -98,3 +162,8 @@ class ID(Scalar):
"""
serialize = str
parse_value = str
+
+ @classmethod
+ def parse_literal(cls, node):
+ if isinstance(node, (StringValueNode, IntValueNode)):
+ return node.value
diff --git a/graphene/types/schema.py b/graphene/types/schema.py
index 1227a4c..9eed481 100644
--- a/graphene/types/schema.py
+++ b/graphene/types/schema.py
@@ -43,7 +43,15 @@ class TypeMap(dict):
def get_function_for_type(self, graphene_type, func_name, name,
default_value):
"""Gets a resolve or subscribe function for a given ObjectType"""
- pass
+ if isinstance(graphene_type, ObjectType):
+ func = getattr(graphene_type, func_name, None)
+ if func:
+ return func
+ if isinstance(graphene_type, type):
+ func = getattr(graphene_type, func_name, None)
+ if func:
+ return get_unbound_function(func)
+ return default_value
class Schema:
@@ -117,19 +125,29 @@ class Schema:
Returns:
:obj:`ExecutionResult` containing any data and errors for the operation.
"""
- pass
+ kwargs = normalize_execute_kwargs(kwargs)
+ return graphql_sync(self.graphql_schema, *args, **kwargs)
async def execute_async(self, *args, **kwargs):
"""Execute a GraphQL query on the schema asynchronously.
Same as `execute`, but uses `graphql` instead of `graphql_sync`.
"""
- pass
+ kwargs = normalize_execute_kwargs(kwargs)
+ return await graphql(self.graphql_schema, *args, **kwargs)
async def subscribe(self, query, *args, **kwargs):
"""Execute a GraphQL subscription on the schema asynchronously."""
- pass
+ kwargs = normalize_execute_kwargs(kwargs)
+ document = parse(query)
+ return await subscribe(self.graphql_schema, document, *args, **kwargs)
def normalize_execute_kwargs(kwargs):
"""Replace alias names in keyword arguments for graphql()"""
- pass
+ if 'request_string' in kwargs:
+ kwargs['source'] = kwargs.pop('request_string')
+ if 'context_value' in kwargs:
+ kwargs['context'] = kwargs.pop('context_value')
+ if 'variable_values' in kwargs:
+ kwargs['variables'] = kwargs.pop('variable_values')
+ return kwargs
diff --git a/graphene/types/structures.py b/graphene/types/structures.py
index 155e1c0..8a3b153 100644
--- a/graphene/types/structures.py
+++ b/graphene/types/structures.py
@@ -24,7 +24,7 @@ class Structure(UnmountedType):
This function is called when the unmounted type (List or NonNull instance)
is mounted (as a Field, InputField or Argument)
"""
- pass
+ return get_type(self._of_type)
class List(Structure):
@@ -51,6 +51,9 @@ class List(Structure):
return isinstance(other, List) and (self.of_type == other.of_type and
self.args == other.args and self.kwargs == other.kwargs)
+ def get_type(self):
+ return List(get_type(self._of_type))
+
class NonNull(Structure):
"""
@@ -87,3 +90,6 @@ class NonNull(Structure):
return isinstance(other, NonNull) and (self.of_type == other.
of_type and self.args == other.args and self.kwargs == other.kwargs
)
+
+ def get_type(self):
+ return NonNull(get_type(self._of_type))
diff --git a/graphene/types/union.py b/graphene/types/union.py
index cabc8df..9e60ecf 100644
--- a/graphene/types/union.py
+++ b/graphene/types/union.py
@@ -61,4 +61,4 @@ class Union(UnmountedType, BaseType):
This function is called when the unmounted type (Union instance)
is mounted (as a Field, InputField or Argument)
"""
- pass
+ return cls
diff --git a/graphene/types/unmountedtype.py b/graphene/types/unmountedtype.py
index 5ca42ce..a786f90 100644
--- a/graphene/types/unmountedtype.py
+++ b/graphene/types/unmountedtype.py
@@ -49,25 +49,28 @@ class UnmountedType(OrderedType):
This function is called when the UnmountedType instance
is mounted (as a Field, InputField or Argument)
"""
- pass
+ return self.__class__
def Field(self):
"""
Mount the UnmountedType as Field
"""
- pass
+ from .field import Field
+ return Field(self.get_type(), *self.args, **self.kwargs)
def InputField(self):
"""
Mount the UnmountedType as InputField
"""
- pass
+ from .inputfield import InputField
+ return InputField(self.get_type(), *self.args, **self.kwargs)
def Argument(self):
"""
Mount the UnmountedType as Argument
"""
- pass
+ from .argument import Argument
+ return Argument(self.get_type(), *self.args, **self.kwargs)
def __eq__(self, other):
return self is other or isinstance(other, UnmountedType
diff --git a/graphene/types/utils.py b/graphene/types/utils.py
index 4c05498..e38c796 100644
--- a/graphene/types/utils.py
+++ b/graphene/types/utils.py
@@ -9,7 +9,11 @@ def get_field_as(value, _as=None):
"""
Get type mounted
"""
- pass
+ if isinstance(value, MountedType):
+ return value
+ elif isinstance(value, UnmountedType):
+ return value.mount_as(_as)
+ return _as(value) if _as else value
def yank_fields_from_attrs(attrs, _as=None, sort=True):
@@ -17,9 +21,17 @@ def yank_fields_from_attrs(attrs, _as=None, sort=True):
Extract all the fields in given attributes (dict)
and return them ordered
"""
- pass
+ fields = []
+ for key, value in attrs.items():
+ if isinstance(value, UnmountedType):
+ fields.append((key, get_field_as(value, _as)))
+ if sort:
+ fields = sorted(fields, key=lambda f: f[1])
+ return fields
def get_underlying_type(_type):
"""Get the underlying type even if it is wrapped in structures like NonNull"""
- pass
+ while hasattr(_type, 'of_type'):
+ _type = _type.of_type
+ return _type
diff --git a/graphene/utils/dataloader.py b/graphene/utils/dataloader.py
index a7136e2..dff0c14 100644
--- a/graphene/utils/dataloader.py
+++ b/graphene/utils/dataloader.py
@@ -33,11 +33,78 @@ class DataLoader(object):
self._cache = cache_map if cache_map is not None else {}
self._queue = []
+ def _schedule_dispatch(self):
+ if not self._queue:
+ return
+ if not hasattr(self, '_dispatch_task') or self._dispatch_task.done():
+ loop = self._loop or get_event_loop()
+ self._dispatch_task = loop.call_soon(dispatch_queue, self)
+
+ def _dispatch_single(self, key, future):
+ try:
+ result = self.batch_load_fn([key])
+ if iscoroutine(result):
+ future.add_done_callback(
+ partial(self._handle_future_result, key=key)
+ )
+ ensure_future(result).add_done_callback(
+ partial(self._handle_batch_result, future=future)
+ )
+ else:
+ self._handle_batch_result(result, future)
+ except Exception as exc:
+ future.set_exception(exc)
+
+ def _handle_future_result(self, _, key):
+ if not self.cache:
+ return
+ cache_key = self.get_cache_key(key)
+ if cache_key in self._cache:
+ del self._cache[cache_key]
+
+ def _handle_batch_result(self, batch_future, future):
+ try:
+ results = batch_future.result() if hasattr(batch_future, 'result') else batch_future
+ if len(results) != 1:
+ raise ValueError(
+ f"DataLoader must be constructed with a function which accepts "
+ f"Iterable<key> and returns Future<Iterable<value>>, but the function did "
+ f"not return a list of the same length as the keys."
+ f"\nResults:\n{results}"
+ )
+ future.set_result(results[0])
+ except Exception as exc:
+ future.set_exception(exc)
+
+def iscoroutinefunctionorpartial(obj):
+ while isinstance(obj, partial):
+ obj = obj.func
+ return iscoroutinefunction(obj)
+
def load(self, key=None):
"""
Loads a key, returning a `Future` for the value represented by that key.
"""
- pass
+ if key is None:
+ raise ValueError("The load method must be called with a key, but got None.")
+
+ cache_key = self.get_cache_key(key)
+
+ if self.cache and cache_key in self._cache:
+ return self._cache[cache_key]
+
+ future = self._loop.create_future() if self._loop else get_event_loop().create_future()
+ self._queue.append(Loader(key=key, future=future))
+
+ if self.batch:
+ self._schedule_dispatch()
+ else:
+ self._dispatch_single(key, future)
+
+ if self.cache:
+ self._cache[cache_key] = future
+
+ return future
def load_many(self, keys):
"""
@@ -52,14 +119,20 @@ class DataLoader(object):
>>> my_loader.load('b')
>>> )
"""
- pass
+ if not isinstance(keys, Iterable):
+ raise TypeError(f"The loader.load_many() method must be called with Iterable<key> but got: {keys}")
+
+ return gather(*[self.load(key) for key in keys])
def clear(self, key):
"""
Clears the value at `key` from the cache, if it exists. Returns itself for
method chaining.
"""
- pass
+ cache_key = self.get_cache_key(key)
+ if cache_key in self._cache:
+ del self._cache[cache_key]
+ return self
def clear_all(self):
"""
@@ -67,14 +140,20 @@ class DataLoader(object):
invalidations across this particular `DataLoader`. Returns itself for
method chaining.
"""
- pass
+ self._cache.clear()
+ return self
def prime(self, key, value):
"""
- Adds the provied key and value to the cache. If the key already exists, no
+ Adds the provided key and value to the cache. If the key already exists, no
change is made. Returns itself for method chaining.
"""
- pass
+ cache_key = self.get_cache_key(key)
+ if cache_key not in self._cache:
+ future = self._loop.create_future() if self._loop else get_event_loop().create_future()
+ future.set_result(value)
+ self._cache[cache_key] = future
+ return self
def dispatch_queue(loader):
@@ -82,12 +161,55 @@ def dispatch_queue(loader):
Given the current state of a Loader instance, perform a batch load
from its current queue.
"""
- pass
+ queue = loader._queue
+ loader._queue = []
+
+ max_batch_size = loader.max_batch_size
+
+ if max_batch_size and max_batch_size < len(queue):
+ chunks = [queue[i:i + max_batch_size] for i in range(0, len(queue), max_batch_size)]
+ else:
+ chunks = [queue]
+
+ for chunk in chunks:
+ keys = [loader.key for loader in chunk]
+ futures = [loader.future for loader in chunk]
+ batch_future = ensure_future(loader.batch_load_fn(keys))
+ batch_future.add_done_callback(
+ partial(_batch_load_fn_callback, loader=loader, keys=keys, futures=futures)
+ )
-def failed_dispatch(loader, queue, error):
+def _batch_load_fn_callback(batch_future, loader, keys, futures):
+ try:
+ results = batch_future.result()
+ if len(results) != len(keys):
+ raise ValueError(
+ f"DataLoader must be constructed with a function which accepts "
+ f"Iterable<key> and returns Future<Iterable<value>>, but the function did "
+ f"not return a list of the same length as the keys."
+ f"\nKeys:\n{keys}"
+ f"\nResults:\n{results}"
+ )
+
+ for future, result in zip(futures, results):
+ if not future.done():
+ future.set_result(result)
+ except Exception as error:
+ failed_dispatch(loader, keys, error)
+
+
+def failed_dispatch(loader, keys, error):
"""
Do not cache individual loads if the entire batch dispatch fails,
but still reject each request so they do not hang.
"""
- pass
+ for key in keys:
+ cache_key = loader.get_cache_key(key)
+ if cache_key in loader._cache:
+ del loader._cache[cache_key]
+
+ for loader_item in loader._queue:
+ if loader_item.key == key:
+ if not loader_item.future.done():
+ loader_item.future.set_exception(error)
diff --git a/graphene/utils/deprecated.py b/graphene/utils/deprecated.py
index d561393..75bd981 100644
--- a/graphene/utils/deprecated.py
+++ b/graphene/utils/deprecated.py
@@ -10,4 +10,24 @@ def deprecated(reason):
as deprecated. It will result in a warning being emitted
when the function is used.
"""
- pass
+ def decorator(func):
+ if isinstance(func, type):
+ fmt = "Call to deprecated class {name} ({reason})."
+ else:
+ fmt = "Call to deprecated function {name} ({reason})."
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ warnings.warn(
+ fmt.format(name=func.__name__, reason=reason),
+ category=DeprecationWarning,
+ stacklevel=2
+ )
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ if isinstance(reason, string_types):
+ return decorator
+ else:
+ return decorator(reason)
diff --git a/graphene/utils/module_loading.py b/graphene/utils/module_loading.py
index 21e42a9..e9f8af8 100644
--- a/graphene/utils/module_loading.py
+++ b/graphene/utils/module_loading.py
@@ -10,4 +10,29 @@ def import_string(dotted_path, dotted_attributes=None):
the first step, and return the corresponding value designated by the
attribute path. Raise ImportError if the import failed.
"""
- pass
+ try:
+ module_path, class_name = dotted_path.rsplit('.', 1)
+ except ValueError as err:
+ raise ImportError("%s doesn't look like a module path" % dotted_path) from err
+
+ try:
+ module = import_module(module_path)
+ except ImportError as err:
+ raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
+ module_path, class_name)) from err
+
+ try:
+ attr = getattr(module, class_name)
+ except AttributeError as err:
+ raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
+ module_path, class_name)) from err
+
+ if dotted_attributes:
+ for attribute in dotted_attributes.split('.'):
+ try:
+ attr = getattr(attr, attribute)
+ except AttributeError as err:
+ raise ImportError('Module "%s" does not define a "%s" attribute' % (
+ dotted_path, dotted_attributes)) from err
+
+ return attr
diff --git a/graphene/utils/props.py b/graphene/utils/props.py
index 114245a..206396d 100644
--- a/graphene/utils/props.py
+++ b/graphene/utils/props.py
@@ -7,3 +7,20 @@ class _NewClass:
_all_vars = set(dir(_OldClass) + dir(_NewClass))
+
+
+def props(x):
+ """
+ Return a list of all properties (including methods) of the given object,
+ excluding those that are present in both _OldClass and _NewClass.
+ """
+ return [prop for prop in dir(x) if prop not in _all_vars]
+
+
+def get_props(x):
+ """
+ Return a dictionary of all properties (including methods) of the given object,
+ excluding those that are present in both _OldClass and _NewClass.
+ The keys are the property names, and the values are the property values.
+ """
+ return {prop: getattr(x, prop) for prop in props(x)}
diff --git a/graphene/utils/tests/test_dataloader.py b/graphene/utils/tests/test_dataloader.py
index 257f6b4..4438bc0 100644
--- a/graphene/utils/tests/test_dataloader.py
+++ b/graphene/utils/tests/test_dataloader.py
@@ -450,3 +450,50 @@ async def test_dataloader_clear_with_missing_key_works():
a_loader, a_load_calls = id_loader(resolve=do_resolve)
assert a_loader.clear("A1") == a_loader
+
+@mark.asyncio
+async def test_load_many_with_invalid_input():
+ identity_loader, _ = id_loader()
+ with raises(TypeError):
+ await identity_loader.load_many("not_an_iterable")
+
+@mark.asyncio
+async def test_load_with_none_key():
+ identity_loader, _ = id_loader()
+ with raises(ValueError):
+ await identity_loader.load(None)
+
+@mark.asyncio
+async def test_prime_and_clear():
+ identity_loader, load_calls = id_loader()
+
+ identity_loader.prime("A", "A_value")
+ identity_loader.prime("B", "B_value")
+
+ a = await identity_loader.load("A")
+ assert a == "A_value"
+ assert load_calls == []
+
+ identity_loader.clear("A")
+
+ a_reloaded = await identity_loader.load("A")
+ b = await identity_loader.load("B")
+
+ assert a_reloaded == "A"
+ assert b == "B_value"
+ assert load_calls == [["A"]]
+
+@mark.asyncio
+async def test_clear_all():
+ identity_loader, load_calls = id_loader()
+
+ identity_loader.prime("A", "A_value")
+ identity_loader.prime("B", "B_value")
+
+ identity_loader.clear_all()
+
+ a, b = await gather(identity_loader.load("A"), identity_loader.load("B"))
+
+ assert a == "A"
+ assert b == "B"
+ assert load_calls == [["A", "B"]]
diff --git a/graphene/utils/thenables.py b/graphene/utils/thenables.py
index 0ad5e44..8513c63 100644
--- a/graphene/utils/thenables.py
+++ b/graphene/utils/thenables.py
@@ -10,4 +10,9 @@ def maybe_thenable(obj, on_resolve):
returning the same type of object inputed.
If the object is not thenable, it should return on_resolve(obj)
"""
- pass
+ if isawaitable(obj):
+ async def resolve():
+ resolved = await obj
+ return on_resolve(resolved)
+ return resolve()
+ return on_resolve(obj)
diff --git a/graphene/validation/disable_introspection.py b/graphene/validation/disable_introspection.py
index d18720b..4fb6c60 100644
--- a/graphene/validation/disable_introspection.py
+++ b/graphene/validation/disable_introspection.py
@@ -5,4 +5,9 @@ from ..utils.is_introspection_key import is_introspection_key
class DisableIntrospection(ValidationRule):
- pass
+ def enter_field(self, node: FieldNode, *args):
+ if is_introspection_key(node.name.value):
+ raise GraphQLError(
+ f"GraphQL introspection is not allowed, but the query contained {node.name.value}",
+ [node]
+ )