I am writing an interpreter in Python 3.12 and my module currently outputs using Python’s print function.
The interpreter module can take a file name as an input. The given file is some code in the language I’m writing (lox) and subsequently the interpreter will run the code from the file and print output to stdout.
In trying to write some unit tests I have found I cannot get the stdout to change between unit tests. (eg; looks like stdout is not flushing or something isn’t being over-written where it should)
I am using tox to execute the unit tests.
I can confirm my interpreter has different output when run it on the command line and I hand it different input files.
Output when I run my interpreter from the console with one input file.
(.venv) $ python -m MyInterpreter.interpreter ./tests/resources/statements.lox
one
True
3
Output when I run my interpreter from the console with the other input file
(.venv) $ python -m MyInterpreter.interpreter ./tests/resources/variableAssignment.lox
5
These are the unit tests I have written. (I know they don’t have assert statements. The problem I’m trying to illustrate isn’t with assertion.)
python
import unittest
import sys
from io import StringIO
from MyInterpreter import interpreter
class TestInterpreter_statements(unittest.TestCase):
def test_statements(self):
capturedOutput = StringIO()
sys.stdout = capturedOutput
interpreter.myInterpreter.runFile('tests/resources/statements.lox')
sys.stdout = sys.__stdout__
print('Captured 00', capturedOutput.getvalue())
class TestInterpreter_variable_assignment(unittest.TestCase):
def test_variableAssignment(self):
capturedOutput = StringIO()
sys.stdout = capturedOutput
interpreter.myInterpreter.runFile('tests/resources/variableAssignment.lox')
sys.stdout = sys.__stdout__
print('Captured 01', capturedOutput.getvalue())
When running those tests through tox I get this:
tests/test_interpreter.py Captured 00 one
True
3
.Captured 01 one
True
3
.
But I expected this
tests/test_interpreter.py Captured 00 one
True
3
.Captured 01 5
.
I have tried a number of ways for capturing stdout, flushing it or clearing it but I always end up with the output of one test becoming the stdout value in the subsequent test.
Maybe I’ve not properly understood some of these solutions and so they didn’t work for me..?
My attempts include concepts from;
- How to capture the stdout/stderr of a unittest in a variable?
- Redirecting stdout to “nothing” in python
- Pythonic way to flush() both sys.stdout & sys.stderr
- Python unittesting based on stdout from program — not all tests running, strange (and changin) result. Flushing problem?
- Usage of sys.stdout.flush() method
- Testing for stdout in Python Unit Test
- How do I revert sys.stdout.close()?