Commits

Antoine Pitrou committed a9cf391

Path('').parent() and Path('/').parent() now raise ValueError

Comments (0)

Files changed (2)

         drv = self._drv
         root = self._root
         parts = self._parts[:-level]
-        if not parts and (drv or root):
-            # If the path is absolute, we keep it absolute
-            parts = [self._parts[0]]
+        if not parts:
+            if level > len(self._parts) - bool(drv or root):
+                raise ValueError("level greater than path length")
         return self._from_parsed_parts(drv, root, parts)
 
     def parents(self):
         self.assertEqual(p.parent(), P('a/b'))
         self.assertEqual(p.parent(2), P('a'))
         self.assertEqual(p.parent(3), P())
-        self.assertEqual(p.parent(4), P())
+        self.assertRaises(ValueError, p.parent, 4)
         # Anchored
         p = P('/a/b/c')
         self.assertEqual(p.parent(), P('/a/b'))
         self.assertEqual(p.parent(2), P('/a'))
         self.assertEqual(p.parent(3), P('/'))
-        self.assertEqual(p.parent(4), P('/'))
+        self.assertRaises(ValueError, p.parent, 4)
+        # Invalid level values
+        self.assertRaises(ValueError, p.parent, 0)
+        self.assertRaises(ValueError, p.parent, -1)
 
     def test_parents_common(self):
         # Relative
         self.assertEqual(p.parent(), P('z:a/b'))
         self.assertEqual(p.parent(2), P('z:a'))
         self.assertEqual(p.parent(3), P('z:'))
-        self.assertEqual(p.parent(4), P('z:'))
+        self.assertRaises(ValueError, p.parent, 4)
         p = P('z:/a/b/c')
         self.assertEqual(p.parent(), P('z:/a/b'))
         self.assertEqual(p.parent(2), P('z:/a'))
         self.assertEqual(p.parent(3), P('z:/'))
-        self.assertEqual(p.parent(4), P('z:/'))
+        self.assertRaises(ValueError, p.parent, 4)
         p = P('//a/b/c/d')
         self.assertEqual(p.parent(), P('//a/b/c'))
         self.assertEqual(p.parent(2), P('//a/b'))
-        self.assertEqual(p.parent(3), P('//a/b'))
+        self.assertRaises(ValueError, p.parent, 3)
 
     def test_parents(self):
         # Anchored
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.