I am trying to test the case where the number of parameters in the script being executed is less than three. When debugging, I see that an IndexError occurs, but for some reason assertRaises does not "see" it. Can anyone help fix this?
my_file.py:
def my_func():
try:
sys.argv[2]
except IndexError:
pass
text_sys_srgv.py
import sys
import unittest
import my_file
from unittest.mock import patch
class TestServer(unittest.TestCase):
def test_my_func(self):
work_dir = os.path.dirname(os.getcwd())
my_file_full_path = os.path.join(work_dir, 'my_file.py')
test_args = [my_file_full_path, 'arg1']
with patch.object(sys, 'argv', test_args):
self.assertRaises(IndexError, my_file.my_func)
if __name__ == '__main__':
unittest.main()
CodePudding user response:
Your my_func
does not raise the exception. It catches it. assertRaises
will confirm if the exception is actually thrown out of the function, instead of caught inside it and suppressed.