Repository: jmcgeheeiv/pyfakefs
Pull request #455 (2018-11-28 20:21:57)

Set initial user and group IDs to real IDs
- added tests running as root to test both root and non-root cases
- adapted code and tests to consider root access

mrbean-bremen: I have one test failing in Python 3.7. I tried to skip it, but for some reason that does not work with root user.
jmcgeheeiv: Instead of using sudo, we can use my Docker container method to run the test as root without endangering the host.
mrbean-bremen: > Instead of using sudo, we can use my Docker container method to run the test as root without endangering the host.

The problem with the Docker image is that it runs only one Python version - or we have to configure it accordingly for each version. That is actually what Travis.CI does for us, and as it runs in cloned VMs that are trashed after the tests, there is no problem with endangering the host (otherwise they wouldn't provide sudo without password...).
Though as I wrote elsewhere, it would be a good idea also to run the tests in the provided Docker image to make sure that it works correctly.

My problem was that I got the wrong environment if run with sudo, so the system python (Python 2.7) was used instead of the Python version installed in the virtual environment. Inheriting PATH fixed this.
mrbean-bremen: Merging after resolviong conflicts again...

Patch:
diff --git a/CHANGES.md b/CHANGES.md
index 5bf3515..c054f47 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -10,6 +10,7 @@ The release versions are PyPi releases.
 #### Fixes
   * fixed `AttributeError` shown while displaying `fs` in a failing pytest 
     in Python 2
+  * fixed permission handling for root user 
 
 ## [Version 3.5.3](https://pypi.python.org/pypi/pyfakefs/3.5.3)
 
diff --git a/pyfakefs/fake_filesystem.py b/pyfakefs/fake_filesystem.py
index d13dd14..45b8494 100644
--- a/pyfakefs/fake_filesystem.py
+++ b/pyfakefs/fake_filesystem.py
@@ -111,13 +111,12 @@ from pyfakefs.extra_packages import use_scandir
 from pyfakefs.helpers import (
     FakeStatResult, FileBufferIO, IS_PY2, NullFileBufferIO,
     is_int_type, is_byte_string, is_unicode_string,
-    make_string_path, text_type
+    make_string_path, text_type, IS_WIN
 )
 
 if sys.version_info[0] < 3:
     import __builtin__
 
-
 __pychecker__ = 'no-reimportself'
 
 __version__ = '3.6'
@@ -167,8 +166,8 @@ FAKE_PATH_MODULE_DEPRECATION = (
 )
 
 NR_STD_STREAMS = 3
-USER_ID = 1
-GROUP_ID = 1
+USER_ID = 1 if IS_WIN else os.getuid()
+GROUP_ID = 1 if IS_WIN else os.getgid()
 
 
 def set_uid(uid):
@@ -4282,6 +4281,8 @@ class FakeOsModule(object):
             if os_error.errno == errno.ENOENT:
                 return False
             raise
+        if is_root():
+            mode &= ~os.W_OK
         return (mode & ((stat_result.st_mode >> 6) & 7)) == mode
 
     def chmod(self, path, mode, dir_fd=None, follow_symlinks=None):
@@ -4423,7 +4424,7 @@ class FakeOsModule(object):
             # note that a default value of 0o600 without a device type is
             # documented - this is not how it seems to work
             mode = S_IFREG | 0o600
-        if device or not mode & S_IFREG:
+        if device or not mode & S_IFREG and not is_root():
             self.filesystem.raise_os_error(errno.EPERM)
 
         filename = self._path_with_dir_fd(filename, self.mknod, dir_fd)
diff --git a/pyfakefs/helpers.py b/pyfakefs/helpers.py
index 4f34fd2..3f98f71 100644
--- a/pyfakefs/helpers.py
+++ b/pyfakefs/helpers.py
@@ -22,6 +22,7 @@ import os
 
 IS_PY2 = sys.version_info[0] < 3
 IS_PYPY = platform.python_implementation() == 'PyPy'
+IS_WIN = sys.platform == 'win32'
 
 try:
     text_type = unicode  # Python 2


Test patch:
diff --git a/.travis/run_tests.sh b/.travis/run_tests.sh
index a04b71e..19ee92c 100755
--- a/.travis/run_tests.sh
+++ b/.travis/run_tests.sh
@@ -5,19 +5,27 @@ if [[ $TRAVIS_OS_NAME == 'osx' ]]; then
 fi
 
 if ! [[ $VM == 'Docker' ]]; then
-python --version
-pip --version
-pip install flake8
+    python --version
+    pip --version
+    pip install flake8
 
-EXCLUDES='--exclude get-pip.py'
-if [[ $PYTHON == 'py27' ]] || [[ $PYTHON == 'pypy2' ]]; then
-    EXCLUDES=$EXCLUDES',pyfakefs/fake_pathlib.py,pyfakefs/tests/fake_pathlib_test.py'
-fi
+    EXCLUDES='--exclude get-pip.py'
+    if [[ $PYTHON == 'py27' ]] || [[ $PYTHON == 'pypy2' ]]; then
+        EXCLUDES=$EXCLUDES',pyfakefs/fake_pathlib.py,pyfakefs/tests/fake_pathlib_test.py'
+    fi
 
-# stop the build if there are Python syntax errors or undefined names
-flake8 . $EXCLUDES --count --select=E901,E999,F821,F822,F823 --show-source --statistics
-# exit-zero treats all errors as warnings
-flake8 . $EXCLUDES --count --exit-zero --max-complexity=12 --statistics
-python -m pyfakefs.tests.all_tests
-python -m pyfakefs.tests.all_tests_without_extra_packages
+    # stop the build if there are Python syntax errors or undefined names
+    flake8 . $EXCLUDES --count --select=E901,E999,F821,F822,F823 --show-source --statistics
+    # exit-zero treats all errors as warnings
+    flake8 . $EXCLUDES --count --exit-zero --max-complexity=12 --statistics
+    echo =======================================================
+    echo Running unit tests with extra packages as non-root user
+    python -m pyfakefs.tests.all_tests
+    echo ==========================================================
+    echo Running unit tests without extra packages as non-root user
+    python -m pyfakefs.tests.all_tests_without_extra_packages
+    echo ============================================
+    echo Running tests without extra packages as root
+    # provide the same path as non-root to get the correct virtualenv
+    sudo env "PATH=$PATH" python -m pyfakefs.tests.all_tests_without_extra_packages
 fi
diff --git a/pyfakefs/tests/fake_filesystem_shutil_test.py b/pyfakefs/tests/fake_filesystem_shutil_test.py
index f26ada7..633312b 100644
--- a/pyfakefs/tests/fake_filesystem_shutil_test.py
+++ b/pyfakefs/tests/fake_filesystem_shutil_test.py
@@ -25,7 +25,7 @@ import sys
 import unittest
 
 from pyfakefs import fake_filesystem_unittest
-from pyfakefs.fake_filesystem import set_uid
+from pyfakefs.fake_filesystem import is_root
 from pyfakefs.tests.test_utils import RealFsTestMixin
 
 is_windows = sys.platform == 'win32'
@@ -103,9 +103,13 @@ class FakeShutilModuleTest(RealFsTestCase):
         file_path = os.path.join(dir_path, 'baz')
         self.create_file(file_path)
         self.os.chmod(dir_path, 0o555)
-        self.assertRaises(OSError, shutil.rmtree, dir_path)
-        self.assertTrue(os.path.exists(file_path))
-        self.os.chmod(dir_path, 0o777)
+        if not is_root():
+            self.assertRaises(OSError, shutil.rmtree, dir_path)
+            self.assertTrue(os.path.exists(file_path))
+            self.os.chmod(dir_path, 0o777)
+        else:
+            shutil.rmtree(dir_path)
+            self.assertFalse(os.path.exists(file_path))
 
     @unittest.skipIf(is_windows, 'Posix specific behavior')
     def test_rmtree_with_open_file_posix(self):
@@ -357,7 +361,6 @@ class RealShutilModuleTest(FakeShutilModuleTest):
 
 class FakeCopyFileTest(RealFsTestCase):
     def tearDown(self):
-        set_uid(1)
         super(FakeCopyFileTest, self).tearDown()
 
     def test_common_case(self):
@@ -414,13 +417,15 @@ class FakeCopyFileTest(RealFsTestCase):
         os.chmod(dst_file, 0o400)
         self.assertTrue(os.path.exists(src_file))
         self.assertTrue(os.path.exists(dst_file))
-        self.assertRaises(IOError, shutil.copyfile, src_file, dst_file)
-        if not self.use_real_fs():
-            set_uid(0)
+
+        if is_root():
             shutil.copyfile(src_file, dst_file)
             self.assertTrue(self.os.path.exists(dst_file))
             with self.open(dst_file) as f:
                 self.assertEqual('contents of source file', f.read())
+        else:
+            self.assertRaises(IOError, shutil.copyfile, src_file, dst_file)
+
         os.chmod(dst_file, 0o666)
 
     @unittest.skipIf(is_windows, 'Posix specific behavior')
@@ -435,8 +440,13 @@ class FakeCopyFileTest(RealFsTestCase):
         os.chmod(dst_dir, 0o555)
         self.assertTrue(os.path.exists(src_file))
         self.assertTrue(os.path.exists(dst_dir))
-        exception = OSError if sys.version_info[0] > 2 else IOError
-        self.assertRaises(exception, shutil.copyfile, src_file, dst_file)
+        if not is_root():
+            exception = OSError if sys.version_info[0] > 2 else IOError
+            self.assertRaises(exception, shutil.copyfile, src_file, dst_file)
+        else:
+            shutil.copyfile(src_file, dst_file)
+            self.assertTrue(os.path.exists(dst_file))
+            self.check_contents(dst_file, src_contents)
 
     def test_raises_if_src_doesnt_exist(self):
         src_file = self.make_path('xyzzy')
@@ -453,7 +463,12 @@ class FakeCopyFileTest(RealFsTestCase):
         self.create_file(src_file, contents=src_contents)
         os.chmod(src_file, 0o000)
         self.assertTrue(os.path.exists(src_file))
-        self.assertRaises(IOError, shutil.copyfile, src_file, dst_file)
+        if not is_root():
+            self.assertRaises(IOError, shutil.copyfile, src_file, dst_file)
+        else:
+            shutil.copyfile(src_file, dst_file)
+            self.assertTrue(os.path.exists(dst_file))
+            self.check_contents(dst_file, src_contents)
 
     def test_raises_if_src_is_a_directory(self):
         src_file = self.make_path('xyzzy')
diff --git a/pyfakefs/tests/fake_filesystem_test.py b/pyfakefs/tests/fake_filesystem_test.py
index 8b92a24..79f2ace 100644
--- a/pyfakefs/tests/fake_filesystem_test.py
+++ b/pyfakefs/tests/fake_filesystem_test.py
@@ -24,7 +24,8 @@ import time
 import unittest
 
 from pyfakefs import fake_filesystem
-from pyfakefs.fake_filesystem import set_uid, set_gid
+from pyfakefs.fake_filesystem import set_uid, set_gid, is_root
+from pyfakefs.helpers import IS_WIN
 from pyfakefs.tests.test_utils import DummyTime, TestCase
 
 
@@ -260,7 +261,6 @@ class FakeFilesystemUnitTest(TestCase):
             'foobaz', filesystem=self.filesystem)
         self.fake_grandchild = fake_filesystem.FakeDirectory(
             'quux', filesystem=self.filesystem)
-        set_uid(1)
 
     def test_new_filesystem(self):
         self.assertEqual('/', self.filesystem.path_separator)
@@ -487,15 +487,19 @@ class FakeFilesystemUnitTest(TestCase):
         dir_path = '/foo/bar'
         self.filesystem.create_dir(dir_path, perm_bits=0o555)
         file_path = dir_path + '/baz'
-        if sys.version_info[0] < 3:
-            self.assert_raises_io_error(errno.EACCES,
-                                        self.filesystem.create_file, file_path)
+
+        if not is_root():
+            if sys.version_info[0] < 3:
+                self.assert_raises_io_error(errno.EACCES,
+                                            self.filesystem.create_file,
+                                            file_path)
+            else:
+                self.assert_raises_os_error(errno.EACCES,
+                                            self.filesystem.create_file,
+                                            file_path)
         else:
-            self.assert_raises_os_error(errno.EACCES,
-                                        self.filesystem.create_file, file_path)
-        set_uid(0)
-        self.filesystem.create_file(file_path)
-        self.assertTrue(self.filesystem.exists(file_path))
+            self.filesystem.create_file(file_path)
+            self.assertTrue(self.filesystem.exists(file_path))
 
     def test_create_file_in_read_only_directory_possible_in_windows(self):
         self.filesystem.is_windows_fs = True
@@ -545,8 +549,12 @@ class FakeFilesystemUnitTest(TestCase):
         self.assertTrue(self.filesystem.exists(os.path.dirname(path)))
         new_file = self.filesystem.get_object(path)
         self.assertEqual(os.path.basename(path), new_file.name)
-        self.assertEqual(1, new_file.st_uid)
-        self.assertEqual(1, new_file.st_gid)
+        if IS_WIN:
+            self.assertEqual(1, new_file.st_uid)
+            self.assertEqual(1, new_file.st_gid)
+        else:
+            self.assertEqual(os.getuid(), new_file.st_uid)
+            self.assertEqual(os.getgid(), new_file.st_gid)
         self.assertEqual(new_file, retval)
 
     def test_create_file_with_changed_ids(self):
@@ -558,8 +566,8 @@ class FakeFilesystemUnitTest(TestCase):
         new_file = self.filesystem.get_object(path)
         self.assertEqual(42, new_file.st_uid)
         self.assertEqual(2, new_file.st_gid)
-        set_uid(1)
-        set_gid(1)
+        set_uid(1 if IS_WIN else os.getuid())
+        set_gid(1 if IS_WIN else os.getgid())
 
     def test_empty_file_created_for_none_contents(self):
         fake_open = fake_filesystem.FakeFileOpen(self.filesystem)
@@ -1829,7 +1837,6 @@ class RealFileSystemAccessTest(TestCase):
         self.pyfakefs_path = os.path.split(
             os.path.dirname(os.path.abspath(__file__)))[0]
         self.root_path = os.path.split(self.pyfakefs_path)[0]
-        set_uid(1)
 
     def test_add_non_existing_real_file_raises(self):
         nonexisting_path = os.path.join('nonexisting', 'test.txt')
@@ -1881,8 +1888,12 @@ class RealFileSystemAccessTest(TestCase):
         with open(real_file_path, 'rb') as f:
             real_contents = f.read()
         self.assertEqual(fake_file.byte_contents, real_contents)
-        self.assert_raises_io_error(
-            errno.EACCES, self.fake_open, real_file_path, 'w')
+        if not is_root():
+            self.assert_raises_io_error(
+                errno.EACCES, self.fake_open, real_file_path, 'w')
+        else:
+            with self.fake_open(real_file_path, 'w'):
+                pass
 
     def check_writable_file(self, fake_file, real_file_path):
         with open(real_file_path, 'rb') as f:
diff --git a/pyfakefs/tests/fake_open_test.py b/pyfakefs/tests/fake_open_test.py
index 0fee12d..e672c74 100644
--- a/pyfakefs/tests/fake_open_test.py
+++ b/pyfakefs/tests/fake_open_test.py
@@ -27,7 +27,7 @@ import time
 import unittest
 
 from pyfakefs import fake_filesystem
-from pyfakefs.fake_filesystem import set_uid
+from pyfakefs.fake_filesystem import is_root
 from pyfakefs.tests.test_utils import TestCase, RealFsTestCase
 
 
@@ -40,7 +40,6 @@ class FakeFileOpenTest(FakeFileOpenTestBase):
     def setUp(self):
         super(FakeFileOpenTest, self).setUp()
         self.orig_time = time.time
-        set_uid(1)
 
     def tearDown(self):
         super(FakeFileOpenTest, self).tearDown()
@@ -452,10 +451,10 @@ class FakeFileOpenTest(FakeFileOpenTestBase):
         self.create_with_permission(file_path, 0o400)
         # actual tests
         self.open(file_path, 'r').close()
-        self.assert_raises_io_error(errno.EACCES, self.open, file_path, 'w')
-        self.assert_raises_io_error(errno.EACCES, self.open, file_path, 'w+')
-        if not self.use_real_fs():
-            set_uid(0)
+        if not is_root():
+            self.assert_raises_io_error(errno.EACCES, self.open, file_path, 'w')
+            self.assert_raises_io_error(errno.EACCES, self.open, file_path, 'w+')
+        else:
             self.open(file_path, 'w').close()
             self.open(file_path, 'w+').close()
 
@@ -465,11 +464,11 @@ class FakeFileOpenTest(FakeFileOpenTestBase):
         file_path = self.make_path('target_file')
         self.create_with_permission(file_path, 0o200)
         # actual tests
-        self.assertRaises(IOError, self.open, file_path, 'r')
         self.open(file_path, 'w').close()
-        self.assertRaises(IOError, self.open, file_path, 'w+')
-        if not self.use_real_fs():
-            set_uid(0)
+        if not is_root():
+            self.assertRaises(IOError, self.open, file_path, 'r')
+            self.assertRaises(IOError, self.open, file_path, 'w+')
+        else:
             self.open(file_path, 'r').close()
             self.open(file_path, 'w+').close()
 
@@ -479,11 +478,11 @@ class FakeFileOpenTest(FakeFileOpenTestBase):
         file_path = self.make_path('target_file')
         self.create_with_permission(file_path, 0o100)
         # actual tests
-        self.assertRaises(IOError, self.open, file_path, 'r')
-        self.assertRaises(IOError, self.open, file_path, 'w')
-        self.assertRaises(IOError, self.open, file_path, 'w+')
-        if not self.use_real_fs():
-            set_uid(0)
+        if not is_root():
+            self.assertRaises(IOError, self.open, file_path, 'r')
+            self.assertRaises(IOError, self.open, file_path, 'w')
+            self.assertRaises(IOError, self.open, file_path, 'w+')
+        else:
             self.open(file_path, 'r').close()
             self.open(file_path, 'w').close()
             self.open(file_path, 'w+').close()
diff --git a/pyfakefs/tests/fake_os_test.py b/pyfakefs/tests/fake_os_test.py
index cae9ab0..fe05835 100644
--- a/pyfakefs/tests/fake_os_test.py
+++ b/pyfakefs/tests/fake_os_test.py
@@ -25,7 +25,7 @@ import time
 import unittest
 
 from pyfakefs import fake_filesystem
-from pyfakefs.fake_filesystem import FakeFileOpen, set_uid
+from pyfakefs.fake_filesystem import FakeFileOpen, is_root
 from pyfakefs.extra_packages import use_scandir, use_scandir_package
 
 from pyfakefs.tests.test_utils import DummyTime, TestCase, RealFsTestCase
@@ -54,7 +54,6 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         super(FakeOsModuleTest, self).setUp()
         self.rwx = self.os.R_OK | self.os.W_OK | self.os.X_OK
         self.rw = self.os.R_OK | self.os.W_OK
-        set_uid(1)
 
     def test_chdir(self):
         """chdir should work on a directory."""
@@ -224,11 +223,12 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         fileno1 = fake_file1.fileno()
         self.os.fdopen(fileno1)
         self.os.fdopen(fileno1, 'r')
-        exception = OSError if self.is_python2 else IOError
-        self.assertRaises(exception, self.os.fdopen, fileno1, 'w')
-        set_uid(0)
-        self.os.fdopen(fileno1, 'w')
-        self.os.close(fileno1)
+        if not is_root():
+            exception = OSError if self.is_python2 else IOError
+            self.assertRaises(exception, self.os.fdopen, fileno1, 'w')
+        else:
+            self.os.fdopen(fileno1, 'w')
+            self.os.close(fileno1)
 
     def test_fstat(self):
         directory = self.make_path('xyzzy')
@@ -754,9 +754,19 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         path = self.os.path.join(parent_dir, 'bar')
         self.create_file(path)
         self.os.chmod(parent_dir, 0o666)  # missing execute permission
-        self.assert_raises_os_error(errno.EACCES, self.os.remove, path)
+        if not is_root():
+            self.assert_raises_os_error(errno.EACCES, self.os.remove, path)
+        else:
+            self.os.remove(path)
+            self.assertFalse(self.os.path.exists(path))
+            self.create_file(path)
         self.os.chmod(parent_dir, 0o555)  # missing write permission
-        self.assert_raises_os_error(errno.EACCES, self.os.remove, path)
+        if not is_root():
+            self.assert_raises_os_error(errno.EACCES, self.os.remove, path)
+        else:
+            self.os.remove(path)
+            self.assertFalse(self.os.path.exists(path))
+            self.create_file(path)
         self.os.chmod(parent_dir, 0o333)
         self.os.remove(path)
         self.assertFalse(self.os.path.exists(path))
@@ -1606,9 +1616,9 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         self.os.chmod(directory, 0o400)
 
         directory = self.make_path('a', 'b')
-        self.assert_raises_os_error(errno.EACCES, self.os.mkdir, directory)
-        if not self.use_real_fs():
-            set_uid(0)
+        if not is_root():
+            self.assert_raises_os_error(errno.EACCES, self.os.mkdir, directory)
+        else:
             self.os.mkdir(directory)
             self.assertTrue(self.os.path.exists(directory))
 
@@ -1680,10 +1690,9 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         self.os.chmod(directory, 0o400)
 
         directory = self.make_path('a', 'b')
-        set_uid(1)
-        self.assertRaises(Exception, self.os.makedirs, directory)
-        if not self.use_real_fs():
-            set_uid(0)
+        if not is_root():
+            self.assertRaises(Exception, self.os.makedirs, directory)
+        else:
             self.os.makedirs(directory)
             self.assertTrue(self.os.path.exists(directory))
 
@@ -1795,10 +1804,14 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         # actual tests
         self.assertTrue(self.os.access(path, self.os.F_OK))
         self.assertTrue(self.os.access(path, self.os.R_OK))
-        self.assertFalse(self.os.access(path, self.os.W_OK))
         self.assertFalse(self.os.access(path, self.os.X_OK))
         self.assertFalse(self.os.access(path, self.rwx))
-        self.assertFalse(self.os.access(path, self.rw))
+        if is_root():
+            self.assertTrue(self.os.access(path, self.os.W_OK))
+            self.assertTrue(self.os.access(path, self.rw))
+        else:
+            self.assertFalse(self.os.access(path, self.os.W_OK))
+            self.assertFalse(self.os.access(path, self.rw))
 
     @unittest.skipIf(sys.version_info < (3, 3),
                      'follow_symlinks new in Python 3.3')
@@ -1814,10 +1827,14 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
         # test file
         self.assertTrue(self.os.access(link_path, self.os.F_OK))
         self.assertTrue(self.os.access(link_path, self.os.R_OK))
-        self.assertFalse(self.os.access(link_path, self.os.W_OK))
+        if is_root():
+            self.assertTrue(self.os.access(link_path, self.os.W_OK))
+            self.assertTrue(self.os.access(link_path, self.rw))
+        else:
+            self.assertFalse(self.os.access(link_path, self.os.W_OK))
+            self.assertFalse(self.os.access(link_path, self.rw))
         self.assertFalse(self.os.access(link_path, self.os.X_OK))
         self.assertFalse(self.os.access(link_path, self.rwx))
-        self.assertFalse(self.os.access(link_path, self.rw))
 
         # test link itself
         self.assertTrue(
@@ -2114,8 +2131,12 @@ class FakeOsModuleTest(FakeOsModuleTestBase):
     def test_mknod_raises_if_unsupported_options(self):
         self.check_posix_only()
         filename = 'abcde'
-        self.assert_raises_os_error(errno.EPERM, self.os.mknod, filename,
-                                    stat.S_IFCHR)
+        if not is_root():
+            self.assert_raises_os_error(errno.EPERM, self.os.mknod, filename,
+                                        stat.S_IFCHR)
+        else:
+            self.os.mknod(filename, stat.S_IFCHR)
+            self.os.remove(filename)
 
     def test_mknod_raises_if_parent_is_not_a_directory(self):
         self.check_linux_only()
@@ -2683,10 +2704,10 @@ class FakeOsModuleTestCaseInsensitiveFS(FakeOsModuleTestBase):
         self.os.fdopen(fileno1)
         self.os.fdopen(fileno1, 'r')
         exception = OSError if self.is_python2 else IOError
-        set_uid(1)
-        self.assertRaises(exception, self.os.fdopen, fileno1, 'w')
-        set_uid(0)
-        self.os.fdopen(fileno1, 'w')
+        if not is_root():
+            self.assertRaises(exception, self.os.fdopen, fileno1, 'w')
+        else:
+            self.os.fdopen(fileno1, 'w')
 
     def test_stat(self):
         directory = self.make_path('xyzzy')