@@ -2329,5 +2329,46 @@ def check(): |
|
|
2329 |
2329 |
check() |
2330 |
2330 |
|
2331 |
2331 |
|
|
2332 |
+class CompatiblePathTest(unittest.TestCase): |
|
2333 |
+""" |
|
2334 |
+ Test that a type can be made compatible with PurePath |
|
2335 |
+ derivatives by implementing division operator overloads. |
|
2336 |
+ """ |
|
2337 |
+ |
|
2338 |
+class CompatPath: |
|
2339 |
+""" |
|
2340 |
+ Minimum viable class to test PurePath compatibility. |
|
2341 |
+ Simply uses the division operator to join a given |
|
2342 |
+ string and the string value of another object with |
|
2343 |
+ a forward slash. |
|
2344 |
+ """ |
|
2345 |
+def __init__(self, string): |
|
2346 |
+self.string = string |
|
2347 |
+ |
|
2348 |
+def __truediv__(self, other): |
|
2349 |
+return type(self)(f"{self.string}/{other}") |
|
2350 |
+ |
|
2351 |
+def __rtruediv__(self, other): |
|
2352 |
+return type(self)(f"{other}/{self.string}") |
|
2353 |
+ |
|
2354 |
+def test_truediv(self): |
|
2355 |
+result = pathlib.PurePath("test") / self.CompatPath("right") |
|
2356 |
+self.assertIsInstance(result, self.CompatPath) |
|
2357 |
+self.assertEqual(result.string, "test/right") |
|
2358 |
+ |
|
2359 |
+with self.assertRaises(TypeError): |
|
2360 |
+# Verify improper operations still raise a TypeError |
|
2361 |
+pathlib.PurePath("test") / 10 |
|
2362 |
+ |
|
2363 |
+def test_rtruediv(self): |
|
2364 |
+result = self.CompatPath("left") / pathlib.PurePath("test") |
|
2365 |
+self.assertIsInstance(result, self.CompatPath) |
|
2366 |
+self.assertEqual(result.string, "left/test") |
|
2367 |
+ |
|
2368 |
+with self.assertRaises(TypeError): |
|
2369 |
+# Verify improper operations still raise a TypeError |
|
2370 |
+10 / pathlib.PurePath("test") |
|
2371 |
+ |
|
2372 |
+ |
2332 |
2373 |
if __name__ == "__main__": |
2333 |
2374 |
unittest.main() |