1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Mock patch sys.stdout to StringIO as a decorator (Python)

Discussão em 'Python' iniciado por Stack, Setembro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to mock.patch sys.stdout to StringIO as a decorator to record the output for testing.

    As a 'with' statement it works this way:

    with mock.patch('sys.stdout', new_callable = StringIO) as recorded_output:
    print('OUTPUT')
    r = recorded_output.getvalue()
    print(r)


    gets 'OUTPUT', but 'getvalue' doesn't work when used as a decorator:

    @mock.patch('sys.stdout', new_callable = StringIO)
    def test_stdout(self, recorded_output):
    print('OUTPUT')
    r = recorded_output.getvalue()
    print(r)


    gets error: Mock object has no attribute 'getvalue'

    Does anyone know how to write this as a decorator?

    Continue reading...

Compartilhe esta Página