WindowsError builtin does not exist when using pdb

62 views Asked by At

I have the following code in a file I'm testing. It checks if WindowsError does not exist and redefines it as a subclass of OSError. When debugging my application with pdb WindowsError is not available as a builtin so the if statement returns true even on Windows computers.

How would I test this file with pdb?

if not getattr(__builtins__, "WindowsError", None):
    class WindowsError(OSError): pass
class TestCases(unittest.TestCase)
    def test_removefile(self):
        try:
            os.remove(fd.filePath)
        except WindowsError as e:
            if e.errno == 2: pass
            else:
                raise e
if __name__ == '__main__':
    unittest.main()
1

There are 1 answers

0
Spitfire19 On

This code block will work inside of the Python debugger and during normal execution:

import exceptions

if not getattr(exceptions, "WindowsError", None):
        class WindowsError(OSError): pass

This solution also works and avoids string literals and an import of the full exceptions library:

try:
    from exceptions import WindowsError
except ImportError:
    class WindowsError(OSError): pass