简体   繁体   中英

can't mock an exception with pytest

I do not seem to be able to test a getopt exception. A very simplified example is here (the main file):

import sys, getopt

def main():
    try:
        options, _ = getopt.getopt(sys.argv[1:], 'h')
    except getopt.GetoptError:
        print("here I want to go")

if __name__ == '__main__':
    main()

And the test file where I am trying to raise the GetoptError exception is here (the test file):

import getopt, mock, main

@mock.patch("getopt.getopt", mock.MagicMock(side_effect=getopt.GetoptError('')))
def main_test():
    try:
        main.main()
        assert False
    except getopt.GetoptError:
        assert True

Unfortunately no exception is raised. The test returns:

    @mock.patch("getopt.getopt", mock.MagicMock(side_effect=getopt.GetoptError('')))
    def main_test():
        try:
            main.main()
>           assert False
E           assert False

main_test.py:7: AssertionError

Can anybody point out what I am missing? Thank you.

Use with pytest.raises for testing exceptions:

def main_test():
  with pytest.raises(getopt.GetoptError)  as err:
     main.main()

Refer pytest assert for http://doc.pytest.org/en/latest/assert.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM