Commits

Antoine Pitrou committed 6622aea

Add the with_name() method.

Comments (0)

Files changed (2)

 
     @property
     def basename(self):
-        """
-        The final path component, minus its last suffix.
-        """
+        """The final path component, minus its last suffix."""
         basename = self.name
         suffix = self.suffix
         if not suffix:
             return basename
         return basename[:-len(suffix)]
 
+    def with_name(self, name):
+        """Return a new path with the file name changed."""
+        if not self.name:
+            raise ValueError("%r has an empty name" % (self,))
+        return self._from_parsed_parts(self._drv, self._root,
+                                       self._parts[:-1] + [name])
+
     def relative(self):
         """Return a new path without any drive and root.
         """
         self.assertEqual(P('a/Some name. Ending with a dot.').basename,
                          'Some name. Ending with a dot.')
 
+    def test_with_name_common(self):
+        P = self.cls
+        self.assertEqual(P('a/b').with_name('d.xml'), P('a/d.xml'))
+        self.assertEqual(P('/a/b').with_name('d.xml'), P('/a/d.xml'))
+        self.assertEqual(P('a/b.py').with_name('d.xml'), P('a/d.xml'))
+        self.assertEqual(P('/a/b.py').with_name('d.xml'), P('/a/d.xml'))
+        self.assertEqual(P('a/Dot ending.').with_name('d.xml'), P('a/d.xml'))
+        self.assertEqual(P('/a/Dot ending.').with_name('d.xml'), P('/a/d.xml'))
+        self.assertRaises(ValueError, P('').with_name, 'd.xml')
+        self.assertRaises(ValueError, P('.').with_name, 'd.xml')
+        self.assertRaises(ValueError, P('/').with_name, 'd.xml')
+
     def test_relative_common(self):
         P = self.cls
         p = P('a/b')
         self.assertEqual(P('c:a/Some name. Ending with a dot.').suffixes, [])
         self.assertEqual(P('c:/a/Some name. Ending with a dot.').suffixes, [])
 
-    def test_basename_common(self):
+    def test_basename(self):
         P = self.cls
         self.assertEqual(P('c:').basename, '')
         self.assertEqual(P('c:.').basename, '')
         self.assertEqual(P('c:a/Some name. Ending with a dot.').basename,
                          'Some name. Ending with a dot.')
 
+    def test_with_name(self):
+        P = self.cls
+        self.assertEqual(P('c:a/b').with_name('d.xml'), P('c:a/d.xml'))
+        self.assertEqual(P('c:/a/b').with_name('d.xml'), P('c:/a/d.xml'))
+        self.assertEqual(P('c:a/Dot ending.').with_name('d.xml'), P('c:a/d.xml'))
+        self.assertEqual(P('c:/a/Dot ending.').with_name('d.xml'), P('c:/a/d.xml'))
+        self.assertRaises(ValueError, P('c:').with_name, 'd.xml')
+        self.assertRaises(ValueError, P('c:/').with_name, 'd.xml')
+
     def test_relative(self):
         P = self.cls
         p = P('c:a/b')