Skip to content

Unittest discovery not working when sys.stdout is set in global scope #17957

@igalassaraf

Description

@igalassaraf

VS Code version

Version: 1.62.0 (user setup)

Extension version

v2021.11.1422169775

OS type

Linux

OS version

21.04 LTS (Hirsute Hippo), Linux 5.11.0-36-generic

Python distribution

Operating system

Python version

3.9.5

Language server

Pylance

Expected behaviour

Unittests discover should work and test should appear in side bar.

Actual behaviour

Nothing appears in testing

Steps to reproduce

import unittest
import sys
from memory_profiler import LogFile

sys.stdout = LogFile()

class TestSum(unittest.TestCase):
    def test_sum(self):
        assert sum([1, 2, 3]) == 6, "Should be 6"

if __name__ == '__main__':
    unittest.main()
  1. Create a test file - example above.
  2. In test file - Import LogFile from memory_profiler package and set sys.stdout with LogFile.

I found that the problem is in:
.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/unittest_discovery.py
The output of discovery is to stdout. Once stdout value is changed within tests code in global scope, unittest_discovery execute this change and therefore discovery output is addressed to another stdout object.

My patch to make it work is in generate_test_cases method:

def generate_test_cases(suite):
    for test in suite:
        if isinstance(test, unittest.TestCase):
            yield test
        else:
            for test_case in generate_test_cases(test):
                yield test_case


try:
    **vscode_stdout = sys.stdout**
    loader = unittest.TestLoader()
    suite = loader.discover(start_dir, pattern=pattern)
    **sys.stdout = vscode_stdout**
    print("start")  # Don't remove this line

Logs

". /intucell/latest/testing/bin/activate && echo 'e8b39361-0157-4923-80e1-22d70d46dee6' && python /home/intucell/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/printEnvVariables.py"
/intucell/latest/testing/bin/python ~/.vscode-server/extensions/ms-python.python-2021.11.1422169775/pythonFiles/testing_tools/unittest_discovery.py . *_test.py
cwd: ~/work/scripts/playground

Code of Conduct

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

Metadata

Metadata

Assignees

Labels

area-testingbugIssue identified by VS Code Team member as probable bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions