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.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Unittest discovery not working when sys.stdout is set in global scope #17957
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()
Create a test file - example above.
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
We are removing the dependency in stdout. This is problematic in other scenarios where python has some library installed, and on load of that library it prints something. This print can occur in pth files which are loaded before any script runs. This will be addressed in #17242
Activity
karthiknadig commentedon Jan 11, 2022
We are removing the dependency in
stdout. This is problematic in other scenarios where python has some library installed, and on load of that library it prints something. This print can occur in pth files which are loaded before any script runs. This will be addressed in #17242