Djent
Djent

Reputation: 3477

System ("pause") in unittest

I've got Python application which is compiled to .exe.
In some cases, program terminates with sys.exit (), but to not close console window I'm doing it with code below, which works fine:

try:
    sys.exit()
except SystemExit:
    raise
finally:
    os.system("pause")

The problem is, that I need to test if my code raises SystemExit, but due to filnally block, tests cannot pass - they are just infinite.
Is there any possibility, to let unittest pass os.system("pause")?
I can add a default parameter, which will prevent pausing, but it will be complicated in my case - if there is any possibility I would like to do it in unittests.

Upvotes: 1

Views: 987

Answers (1)

kwarunek
kwarunek

Reputation: 12587

I would simply mock os.system. More over even sys.exit to assert if it is called.

# your_module.py
import sys 
import os


def something():
    try:
        sys.exit()
    except SystemExit:
        raise
    finally:
        os.system("pause")

And the test

import unittest
import your_module
try:
    from unittest.mock import patch
except ImportError:
    from mock import patch


class TestSysexit(unittest.TestCase):

    @patch('your_module.os.system')
    def test_system_exit(self, mock_os_system):

        with self.assertRaises(SystemExit):
            your_module.something()
        mock_os_system.assert_called_once_with('pause')

if __name__ == '__main__':
    unittest.main()

mock and patch is in unittest.mock on python3 and in mock library on python2.

Upvotes: 3

Related Questions