from unittest import TestCase, main import os import sys def new_fspath(path): if isinstance(path, (str, bytes)): return path try: return path.__fspath__() except AttributeError: if hasattr(path, '__fspath__'): raise return path class TestFSPath(TestCase): def test_bad_fspath(self): # already works (meaning the exception bubbles up) class Buggy: def __fspath__(self): self.blah_blah self.assertRaises(AttributeError, fspath, Buggy()) def test_bad_return_from_fspath(self): # already works class NoPath: def __fspath__(self): return 42 self.assertEqual(fspath(NoPath()), 42) def test_nonpath_in_to_fspath(self): # will work with proposed change self.assertEqual(fspath(13), 13) def test_custom_exception(self): # will work with proposed change with self.assertRaises(ValueError): class NoPath: pass this = fspath(NoPath()) if not isinstance(this, (str, int)): raise ValueError('bytes not allowed!') if sys.argv[1:2] == ['new']: fspath = new_fspath sys.argv.pop(1) else: fspath = os.fspath main()