对kotti_image项目进行pytest测试操作实践(失败)
对kotti_image项目进行pytest测试操作实践
因为前期在升级kotti_image到kotti_image2的过程中,pytest报错,于是准备在kotti_image下先试用pytest测试一下,以便解决kotti_image2 测试报错的问题。
系统Ubuntu22.04
python环境:python3.12
后改成python3.10 ,后又改成python3.9 ,但是都测试没通过.....估计是kotti_image太老了,跟很多库不匹配导致的。
源码安装kotti
git clone https://gitcode.com/gh_mirrors/ko/Kotti
cd Kotti
pip install -r requirements.txt
源码安装kotti_image
首先fork kotti_image项目到自己的账号,
git clone下载到本地:
git clone https://github.com/skywalk163/kotti_image
进入目录,pip安装
cd kotti_image
pip install -e .
显示输出
pip install -e .
Defaulting to user installation because normal site-packages is not writeable
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Obtaining file:///home/skywalk/github/kotti_imageInstalling build dependencies ... doneChecking if build backend supports build_editable ... done
安装附加库
pip install mock
pip install pytest-cov
pip install webtest
安装测试库
pip install -e ".[testing]"
到了这才明白,原来测试需要安装测试库,怪不得在项目根目录找不到测试需要安装的库,原来是写到setup.py文件里面了,需要使用 pip install -e ".[testing]" 语句来安装
最终
安装Kotti==2.0.9
pip install Kotti==2.0.9 --break-system-packages
然后测试的时候加上这句:
pytest -p no:typeguard
调试
pytest报错AttributeError: module 'sqlalchemy.ext.baked' has no attribute 'bake_lazy_loaders'
pytest
Traceback (most recent call last):File "/usr/local/bin/pytest", line 8, in <module>sys.exit(console_main())^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/_pytest/config/__init__.py", line 197, in console_maincode = main()^^^^^^File "/usr/local/lib/python3.11/site-packages/_pytest/config/__init__.py", line 155, in mainconfig = _prepareconfig(args, plugins)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/_pytest/config/__init__.py", line 337, in _prepareconfigconfig = pluginmanager.hook.pytest_cmdline_parse(^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/pluggy/_hooks.py", line 513, in __call__return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/pluggy/_manager.py", line 120, in _hookexecreturn self._inner_hookexec(hook_name, methods, kwargs, firstresult)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/pluggy/_callers.py", line 139, in _multicallraise exception.with_traceback(exception.__traceback__)File "/usr/local/lib/python3.11/site-packages/pluggy/_callers.py", line 122, in _multicallteardown.throw(exception) # type: ignore[union-attr]^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/_pytest/helpconfig.py", line 105, in pytest_cmdline_parseconfig = yield^^^^^File "/usr/local/lib/python3.11/site-packages/pluggy/_callers.py", line 103, in _multicallres = hook_impl.function(*args)^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1143, in pytest_cmdline_parseself.parse(args)File "/usr/local/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1492, in parseself._preparse(args, addopts=addopts)File "/usr/local/lib/python3.11/site-packages/_pytest/config/__init__.py", line 1379, in _preparseself.pluginmanager.load_setuptools_entrypoints("pytest11")File "/usr/local/lib/python3.11/site-packages/pluggy/_manager.py", line 421, in load_setuptools_entrypointsplugin = ep.load()^^^^^^^^^File "/usr/local/lib/python3.11/importlib/metadata/__init__.py", line 202, in loadmodule = import_module(match.group('module'))^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_modulereturn _bootstrap._gcd_import(name[level:], package, level)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "<frozen importlib._bootstrap>", line 1204, in _gcd_importFile "<frozen importlib._bootstrap>", line 1176, in _find_and_loadFile "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlockedFile "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removedFile "<frozen importlib._bootstrap>", line 1204, in _gcd_importFile "<frozen importlib._bootstrap>", line 1176, in _find_and_loadFile "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlockedFile "<frozen importlib._bootstrap>", line 690, in _load_unlockedFile "/usr/local/lib/python3.11/site-packages/_pytest/assertion/rewrite.py", line 178, in exec_moduleexec(co, module.__dict__)File "/home/skywalk/.local/lib/python3.11/site-packages/kotti/__init__.py", line 18, in <module>from kotti.sqla import Base as KottiBaseFile "<frozen importlib._bootstrap>", line 1176, in _find_and_loadFile "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlockedFile "<frozen importlib._bootstrap>", line 690, in _load_unlockedFile "/usr/local/lib/python3.11/site-packages/_pytest/assertion/rewrite.py", line 178, in exec_moduleexec(co, module.__dict__)File "/home/skywalk/.local/lib/python3.11/site-packages/kotti/sqla.py", line 17, in <module>baked.bake_lazy_loaders()^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'sqlalchemy.ext.baked' has no attribute 'bake_lazy_loaders'
一看,sqlachemy的版本不对啊!当前是:SQLAlchemy 2.0.41
kotti需要的是:SQLAlchemy==1.4.36
用pip安装kotti,版本无法控制住,一定要pip install安装,才能控制住版本。
pytest报错error: unrecognized arguments: --cov=kotti_image --cov-report=term-missing --cov-config kotti_image/tests
skywalk@fb:~/github/kotti_image $ pytest
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --cov=kotti_image --cov-report=term-missing --cov-config kotti_image/testsinifile: /home/skywalk/github/kotti_image/pytest.inirootdir: /home/skywalk/github/kotti_image
当前pytest8.1.1版本,降低版本试试,不行。后来发现是这个错误表明pytest 命令中使用了 --cov
相关参数,但系统没有安装 pytest-cov 插件。以下是解决方案:
安装必要插件
pip install pytest-cov
pytest报错:超长信息输出
kotti_image/tests/test_functional.py FF
kotti_image/tests/test_scaling.py .
================================================== FAILURES ===================================================
_______________________________________________ test_add_images _______________________________________________
request = <Request at 0x3f498b82cf50 GET http://localhost/my-gallery>
exc = NotImplementedError("Can't perform this operation for unregistered loader type")
def _error_handler(request, exc):
# NOTE: we do not need to delete exc_info because this function
# should never be in the call stack of the exception
exc_info = sys.exc_info()
try:
> response = request.invoke_exception_view(exc_info)
../../.local/lib/python3.11/site-packages/pyramid/tweens.py:13:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <Request at 0x3f498b82cf50 GET http://localhost/my-gallery>
exc_info = (<class 'NotImplementedError'>, NotImplementedError("Can't perform this operation for unregistered loader type"), <traceback object at 0x3f498b86b480>)
request = <Request at 0x3f498b82cf50 GET http://localhost/my-gallery>, secure = True, reraise = False
def invoke_exception_view(
self, exc_info=None, request=None, secure=True, reraise=False
):
"""Executes an exception view related to the request it's called upon.
The arguments it takes are these:
``exc_info``
If provided, should be a 3-tuple in the form provided by
``sys.exc_info()``. If not provided,
``sys.exc_info()`` will be called to obtain the current
interpreter exception information. Default: ``None``.
``request``
If the request to be used is not the same one as the instance that
this method is called upon, it may be passed here. Default:
``None``.
``secure``
If the exception view should not be rendered if the current user
does not have the appropriate permission, this should be ``True``.
Default: ``True``.
``reraise``
A boolean indicating whether the original error should be reraised
if a :term:`response` object could not be created. If ``False``
then an :class:`pyramid.httpexceptions.HTTPNotFound`` exception
will be raised. Default: ``False``.
If a response is generated then ``request.exception`` and
``request.exc_info`` will be left at the values used to render the
response. Otherwise the previous values for ``request.exception`` and
``request.exc_info`` will be restored.
.. versionadded:: 1.7
.. versionchanged:: 1.9
The ``request.exception`` and ``request.exc_info`` properties will
reflect the exception used to render the response where previously
they were reset to the values prior to invoking the method.
Also added the ``reraise`` argument.
"""
if request is None:
request = self
registry = getattr(request, 'registry', None)
if registry is None:
registry = get_current_registry()
if registry is None:
raise RuntimeError("Unable to retrieve registry")
if exc_info is None:
exc_info = sys.exc_info()
exc = exc_info[1]
attrs = request.__dict__
context_iface = providedBy(exc)
# clear old generated request.response, if any; it may
# have been mutated by the view, and its state is not
# sane (e.g. caching headers)
with hide_attrs(request, 'response', 'exc_info', 'exception'):
attrs['exception'] = exc
attrs['exc_info'] = exc_info
# we use .get instead of .__getitem__ below due to
# https://github.com/Pylons/pyramid/issues/700
request_iface = attrs.get('request_iface', IRequest)
manager.push({'request': request, 'registry': registry})
try:
response = _call_view(
registry,
request,
exc,
context_iface,
'',
view_types=None,
view_classifier=IExceptionViewClassifier,
secure=secure,
request_iface=request_iface.combined,
)
except Exception:
if reraise:
reraise_(*exc_info)
raise
finally:
manager.pop()
if response is None:
if reraise:
reraise_(*exc_info)
> raise HTTPNotFound
E pyramid.httpexceptions.HTTPNotFound: The resource could not be found.
../../.local/lib/python3.11/site-packages/pyramid/view.py:795: HTTPNotFound
During handling of the above exception, another exception occurred:
webtest = <webtest.app.TestApp object at 0x3f498b808f90>, gallery = None
assets = {'img1': {'content': b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xed\x00\\Photoshop 3.0\x008B...\x08\x00\x00\xc0K/\x00NO\xdciHu~;\x00\x00\x00\x00IEND\xaeB`\x82', 'content_type': 'image/png', 'filename': 'logo.png'}}
@pytest.mark.user("admin")
def test_add_images(webtest, gallery, assets):
# add img 1
> resp = webtest.app.get("/my-gallery")
kotti_image/tests/test_functional.py:41:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
../../.local/lib/python3.11/site-packages/webtest/app.py:328: in get
return self.do_request(req, status=status,
../../.local/lib/python3.11/site-packages/webtest/app.py:627: in do_request
res = req.get_response(app, catch_exc_info=True)
../../.local/lib/python3.11/site-packages/webob/request.py:1309: in send
status, headers, app_iter, exc_info = self.call_application(
../../.local/lib/python3.11/site-packages/webob/request.py:1278: in call_application
app_iter = application(self.environ, start_response)
../../.local/lib/python3.11/site-packages/webtest/lint.py:196: in lint_app
iterator = application(environ, start_response_wrapper)
../../.local/lib/python3.11/site-packages/pyramid/router.py:274: in __call__
response = self.execution_policy(environ, self)
../../.local/lib/python3.11/site-packages/pyramid/router.py:283: in default_execution_policy
return request.invoke_exception_view(reraise=True)
../../.local/lib/python3.11/site-packages/pyramid/view.py:794: in invoke_exception_view
reraise_(*exc_info)
../../.local/lib/python3.11/site-packages/pyramid/_compat.py:179: in reraise
raise value
../../.local/lib/python3.11/site-packages/pyramid/router.py:281: in default_execution_policy
return router.invoke_request(request)
../../.local/lib/python3.11/site-packages/pyramid/router.py:249: in invoke_request
response = handle_request(request)
../../.local/lib/python3.11/site-packages/kotti/filedepot.py:582: in __call__
response = self.handler(request)
../../.local/lib/python3.11/site-packages/pyramid/tweens.py:43: in excview_tween
response = _error_handler(request, exc)
../../.local/lib/python3.11/site-packages/pyramid/tweens.py:17: in _error_handler
reraise(*exc_info)
../../.local/lib/python3.11/site-packages/pyramid/_compat.py:179: in reraise
raise value
../../.local/lib/python3.11/site-packages/pyramid/tweens.py:41: in excview_tween
response = handler(request)
../../.local/lib/python3.11/site-packages/pyramid/router.py:147: in handle_request
response = _call_view(
../../.local/lib/python3.11/site-packages/pyramid/view.py:683: in _call_view
response = view_callable(context, request)
../../.local/lib/python3.11/site-packages/pyramid/viewderivers.py:401: in viewresult_to_response
result = view(context, request)
../../.local/lib/python3.11/site-packages/kotti/views/view.py:24: in view_content_default
response = render_view_to_response(context, request, name=view_name)
../../.local/lib/python3.11/site-packages/pyramid/view.py:75: in render_view_to_response
response = _call_view(
../../.local/lib/python3.11/site-packages/pyramid/view.py:683: in _call_view
response = view_callable(context, request)
../../.local/lib/python3.11/site-packages/pyramid/viewderivers.py:325: in secured_view
return view(context, request)
../../.local/lib/python3.11/site-packages/pyramid/viewderivers.py:459: in rendered_view
response = view_renderer.render_view(
../../.local/lib/python3.11/site-packages/pyramid/renderers.py:451: in render_view
return self.render_to_response(response, system, request=request)
../../.local/lib/python3.11/site-packages/pyramid/renderers.py:474: in render_to_response
result = self.render(value, system_values, request=request)
../../.local/lib/python3.11/site-packages/pyramid/renderers.py:454: in render
renderer = self.renderer
../../.local/lib/python3.11/site-packages/pyramid/decorator.py:40: in __get__
val = self.wrapped(inst)
../../.local/lib/python3.11/site-packages/pyramid/renderers.py:436: in renderer
return factory(self)
../../.local/lib/python3.11/site-packages/pyramid_chameleon/zpt.py:10: in renderer_factory
return renderer.template_renderer_factory(info, ZPTTemplateRenderer)
../../.local/lib/python3.11/site-packages/pyramid_chameleon/renderer.py:140: in template_renderer_factory
return lookup(info)
../../.local/lib/python3.11/site-packages/pyramid_chameleon/renderer.py:116: in __call__
if not pkg_resources.resource_exists(package_name, filename):
/usr/local/lib/python3.11/site-packages/pkg_resources/__init__.py:1144: in resource_exists
return get_provider(package_or_requirement).has_resource(resource_name)
/usr/local/lib/python3.11/site-packages/pkg_resources/__init__.py:1415: in has_resource
return self._has(self._fn(self.module_path, resource_name))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <pkg_resources.NullProvider object at 0x3f498b86aed0>
path = '/home/skywalk/.local/lib/python3.11/site-packages/kotti/templates/view/document.pt'
def _has(self, path):
> raise NotImplementedError(
"Can't perform this operation for unregistered loader type"
)
E NotImplementedError: Can't perform this operation for unregistered loader type
/usr/local/lib/python3.11/site-packages/pkg_resources/__init__.py:1482: NotImplementedError
____________________________________________ TestTween.test_tween _________________________________
太长了,不光我找不到问题所在,AI也给出了很多建议,证明它也没法快速定位问题所在。
终于找到原因了,是没有安装测试的库啊!
pip install -e ".[testing]"
pytest报错ImportError: cannot import name 'console_main' from 'pytest'
pytest
Traceback (most recent call last):
File "/usr/local/bin/pytest", line 5, in <module>
from pytest import console_main
ImportError: cannot import name 'console_main' from 'pytest' (/home/skywalk/.local/lib/python3.11/site-packages/pytest.py)
升级到最新版
pip install pytest -U
Successfully installed pluggy-1.6.0 pytest-8.4.1
报错变成这样:
______________________________________ ERROR at setup of test_add_images ______________________________________
file /home/skywalk/github/kotti_image/kotti_image/tests/test_functional.py, line 37@pytest.mark.user("admin")def test_add_images(webtest, gallery, assets):
E fixture 'webtest' not found
> available fixtures: anyio_backend, anyio_backend_name, anyio_backend_options, app, assets, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, cov, custom_settings, dash_br, dash_duo, dash_duo_mp, dash_multi_process_server, dash_process_server, dash_thread_server, dashjl, dashjl_server, dashr, dashr_server, diskcache_manager, doctest_namespace, free_tcp_port, free_tcp_port_factory, free_udp_port, free_udp_port_factory, gallery, monkeypatch, no_cover, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, virtualenv, workspace
> use 'pytest --fixtures [testpath]' for help on them./home/skywalk/github/kotti_image/kotti_image/tests/test_functional.py:37
___________________________________ ERROR at setup of TestTween.test_tween ____________________________________
file /home/skywalk/github/kotti_image/kotti_image/tests/test_functional.py, line 164@pytest.mark.user("admin")def test_tween(self, connection, webtest, filedepot, root, image_asset, db_session):
E fixture 'connection' not found
> available fixtures: anyio_backend, anyio_backend_name, anyio_backend_options, app, assets, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, cov, custom_settings, dash_br, dash_duo, dash_duo_mp, dash_multi_process_server, dash_process_server, dash_thread_server, dashjl, dashjl_server, dashr, dashr_server, diskcache_manager, doctest_namespace, free_tcp_port, free_tcp_port_factory, free_udp_port, free_udp_port_factory, gallery, monkeypatch, no_cover, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, virtualenv, workspace
> use 'pytest --fixtures [testpath]' for help on them./home/skywalk/github/kotti_image/kotti_image/tests/test_functional.py:164
================================================== FAILURES ===================================================
_________________________________________ test_image_scale_loading_it _________________________________________def test_image_scale_loading_it():> from kotti_image.views import _load_image_scales, image_scaleskotti_image/tests/test_scaling.py:3:
pytest测试的时候非常慢
不知道是机器原因还是怎么回事,非常慢
同时运行的infini-synapse也是卡在那里
最后结果终于出来了:
TOTAL 3975 337 92%
=========================================== short test summary info ===========================================
FAILED kotti/tests/test_app.py::flake-8::FLAKE8
FAILED kotti/tests/test_file.py::TestFileEditForm::test_edit_without_file - TypeError: a bytes-like object is required, not 'FieldStorage'
FAILED kotti/tests/test_file.py::TestDepotStore::test_create[File] - TypeError: a bytes-like object is required, not 'FieldStorage'
FAILED kotti/tests/test_file.py::TestDepotStore::test_edit_content[File] - TypeError: a bytes-like object is required, not 'FieldStorage'
FAILED kotti/tests/test_file.py::TestUploadedFileResponse::test_unknown_filename - AssertionError: assert 'application/....brew-app-res' == 'application/octet-stream'
FAILED kotti/tests/test_file.py::TestStoredFileResponse::test_unknown_filename - AssertionError: assert 'application/....brew-app-res' == 'application/octet-stream'
FAILED kotti/tests/test_tags.py::flake-8::FLAKE8
=========================== 7 failed, 447 passed, 5 warnings in 3763.17s (1:02:43) ============================
勉强算pass
pytest kotti_image报错
Traceback (most recent call last):File "<frozen importlib._bootstrap>", line 939, in _find_spec
AttributeError: 'AssertionRewritingHook' object has no attribute 'find_spec'During handling of the above exception, another exception occurred:Traceback (most recent call last):File "/home/skywalk/.local/bin/pytest", line 8, in <module>sys.exit(main())File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 65, in mainconfig = _prepareconfig(args, plugins)File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 213, in _prepareconfigreturn pluginmanager.hook.pytest_cmdline_parse(File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/hooks.py", line 286, in __call__return self._hookexec(self, self.get_hookimpls(), kwargs)File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/manager.py", line 93, in _hookexecreturn self._inner_hookexec(hook, methods, kwargs)File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/manager.py", line 84, in <lambda>self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/callers.py", line 203, in _multicallgen.send(outcome)File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/helpconfig.py", line 94, in pytest_cmdline_parseconfig = outcome.get_result()File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/callers.py", line 80, in get_resultraise ex[1].with_traceback(ex[2])File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/callers.py", line 187, in _multicallres = hook_impl.function(*args)File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 789, in pytest_cmdline_parseself.parse(args)File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 997, in parseself._preparse(args, addopts=addopts)File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/config/__init__.py", line 943, in _preparseself.pluginmanager.load_setuptools_entrypoints("pytest11")File "/home/skywalk/.local/lib/python3.10/site-packages/pluggy/manager.py", line 299, in load_setuptools_entrypointsplugin = ep.load()File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 171, in loadmodule = import_module(match.group('module'))File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_modulereturn _bootstrap._gcd_import(name[level:], package, level)File "<frozen importlib._bootstrap>", line 1050, in _gcd_importFile "<frozen importlib._bootstrap>", line 1027, in _find_and_loadFile "<frozen importlib._bootstrap>", line 1002, in _find_and_load_unlockedFile "<frozen importlib._bootstrap>", line 941, in _find_specFile "<frozen importlib._bootstrap>", line 915, in _find_spec_legacyFile "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/assertion/rewrite.py", line 169, in find_modulesource_stat, co = _rewrite_test(self.config, fn_pypath)File "/home/skywalk/.local/lib/python3.10/site-packages/_pytest/assertion/rewrite.py", line 406, in _rewrite_testco = compile(tree, fn.strpath, "exec", dont_inherit=True)
TypeError: required field "lineno" missing from alias
尝试重装pytest
pip uninstall pytest pytest-cov pytest-mock -y
pip install --force-reinstall pytest pytest-cov pytest-mock
现在可以测试了,测试输出:
============================================== warnings summary ===============================================
kotti_image/tests/test_functional.py::test_add_images
kotti_image/tests/test_functional.py::TestTween::test_tween/home/skywalk/github/kotti/kotti/tests/__init__.py:205: SAWarning: transaction already deassociated from connectiontrans.rollback()-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
=============================================== tests coverage ================================================
______________________________ coverage: platform linux, python 3.10.12-final-0 _______________________________Name Stmts Miss Cover Missing
-------------------------------------------------------------
kotti_image/__init__.py 9 0 100%
kotti_image/interfaces.py 2 0 100%
kotti_image/resources.py 14 0 100%
kotti_image/views/__init__.py 45 23 49% 41-42, 52, 73-117, 128-130
kotti_image/views/edit.py 11 0 100%
-------------------------------------------------------------
TOTAL 81 23 72%
=========================================== short test summary info ===========================================
FAILED kotti_image/tests/test_functional.py::test_add_images - NotImplementedError: Can't perform this operation for unregistered loader type
FAILED kotti_image/tests/test_functional.py::TestTween::test_tween - AttributeError: seek
这个测试就没有过啊!
尝试
pip install -e ".[testing]"
这回的pytest又有了新进展,有如下报错
pytest kotti_image报错ModuleNotFoundError: No module named 'imp'
pytest
Traceback (most recent call last):
File "/home/skywalk/py312/bin/pytest", line 5, in <module>
from pytest import main
File "/home/skywalk/py312/lib/python3.12/site-packages/pytest.py", line 8, in <module>
from _pytest.assertion import register_assert_rewrite
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/assertion/__init__.py", line 13, in <module>
from _pytest.assertion import rewrite
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/assertion/rewrite.py", line 9, in <module>
import imp
ModuleNotFoundError: No module named 'imp'
- 在 Python 3.4 及以后的版本中,
imp
模块已被标记为过时(deprecated),并在 Python 3.10 中被完全移除。
当前Name: pytest
Version: 4.6.11
是不是pytest版本太低的缘故?
升级到5.3.3
pytest升级到5.3.3报错:TypeError: required field "lineno" missing from alias
Traceback (most recent call last):
File "/home/skywalk/py312/bin/pytest", line 8, in <module>
sys.exit(main())
^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/config/__init__.py", line 73, in main
config = _prepareconfig(args, plugins)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/config/__init__.py", line 223, in _prepareconfig
return pluginmanager.hook.pytest_cmdline_parse(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/hooks.py", line 286, in __call__
return self._hookexec(self, self.get_hookimpls(), kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/manager.py", line 93, in _hookexec
return self._inner_hookexec(hook, methods, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/manager.py", line 84, in <lambda>
self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/callers.py", line 203, in _multicall
gen.send(outcome)
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/helpconfig.py", line 89, in pytest_cmdline_parse
config = outcome.get_result()
^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/callers.py", line 80, in get_result
raise ex[1].with_traceback(ex[2])
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/callers.py", line 187, in _multicall
res = hook_impl.function(*args)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/config/__init__.py", line 794, in pytest_cmdline_parse
self.parse(args)
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/config/__init__.py", line 1000, in parse
self._preparse(args, addopts=addopts)
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/config/__init__.py", line 948, in _preparse
self.pluginmanager.load_setuptools_entrypoints("pytest11")
File "/home/skywalk/py312/lib/python3.12/site-packages/pluggy/manager.py", line 299, in load_setuptools_entrypoints
plugin = ep.load()
^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/importlib/metadata/__init__.py", line 205, in load
module = import_module(match.group('module'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/importlib/__init__.py", line 90, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/assertion/rewrite.py", line 134, in exec_module
source_stat, co = _rewrite_test(fn, self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/skywalk/py312/lib/python3.12/site-packages/_pytest/assertion/rewrite.py", line 321, in _rewrite_test
co = compile(tree, fn, "exec", dont_inherit=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: required field "lineno" missing from alias
根本原因 Python 3.12兼容性问题:
不对啊,我是python3.10啊,去看了一下,晕,怎么又变成python3.12啦!
换成python3.10 有报错:
,这回的3.10有点特殊,所以用路径来使用:
/usr/bin/python3.10 -m pytest
原来是pytest-4.6.11
换成5.3.3
/usr/bin/python3.10 -m pip install pytest==5.3.3
现在的问题是5.3.3在python3.10下也是报错 TypeError: required field "lineno" missing from alias
升级到新版本:
/usr/bin/python3.10 -m pip install --upgrade pytest pytest-covSuccessfully installed pluggy-1.6.0 pytest-8.4.1 pytest-cov-6.2.1 pytest-xdist-3.7.0
现在报错
FAILED kotti_image/tests/test_functional.py::test_add_images - NotImplementedError: Can't perform this operation for unregistered loader type
FAILED kotti_image/tests/test_functional.py::TestTween::test_tween - AttributeError: seek
重新安装了python3.9版本环境,测试报错TypeError: __call__() got an unexpected keyword argument 'wrapper'
报错
File "/home/skywalk/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/importlib/__init__.py", line 127, in import_modulereturn _bootstrap._gcd_import(name[level:], package, level)File "<frozen importlib._bootstrap>", line 1030, in _gcd_importFile "<frozen importlib._bootstrap>", line 1007, in _find_and_loadFile "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlockedFile "<frozen importlib._bootstrap>", line 664, in _load_unlockedFile "<frozen importlib._bootstrap>", line 627, in _load_backward_compatibleFile "/home/skywalk/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/site-packages/_pytest/assertion/rewrite.py", line 304, in load_moduleexec(co, mod.__dict__)File "/home/skywalk/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/site-packages/pytest_cov/plugin.py", line 201, in <module>class CovPlugin:File "/home/skywalk/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/site-packages/pytest_cov/plugin.py", line 318, in CovPlugin@pytest.hookimpl(wrapper=True)
TypeError: __call__() got an unexpected keyword argument 'wrapper'
- 根本原因:
pytest-cov
版本与pytest
主版本不匹配uv
管理的环境中可能存在版本冲突
安装pytest-cov 4.1.0版本
pip install pytest-cov==4.1.0 --break-system-packages
有了改观....
问题先总结一下
现在kotti 手工安装的时候是Kotti-2.0.10.dev0
kotti_image手工安装的时候依赖kotti是Kotti-2.0.9
而且类似sqlalchemy这样的,版本一弄就升到2.x,又要手工降低回1.4.36版...
报错:ImportError: cannot import name 'DBSession' from 'kotti' (unknown location)
测试了一下,竟然没法import kotti ,什么情况?
安装一下
pip install Kotti==2.0.9 --break-system-packages
然后测试的时候加上这句:
pytest -p no:typeguard
pytest -p no:typeguard报错:__init__.py:205: SAWarning: transaction already deassociated from connection
报错很多测试失败分析与解决方案
1. 测试失败详情
在 TestTween.test_tween 测试中,出现了一个 AttributeError,错误发生在尝试调用 seek方法时。错误信息如下:
text
Copy Code
1
AttributeError: seek
该错误源于 cgi.py 文件中的 FieldStorage 对象,该对象没有 seek 方法。错误堆栈显示,这个问题发生在处理图像数据时,特别是在 depot.io.utils.py 的 file_from_content 函数中尝试将内容重置到文件开头时。
2. 错误原因分析
数据类型不匹配:FieldStorage 对象通常用于处理通过 HTTP POST 请求上传的文件。在这里,它似乎被错误地用作了包含原始图像数据的对象。
图像数据处理不当:在 test_tween 测试中,图像数据是通过 image_asset.read() 读取的,这可能返回了一个字节串(bytes),而不是一个文件对象。
3. 解决方案
确保数据类型正确:检查 image_asset 的来源和类型,确保它是一个文件对象,或者如果它是一个字节串,需要适当地将其转换为文件对象或处理为字节数据。
修改测试代码:如果 image_asset 是一个字节串,你可以考虑使用 io.BytesIO 将其封装为一个类文件对象,这样它就可以支持 seek 方法了。
例如:
from io import BytesIO# 假设 image_asset.read() 返回的是字节串
image_data = image_asset.read()
image_file = BytesIO(image_data)# 然后将 image_file 传递给 Image 构造函数
root["img"] = Image(data=image_file, title="Image")
检查其他相关代码:确保 Image 类的 data 属性能够正确处理类文件对象或字节串。
4. 警告信息
此外,测试还产生了一个警告:
text
Copy Code
1
SAWarning: transaction already deassociated from connection
这个警告通常与 SQLAlchemy 的事务管理有关,可能是在事务已经结束后尝试执行回滚操作。虽然这个警告不会直接导致测试失败,但建议检查相关的数据库操作代码,确保事务被正确管理。
5. 总结
修改测试代码以确保正确处理图像数据。
检查数据库操作代码以管理事务。
重新运行测试以验证问题是否已解决。
暂时放弃!