From da2c52a50211af97f215148a5cf73dab936fba21 Mon Sep 17 00:00:00 2001 From: Jonathan Lange Date: Sat, 4 Aug 2012 18:32:01 +0100 Subject: Add an 'abspath' helper. --- lib/fixtures/_fixtures/tempdir.py | 10 ++++++++++ lib/fixtures/tests/_fixtures/test_tempdir.py | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lib/fixtures/_fixtures/tempdir.py b/lib/fixtures/_fixtures/tempdir.py index fd5502c..b37a32b 100644 --- a/lib/fixtures/_fixtures/tempdir.py +++ b/lib/fixtures/_fixtures/tempdir.py @@ -18,6 +18,7 @@ __all__ = [ 'TempDir', ] +import os import shutil import tempfile @@ -43,6 +44,15 @@ class TempDir(fixtures.Fixture): self.path = tempfile.mkdtemp(dir=self.rootdir) self.addCleanup(shutil.rmtree, self.path, ignore_errors=True) + def abspath(self, *children): + """Return an absolute path, given one relative to this ``TempDir``. + + WARNING: This does not do any checking of ``children`` to make sure + they aren't walking up the tree using path segments like '..' or + '/usr'. Use at your own risk. + """ + return os.path.abspath(os.path.join(self.path, *children)) + class NestedTempfile(fixtures.Fixture): """Nest all temporary files and directories inside another directory. diff --git a/lib/fixtures/tests/_fixtures/test_tempdir.py b/lib/fixtures/tests/_fixtures/test_tempdir.py index 7fc5d45..cb0584e 100644 --- a/lib/fixtures/tests/_fixtures/test_tempdir.py +++ b/lib/fixtures/tests/_fixtures/test_tempdir.py @@ -46,6 +46,27 @@ class TestTempDir(testtools.TestCase): with fixture: self.assertThat(fixture.path, StartsWith(root)) + def test_abspath(self): + temp_dir = self.useFixture(TempDir()) + root = temp_dir.path + relpath = 'foo/bar/baz' + self.assertEqual( + os.path.join(root, relpath), temp_dir.abspath(relpath)) + + def test_abspath_multiple_children(self): + temp_dir = self.useFixture(TempDir()) + root = temp_dir.path + self.assertEqual( + os.path.join(root, 'foo', 'bar', 'baz'), + temp_dir.abspath('foo', 'bar', 'baz')) + + def test_abspath_naughty_children(self): + temp_dir = self.useFixture(TempDir()) + root = temp_dir.path + self.assertEqual( + os.path.abspath(os.path.join(root, '..', 'bar', 'baz')), + temp_dir.abspath('..', 'bar', 'baz')) + class NestedTempfileTest(testtools.TestCase): """Tests for `NestedTempfile`.""" -- cgit v1.2.1