lundi 30 septembre 2019

Cross platform unit testing on functions using os.system in Python

I want to write (using pytest preferably) a unit test to determine whether the following function successfully clears the terminal across multiple platforms given an os_name ("nt" or something else like "posix"):

    def clear_terminal(os_name):
        code = os.system('cls' if os_name == 'nt' else 'clear')
        print()  # add padding at top of cleared screen

This is tricky because I currently only have access to a UNIX based platform, and I can't think of a straightforward way to test if giving the os_name as 'nt' will work on a Windows machine.

So far I have the following test (where os_name is a pytest fixture that can be one of "nt" or "posix"):

    def test_clear_terminal(os_name):
        with unittest.mock.patch(target='os.system') as os_system:
            clear_terminal()
            assert os_system.called_once_with(os_name)

The issue I have with that test is that it's really just patching the code I'm testing so it's basically useless! What would a rigorous approach to testing this code be? Would you have to just run the test on multiple different platforms or is there another way?

Aucun commentaire:

Enregistrer un commentaire