Error discovering pytest tests

VS Code version 1.62.1 Extension version v2021.11.1422169775 OS type macOS OS version 10.15.5 Python distribution python.org Python version 3.9.6 Language server Default Expected behaviour Tests ar...

VS Code version

1.62.1

Extension version

v2021.11.1422169775

OS type

macOS

OS version

10.15.5

Python distribution

python.org

Python version

3.9.6

Language server

Default

Expected behaviour

Tests are properly discovered.

Actual behaviour

I get «Error discovering pytest tests»

Steps to reproduce

settings.json:

{
    "python.testing.pytestArgs": [
        "server/src"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.linting.enabled": true
}

server/src/e2e/test_questions.py:

def test_addition():
    "tests whether 1+1 = 2"
    assert 1 + 1 == 2

Click «Refresh Tests» in the testing panel triggers the above error in output > python

Logs

> ~/dev/second/server/.venv/bin/python ~/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir ~/dev/second -s --cache-clear server/src
cwd: ~/dev/second
Error 2021-11-16 23:44:18: Error discovering pytest tests:
 r [Error]: ============================= test session starts ==============================
platform darwin -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: /Users/rbhalla/dev/second
plugins: pspec-0.0.4, mock-3.6.1, anyio-3.3.4
The Python extension has run into an unexpected situation
while processing a pytest node during test discovery.  Please
Please open an issue at:
  https://github.com/microsoft/vscode-python/issues
and paste the following output there.

nodeid: server/src/e2e/test_questions.py::::tests whether 1+1 = 2
kind: ('function', False)
class: Function
name: test_addition
fspath: /Users/rbhalla/dev/second/server/src/e2e/test_questions.py
location: ('server/src/e2e/test_questions.py', 7, 'test_addition')
function: <function test_addition at 0x104b5db80>
markers: []
user_properties: []
attrnames: ['_ALLOW_MARKERS', '__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_fixtureinfo', '_getobj', '_initrequest', '_nodeid', '_obj', '_prunetraceback', '_pyfuncitem', '_report_sections', '_repr_failure_py', '_request', '_store', 'add_marker', 'add_report_section', 'addfinalizer', 'cls', 'config', 'extra_keyword_matches', 'fixturenames', 'from_parent', 'fspath', 'funcargs', 'function', 'get_closest_marker', 'getmodpath', 'getparent', 'ihook', 'instance', 'iter_markers', 'iter_markers_with_node', 'keywords', 'listchain', 'listextrakeywords', 'listnames', 'location', 'module', 'name', 'nextitem', 'nodeid', 'obj', 'originalname', 'own_markers', 'parent', 'reportinfo', 'repr_failure', 'runtest', 'session', 'setup', 'teardown', 'user_properties', 'warn']

extra info:
fullname: test_addition
testfunc: .tests whether 1+1 = 2
parameterized:

traceback:
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 30, in discover
    ec = _pytest_main(pytestargs, [_plugin])
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/config/__init__.py", line 162, in main
    ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 316, in pytest_cmdline_main
    return wrap_session(config, _main)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 269, in wrap_session
    session.exitstatus = doit(config, session) or 0
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 322, in _main
    config.hook.pytest_collection(session=session)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 333, in pytest_collection
    session.perform_collect()
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 637, in perform_collect
    hook.pytest_collection_modifyitems(
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 92, in pytest_collection_modifyitems
    test, parents = self.parse_item(item)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 77, in parse_item
    return parse_item(item)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py", line 172, in parse_item
    raise should_never_reach_here(
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py", line 132, in should_never_reach_here
    traceback.print_stack()
collected 1 item

<Module server/src/e2e/test_questions.py>
  <Function test_addition>
The Python extension has run into an unexpected situation
while processing a pytest node during test discovery.  Please
Please open an issue at:
  https://github.com/microsoft/vscode-python/issues
and paste the following output there.

nodeid: server/src/e2e/test_questions.py::::tests whether 1+1 = 2
kind: ('function', False)
class: Function
name: test_addition
fspath: /Users/rbhalla/dev/second/server/src/e2e/test_questions.py
location: ('server/src/e2e/test_questions.py', 7, 'test_addition')
function: <function test_addition at 0x104b5db80>
markers: []
user_properties: []
attrnames: ['_ALLOW_MARKERS', '__annotations__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_fixtureinfo', '_getobj', '_initrequest', '_nodeid', '_obj', '_prunetraceback', '_pyfuncitem', '_report_sections', '_repr_failure_py', '_request', '_store', 'add_marker', 'add_report_section', 'addfinalizer', 'cls', 'config', 'extra_keyword_matches', 'fixturenames', 'from_parent', 'fspath', 'funcargs', 'function', 'get_closest_marker', 'getmodpath', 'getparent', 'ihook', 'instance', 'iter_markers', 'iter_markers_with_node', 'keywords', 'listchain', 'listextrakeywords', 'listnames', 'location', 'module', 'name', 'nextitem', 'nodeid', 'obj', 'originalname', 'own_markers', 'parent', 'reportinfo', 'repr_failure', 'runtest', 'session', 'setup', 'teardown', 'user_properties', 'warn']

extra info:
fullname: test_addition
testfunc: .tests whether 1+1 = 2
parameterized:

traceback:
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 30, in discover
    ec = _pytest_main(pytestargs, [_plugin])
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/config/__init__.py", line 162, in main
    ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 316, in pytest_cmdline_main
    return wrap_session(config, _main)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 269, in wrap_session
    session.exitstatus = doit(config, session) or 0
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 322, in _main
    config.hook.pytest_collection(session=session)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 333, in pytest_collection
    session.perform_collect()
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 641, in perform_collect
    hook.pytest_collection_finish(session=self)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
    res = hook_impl.function(*args)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 107, in pytest_collection_finish
    test, parents = self.parse_item(item)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 77, in parse_item
    return parse_item(item)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py", line 172, in parse_item
    raise should_never_reach_here(
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py", line 132, in should_never_reach_here
    traceback.print_stack()
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 637, in perform_collect
INTERNALERROR>     hook.pytest_collection_modifyitems(
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 60, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_result.py", line 60, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 92, in pytest_collection_modifyitems
INTERNALERROR>     test, parents = self.parse_item(item)
INTERNALERROR>   File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 77, in parse_item
INTERNALERROR>     return parse_item(item)
INTERNALERROR>   File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py", line 172, in parse_item
INTERNALERROR>     raise should_never_reach_here(
INTERNALERROR> NotImplementedError: Unexpected pytest node (see printed output).
INTERNALERROR> 
INTERNALERROR> During handling of the above exception, another exception occurred:
INTERNALERROR> 
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 269, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 322, in _main
INTERNALERROR>     config.hook.pytest_collection(session=session)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 60, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_result.py", line 60, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 333, in pytest_collection
INTERNALERROR>     session.perform_collect()
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/_pytest/main.py", line 641, in perform_collect
INTERNALERROR>     hook.pytest_collection_finish(session=self)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 60, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_result.py", line 60, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/Users/rbhalla/dev/second/server/.venv/lib/python3.9/site-packages/pluggy/_callers.py", line 39, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 107, in pytest_collection_finish
INTERNALERROR>     test, parents = self.parse_item(item)
INTERNALERROR>   File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 77, in parse_item
INTERNALERROR>     return parse_item(item)
INTERNALERROR>   File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py", line 172, in parse_item
INTERNALERROR>     raise should_never_reach_here(
INTERNALERROR> NotImplementedError: Unexpected pytest node (see printed output).

========================== 1 test collected in 0.03s ===========================

Traceback (most recent call last):
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/run_adapter.py", line 22, in <module>
    main(tool, cmd, subargs, toolargs)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/__main__.py", line 100, in main
    parents, result = run(toolargs, **subargs)
  File "/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/adapter/pytest/_discovery.py", line 44, in discover
    raise Exception("pytest discovery failed (exit code {})".format(ec))
Exception: pytest discovery failed (exit code 3)

    at ChildProcess.<anonymous> (/Users/rbhalla/.vscode/extensions/ms-python.python-2021.11.1422169775/out/client/extension.js:17:38446)
    at Object.onceWrapper (events.js:422:26)
    at ChildProcess.emit (events.js:315:20)
    at maybeClose (internal/child_process.js:1048:16)
    at Socket.<anonymous> (internal/child_process.js:439:11)
    at Socket.emit (events.js:315:20)
    at Pipe.<anonymous> (net.js:673:12)

Code of Conduct

  • I agree to follow this project’s Code of Conduct

Содержание

  1. Tests not discovered by Test Explorer #67
  2. Comments
  3. Error discovering tests #183
  4. Comments
  5. Ошибка обнаружения теста VSCode pytest

Tests not discovered by Test Explorer #67

I can run my unit tests in visual studio code with the built-in tester (see image):

But when I click the refresh button on the Test Explorer view, I get the following exception in the Python Test Adapter output:
Especially the «Error: spawn python ENOENT» is unclear to me. Any idea on what I need to change?

2019-02-21T15:13:43.723Z info at ‘python-musings’ [unittest runner]: Reading configuration for workspace python-musings
2019-02-21T15:13:43.727Z info at ‘python-musings’ [pytest runner]: Reading configuration for workspace python-musings
2019-02-21T15:13:43.727Z info at ‘python-musings’ [pytest runner]: Pytest test discovery is disabled
2019-02-21T15:13:43.728Z info at ‘python-musings’ [unittest runner]: Environment variables file d:githubpython-musings.env does not exist
2019-02-21T15:13:43.730Z info at ‘python-musings’ [unittest runner]: Discovering tests using python path «python» in d:githubpython-musings with pattern test*.py and start directory d:githubpython-musingssrc1-regular-expressions
2019-02-21T15:13:43.736Z crit at ‘python-musings’ [unittest runner]: Test loading failed: Error occurred during process execution: Error: spawn python ENOENT

Below, you can see the settings.json file:

The text was updated successfully, but these errors were encountered:

Источник

Error discovering tests #183

From @JamesNK on August 2, 2015 5:42

Error in VS2015 Output window. Using beta 6.

No tests are shown in Test Explorer window.

The text was updated successfully, but these errors were encountered:

@rynowak @vijayrkn I think you two guys might know something about this?

From @JamesNK on August 2, 2015 6:42

I tracked this down to a bug I added to Json.NET while making changes. The test host uses Json.NET so my bug took down the host when it encountered the bug.

So no bug in the host but I think you should add more error handling so it doesn’t crash so badly and pass the error message back to VS. That will help the user a better idea of what has gone wrong.

From @dougbu on August 2, 2015 19:33

@JamesNK do any released versions of Json.NET contain the bug? For example are «Newtonsoft.Json»: «6.0.6» through . «6.0.8» fine while . «7.0.1» has this problem and . «7.0.2» will be fine again?

From @JamesNK on August 2, 2015 20:52

No, it was from wip dev changes. Testing Json.NET is slightly difficult if the change I make during dev breaks the test application 😄

From @rynowak on August 3, 2015 15:49

@JamesNK — do you happen to know offhand what the callstack was that throwing?

@vijayrkn My guess is that we’ll want to do something dumber to serialize error messages.

@rynowak we do have our super simple JavaScript serializer/deserializer. or actually I don’t know if we have a serializer; we may have only put in a deserializer.

From @rynowak on August 3, 2015 16:26

yeah, that would be good as well, we should remove json.net as a dependency as possible so you can use whatever version you want

If we want to do this I’d have to go dig up my old source codez to find the missing features.

From @vijayrkn on August 3, 2015 17:4

Created a bug in tooling repo (#129) to track ‘removing the json.net dependency’ from VS unit test adapter.

From @JamesNK on August 3, 2015 23:21

@JamesNK — do you happen to know offhand what the callstack was that throwing?

From @JamesNK on August 3, 2015 23:26

yeah, that would be good as well, we should remove json.net as a dependency as possible so you can use whatever version you want

You already can. The test tools were using my dev version which had a bug which is why I got that error.

The GitHub Issue Tracker for the aspnet/Tooling repo is being deprecated in favor of Visual Studio’s Report a Problem tool.

If this issue is still a problem with the RTW release of Visual Studio 2017, please report a new issue using the Report a Problem tool. While you can still use .NET Core and ASP.NET Preview tools with Visual Studio 2015, Visual Studio 2017 is now the officially supported tool for developing .NET Core and ASP.NET Core projects.

By using the Report a Problem tool (available in both VS 2017 and VS 2015), you can collect detailed information about the problem, and send it to Microsoft with just a few button clicks. See Visual Studio’s Talk to Us page for more details.

Please use the discussion topic here for feedback and questions on the deprecation of this issue tracker. Thanks!

Источник

Ошибка обнаружения теста VSCode pytest

Обнаружение теста Pytest не работает. В пользовательском интерфейсе указано:

Test discovery error, please check the configuration settings for the tests

В окне вывода указано:

Вот мои настройки:

Я могу успешно запустить pytest из командной строки FWIW.

Как вы запускаете pytest из командной строки? Используете ли вы pytest из своей виртуальной среды с теми же аргументами, которые указаны в вашем settings.json?

Из командной строки я просто делаю pytest tests из той же виртуальной среды, которую использует VS Code.

да, я также запускаю pytest с терминала в VSCode, после чего он был обнаружен, чтобы впоследствии я мог запустить его из графического интерфейса.

Глядя на https://docs.pytest.org/en/latest/usage.html#possible-exit-codes, кажется, что сам pytest падает из-за какой-то внутренней ошибки.

Это не полный ответ, так как я не знаю, почему это происходит, и может не иметь отношения к вашей проблеме, в зависимости от того, как вы структурировали свои тесты.

Я решил эту проблему, поместив файл __init__.py в папку с тестами.

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

У меня есть __init__.py в моем tests каталоге.

@devlife решение helgso применимо к вам? связь Я могу подтвердить, что при переходе на более раннюю версию возникает та же проблема с кодом выхода 3.

Если у вас есть подмодули в папке tests , добавьте файл __init__ в эти подпапки.

Мое решение состояло в том, чтобы сделать наоборот: убери __init__.py . Не уверен, почему это исправляет это или почему оно вообще сломалось. Я уверен, что некоторое время назад мне пришлось добавить его вместо этого.

Я решил проблему, обновив pytest до последней версии: 4.4.1 с помощью «pip install —upgrade pytest». У меня, видимо, была старая версия 3.4.2.

Лучшим ответом будет: 1. Расскажите, почему именно старая версия вызывала проблему. 2. Расскажите, как в новой версии проблема решена. Произвольное обновление является очевидным решением, и большинству из них не нужно заходить в stackoverflow, чтобы узнать об этом.

Похоже на ошибку в последней версии расширения VS Code Python. У меня была такая же проблема, затем я понизил расширение Python до 2019.3.6558, и оно снова заработало. Итак, мы должны перейти к нашему списку расширений VS Code, выбрать расширение Python и «Установить другую версию . » в настройках этого расширения.

Я надеюсь, что это сработает и для вас.

Большое спасибо ! при переходе с 2020.1.58038 на 2019.3.6558 мои тесты обнаружены. Раньше у меня не было ModuleNotFoundError: нет модуля с именем «tests.conftest»

Я потратил целую вечность, пытаясь расшифровать эту бесполезную ошибку после создания теста с ошибками импорта. Убедитесь, что ваш набор тестов действительно может быть выполнен, прежде чем приступать к более глубокому устранению неполадок.

pytest —collect-only твой друг.

Каким должен быть результат?

Little Bobby Tables

@autumn Но это просто обнаружение и отображение в командной строке, которое мне нужно увидеть на вкладке проверки кода?

и что делать, если это не удается?

У меня была такая же проблема, и я отследил ее до моего файла pytest.ini . Удаление большей части addopts из этого файла решило проблему.

Прежде чем начать обнаружение тестов, убедитесь, что python.testing.cwd правильно указывает на ваш каталог тестов, а ваш python.testing.pytestEnabled установлен на true .

После того, как эти требования установлены правильно, запустите обнаружение тестов и их вывод (см. окно ВЫХОД). Вы должны увидеть что-то вроде этого:

Здесь важно выделить последнюю строчку: collected N items / M errors . Следующие строки будут содержать информацию о тестах, обнаруженных pytest . Итак, ваши тесты обнаруживаются, но есть ошибки, связанные с их корректным выполнением.

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

Убедитесь, что все ваши зависимости были загружены ранее. Если вы работаете с определенными версиями зависимостей (в файле requirements.txt у вас есть что-то вроде your_package == X.Y.Z ), убедитесь, что это правильная версия, которая вам нужна.

Я просто подумал, что добавлю сюда свой ответ, так как это может повлиять на тех, кто использует файл .env для настроек среды своего проекта, поскольку это такая распространенная конфигурация для 12-факторных приложений.

В моем примере предполагается, что вы используете pipenv для управления виртуальной средой и что у вас есть файл .env в корневом каталоге проекта.

JSON-файл настроек рабочего пространства vscode выглядит следующим образом. Решающей линией для меня здесь была «python.envFile»: «$/.env»,

Я надеюсь, что это сэкономит кому-то время, которое я потратил на выяснение этого.

Спасибо, настройка файла env сработала и в моем случае. Мне требовались либо параметры CLI, либо, альтернативно, переменные среды, чтобы установить критические значения для моих тестов. И указать их в tox.ini и т.п. было невозможно, так как они носили частный характер.

Для меня это было «python.testing.pytestPath»: «<$workspaceFolder>\Lib\pytest»,

В моем случае проблема с невозможностью обнаружения тестов vscode заключалась в том, что модуль покрытие был включен в setup.cfg (в качестве альтернативы это может быть pytest.ini ), т.е.

что привело к сбою тестового обнаружения из-за низкого охвата. Решение состояло в том, чтобы удалить эту строку из файла конфигурации.

Кроме того, как предлагается в документация:

You can also configure testing manually by setting one and only one of the following settings to true: python.testing.unittestEnabled , python.testing.pytestEnabled , and python.testing.nosetestsEnabled .

Немного связанно — в случае более сложных проектов может также потребоваться изменить параметр rootdir (внутри вашего settings.json ) при запуске тестов с питест (в случае ModuleNotFoundError ):

Я потратил более нескольких недель, пытаясь выяснить ошибку обнаружения pytest. Явная установка rootdir окончательно устранила проблему. Благодаря тонну.

Если у вас возникли проблемы с pytest Я боролся с тестовой частью обнаружения.

Читая некоторые открытый вопрос(разное) в vscode, я нашел обходной путь, используя расширение the test-adapter

Расширение работает как шарм. (и решить мою проблему обнаружения)

Я искал в настройках «python» и нашел это:

Переключение на pytest автоматически определяет мои тесты:

У меня была эта проблема, и я боролся с ней часами. Я думаю, что для каждой другой конфигурации платформы есть особое разрешение. Моя платформа:

  • VSCode: 1.55.0 (Убунту)
  • Питест: 6.2.3
  • Расширение MS Python (ms-python.python 2021.3.680753044)
  • Обозреватель тестов Python для кода Visual Studio (littlefoxteam.vscode-python-test-adapter — 0.6.7)

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

В итоге проблема была

параметры, которые не были распознаны инструментом проводника тестирования VSCode (который я скопировал с какой-то страницы в Интернете), и ошибка была показана расширением littlefoxteam.vscode-python-тест-адаптер, и это может помочь вам найти, где что-то не работает.

Эта ошибка так расстраивает.. В моем случае ошибка исправлена ​​​​путем изменения параметра python.pythonPath в settings.json (находится внутри папки .vscode в корневом каталоге проекта) на путь, который я получил с помощью which python в терминале (например, /usr/local/var/pyenv/shims/python )

Я использую pyenv с python3.9, и моя ошибка говорила ранее:

Error: Process returned an error: /Users/»user-name»/.pyenv/shims/python: line 21: /usr/local/Cellar/pyenv/1.2.23/libexec/pyenv: No such file or directory

at ChildProcess. (/Users/»user-name»/.vscode/extensions/littlefoxteam.vscode-python-test-adapter-0.6.8/out/src/processRunner.js:35:36) at Object.onceWrapper (events.js:422:26) at ChildProcess.emit (events.js:315:20) at maybeClose (internal/child_process.js:1021:16) at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)

В моем случае одна и та же проблема возникала каждый раз, когда flake8 линтер сообщал об ошибках. Даже одной ошибки было достаточно, чтобы провалить тестовое обнаружение VS Code. Таким образом, исправление заключается в том, чтобы либо отключить линтер, либо исправить ошибки линтера. Я использую настройку описанную здесь.

В моем случае это была проблема расширения vscode python. Я переключил тестовую платформу с pytest и снова переключился на нее, и тесты были обнаружены. Кажется, что когда тестирование включено повсеместно для всех проектов Python и оно не может обнаружить тесты в начале, оно терпит неудачу навсегда!

Пожалуйста, найдите ниже настройки, которые я использовал, чтобы заставить pytest работать в VsCode после большого разочарования. Я нашел много полезных советов здесь и в других местах в Интернете, но ни один из них не был достаточно полным, чтобы избавить меня от ругательств. Я надеюсь, что следующее поможет кому-то. Эта настройка позволяет мне визуально запускать тестирование из расширения проводника тестов, а также из встроенного терминала. Я использую формат src в своей рабочей области и Conda для управления средой. Настройки, связанные с настройкой терминала, избавляют меня от необходимости вручную включать мою среду Conda или устанавливать путь python. Возможно, люди, которые используют VSCODE более двух дней, могли бы добавить что-то хорошее, чтобы сделать его лучше и/или более полным.

Версия: 1.63.2 (универсальная) Фиксация: 899d46d82c4c95423fb7e10e68eba52050e30ba3 Дата: 2021-12-15T09:37:28.172Z (1 неделю назад) Электрон: 13.5.2 Хром: 91.0.4472.164 Node.js: 14.16.0 V8: 9.1.269.39-электрон.0 ОС: Дарвин x64 20.6.0

Обозреватель тестов Python для кода Visual Studio расширение установлено, v. 0.7.0

##### .env файл (в корневом каталоге, но см. параметр «python.envFile» в settings.json)

Вот общий способ запустить тесты Django с поддержкой полный vscode.

  1. Настроить тесты Python
    1. Выберите модульный тест
    2. Корневая директория
    3. test*.py
  2. Тогда каждый тестовый пример должен выглядеть следующим образом:

Любые функции, которые вы хотите импортировать имеют, будут импортированы внутри тестового примера (как показано). setUpClass запускается перед настройкой тестового класса и настроит ваш проект django. После настройки вы можете импортировать функции внутри методов тестирования. Если вы попытаетесь импортировать модели/представления в верхней части вашего скрипта, это вызовет исключение, поскольку django не настроен. Если у вас есть какая-либо другая предварительная инициализация, которую необходимо выполнить для работы вашего проекта django, запустите ее внутри setUpClass . Pytest может работать так же, я не проверял.

Источник

Pytest does not discover tests #10313

Comments

MatKie commented Feb 25, 2020

  1. Configure Tests
  2. choose pytest and the directory the tests are in
  3. Test discovery fails

platform win32 — Python 2.7.14, pytest-4.6.9, py-1.8.1, pluggy-0.13.1

python c:Usersmk8118.vscodeextensionsms-python.python-2020.2.64397pythonFilestesting_toolsrun_adapter.py discover pytest — —rootdir c:Usersmk8118Anaconda2envsgsaftmmLibsite-packagesgSAFTmm_3p6 -s —cache-clear test
Test Discovery failed:
Error: ============================= test session starts =============================
platform win32 — Python 2.7.14, pytest-4.6.9, py-1.8.1, pluggy-0.13.1
rootdir: c:Usersmk8118Anaconda2envsgsaftmmLibsite-packagesgSAFTmm_3p6
collected 0 items

======================== no tests ran in 0.02 seconds =========================
ERROR: file not found: test

Traceback (most recent call last):
File «c:Usersmk8118.vscodeextensionsms-python.python-2020.2.64397pythonFilestesting_toolsrun_adapter.py», line 15, in
main(tool, cmd, subargs, toolargs)
File «c:Usersmk8118.vscodeextensionsms-python.python-2020.2.64397pythonFilestesting_toolsadapter_main_.py», line 87, in main
parents, result = run(toolargs, **subargs)
File «c:Usersmk8118.vscodeextensionsms-python.python-2020.2.64397pythonFilestesting_toolsadapterpytest_discovery.py», line 39, in discover
raise Exception(«pytest discovery failed (exit code <>)».format(ec))
Exception: pytest discovery failed (exit code 4)

Extension version: 2020.2.64397
VS Code version: Code 1.42.1 (c47d83b293181d9be64f27ff093689e8e7aed054, 2020-02-11T14:45:59.656Z)
OS version: Windows_NT x64 10.0.17134

The text was updated successfully, but these errors were encountered:

Источник

Test discovery error with pytest #10636

Comments

mblackgeo commented Mar 18, 2020

I have had a few issues with test discovery from vscode, usually related to some package specific imports. I have previously had problems with running tests that import apache-airflow (with ImportError for zope.deprecation), and now my latest is with streamlit. I can provide an example to reproduce this error.

Environment data

  • VS Code version: 1.43.0
  • Extension version (available under the Extensions sidebar): 2020.2.64397
  • OS and version: Ubuntu 18.04.4 LTS
  • Python version (& distribution if applicable, e.g. Anaconda): python 3.6.8
  • Type of virtual environment used (N/A | venv | virtualenv | conda | . ): virtualenv
  • Relevant/affected Python packages and their versions:
  • Relevant/affected Python-related VS Code extensions and their versions: n/a
  • Jedi or Language Server? (i.e. what is «python.jediEnabled» set to; more info

Expected behaviour

Tests would be discovered and code lenses would appear in the UI.

Actual behaviour

Tests can be ran from the command line with success using pytest directly with no errors, however test discovery in vscode fails with error:

Steps to reproduce:

  1. Create a minimal python environment
  1. Create a new folder and add a file test_streamlit.py with contents:
  1. Open vscode, set python environment and discover tests.

Output for Python in the Output panel ( View → Output , change the drop-down the upper-right of the Output panel to Python )

/.virtualenvs/test2/bin/python -c «import sys;print(sys.executable)» > conda info —json > conda env list Starting Jedi Python language engine. > conda —version >

/.virtualenvs/test2/bin/python -c «import notebook» >

/.virtualenvs/test2/bin/python -c «import jupyter» >

/.vscode/extensions/ms-python.python-2020.2.64397/pythonFiles/testing_tools/run_adapter.py discover pytest — —rootdir

/r/testing -s —cache-clear . cwd:

/.virtualenvs/test2/bin/python -m jupyter kernelspec —version >

/.virtualenvs/test2/bin/python -c «import sys;print(sys.prefix)» cwd:

/.virtualenvs/test2/bin/python -c «import sys;print(sys.prefix)» cwd:

/.virtualenvs/test2/bin/python -c «import sys;print(sys.executable)» cwd:

/.virtualenvs/test2/bin/python -c «import sys;print(sys.executable)» cwd:

/.virtualenvs/test2/bin/python -c «from distutils.sysconfig import get_python_lib; print(get_python_lib())» cwd:

/.virtualenvs/test2/bin/python -c «from distutils.sysconfig import get_python_lib; print(get_python_lib())» cwd:

/.virtualenvs/test2/bin/python -m site —user-site cwd:

/.virtualenvs/test2/bin/python -m site —user-site cwd:

/.virtualenvs/test2/bin/python completion.py cwd:

Output from Console under the Developer Tools panel (toggle Developer Tools on under Help ; turn on source maps to make any tracebacks be useful by running Enable source map support for extension debugging )

These are the errors only:

The text was updated successfully, but these errors were encountered:

amonod commented Mar 18, 2020

can confirm I have the same issue. pytest works just fine within a terminal, but VSCode discovery fails (output log shows ImportError: numpy.core.multiarray failed to import .)

VS Code version: 1.43.0
Extension version (available under the Extensions sidebar): 2020.2.64397
OS and version: Windows 10 1903
Python version (& distribution if applicable, e.g. Anaconda): Python 3.7.5 Anaconda
Type of virtual environment used (N/A | venv | virtualenv | conda | . ): conda env (not base one)

I remember having a similar issue on a previous install, managed to solve it but I had to tinker a few things I don’t remember.

mblackgeo commented Mar 18, 2020

Yes I’ve had the same ImportError problem before with other modules but I wasn’t able to make a repro until this time round. I had a dig around in the python extension to find out what is happening with no luck. Again, it’s unusual as just running pytest at the terminal is fine 😕

karthiknadig commented Mar 24, 2020

@mblack20 Can you try running the discovery from command line? I am suspecting something is wrong with how discovery is invoked:

mblackgeo commented Mar 24, 2020

@mblack20 Can you try running the discovery from command line? I am suspecting something is wrong with how discovery is invoked:

Yep that discovers the tests with no problems, here is the output:

karthiknadig commented Mar 25, 2020

I have tried the repro steps, I am not able to repro this locally. I had to use streamlit version 0.56.0 i could not find version 0.50.6 .

Lets try that with the discovery script. This should dump a JSON array.

Can you also try the two commands without activating the environment? It could be the case that discovery is running is an environment without activating. It is picking up wrong version of streamlit.

mblackgeo commented Mar 25, 2020

I have tried the repro steps, I am not able to repro this locally. I had to use streamlit version 0.56.0 i could not find version 0.50.6.

Apologies, that must have been a typo!

Thanks for the help so far. With the environment activated, this is output from the python extension when running from the terminal:

Without the environment activated, the commands fail as I do not have pytest or streamlit installed in my system python.

Could there be something in my settings that is modifying or interfering with the python path? For example for an unrelated issue I had found the system python dist-packages was being added to PYTHONPATH for the integrated terminal.

My project settings are:

and my user settings (python ones) are:

I’m also having this problem on with the latest version (2020.3.69010) as well.

Источник

pytest test discovery failed with pytest-pep8 installed #7287

Comments

zztalker commented Sep 9, 2019

Environment data

Version: 1.38.0
Commit: 3db7e09f3b61f915d03bbfa58e258d6eee843f35
Date: 2019-09-03T21:51:09.716Z
Electron: 4.2.10
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Linux x64 4.15.0-36-generic
Extension Name: Python
Id: ms-python.python
Version: 2019.9.34911
Publisher: Microsoft
Python version: 3.5/3.6/3.7

Expected behavior

Actual behavior

Tests discovering failed.

The workaround is to remove —pep8 keyword from pytestArgs property.

Steps to reproduce:

  1. clone https://github.com/zztalker/just_for_test ( git clone https://github.com/zztalker/just_for_test )
  2. Install requrements ( pip install -r requirements.txt ), we need only pytest-pep8
  3. Open VS Code from folder ( code . )
  4. Turn on test discovery and add in settings:

Output for Python Test Log in the Output panel ( View → Output , change the drop-down the upper-right of the Output panel to Python )

test_pytest1.py None INTERNALERROR> Traceback (most recent call last): INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/_pytest/main.py», line 498, in perform_collect INTERNALERROR> session=self, config=self.config, items=items INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/hooks.py», line 289, in __call__ INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/manager.py», line 87, in _hookexec INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/manager.py», line 81, in INTERNALERROR> firstresult=hook.spec.opts.get(«firstresult») if hook.spec else False, INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 208, in _multicall INTERNALERROR> return outcome.get_result() INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 80, in get_result INTERNALERROR> raise ex[1].with_traceback(ex[2]) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 187, in _multicall INTERNALERROR> res = hook_impl.function(*args) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_discovery.py», line 80, in pytest_collection_modifyitems INTERNALERROR> test, parents = self.parse_item(item) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_discovery.py», line 65, in parse_item INTERNALERROR> return parse_item(item) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py», line 163, in parse_item INTERNALERROR> testroot, relfile = _split_fspath(str(item.fspath), fileid, item) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py», line 142, in INTERNALERROR> _split_fspath=(lambda *a: _split_fspath(*a)), INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py», line 232, in _split_fspath INTERNALERROR> relsuffix = fileid[1:] # Drop (only) the «.» prefix. INTERNALERROR> TypeError: ‘NoneType’ object is not subscriptable INTERNALERROR> INTERNALERROR> During handling of the above exception, another exception occurred: INTERNALERROR> INTERNALERROR> Traceback (most recent call last): INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/_pytest/main.py», line 206, in wrap_session INTERNALERROR> session.exitstatus = doit(config, session) or 0 INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/_pytest/main.py», line 249, in _main INTERNALERROR> config.hook.pytest_collection(session=session) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/hooks.py», line 289, in __call__ INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/manager.py», line 87, in _hookexec INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/manager.py», line 81, in INTERNALERROR> firstresult=hook.spec.opts.get(«firstresult») if hook.spec else False, INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 208, in _multicall INTERNALERROR> return outcome.get_result() INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 80, in get_result INTERNALERROR> raise ex[1].with_traceback(ex[2]) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 187, in _multicall INTERNALERROR> res = hook_impl.function(*args) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/_pytest/main.py», line 259, in pytest_collection INTERNALERROR> return session.perform_collect() INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/_pytest/main.py», line 501, in perform_collect INTERNALERROR> hook.pytest_collection_finish(session=self) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/hooks.py», line 289, in __call__ INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/manager.py», line 87, in _hookexec INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/manager.py», line 81, in INTERNALERROR> firstresult=hook.spec.opts.get(«firstresult») if hook.spec else False, INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 208, in _multicall INTERNALERROR> return outcome.get_result() INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 80, in get_result INTERNALERROR> raise ex[1].with_traceback(ex[2]) INTERNALERROR> File «/home/pz/.local/lib/python3.7/site-packages/pluggy/callers.py», line 187, in _multicall INTERNALERROR> res = hook_impl.function(*args) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_discovery.py», line 94, in pytest_collection_finish INTERNALERROR> test, parents = self.parse_item(item) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_discovery.py», line 65, in parse_item INTERNALERROR> return parse_item(item) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py», line 163, in parse_item INTERNALERROR> testroot, relfile = _split_fspath(str(item.fspath), fileid, item) INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py», line 142, in INTERNALERROR> _split_fspath=(lambda *a: _split_fspath(*a)), INTERNALERROR> File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_pytest_item.py», line 232, in _split_fspath INTERNALERROR> relsuffix = fileid[1:] # Drop (only) the «.» prefix. INTERNALERROR> TypeError: ‘NoneType’ object is not subscriptable ========================== 1 warnings in 0.02 seconds ========================== Traceback (most recent call last): File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/run_adapter.py», line 18, in main(tool, cmd, subargs, toolargs) File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/__main__.py», line 90, in main parents, result = run(toolargs, **subargs) File «/home/pz/.vscode/extensions/ms-python.python-2019.9.34911/pythonFiles/testing_tools/adapter/pytest/_discovery.py», line 35, in discover raise Exception(‘pytest discovery failed (exit code <>)’.format(ec)) Exception: pytest discovery failed (exit code 3) «>

The text was updated successfully, but these errors were encountered:

Источник

I’m trying to set up VSCode to allow me to effectively use pytest, but the test files just aren’t being found (they’re in a top-level folder called «tests»). I get the following popup message from VSCode:

No tests discovered, please check the configuration settings for the tests.

My research tells me I should have a nodeids file in my .pytest_cache/v/cache/nodeids file, but nodeids isn’t appearing there when using VSCode to discover tests; running pytest manually in the command line does create a nodeids file, but the file just contains [] and it doesn’t detect the tests, and I’ve tried uninstalling the python extensions and restarting, but to no avail.

I have also confirmed that there are no syntax errors in my project (I heard that syntax errors can cause pytest to fail to find tests).

I believe during configuration of the test framework (https://code.visualstudio.com/docs/python/testing#_enable-a-test-framework), after choosing the folder, I’m meant to choose the pattern used to identify test files, but this option never appears to me at all; test framework «configuration» just ends immediately when I select the tests file.

Using VSCode, nothing happens in the terminal, but if I type in pytest manually, the test session starts this is printed:

platform linux -- Python 3.7.8, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/user/Desktop/_Projects/my_project
collected 0 items

My settings.json file for the project looks like this:

{
    "python.linting.enabled": true,

    "python.testing.pytestArgs": [
        "tests"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true
}

And for VSCode in general has this settings.json:

{
    "msbuildProjectTools.nuget.includePreRelease": true,
    "msbuildProjectTools.nuget.newestVersionsFirst": true,
    "msbuildProjectTools.logging.seq.level": "Verbose",
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "window.titleBarStyle": "custom",
    "python.languageServer": "Pylance",
    "telemetry.enableTelemetry": false,
    "telemetry.enableCrashReporter": false,
    "python.venvPath": "${workspaceFolder}/.venv",

    "python.venvFolders": [
        "home/desktop/user/.venv/py37/pyside2"
    ],
    "python.terminal.activateEnvInCurrentTerminal": true,
    "files.watcherExclude": {
        "**/.venv/**": true
    },
}

To be clear, I am indeed using a virtual enviroment (venv).

Can someone help me figure out how to fix this?

Обнаружение теста Pytest не выполняется. Пользовательский интерфейс заявляет:

Test discovery error, please check the configuration settings for the tests

Окно вывода состояния:

Test Discovery failed: 
Error: Traceback (most recent call last):
  File "C:Usersmikep.vscodeextensionsms-python.python-2019.4.11987pythonFilestesting_toolsrun_adapter.py", line 16, in <module>
    main(tool, cmd, subargs, toolargs)
  File "C:Usersmikep.vscodeextensionsms-python.python-2019.4.11987pythonFilestesting_toolsadapter__main__.py", line 90, in main
    parents, result = run(toolargs, **subargs)
  File "C:Usersmikep.vscodeextensionsms-python.python-2019.4.11987pythonFilestesting_toolsadapterpytest.py", line 43, in discover
    raise Exception('pytest discovery failed (exit code {})'.format(ec))
Exception: pytest discovery failed (exit code 3)

Вот мои настройки:

{
    "python.pythonPath": ".venv\Scripts\python.exe",
    "python.testing.pyTestArgs": [
        "tests"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pyTestEnabled": true
}

Я могу запустить pytest из командной строки успешно FWIW.

In my case the problem with vscode being unable to discover tests was the coverage module being enabled in the setup.cfg (alternatively this could be a pytest.ini), i.e.

addopts= --cov <path> -ra

which caused the test discovery to fail due to low coverage. The solution was to remove that line from the config file.

Also, as suggested in the documentation:

You can also configure testing manually by setting one and only one of the following settings to true: python.testing.unittestEnabled, python.testing.pytestEnabled, and python.testing.nosetestsEnabled.

In settings.json you can also disable coverage using --no-cov flag:

"python.testing.pytestArgs": ["--no-cov"],

EDIT:

Slightly related — in case of more complex projects it might be also necessary to change the rootdir parameter (inside your settings.json) when running tests with pytest (in case of ModuleNotFoundError):

    "python.testing.pytestArgs": [
        "--rootdir","${workspaceFolder}/<path-to-directory-with-tests>"
    ],

I just thought I would add my answer here as this might well affect someone who uses a .env file for their project’s environment settings since it is such a common configuration for 12 factor apps.

My example assumes that you’re using pipenv for your virtual environment management and that you have a .env file at the project’s root directory.

My vscode workspace settings json file looks like below. The crucial line for me here was "python.envFile": "${workspaceFolder}/.env",

{
    "python.pythonPath": ".venv/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.linting.pycodestyleEnabled": false,
    "python.linting.flake8Enabled": false,
    "python.linting.pylintPath": ".venv/bin/pylint",
    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django",
    ],
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": [
        "--line-length",
        "100"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestPath": ".venv/bin/pytest",
    "python.envFile": "${workspaceFolder}/.env",
    "python.testing.pytestArgs": [
        "--no-cov"
    ],
}

I hope this saves someone the time I spent figuring this out.

I spent ages trying to decipher this unhelpful error after creating a test that had import errors. Verify that your test suite can actually be executed before doing any deeper troubleshooting.

pytest --collect-only is your friend.

This is not a complete answer as I do not know why this is happening and may not relate to your problem, depending how you have your tests structured.

I resolved this issue by putting an __init__.py file in my tests folder

E.G.:


├───.vscode
│       settings.json
│
├───app
│       myapp.py
│
└───tests
        test_myapp.py
        __init__.py

this was working a few days ago without this but the python extension was recently updated. I am not sure if this is the intended behavior or a side effect of how discoveries are now being made

https://github.com/Microsoft/vscode-python/blob/master/CHANGELOG.md
Use Python code for discovery of tests when using pytest. (#4795)

Обнаружение теста Pytest не выполняется. Пользовательский интерфейс заявляет:

Test discovery error, please check the configuration settings for the tests

Окно вывода состояния:

Test Discovery failed: 
Error: Traceback (most recent call last):
  File "C:Usersmikep.vscodeextensionsms-python.python-2019.4.11987pythonFilestesting_toolsrun_adapter.py", line 16, in <module>
    main(tool, cmd, subargs, toolargs)
  File "C:Usersmikep.vscodeextensionsms-python.python-2019.4.11987pythonFilestesting_toolsadapter__main__.py", line 90, in main
    parents, result = run(toolargs, **subargs)
  File "C:Usersmikep.vscodeextensionsms-python.python-2019.4.11987pythonFilestesting_toolsadapterpytest.py", line 43, in discover
    raise Exception('pytest discovery failed (exit code {})'.format(ec))
Exception: pytest discovery failed (exit code 3)

Вот мои настройки:

{
    "python.pythonPath": ".venv\Scripts\python.exe",
    "python.testing.pyTestArgs": [
        "tests"
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pyTestEnabled": true
}

Я могу запустить pytest из командной строки успешно FWIW.

6 ответов

Лучший ответ

Я решил проблему, обновив pytest до последней версии: 4.4.1 с помощью «pip install —upgrade pytest». Я очевидно работал на старой версии 3.4.2


2

helgso
25 Апр 2019 в 20:12

Похоже, ошибка в последней версии расширения VS Code Python. У меня была та же проблема, затем я понизил расширение Python до 2019.3.6558 , а затем оно снова работает. Поэтому мы должны перейти к нашему списку расширений VS Code, выбрать расширение Python и «Установить другую версию …» в настройках этого расширения.

Надеюсь, это сработает и для вас.


7

Niklas
26 Апр 2019 в 09:51

Это не полный ответ, так как я не знаю, почему это происходит, и может не относиться к вашей проблеме, в зависимости от того, как вы структурировали свои тесты.

Я решил эту проблему, поместив файл __init__.py в папку с тестами

НАПРИМЕР.:


├───.vscode
│       settings.json
│
├───app
│       myapp.py
│
└───tests
        test_myapp.py
        __init__.py

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

https://github.com/Microsoft/vscode-python/blob/master /CHANGELOG.md
Use Python code for discovery of tests when using pytest. (#4795)


7

WildStriker
24 Апр 2019 в 22:30

У меня была такая же проблема, и я нашел ее в pytest.ini файле. Удаление большей части addopts из этого файла решило проблему.


0

Brendan Abel
3 Окт 2019 в 22:40

Я потратил целую вечность, пытаясь расшифровать эту бесполезную ошибку после создания теста с ошибками импорта. Убедитесь, что ваш набор тестов действительно может быть выполнен, прежде чем приступать к более глубокому устранению неполадок.

pytest --collect-only твой друг.


3

Autumn
16 Сен 2019 в 19:38

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Понравилась статья? Поделить с друзьями:
  • Error disable recovery cisco
  • Error disable quad failed
  • Error disable faceit and vanguard anticheats
  • Error disable cisco link flap
  • Error dirty database version 1 fix and force version