Skip to content

capsys doesn't work correctly when you use C++ iostream from conftest #5134

Closed
@antocuni

Description

@antocuni

The title is a bit obscure, but I think it is better explained with an example. Suppose that the following conditions are met:

  1. a C++ extension which uses std::cout inside its initxxx(void) function
  2. you import this extension in the conftest
  3. you use --capture=fd (the default)
  4. you use with capsys.disabled(): (either directly or indirectly by using --pdb)

In that case, calls to stdio.write() are not flushed automatically. The following gist includes a working example:
https://gist.github.com/antocuni/b444c2c8b37821a95f45bee42e78d3cf

To reproduce, simply run:

$ python setup.py build_ext -i
$ py.test test_noflush.py

You should be able to see the numbers 0..9 to be printed at regular intervals. However, you see them only when stdout is flushed.

Another way to see the problem is to use --pdb; using the provided gist, do the following:

py.test test_noflush.py -k test_enter_pdb --pdb
...
(Pdb) sys.stdout.write('hello\n'); time.sleep(1)
hello

Normally, you would expect to see hello while sleeping; however, because of the bug you see hello only AFTER the sleep (this happens because pdb uses readline which flushes stdout before displaying the prompt).

If you do either one of the following things, the bug disappear:

  1. comment out import dummy inside conftest.py OR
  2. comment out the call to std::cout inside dummy.cpp OR
  3. uncomment the call to sys.stdout.flush() in test_noflush.py

Additional info:

  • pip list of the virtual environment you are using
Package        Version
-------------- -------
atomicwrites   1.3.0  
attrs          19.1.0 
funcsigs       1.0.2  
more-itertools 5.0.0  
pathlib2       2.3.3  
pip            19.0.3 
pluggy         0.9.0  
py             1.8.0  
pytest         4.4.1  
scandir        1.10.0 
setuptools     41.0.0 
six            1.12.0 
wheel          0.33.1 
  • pytest and operating system versions:
$ pytest --version
This is pytest version 4.4.1, imported from /tmp/yyy/local/lib/python2.7/site-packages/pytest.pyc

$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 18.04.2 LTS
Release:	18.04
Codename:	bionic

Metadata

Metadata

Assignees

No one assigned

    Labels

    plugin: capturerelated to the capture builtin plugintype: bugproblem that needs to be addressed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions