Search code examples
pythonpython-3.xunit-testingstdoutprogram-entry-point

Python3 - output __main__ file prints when running unittests (from actual program, not unittests)


How can I make that my __main__ file prints are outputted, when I run tests? I mean prints from that file, not unittests files prints.

I have this sample structure (all files are in the same directory):

main.py:

import argparse

print('print me?')  # no output
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('name')
    args = parser.parse_args()
    print(args.name)  # no output

other.py:

def print_me():
    print('ran print_me')

test.py:

import unittest
import sh
import other


class TestMain(unittest.TestCase):

    def test_main(self):
        print('test_main')  # prints it.
        sh.python3('main.py', 'test123')

    def test_other(self):
        print('test_other')  # prints it.
        other.print_me()

And I run it with python3 -m nose -s or python3 -m unittest, but it makes no difference, prints are not outputted from main.py, only the ones that are defined directly on test file. Here is what I do get:

user@user:~/python-programs/test_main$ python3 -m nose -s
test_main
.test_other
ran print_me
.
----------------------------------------------------------------------
Ran 2 tests in 0.040s

OK

P.S. Of course if I run main.py without using tests, then it prints normally (for example using python shell/interpreter and calling main.py with sh, just like in unittests)


Solution

  • sh.python3 starts new process and its output is not captured by nose. You can redirect the output printing the result from it:

    print(sh.python3('main.py', 'test123'))