pytest-dev / pytest-dev/pytest

Testing argparse accepting strings from stdin raises OSError

Open
#7,284 14 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: bug
Dominant language
Python
Stars
14.5k
Forks
3.4k
Avg merge
2d 9h
Merged PRs (30d)
35

Description

  • a detailed description of the bug or suggestion

I was working on an enhancement of the astpretty module, which eventually should support piping strings into it like echo "x = y" | astpretty. However, if testing the approach I used to implement this feature, pytest raises an OSError.

  • minimal example if possible
$ tree .
.
├── test
│   └── test_main.py
└── t.py

1 directory, 2 files
# t.py
import sys
from argparse import ArgumentParser


def main(argv=None):
    parser = ArgumentParser()
    parser.add_argument('filename', nargs='?')
    args = parser.parse_args(argv)

    if args.filename:
        with open(args.filename, 'rb') as f:
            contents = f.read()
    elif not sys.stdin.isatty():
        contents = sys.stdin.read().encode('utf-8')
    else:
        parser.print_help()
        return 0

    print("Finished")
    return 0


if __name__ == "__main__":
    exit(main())
# test/test_main.py
import t


def test_main(capsys, tmpdir):
    expected = '''\
usage: t.py [-h] [filename]

positional arguments:
  filename

optional arguments:
  -h, --help  show this help message and exit'''
    t.main()
    out, _ = capsys.readouterr()
    assert out == expected
$ pytest
============================= test session starts ==============================
platform linux -- Python 3.9.0b1, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /tmp/pytest
collected 1 item

test/test_main.py F                                                      [100%]

=================================== FAILURES ===================================
__________________________________ test_main ___________________________________

capsys = <_pytest.capture.CaptureFixture object at 0x7f99d29183d0>
tmpdir = local('/tmp/pytest-of-florian/pytest-34/test_main0')

    def test_main(capsys, tmpdir):
        expected = '''\
    usage: t.py [-h] [filename]
    
    positional arguments:
      filename
    
    optional arguments:
      -h, --help  show this help message and exit'''
>       t.main()

test/test_main.py:13: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
t.py:14: in main
    contents = sys.stdin.read().encode('utf-8')
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <_pytest.capture.DontReadFromInput object at 0x7f99d2a07820>, args = ()

    def read(self, *args):
>       raise IOError(
            "pytest: reading from stdin while output is captured!  Consider using `-s`."
        )
E       OSError: pytest: reading from stdin while output is captured!  Consider using `-s`.

.venv/lib/python3.9/site-packages/_pytest/capture.py:732: OSError
=========================== short test summary info ============================
FAILED test/test_main.py::test_main - OSError: pytest: reading from stdin whi...
============================== 1 failed in 0.04s ===============================

Note: The used approach (if not sys.stdin.isatty()) seems to be the recommended way to check whether stdin has some data to access. In fact, running and testing the script manually works fine.

  • output of pip list from the virtual environment you are using
Package        Version
-------------- -------
attrs          19.3.0
more-itertools 8.3.0
packaging      20.4
pip            20.1.1
pluggy         0.13.1
py             1.8.1
pyparsing      2.4.7
pytest         5.4.2
setuptools     41.2.0
six            1.15.0
wcwidth        0.1.9
  • pytest and operating system versions
$ pytest --version
This is pytest version 5.4.2
$ lsb_release -a
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04 LTS
Release:	20.04
Codename:	focal

Any ideas are welcomed. If I'm missing something, please point me in the right direction. Thanks for making pytest such a great framework!

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the failure using the example t.py and test/test_main.py with pytest 5.4.2, then read the captured-stdin behavior involved in the traceback. Determine the expected interaction between isatty(), stdin reads, and pytest capture; done means the behavior is defined and covered by a regression test without breaking normal stdin capture.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.