Pytest error unrecognized arguments

Command i am trying to execute: pytest --show-capture=no -v --dsn="emulator-5554" -m bat --reruns=2 LINE NUMBERS usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: u...

@jain18aditya

Command i am trying to execute:
pytest --show-capture=no -v --dsn="emulator-5554" -m bat --reruns=2

LINE NUMBERS 
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --show-capture=no
  inifile: /home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/54/workspace/test/pytest.ini
  rootdir: /home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/54/workspace/test
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --show-capture=no
  inifile: /home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/54/workspace/test/pytest.ini
  rootdir: /home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/54/workspace/test
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --show-capture=no
  inifile: /home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/54/workspace/test/pytest.ini
  rootdir: /home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/54/workspace/test

Pytest version i am using:

This is pytest version 5.3.5, imported from /home/ANT.AMAZON.COM/jaiadi/kats-ag...-packages/pytest/__init__.py
setuptools registered plugins:
pytest-rerunfailures-8.0 at /home/ANT.AMAZON.COM/jaiadi/kats-ag...ages/pytest_rerunfailures.py
pytest-cov-2.3.1 at /home/ANT.AMAZON.COM/jaiadi/kats-ag...ackages/pytest_cov/plugin.py

@RonnyPfannschmidt

whats the content of pytest.ini and whats the output of pytest --help

@jain18aditya

$ pytest --help
general:
  -k EXPRESSION         only run tests which match the given substring
                        expression. An expression is a python evaluatable
                        expression where all names are substring-matched
                        against test names and their parent classes. Example:
                        -k 'test_method or test_other' matches all test
                        functions and classes whose name contains
                        'test_method' or 'test_other', while -k 'not
                        test_method' matches those that don't contain
                        'test_method' in their names. Additionally keywords
                        are matched to classes and functions containing extra
                        names in their 'extra_keyword_matches' set, as well as
                        functions which have names assigned directly to them.
  -m MARKEXPR           only run tests matching given mark expression.
                        example: -m 'mark1 and not mark2'.
  --markers             show markers (builtin, plugin and per-project ones).
  -x, --exitfirst       exit instantly on first error or failed test.
  --maxfail=num         exit after first num failures or errors.
  --strict              marks not registered in configuration file raise
                        errors.
  -c file               load configuration from `file` instead of trying to
                        locate one of the implicit configuration files.
  --continue-on-collection-errors
                        Force test execution even if collection errors occur.
  --fixtures, --funcargs
                        show available fixtures, sorted by plugin appearance
  --fixtures-per-test   show fixtures per test
  --import-mode={prepend,append}
                        prepend/append to sys.path when importing test
                        modules, default is to prepend.
  --pdb                 start the interactive Python debugger on errors.
  --pdbcls=modulename:classname
                        start a custom interactive Python debugger on errors.
                        For example:
                        --pdbcls=IPython.terminal.debugger:TerminalPdb
  --capture=method      per-test capturing method: one of fd|sys|no.
  -s                    shortcut for --capture=no.
  --runxfail            run tests even if they are marked xfail
  --lf, --last-failed   rerun only the tests that failed at the last run (or
                        all if none failed)
  --ff, --failed-first  run all tests but run the last failures first. This
                        may re-order tests and thus lead to repeated fixture
                        setup/teardown
  --cache-show          show cache contents, don't perform collection or tests
  --cache-clear         remove all cache contents at start of test run.
 
reporting:
  -v, --verbose         increase verbosity.
  -q, --quiet           decrease verbosity.
  -r chars              show extra test summary info as specified by chars
                        (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed,
                        (p)passed, (P)passed with output, (a)all except pP.
                        Warnings are displayed at all times except when
                        --disable-warnings is set
  --disable-warnings, --disable-pytest-warnings
                        disable warnings summary
  -l, --showlocals      show locals in tracebacks (disabled by default).
  --tb=style            traceback print mode (auto/long/short/line/native/no).
  --full-trace          don't cut any tracebacks (default is to cut).
  --color=color         color terminal output (yes/no/auto).
  --durations=N         show N slowest setup/test durations (N=0 for all).
  --pastebin=mode       send failed|all info to bpaste.net pastebin service.
  --junit-xml=path      create junit-xml style report file at given path.
  --junit-prefix=str    prepend prefix to classnames in junit-xml output
  --result-log=path     DEPRECATED path for machine-readable result log.
 
collection:
  --collect-only        only collect tests, don't execute them.
  --pyargs              try to interpret all arguments as python packages.
  --ignore=path         ignore path during collection (multi-allowed).
  --confcutdir=dir      only load conftest.py's relative to specified dir.
  --noconftest          Don't load any conftest.py files.
  --keep-duplicates     Keep duplicate tests.
  --collect-in-virtualenv
                        Don't ignore tests in a local virtualenv directory
  --doctest-modules     run doctests in all .py modules
  --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
                        choose another output format for diffs on doctest
                        failure
  --doctest-glob=pat    doctests file matching pattern, default: test*.txt
  --doctest-ignore-import-errors
                        ignore doctest ImportErrors
 
test session debugging and configuration:
  --basetemp=dir        base temporary directory for this test run.
  --version             display pytest lib version and import information.
  -h, --help            show help message and configuration info
  -p name               early-load given plugin (multi-allowed). To avoid
                        loading of plugins, use the `no:` prefix, e.g.
                        `no:doctest`.
  --trace-config        trace considerations of conftest.py files.
  --debug               store internal tracing debug information in
                        'pytestdebug.log'.
  -o [OVERRIDE_INI [OVERRIDE_INI ...]], --override-ini=[OVERRIDE_INI [OVERRIDE_INI ...]]
                        override config option with option=value style, e.g.
                        `-o xfail_strict=True`.
  --assert=MODE         Control assertion debugging tools. 'plain' performs no
                        assertion debugging. 'rewrite' (the default) rewrites
                        assert statements in test modules on import to provide
                        assert expression information.
  --setup-only          only setup fixtures, do not execute tests.
  --setup-show          show setup of fixtures while executing tests.
  --setup-plan          show what fixtures and tests would be executed but
                        don't execute anything.
 
pytest-warnings:
  -W PYTHONWARNINGS, --pythonwarnings=PYTHONWARNINGS
                        set which warnings to report, see -W option of python
                        itself.
 
logging:
  --no-print-logs       disable printing caught logs on failed tests.
  --log-level=LOG_LEVEL
                        logging level used by the logging module
  --log-format=LOG_FORMAT
                        log format as used by the logging module.
  --log-date-format=LOG_DATE_FORMAT
                        log date format as used by the logging module.
  --log-cli-level=LOG_CLI_LEVEL
                        cli logging level.
  --log-cli-format=LOG_CLI_FORMAT
                        log format as used by the logging module.
  --log-cli-date-format=LOG_CLI_DATE_FORMAT
                        log date format as used by the logging module.
  --log-file=LOG_FILE   path to a file when logging will be written to.
  --log-file-level=LOG_FILE_LEVEL
                        log file logging level.
  --log-file-format=LOG_FILE_FORMAT
                        log format as used by the logging module.
  --log-file-date-format=LOG_FILE_DATE_FORMAT
                        log date format as used by the logging module.
 
re-run failing tests to eliminate flaky failures:
  --reruns=RERUNS       number of times to re-run failed tests. defaults to 0.
 
coverage reporting with distributed testing support:
  --cov=[path]          measure coverage for filesystem path (multi-allowed)
  --cov-report=type     type of report to generate: term, term-missing,
                        annotate, html, xml (multi-allowed). term, term-
                        missing may be followed by ":skip-covered".annotate,
                        html and xml may be be followed by ":DEST" where DEST
                        specifies the output location.
  --cov-config=path     config file for coverage, default: .coveragerc
  --no-cov-on-fail      do not report coverage if test run fails, default:
                        False
  --cov-fail-under=MIN  Fail if the total coverage is less than MIN.
  --cov-append          do not delete coverage but append to current, default:
                        False
 
custom options:
  --mode=MODE           my option: with_setup or without_setup
  --pin=PIN             my option: Yes or No
  --dsn=DSN             List of DSNs.
  --devicetype=DEVICETYPE
                        Enter device varient type e.g. vega, falcon
  --application={mmsdk,vega,falcon,gemini}
                        Enter application e.g. mmsdk, vega, falcon
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:
 
  markers (linelist)       markers for test functions
  norecursedirs (args)     directory patterns to avoid for recursion
  testpaths (args)         directories to search for tests when no files or dire
  console_output_style (string) console output: classic or with additional progr
  usefixtures (args)       list of default fixtures to be used with this project
  python_files (args)      glob-style file patterns for Python test module disco
  python_classes (args)    prefixes or glob names for Python test class discover
  python_functions (args)  prefixes or glob names for Python test function and m
  xfail_strict (bool)      default for the strict parameter of xfail markers whe
  junit_suite_name (string) Test suite name for JUnit report
  doctest_optionflags (args) option flags for doctests
  doctest_encoding (string) encoding used for doctest files
  cache_dir (string)       cache directory path.
  filterwarnings (linelist) Each line specifies a pattern for warnings.filterwar
  log_print (bool)         default value for --no-print-logs
  log_level (string)       default value for --log-level
  log_format (string)      default value for --log-format
  log_date_format (string) default value for --log-date-format
  log_cli_level (string)   default value for --log-cli-level
  log_cli_format (string)  default value for --log-cli-format
  log_cli_date_format (string) default value for --log-cli-date-format
  log_file (string)        default value for --log-file
  log_file_level (string)  default value for --log-file-level
  log_file_format (string) default value for --log-file-format
  log_file_date_format (string) default value for --log-file-date-format
  addopts (args)           extra command line options
  minversion (string)      minimally required pytest version
 
environment variables:
  PYTEST_ADDOPTS           extra command line options
  PYTEST_PLUGINS           comma-separated plugins to load during startup
  PYTEST_DEBUG             set to enable debug tracing of pytest's internals

Pytest version using at runtime

This is pytest version 3.3.2, imported from /home/ANT.AMAZON.COM/jaiadi/kats-ag...n3.7/site-packages/pytest.py
setuptools registered plugins:
pytest-rerunfailures-2.2 at /home/ANT.AMAZON.COM/jaiadi/kats-ag...ages/pytest_rerunfailures.py
pytest-cov-2.3.1 at /home/ANT.AMAZON.COM/jaiadi/kats-ag...ackages/pytest_cov/plugin.py
# Content of Pytest.ini file
[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
markers =
    bat: test eligible for bat run and will run in Version set stage of pipeline
    regression: test eligible for regression run and will run in development stage of pipeline

@RonnyPfannschmidt

pytest version 3.3.2 unlike the 5.3.5 does not have the option you mention, please investigate why that environment is different

@jain18aditya

After making upgrade workaround i ran in to different issue

INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/_pytest/main.py", line 191, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/_pytest/main.py", line 247, in _main
INTERNALERROR>     config.hook.pytest_runtestloop(session=session)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/_pytest/main.py", line 272, in pytest_runtestloop
INTERNALERROR>     item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/64/workspace/.env/lib/python3.7/site-packages/pytest_rerunfailures.py", line 49, in pytest_runtest_protocol
INTERNALERROR>     rerun_marker = item.get_marker("flaky")
INTERNALERROR> AttributeError: 'Function' object has no attribute 'get_marker'

@RonnyPfannschmidt

Please update the rerunfailures plugin as well, and please start to use the code formatting feature of github, it’s painful to read unformatted pastes

@jain18aditya

Upgrading rerunfailure didnt work i suppose or may be it need some more plugins

INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/_pytest/main.py", line 191, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/_pytest/main.py", line 247, in _main
INTERNALERROR>     config.hook.pytest_runtestloop(session=session)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/_pytest/main.py", line 272, in pytest_runtestloop
INTERNALERROR>     item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/hooks.py", line 286, in __call__
INTERNALERROR>     return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 93, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/manager.py", line 87, in <lambda>
INTERNALERROR>     firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 80, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pluggy/callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pytest_rerunfailures.py", line 194, in pytest_runtest_protocol
INTERNALERROR>     _remove_cached_results_from_failed_fixtures(item)
INTERNALERROR>   File "/home/ANT.AMAZON.COM/jaiadi/kats-agent/workdir/65/workspace/.env/lib/python3.7/site-packages/pytest_rerunfailures.py", line 135, in _remove_cached_results_from_failed_fixtures
INTERNALERROR>     result, cache_key, err = getattr(fixture_def, cached_result)
INTERNALERROR> TypeError: cannot unpack non-iterable NoneType object

@jain18aditya

@RonnyPfannschmidt Formatting is not working for this log somehow. I tried that. I am getting this error consistently.
Versions used:

Successfully installed importlib-metadata-1.5.0 more-itertools-8.2.0 pluggy-0.13.1 pytest-5.4.1 wcwidth-0.1.8 zipp-3.1.0
Successfully installed pytest-rerunfailures-8.0

@RonnyPfannschmidt

Please downgrade pytest as rerunfailures is currently not yet supporting pytest 5.4

@neumond

Probably not the best place to report it, but I have irrelevant pytest: error: unrecognized arguments in the following case:

Directory structure:

src/
tests/
  conftest.py
setup.cfg

setup.cfg contents:

[tool:pytest]
testpaths = tests
addopts = --aiohttp-fast

There is a custom argument inside tests/conftest.py:

def pytest_addoption(parser):
    parser.addoption(
        '--swagger', action='store_true',
        default=False, help='validate swagger schema'
    )

Now, it works as expected, I can run following:

pytest --swagger
pytest --swagger tests/subdir/

But if I mistakingly run

pytest --swagger src/subdir/

I get pytest: error: unrecognized arguments: --swagger. If I run pytest src/subdir it outputs simply no tests ran, without errors.

$ pytest --version
This is pytest version 5.3.1, imported from /usr/local/lib/python3.7/site-packages/pytest.py
setuptools registered plugins:
  pytest-aiohttp-0.3.0 at /usr/local/lib/python3.7/site-packages/pytest_aiohttp/__init__.py
  pytest-timeout-1.3.3 at /usr/local/lib/python3.7/site-packages/pytest_timeout.py
  pytest-cov-2.8.1 at /usr/local/lib/python3.7/site-packages/pytest_cov/plugin.py
$ python -V
Python 3.7.4

@neumond

I think I get why this error happens. Since option is defined in tests/conftest.py it exists inside tests. Whenever I run pytest outside tests I get unrecognized argument error.

@Zac-HD

Closing this issue as the problem seems to be using old or incompatible versions of pytest and plugins, rather than a bug per se.

@RonnyPfannschmidt

based on the description i believe this is yet another rootdir/conftest finding issue

@RonnyPfannschmidt

oh wiat, iwas misstaken, the original issue is mixing, the thrown in other issue is something else

@nicoddemus

Содержание

  1. pytest: error: unrecognized arguments: —doctest-module #5554
  2. Comments
  3. unrecognized arguments: —html=report.htm #146
  4. Comments
  5. error: unrecognized arguments: -n #7943
  6. Comments
  7. Footer
  8. Command line parsing fails when path is a value for an option #906
  9. Comments

pytest: error: unrecognized arguments: —doctest-module #5554

  • a detailed description of the bug or suggestion
  • output of pip list from the virtual environment you are using
  • pytest and operating system versions
  • minimal example if possible
  • pytest version 5.0.0.
  • setuptools registered plugins:
    • doubles-1.5.3
    • pytest-factoryboy-2.0.3
    • pytest-cov-2.7.1
    • pytest-osxnotify-0.1.7
    • pytest-flask-0.15.0

Since v5.0.0, I’m getting unrecognized arguments: —doctest-module .

pytest section of my setup.cfg :

The v5 changelog does mention something about —doctest-module but it does not offer any explanation why my case would fail. Also, I’m still following the setup recommended in https://docs.pytest.org/en/latest/doctest.html

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

The option is named —doctest-modules (plural). This used to work prior 5.0 because ArgumentParser contains a feature that accepts «partial options», that’s why —doctest-module used to work. We have disabled «partial options» because it brings a number of problems.

This is mentioned in more details on the CHANGELOG:

#1149: Pytest no longer accepts prefixes of command-line arguments, for example typing pytest —doctest-mod inplace of —doctest-modules. This was previously allowed where the ArgumentParser thought it was unambiguous, but this could be incorrect due to delayed parsing of options for plugins. See for example issues #1149, #3413, and #4009.

I’m closing for now, feel free to follow up with other questions. 👍

Источник

unrecognized arguments: —html=report.htm #146

I see below error when i tried to run my py test

command tried : pytest test_blank_pages.py —html=report.html

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

It seems pytest-html is not installed, can you please post the output of pytest —version ?

Closing due to inactivity.

]# pytest —html=report.html
usage: pytest [options] [file_or_dir] [file_or_dir] [. ]
pytest: error: unrecognized arguments: —html=report.html
inifile: None
rootdir: /root

pip install pytest-html, had done.

@goblinintree please show the output from pip install pytest-html and pytest —version thanks.


Hey @lovto1314, if pytest-html is properly installed the output should be something like:

If some message like the above doesn’t show up, please do pip install pytest-html .

I think pytest does not support python2.7;
When I specify the python version with python3 ,It work.
python3 -m pytest —html=./report.html test/example.py

Hi @banrieen, pytest does support Python 2, what is happening is that you have installed pytest into your Python 3 interpreter.

When I type «pytest —capture=no —verbose —html=report.html test_XXXX.py» in CLI, i just run across the same error, the reason is pytest-html was installed into Python2 environment instead of Python3(I have both Python2 and Python3 installed ). After finishing «pip3 install pytest-html», the problem solved.

@goblinintree please show the output from pip install pytest-html and pytest —version thanks.

pytest-html is a plugin for pytest, not part of pytest library.

«pip3 install pytest-html»

run this command and it will solve your issue.

When I execute python executable file getting below error. python=3.9

MacBook-Pro:dist$ ./example
Running tests, tests_file = /var/folders/lc/jj6rl3p14pgfvmndp_jghnmc0000gn/T/_MEIyyLKQu/tests.py
ERROR: usage: example [options] [file_or_dir] [file_or_dir] [. ]
example: error: unrecognized arguments: —html=report.html —self-contained-html
inifile: None
rootdir: /Users/Downloads/example-pytest-html-in-pyinstaller-master/mypkg/dist

MacBook-Pro:$ pytest —version
pytest 7.1.2

Installed pip3 install pytest-html also, but still no use

When I execute python executable file getting below error. python=3.9

MacBook-Pro:dist$ ./example Running tests, tests_file = /var/folders/lc/jj6rl3p14pgfvmndp_jghnmc0000gn/T/_MEIyyLKQu/tests.py ERROR: usage: example [options] [file_or_dir] [file_or_dir] [. ] example: error: unrecognized arguments: —html=report.html —self-contained-html inifile: None rootdir: /Users/Downloads/example-pytest-html-in-pyinstaller-master/mypkg/dist

MacBook-Pro:$ pytest —version pytest 7.1.2

Installed pip3 install pytest-html also, but still now use

Did you install pytest with pip3 as well?

Yes, here is the list of packages installed

MacBook-Pro:$ pip3 list
Package Version

altgraph 0.17.2
appdirs 1.4.4
argparse-addons 0.7.0
art 5.2
attrs 21.4.0
bcrypt 3.2.0
bincopy 17.9.0
certifi 2021.5.30
cffi 1.14.5
chardet 4.0.0
crcmod 1.7
cryptography 3.4.4
distlib 0.3.4
filelock 3.6.0
freya 0.0.1
helpers 0.2.0
html-testRunner 1.2.1
humanfriendly 9.2
idna 2.10
iniconfig 1.1.1
Jinja2 3.1.2
macholib 1.16
MarkupSafe 2.1.1
outcome 1.1.0
packaging 21.3
paramiko 2.10.4
pc-ble-driver-py 0.16.2
pip 21.1.1
platformdirs 2.5.1
pluggy 1.0.0
py 1.11.0
pycparser 2.20
pyinstaller 4.10
pyinstaller-hooks-contrib 2022.3
PyNaCl 1.5.0
pyparsing 3.0.7
PyQt5 5.15.6
PyQt5-Qt5 5.15.2
PyQt5-sip 12.10.1
PyQt5-stubs 5.15.6.0
PyQtWebEngine 5.15.5
PyQtWebEngine-Qt5 5.15.2
pyreadline 2.1
pyserial 3.5
pysftp 0.2.9
pytest 7.1.2
pytest-html 3.1.1
pytest-metadata 2.0.1
requests 2.25.1
setuptools 56.0.0
sftpclient 1.0.0
six 1.16.0
tomli 2.0.1
urllib3 1.26.5
virtualenv 20.14.0
wheel 0.37.1
wrapt 1.14.0

Here is the code:

if name == «main«:
test_module = resource_path(«tests.py»)
print(«Running tests, tests_file = <>«.format(test_module))
pytest.main([«-vvv», «-p»,
«pytest_html»,
«—html=report.html»,
«—self-contained-html»,
«—capture=tee-sys»,
«—junitxml=report.xml», test_module])

I see below error when i tried to run my py test

command tried : pytest test_blank_pages.py —html=report.html

@anand853 Did this issue resolve?

Hello, I’m facing a similar issue when I try to execute for .exe file creation

.
pyinstaller —onefile —noconfirm —nowindow —exclude-module PyQt5
—add-data «3rdparty/pytest_html:./pytest_html»
—add-data «tests:tests»
—add-data «mypkg:mypkg»
—additional-hooks-dir=hooks
—hidden-import=pytest_html
-n example mypkg/main.py
.

After running the above command in my windows cmd tool, I’m getting an error

.
File «d:report_genaration codeexample-pytest-html-in-pyinstallervenvlibsite-packagesPyInstallerbuildingbuild_main.py», line 481, in assemble
priority_scripts.append(self.graph.add_script(script))
File «d:report_genaration codeexample-pytest-html-in-pyinstallervenvlibsite-packagesPyInstallerdependanalysis.py», line 265, in add_script
self._top_script_node = super().add_script(pathname)
File «d:report_genaration codeexample-pytest-html-in-pyinstallervenvlibsite-packagesPyInstallerlibmodulegraphmodulegraph.py», line 1415, in add_script
with open(pathname, ‘rb’) as fp:
FileNotFoundError: [Errno 2] No such file or directory: ‘D:’

(venv) D:Report_genaration codeexample-pytest-html-in-pyinstaller> —add-data «3rdparty/pytest_html:./pytest_html»
‘—add-data’ is not recognized as an internal or external command,
operable program or batch file.

(venv) D:Report_genaration codeexample-pytest-html-in-pyinstaller> —add-data «tests:tests»
‘—add-data’ is not recognized as an internal or external command,
operable program or batch file.

(venv) D:Report_genaration codeexample-pytest-html-in-pyinstaller> —add-data «mypkg:mypkg»
‘—add-data’ is not recognized as an internal or external command,
operable program or batch file.

(venv) D:Report_genaration codeexample-pytest-html-in-pyinstaller> —additional-hooks-dir=hooks
‘—additional-hooks-dir’ is not recognized as an internal or external command,
operable program or batch file.

(venv) D:Report_genaration codeexample-pytest-html-in-pyinstaller> —hidden-import=pytest_html
‘—hidden-import’ is not recognized as an internal or external command,
operable program or batch file.

Источник

error: unrecognized arguments: -n #7943

I have a hello.py file which includes

When I am running this file using python hello.py, I am getting following error:

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

Hello, @saurabhkdhiman as a first thing, your function:

takes no args, perhaps start with:

Can you share the contents of your pytest.ini file also please

@symonk Thanks for quick reply.
I have executed it without specifying plugins( pytest.main(YOUR_ARGS_HERE)) and it worked fine but when I created package of this .py file using pyinstaller and executed this .exe file, I am getting same error:

ERROR: usage: run_test.exe [options] [file_or_dir] [file_or_dir] [. ]
hello.exe: error: unrecognized arguments: —html=report.html -n 2
inifile: C:UserssauraDocumentsLatestunifiedclientautomationpytest.ini
rootdir: C:UserssauraDocumentsLatestunifiedclientautomation

Pytest.ini file content:
[pytest]
log_cli = True
addopts = -v -s —html=report.html

Under pyinstaller xdist does not work for technical reasons (pyinstaller breaks things)

Good to know @RonnyPfannschmidt thanks for the info

@saurabhkdhiman can we close this query based on Ronnys feedback?

@symonk can I get a fix OR any solution for this?

@saurabhkdhiman unfortunately there’s no easy fix, pytest-xdist and any freeze method (pyinstaller, cx_freeze, etc) are not really compatible.

These are the problems:

  1. On those environments setuptools entry points are not processed (so xdist, and any other plugins, are not loaded).
  2. pytest-xdist in particular spawns other python processes using sys.executable -c , executing xdist.remote as source code passed as argument. This is a problem because a) your executable needs to understand -c and execute the code given, and b) pytest-dist uses inspect.getsource to obtain the source code of xdist.remote , and that does not work in a frozen environment.

So there are a number of problems that need to be overcome, which can’t really be fixed by xdist or the frozen environments directly. It is not impossible, I’ve managed to do it at work but only in a very custom workflow that’s not really shareable, but it is pretty complex.

Closing for now, but feel free to follow up with further questions.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Command line parsing fails when path is a value for an option #906

On Mac OS X 10.10.4 using the latest homebrew Python 2.7.10, and py.test 2.7.2, if type on the command line:
py.test —app

/path/to/app —host http://localhost:4444 tests/mobile

I get the following error:

This seems to be an issue regardless of OS or Python version.

This only works if I put the path as a last option. But this defeats the purpose of having options that can be set in «any» order.

This is a section of my conftest.py:

Things to note: A full path name works okay, but it seems that a

and a $varialbe will fail to parse.

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

can you please show your folder layout as well including where you run py.test

Running Python and Py.test in a virtualenv

I run py.test from at . /automation/ as my root folder.

The problem is how conftest files and command-line options interact. This section explains in detail how plugins and conftest files are loaded during startup, but relevant to this issue is this note:

Note that pytest does not find conftest.py files in deeper nested sub directories at tool startup. It is usually a good idea to keep your conftest.py file in the top level test or project root directory.

So pytest starts and loads the initial plugins (registered using setuptools) and conftest files (just those found in cwd), reads command line options defined by plugins and conftest files found, parses the command line supplied by the user and starts collecting tests and other conftest files. That’s the reason you see the error about the unknown command line option if the conftest file is not at the cwd, as it would be loaded only later during test collection.

To fix this I suggest the following options:

Move your options to a «proper» setuptools plugin (docs here;

If the conftest is inside your application’s package, you can move it to a separate module and ask pytest to treat it as a plugin by using the —addopts option in a pytest.ini file:

This will ensure pytest will load your plugin before actually parsing the command-line supplied by the user.

Having said all that, I think we should add something to the docs about this issue, as I believe it is a common source of confusion.

I am not convinced your explanation is the reason why this fail. If I reverse the options to py.test —host http://localhost:4444 tests/mobile —app

/path/to/app I have no issues.

Hmmm sorry, I missed your note at the end:

Things to note: A full path name works okay, but it seems that a

and a $varialbe will fail to parse.

So, if you execute:

But if you execute:

That is correct.

Thanks, sorry I misunderstood the problem initially.

This certainly looks like a bug, thanks for the report!

@Dude-x I’m having trouble obtaining the same error using the conftest.py file you provided, on Windows and Ubuntu, pytest version 2.7.2 and master . Could you provide a minimal example which reproduces your problem?

It seems issue #949 is somewhat related. I’ll whip up a minimum viable test case later.

Here’s a simple test case, using the latest stable release of py.test (2.7.2)
Directory structure:

Content of conftest.py

Command line at /Users/dude-x/development/test-case

The thing to notice is that the rootdir is wrong, it should be /test-case, and not my parent.

Here’s one where it fails to parse:

Hi @Dude-x, thanks for posting the example. 😄

I think I know what’s going on. During initialization, pytest tries to parse the arguments from the command-line. At this stage only builtin and plugin options are known, so the unknown args are kept aside for later inspection. After this, it tries to determine the rootdir by looking at all unknown arguments which are clearly not options (don’t start with — ). At this point, it doesn’t know your —host option takes a parameter (it could be a flag for all pytest knows at this point) so it looks at the next argument and seeing a directory, tries to use it to determine rootdir . Only later it will load the conftest files and parse the remaining arguments.

So, it all boils down to the fact that conftests are loaded at a later stage than builtin and plugin options, which can affect which command line options will actually be validated and used as this mechanism depends entirely from where you execute py.test , or which arguments are passed on the command line.

If you change your conftest file into a plugin, it should work consistently no matter where you call py.test from, or what you pass on the command-line.

It is unfortunate (but understandable) that there’s this gotcha when working with pytest_addoption and conftest files, because conftest initialization being lazy as it is now can lead to surprising errors. Perhaps a note to pytest_addoption discouraging its use from conftest files would at least warn users of these pitfall?

Источник

The problem is that pytest searches for //pytest.ini, //tox.ini, //setup.cfg, and //setup.py. Each of them caused either genericpath.exists() or genericpath.isfile() to consume about 2.5 seconds.

On fix is to add the lines below to genericpath.exists() and genericpath.isfile() to skip those four specific paths.

if path.startswith(r'//'):
    return False

An alternative fix would be to modify _pytest/config.py so it does not form those double-slash in the paths to search.

The code used to find out the exact problem is pasted below. Set myshow = True so it will show how time is consumed for every file it is searching for.

$ diff -u /usr/lib/python2.6/genericpath.py genericpath.py
--- /usr/lib/python2.6/genericpath.py   2012-06-09 08:33:12.000000000 -0700
+++ genericpath.py      2015-06-11 11:46:33.674285900 -0700
@@ -9,14 +9,29 @@
 __all__ = ['commonprefix', 'exists', 'getatime', 'getctime', 'getmtime',
            'getsize', 'isdir', 'isfile']

+myshow = False
+import time as mytime
+mybasetime = mytime.time()
+def myshowtime():
+    currenttime = mytime.time()
+    tmdiff = currenttime - mybasetime
+    global mybasetime
+    mybasetime = currenttime
+    return tmdiff

 # Does a path exist?
 # This is false for dangling symbolic links on systems that support them.
 def exists(path):
     """Test whether a path exists.  Returns False for broken symbolic links"""
+    pretime = myshowtime()
+    if path.startswith(r'//'):
+        if myshow: print "n  genericpath exists  %8.3f %8.3f False " % (pretime, myshowtime()), " ", path, "n"
+        return False
     try:
         st = os.stat(path)
+        if myshow: print "n  genericpath exists  %8.3f %8.3f True  " % (pretime, myshowtime()), " ", path, "n"
     except os.error:
+        if myshow: print "n  genericpath exists  %8.3f %8.3f False " % (pretime, myshowtime()), " ", path, "n"
         return False
     return True

@@ -25,9 +40,15 @@
 # for the same path ono systems that support symlinks
 def isfile(path):
     """Test whether a path is a regular file"""
+    pretime = myshowtime()
+    if path.startswith(r'//'):
+        if myshow: print "n  genericpath isfile  %8.3f %8.3f False " % (pretime, myshowtime()), " ", path, "n"
+        return False
     try:
         st = os.stat(path)
+        if myshow: print "n  genericpath isfile  %8.3f %8.3f True  " % (pretime, myshowtime()), " ", path, "n"
     except os.error:
+        if myshow: print "n  genericpath isfile  %8.3f %8.3f False " % (pretime, myshowtime()), " ", path, "n"
         return False
     return stat.S_ISREG(st.st_mode)

Hi Guys,

I am trying to create one Pytest report in HTML format. But It is showing me the below error.

C:UsersNadeem Akhterpytest>pytest -v --html=basic.html
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --html=basic.html
  inifile: None
  rootdir: C:UsersNadeem Akhterpytest

How can I solve this error?







Jun 24, 2020


in Python


by



• 38,240 points





5,227 views



1 answer to this question.

Hi@akhtar,

You have to install one module named pytest-html. It allows you to create one report in HTML format. You can use the below-given command to install a pytest-html module.

$ pip install pytest-html==2.1.1

I hope this will help you.






answered

Jun 24, 2020


by
MD


• 95,420 points



Related Questions In Python

  • All categories

  • ChatGPT
    (4)

  • Apache Kafka
    (84)

  • Apache Spark
    (596)

  • Azure
    (131)

  • Big Data Hadoop
    (1,907)

  • Blockchain
    (1,673)

  • C#
    (141)

  • C++
    (271)

  • Career Counselling
    (1,060)

  • Cloud Computing
    (3,446)

  • Cyber Security & Ethical Hacking
    (147)

  • Data Analytics
    (1,266)

  • Database
    (855)

  • Data Science
    (75)

  • DevOps & Agile
    (3,575)

  • Digital Marketing
    (111)

  • Events & Trending Topics
    (28)

  • IoT (Internet of Things)
    (387)

  • Java
    (1,247)

  • Kotlin
    (8)

  • Linux Administration
    (389)

  • Machine Learning
    (337)

  • MicroStrategy
    (6)

  • PMP
    (423)

  • Power BI
    (516)

  • Python
    (3,188)

  • RPA
    (650)

  • SalesForce
    (92)

  • Selenium
    (1,569)

  • Software Testing
    (56)

  • Tableau
    (608)

  • Talend
    (73)

  • TypeSript
    (124)

  • Web Development
    (3,002)

  • Ask us Anything!
    (66)

  • Others
    (1,938)

  • Mobile Development
    (263)

Subscribe to our Newsletter, and get personalized recommendations.

Already have an account? Sign in.

Понравилась статья? Поделить с друзьями:
  • Pytest assert error
  • Pyscripter could not load a python engine ошибка
  • Pyqtdeploy build there was an error reading the project file
  • Pxe e23 client received tftp error from server
  • Pyqt5 qmessagebox error