jeudi 18 février 2021

Execute python script, get its print and logging output and assert unittest

So I just recently stumbled into unittest and I have a program which I normally start like this python run.py -config /path/to/config.file -y. I wanted to write a simple test in a separate test.py file: Execute the script (it uses if __name__ == "__main__" as entry point), pass the mentioned arguments and get all of its output. I pass a prepared config file which is missing certain things, so the run.py will break and exactly log this error: "xyz was missing in Config file!" (see example below). I'll get a few words from print() and then the logging instance kicks in and handles from there on. How do I get its output so I can check it? Feel free to rewrite this, as I'm still learning, please bear with me.

Simplified example:

run.py

import logging

if __name__ == "__main__":
  print("Welcome! Starting execution.")

  < code to parse arguments: >
  < config = /path/to/config.file >

  logger = logging.getLogger(__name__)
  console_handler = logging.StreamHandler()
  logger.addHandler(console_handler)
  logger.info("Logging activated, let's go!")

  < code >

  if xyz not in config:
    logger.error("xyz was missing in Config file!")
    exit(1)

test.py

import unittest
import subprocess
import re

class TestEmpty(unittest.TestCase):
    def test_empty(self):
        with subprocess.Popen(["python", "run.py", "-config", "/path/to/config.file", "-y"], stdout=subprocess.PIPE) as p:
            out = p.stdout.read()
        regex = "xyz was missing in Config file!"
        assert re.match(regex, out)

if __name__ == "__main__":
    unittest.main()

Aucun commentaire:

Enregistrer un commentaire