stdout and stderr capture with capsys

Suzanno Hogwarts :

I have a code where i need to check if password entered is empty. If yes, print message and exit from the script.

I am using pytest to validate this code and capturing the output using capsys fixture. But capsys.readouterr() is not capturing the output.

Code to Test

def get_password():
    password = getpass.getpass('Password required :', stream=None)
    if not password:
        print("NoPasswordError: Password not provided.Exiting from run")
        '''return -1'''
        sys.exit(-1)
    else:
        return password

pytest code

def test_input_validation_nopass(self,getpass,capsys):
    getpass.return_value = ''
    get_password()
    out, err = capsys.readouterr()
    sys.stdout.write(out)
    assert re.match('NoPasswordError',out,re.I)

However if I remove the sys.exit and place return, the output is captured. Currently I am getting below error:

pytest -q UnitTest.py -k test_input_validation_nopass -rx -rP
F                                                                                                                                                                 [100%]
=============================================================================== FAILURES ================================================================================
________________________________________________________________ TestClass.test_input_validation_nopass _________________________________________________________________

self = <UnitTest_buildUpgrade.TestClass object at 0x10d179978>, getpass = <MagicMock name='getpass' id='4514617832'>
capsys = <_pytest.capture.CaptureFixture object at 0x10d179a20>

    def test_input_validation_nopass(self,getpass,capsys):
        getpass.return_value = ''
>       get_password()

UnitTest_buildUpgrade.py:78: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    def get_password():
        password = getpass.getpass('Password required :', stream=None)
        if not password:
            print("NoPasswordError: Password not provided .Exiting from run")
            '''return -1'''
>           sys.exit(-1)
E           SystemExit: -1

CitrixADCUpgrade.py:19: SystemExit
------------------------------------------------------------------------- Captured stdout call --------------------------------------------------------------------------
NoPasswordError: Password not providedExiting from run
1 failed, 7 deselected in 0.45s
hoefling :

Calling sys.exit will raise a SystemExit. You need to catch this exception in the test:

import pytest

def test_input_validation_nopass(getpass, capsys):
    getpass.return_value = ''
    with pytest.raises(SystemExit):
        get_password()
    out, err = capsys.readouterr()
    assert re.match('NoPasswordError', out, re.I)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386105&siteId=1