2

Читал книгу "Изучаем программирование на Python автор Бэрри П.".

В книге было задание проверить код на соответствие правилам PEP8.

По инструкции в книге я установил pytest pip install pytest и плагин к нему pytest-pep8 pip install pytest-pep8. Все установилось успешно.

Далее я запустил проверку своего модуля в командной строке py.test --pep8 D:\code\HeadFirst\webapp\vsearch.py результат:

C:\Users\titelivus>py.test --pep8 D:\code\HeadFirst\webapp\vsearch.py
c:\python\lib\site-packages\pep8.py:110: FutureWarning: Possible nested set at position 1
  EXTRANEOUS_WHITESPACE_REGEX = re.compile(r'[[({] | []}),;:]')
============================= test session starts ==============================
platform win32 -- Python 3.8.3, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
rootdir: C:\Users\titelivus
plugins: pep8-1.0.6
collected 0 items / 1 error

==================================== ERRORS ====================================
________________________ ERROR collecting test session _________________________
c:\python\lib\site-packages\pluggy\hooks.py:286: in __call__
    return self._hookexec(self, self.get_hookimpls(), kwargs)
c:\python\lib\site-packages\pluggy\manager.py:93: in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
c:\python\lib\site-packages\pluggy\manager.py:84: in <lambda>
    self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall(
c:\python\lib\site-packages\pytest_pep8.py:38: in pytest_collect_file
    return Pep8Item(path, parent, pep8ignore, config._max_line_length)
c:\python\lib\site-packages\_pytest\nodes.py:95: in __call__
    warnings.warn(NODE_USE_FROM_PARENT.format(name=self.__name__), stacklevel=2)
E   pytest.PytestDeprecationWarning: Direct construction of Pep8Item has been deprecated, please use Pep8Item.from_parent.
E   See https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent for more details.
=========================== short test summary info ============================
ERROR  - pytest.PytestDeprecationWarning: Direct construction of Pep8Item has ...
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.14s ===============================

Я внимательно прочитал текст ошибки, перешел по указанной ссылке, прочитал ее решение, но оно для меня не было понятным.

Нужно в каком то файле (догадываюсь что здесь c:\python\lib\site-packages\pytest_pep8.py:38: in pytest_collect_file), что-то изменить, чтобы все заработало.

1 ответ 1

2

Update

Невнимательно прочитал вопрос, исправляюсь! Проблема pytest-pep8 с версией pytest>=6.0, поскольку deprecations, введенные в версиях 5.Х, с версии 6.0 начинают кидать исключения. В данном случае речь идет о Node Construction changed to Node.from_parent. В качестве костыля можно использовать небольшой патч:

diff --git a/pytest_pep8.py b/pytest_pep8.py
index 6e6cd7e..0b7ad62 100644
--- a/pytest_pep8.py
+++ b/pytest_pep8.py
@@ -35,7 +35,7 @@ def pytest_collect_file(path, parent):
     if config.option.pep8 and path.ext == '.py':
         pep8ignore = config._pep8ignore(path)
         if pep8ignore is not None:
-            return Pep8Item(path, parent, pep8ignore, config._max_line_length)
+            return Pep8Item.from_parent(fspath=path, parent=parent, pep8ignore=pep8ignore, max_line_length=config._max_line_length)


 def pytest_sessionfinish(session):
@@ -50,8 +50,8 @@ class Pep8Error(Exception):

 class Pep8Item(pytest.Item, pytest.File):

-    def __init__(self, path, parent, pep8ignore, max_line_length):
-        super(Pep8Item, self).__init__(path, parent)
+    def __init__(self, fspath, parent, pep8ignore, max_line_length):
+        super(Pep8Item, self).__init__(fspath, parent)
         self.add_marker("pep8")
         self.pep8ignore = pep8ignore
         self.max_line_length = max_line_length

Пример использования: сохрани сниппет в файл (к примеру, changes.patch) и используй либо patch, либо git для применения патча:

> python -c "import site; print(site.getsitepackages()[0])"

выдаст путь, в котором установлен pytest-pep8 и лежит файл pytest_pep8.py. Теперь примени патч:

> patch -d путь/к/site-packages -p1 < сhanges.patch

либо

> git apply changes.patch --no-index --directory=путь/к/site-packages

(я не пользуюсь Windows, поэтому не могу сказать, как настроить эти программы под ней)

Либо просто открой файл pytest_pep8.py, найдешь его с помощью

> python -c "import pytest_pep8; print(pytest_pep8.__file__)"

и поменяй строки, руководствуясь патчем (пары минус-плюс подскажут, какую строку нужно заменить на какую).

4
  • Ваш ответ не связан с моей проблемой, пожалуйста прочтите внимательно мою проблему.
    – pyrexdraum
    12 авг 2020 в 4:16
  • @titelivus извиняюсь, ступил. Посмотри обновленный ответ, должно помочь.
    – hoefling
    12 авг 2020 в 10:32
  • Большое спасибо! Проблема решена.
    – pyrexdraum
    13 авг 2020 в 5:07
  • Рад был помочь!
    – hoefling
    13 авг 2020 в 6:43

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.