Python | Тестирование вывода на стандартный вывод

Опубликовано: 12 Апреля, 2022

Тестирование является важной частью разработки, поскольку нет компилятора для анализа кода до того, как Python выполнит его.
Для программы, у которой есть метод, вывод которого идет на стандартный вывод (sys.stdout) . Это почти всегда означает, что он выводит текст на экран. Любят написать тест для кода, чтобы доказать, что при правильном вводе отображается правильный вывод.

Using the unittest.mock module’s patch() function, it’s pretty simple to mock out sys.stdout for just a single test, and put it back again, without messy temporary variables or leaking mocked-out state between test cases.

Code #1 : Example
def urlprint(protocol, host, domain):
    url = "{}://{}.{}".format(protocol, host, domain)
    print(url)

The built-in print function, by default, sends output to sys.stdout. In order to test that output is actually getting there, it is to be mocked out using a stand-in object, and then make assertions about what happened.

Using the unittest.mock module’s patch() method makes it convenient to replace objects only within the context of a running test, returning things to their original state immediately after the test is complete.

 
Code #2 : Test code for the above code

from io import StringIO
from unittest import TestCase
from unittest.mock import patch
import mymodule
  
class TestURLPrint(TestCase):
      
    def test_url_gets_to_stdout(self):
        protocol = "http"
        host = "www"
        domain = "example.com"
        expected_url = "{}://{}.{} ".format(protocol, host, domain)
          
        with patch("sys.stdout", new = StringIO()) as fake_out:
            mymodule.urlprint(protocol, host, domain)
            self.assertEqual(fake_out.getvalue(), expected_url)

 

  • The urlprint() function takes three arguments, and the test starts by setting up dummy arguments for each one. The expected_url variable is set to a string containing the expected output.
  • To run the test, the unittest.mock.patch() function is used as a context manager to replace the value of sys.stdout with a StringIO object as a substitute.
  • The fake_out variable is the mock object that’s created in this process. This can be used inside the body of the with statement to perform various checks. When the with statement completes, patch conveniently puts everything back the way it was before the test ever ran.
  • It’s worth noting that certain C extensions to Python may write directly to standard output, bypassing the setting of sys.stdout.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.