• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2014 Altera Corporation. All Rights Reserved.
2# Copyright 2015-2017 John McGehee
3# Author: John McGehee
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Test the :py:class`pyfakefs.fake_filesystem_unittest.TestCase` base class.
19"""
20
21import glob
22import importlib.util
23import io
24import multiprocessing
25import os
26import pathlib
27import runpy
28import shutil
29import sys
30import tempfile
31import unittest
32import warnings
33from contextlib import redirect_stdout
34from io import StringIO
35from pathlib import Path
36from unittest import TestCase, mock
37
38import pyfakefs.tests.import_as_example
39import pyfakefs.tests.logsio
40from pyfakefs import fake_filesystem_unittest, fake_filesystem
41from pyfakefs.fake_filesystem import OSType
42from pyfakefs.fake_filesystem_unittest import (
43    Patcher,
44    Pause,
45    patchfs,
46    PatchMode,
47)
48from pyfakefs.tests.fixtures import module_with_attributes
49
50if sys.version_info < (3, 12):
51    # distutils removed in Python 3.12
52    from distutils.dir_util import copy_tree, remove_tree
53
54
55# Work around pyupgrade auto-rewriting `io.open()` to `open()`.
56io_open = io.open
57
58
59class TestPatcher(TestCase):
60    def test_context_manager(self):
61        with Patcher() as patcher:
62            patcher.fs.create_file("/foo/bar", contents="test")
63            with open("/foo/bar", encoding="utf8") as f:
64                contents = f.read()
65            self.assertEqual("test", contents)
66
67    @patchfs
68    def test_context_decorator(self, fake_fs):
69        fake_fs.create_file("/foo/bar", contents="test")
70        with open("/foo/bar", encoding="utf8") as f:
71            contents = f.read()
72        self.assertEqual("test", contents)
73
74
75class TestPatchfsArgumentOrder(TestCase):
76    @patchfs
77    @mock.patch("os.system")
78    def test_argument_order1(self, fake_fs, patched_system):
79        fake_fs.create_file("/foo/bar", contents="test")
80        with open("/foo/bar", encoding="utf8") as f:
81            contents = f.read()
82        self.assertEqual("test", contents)
83        os.system("foo")
84        patched_system.assert_called_with("foo")
85
86    @mock.patch("os.system")
87    @patchfs
88    def test_argument_order2(self, patched_system, fake_fs):
89        fake_fs.create_file("/foo/bar", contents="test")
90        with open("/foo/bar", encoding="utf8") as f:
91            contents = f.read()
92        self.assertEqual("test", contents)
93        os.system("foo")
94        patched_system.assert_called_with("foo")
95
96
97class TestPyfakefsUnittestBase(fake_filesystem_unittest.TestCase):
98    def setUp(self):
99        """Set up the fake file system"""
100        self.setUpPyfakefs()
101
102
103class TestPyfakefsUnittest(TestPyfakefsUnittestBase):  # pylint: disable=R0904
104    """Test the `pyfakefs.fake_filesystem_unittest.TestCase` base class."""
105
106    def test_open(self):
107        """Fake `open()` function is bound"""
108        self.assertFalse(os.path.exists("/fake_file.txt"))
109        with open("/fake_file.txt", "w", encoding="utf8") as f:
110            f.write("This test file was created using the open() function.\n")
111        self.assertTrue(self.fs.exists("/fake_file.txt"))
112        with open("/fake_file.txt", encoding="utf8") as f:
113            content = f.read()
114        self.assertEqual(
115            "This test file was created using the open() function.\n",
116            content,
117        )
118
119    def test_io_open(self):
120        """Fake io module is bound"""
121        self.assertFalse(os.path.exists("/fake_file.txt"))
122        with io_open("/fake_file.txt", "w", encoding="utf8") as f:
123            f.write("This test file was created using the io.open() function.\n")
124        self.assertTrue(self.fs.exists("/fake_file.txt"))
125        with open("/fake_file.txt", encoding="utf8") as f:
126            content = f.read()
127        self.assertEqual(
128            "This test file was created using the io.open() function.\n",
129            content,
130        )
131
132    def test_os(self):
133        """Fake os module is bound"""
134        self.assertFalse(self.fs.exists("/test/dir1/dir2"))
135        os.makedirs("/test/dir1/dir2")
136        self.assertTrue(self.fs.exists("/test/dir1/dir2"))
137
138    def test_glob(self):
139        """Fake glob module is bound"""
140        is_windows = sys.platform.startswith("win")
141        self.assertEqual([], glob.glob("/test/dir1/dir*"))
142        self.fs.create_dir("/test/dir1/dir2a")
143        matching_paths = glob.glob("/test/dir1/dir*")
144        if is_windows:
145            self.assertEqual([r"/test/dir1\dir2a"], matching_paths)
146        else:
147            self.assertEqual(["/test/dir1/dir2a"], matching_paths)
148        self.fs.create_dir("/test/dir1/dir2b")
149        matching_paths = sorted(glob.glob("/test/dir1/dir*"))
150        if is_windows:
151            self.assertEqual([r"/test/dir1\dir2a", r"/test/dir1\dir2b"], matching_paths)
152        else:
153            self.assertEqual(["/test/dir1/dir2a", "/test/dir1/dir2b"], matching_paths)
154
155    def test_shutil(self):
156        """Fake shutil module is bound"""
157        self.fs.create_dir("/test/dir1/dir2a")
158        self.fs.create_dir("/test/dir1/dir2b")
159        self.assertTrue(self.fs.exists("/test/dir1/dir2b"))
160        self.assertTrue(self.fs.exists("/test/dir1/dir2a"))
161
162        shutil.rmtree("/test/dir1")
163        self.assertFalse(self.fs.exists("/test/dir1"))
164
165    def test_fakepathlib(self):
166        p = pathlib.Path("/fake_file.txt")
167        with p.open("w", encoding="utf8") as f:
168            f.write("text")
169        is_windows = sys.platform.startswith("win")
170        if is_windows:
171            self.assertTrue(self.fs.exists(r"\fake_file.txt"))
172        else:
173            self.assertTrue(self.fs.exists("/fake_file.txt"))
174
175
176class TestPatchingImports(TestPyfakefsUnittestBase):
177    def test_import_as_other_name(self):
178        file_path = "/foo/bar/baz"
179        self.fs.create_file(file_path)
180        self.assertTrue(self.fs.exists(file_path))
181        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists1(file_path))
182
183    def test_import_path_from_os(self):
184        """Make sure `from os import path` patches `path`."""
185        file_path = "/foo/bar/baz"
186        self.fs.create_file(file_path)
187        self.assertTrue(self.fs.exists(file_path))
188        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists2(file_path))
189
190    def test_import_path_from_pathlib(self):
191        file_path = "/foo/bar"
192        self.fs.create_dir(file_path)
193        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists3(file_path))
194
195    def test_import_exists_from_os_path(self):
196        file_path = "/foo/bar"
197        self.fs.create_dir(file_path)
198        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists5(file_path))
199
200    def test_import_isfile_from_os_path(self):
201        file_path = "/foo/bar"
202        self.fs.create_file(file_path)
203        self.assertTrue(pyfakefs.tests.import_as_example.check_if_isfile(file_path))
204
205    def test_import_isdir_from_os_path(self):
206        file_path = "/foo/bar"
207        self.fs.create_dir(file_path)
208        self.assertTrue(pyfakefs.tests.import_as_example.check_if_isdir(file_path))
209
210    def test_import_islink_from_os_path(self):
211        file_path = "/foo/bar"
212        link_path = "/foo/link"
213        self.fs.create_file(file_path)
214        self.fs.create_symlink(link_path, file_path)
215        self.assertTrue(pyfakefs.tests.import_as_example.check_if_islink(link_path))
216
217    def test_import_function_from_os_path_as_other_name(self):
218        file_path = "/foo/bar"
219        self.fs.create_dir(file_path)
220        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists6(file_path))
221
222    def test_import_pathlib_path(self):
223        file_path = "/foo/bar"
224        self.fs.create_dir(file_path)
225        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists7(file_path))
226
227    def test_import_function_from_os(self):
228        file_path = "/foo/bar"
229        self.fs.create_file(file_path, contents=b"abc")
230        stat_result = pyfakefs.tests.import_as_example.file_stat1(file_path)
231        self.assertEqual(3, stat_result.st_size)
232
233    def test_import_function_from_os_as_other_name(self):
234        file_path = "/foo/bar"
235        self.fs.create_file(file_path, contents=b"abc")
236        stat_result = pyfakefs.tests.import_as_example.file_stat2(file_path)
237        self.assertEqual(3, stat_result.st_size)
238
239    def test_import_open_as_other_name(self):
240        file_path = "/foo/bar"
241        self.fs.create_file(file_path, contents=b"abc")
242        contents = pyfakefs.tests.import_as_example.file_contents1(file_path)
243        self.assertEqual("abc", contents)
244
245    def test_import_io_open_as_other_name(self):
246        file_path = "/foo/bar"
247        self.fs.create_file(file_path, contents=b"abc")
248        contents = pyfakefs.tests.import_as_example.file_contents2(file_path)
249        self.assertEqual("abc", contents)
250
251
252class TestPatchingDefaultArgs(fake_filesystem_unittest.TestCase):
253    def setUp(self):
254        self.setUpPyfakefs(patch_default_args=True)
255
256    def test_path_exists_as_default_arg_in_function(self):
257        file_path = "/foo/bar"
258        self.fs.create_dir(file_path)
259        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists4(file_path))
260
261    def test_path_exists_as_default_arg_in_method(self):
262        file_path = "/foo/bar"
263        self.fs.create_dir(file_path)
264        sut = pyfakefs.tests.import_as_example.TestDefaultArg()
265        self.assertTrue(sut.check_if_exists(file_path))
266
267    def test_fake_path_exists4(self):
268        self.fs.create_file("foo")
269        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists4("foo"))
270
271
272class TestAttributesWithFakeModuleNames(TestPyfakefsUnittestBase):
273    """Test that module attributes with names like `path` or `io` are not
274    stubbed out.
275    """
276
277    def test_attributes(self):
278        """Attributes of module under test are not patched"""
279        self.assertEqual(module_with_attributes.os, "os attribute value")
280        self.assertEqual(module_with_attributes.path, "path attribute value")
281        self.assertEqual(module_with_attributes.pathlib, "pathlib attribute value")
282        self.assertEqual(module_with_attributes.shutil, "shutil attribute value")
283        self.assertEqual(module_with_attributes.io, "io attribute value")
284
285
286import math as path  # noqa: E402 wanted import not at top
287
288
289class TestPathNotPatchedIfNotOsPath(TestPyfakefsUnittestBase):
290    """Tests that `path` is not patched if it is not `os.path`.
291    An own path module (in this case an alias to math) can be imported
292    and used.
293    """
294
295    def test_own_path_module(self):
296        self.assertEqual(2, path.floor(2.5))
297
298
299class FailedPatchingTest(TestPyfakefsUnittestBase):
300    """Negative tests: make sure the tests for `modules_to_reload` and
301    `modules_to_patch` fail if not providing the arguments.
302    """
303
304    @unittest.expectedFailure
305    def test_system_stat(self):
306        file_path = "/foo/bar"
307        self.fs.create_file(file_path, contents=b"test")
308        self.assertEqual(
309            4, pyfakefs.tests.import_as_example.system_stat(file_path).st_size
310        )
311
312
313class ReloadModuleTest(fake_filesystem_unittest.TestCase):
314    """Make sure that reloading a module allows patching of classes not
315    patched automatically.
316    """
317
318    def setUp(self):
319        """Set up the fake file system"""
320        self.setUpPyfakefs(modules_to_reload=[pyfakefs.tests.import_as_example])
321
322
323class NoSkipNamesTest(fake_filesystem_unittest.TestCase):
324    """Reference test for additional_skip_names tests:
325    make sure that the module is patched by default."""
326
327    def setUp(self):
328        self.setUpPyfakefs()
329
330    def test_path_exists(self):
331        self.assertFalse(pyfakefs.tests.import_as_example.exists_this_file())
332
333    def test_fake_path_exists1(self):
334        self.fs.create_file("foo")
335        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists1("foo"))
336
337    def test_fake_path_exists2(self):
338        self.fs.create_file("foo")
339        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists2("foo"))
340
341    def test_fake_path_exists3(self):
342        self.fs.create_file("foo")
343        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists3("foo"))
344
345    def test_fake_path_exists5(self):
346        self.fs.create_file("foo")
347        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists5("foo"))
348
349    def test_fake_path_exists6(self):
350        self.fs.create_file("foo")
351        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists6("foo"))
352
353    def test_fake_path_exists7(self):
354        self.fs.create_file("foo")
355        self.assertTrue(pyfakefs.tests.import_as_example.check_if_exists7("foo"))
356
357    def test_open_fails(self):
358        with self.assertRaises(OSError):
359            pyfakefs.tests.import_as_example.open_this_file()
360
361    def test_open_patched_in_module_ending_with_io(self):
362        # regression test for #569
363        file_path = "/foo/bar"
364        self.fs.create_file(file_path, contents=b"abc")
365        contents = pyfakefs.tests.logsio.file_contents(file_path)
366        self.assertEqual(b"abc", contents)
367
368
369class AdditionalSkipNamesTest(fake_filesystem_unittest.TestCase):
370    """Make sure that modules in additional_skip_names are not patched.
371    Passes module name to `additional_skip_names`."""
372
373    def setUp(self):
374        self.setUpPyfakefs(additional_skip_names=["pyfakefs.tests.import_as_example"])
375
376    def test_path_exists(self):
377        self.assertTrue(pyfakefs.tests.import_as_example.exists_this_file())
378
379    def test_fake_path_does_not_exist1(self):
380        self.fs.create_file("foo")
381        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists1("foo"))
382
383    def test_fake_path_does_not_exist2(self):
384        self.fs.create_file("foo")
385        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists2("foo"))
386
387    def test_fake_path_does_not_exist3(self):
388        self.fs.create_file("foo")
389        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists3("foo"))
390
391    def test_fake_path_does_not_exist4(self):
392        self.fs.create_file("foo")
393        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists4("foo"))
394
395    def test_fake_path_does_not_exist5(self):
396        self.fs.create_file("foo")
397        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists5("foo"))
398
399    def test_fake_path_does_not_exist6(self):
400        self.fs.create_file("foo")
401        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists6("foo"))
402
403    def test_fake_path_does_not_exist7(self):
404        self.fs.create_file("foo")
405        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists7("foo"))
406
407    def test_open_succeeds(self):
408        pyfakefs.tests.import_as_example.open_this_file()
409
410    def test_path_succeeds(self):
411        pyfakefs.tests.import_as_example.return_this_file_path()
412
413
414class AdditionalSkipNamesModuleTest(fake_filesystem_unittest.TestCase):
415    """Make sure that modules in additional_skip_names are not patched.
416    Passes module to `additional_skip_names`."""
417
418    def setUp(self):
419        self.setUpPyfakefs(additional_skip_names=[pyfakefs.tests.import_as_example])
420
421    def test_path_exists(self):
422        self.assertTrue(pyfakefs.tests.import_as_example.exists_this_file())
423
424    def test_fake_path_does_not_exist1(self):
425        self.fs.create_file("foo")
426        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists1("foo"))
427
428    def test_fake_path_does_not_exist2(self):
429        self.fs.create_file("foo")
430        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists2("foo"))
431
432    def test_fake_path_does_not_exist3(self):
433        self.fs.create_file("foo")
434        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists3("foo"))
435
436    def test_fake_path_does_not_exist4(self):
437        self.fs.create_file("foo")
438        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists4("foo"))
439
440    def test_fake_path_does_not_exist5(self):
441        self.fs.create_file("foo")
442        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists5("foo"))
443
444    def test_fake_path_does_not_exist6(self):
445        self.fs.create_file("foo")
446        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists6("foo"))
447
448    def test_fake_path_does_not_exist7(self):
449        self.fs.create_file("foo")
450        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists7("foo"))
451
452    def test_open_succeeds(self):
453        pyfakefs.tests.import_as_example.open_this_file()
454
455    def test_path_succeeds(self):
456        pyfakefs.tests.import_as_example.return_this_file_path()
457
458
459class RuntimeSkipModuleTest(fake_filesystem_unittest.TestCase):
460    """Emulates skipping a module using RUNTIME_SKIPMODULES.
461    Not all functionality implemented for skip modules will work here."""
462
463    def setUp(self):
464        Patcher.RUNTIME_SKIPMODULES.update(
465            {"pyfakefs.tests.import_as_example": ["pyfakefs.tests.import_"]}
466        )
467        self.setUpPyfakefs()
468
469    def tearDown(self):
470        del self.patcher.RUNTIME_SKIPMODULES["pyfakefs.tests.import_as_example"]
471
472    def test_fake_path_does_not_exist1(self):
473        self.fs.create_file("foo")
474        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists1("foo"))
475
476    def test_fake_path_does_not_exist2(self):
477        self.fs.create_file("foo")
478        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists2("foo"))
479
480    def test_fake_path_does_not_exist3(self):
481        self.fs.create_file("foo")
482        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists3("foo"))
483
484    def test_fake_path_does_not_exist4(self):
485        self.fs.create_file("foo")
486        self.assertFalse(pyfakefs.tests.import_as_example.check_if_exists4("foo"))
487
488
489class FakeExampleModule:
490    """Used to patch a function that uses system-specific functions that
491    cannot be patched automatically."""
492
493    _orig_module = pyfakefs.tests.import_as_example
494
495    def __init__(self, fs):
496        pass
497
498    def system_stat(self, filepath):
499        return os.stat(filepath)
500
501    def __getattr__(self, name):
502        """Forwards any non-faked calls to the standard module."""
503        return getattr(self._orig_module, name)
504
505
506class PatchModuleTest(fake_filesystem_unittest.TestCase):
507    """Make sure that reloading a module allows patching of classes not
508    patched automatically.
509    """
510
511    def setUp(self):
512        """Set up the fake file system"""
513        self.setUpPyfakefs(
514            modules_to_patch={"pyfakefs.tests.import_as_example": FakeExampleModule}
515        )
516
517    def test_system_stat(self):
518        file_path = "/foo/bar"
519        self.fs.create_file(file_path, contents=b"test")
520        self.assertEqual(
521            4, pyfakefs.tests.import_as_example.system_stat(file_path).st_size
522        )
523
524
525class PatchModuleTestUsingDecorator(unittest.TestCase):
526    """Make sure that reloading a module allows patching of classes not
527    patched automatically - use patchfs decorator with parameter.
528    """
529
530    @patchfs
531    @unittest.expectedFailure
532    def test_system_stat_failing(self, fake_fs):
533        file_path = "/foo/bar"
534        fake_fs.create_file(file_path, contents=b"test")
535        self.assertEqual(
536            4, pyfakefs.tests.import_as_example.system_stat(file_path).st_size
537        )
538
539    @patchfs(modules_to_patch={"pyfakefs.tests.import_as_example": FakeExampleModule})
540    def test_system_stat(self, fake_fs):
541        file_path = "/foo/bar"
542        fake_fs.create_file(file_path, contents=b"test")
543        self.assertEqual(
544            4, pyfakefs.tests.import_as_example.system_stat(file_path).st_size
545        )
546
547
548class NoRootUserTest(fake_filesystem_unittest.TestCase):
549    """Test allow_root_user argument to setUpPyfakefs."""
550
551    def setUp(self):
552        self.setUpPyfakefs(allow_root_user=False)
553
554    def test_non_root_behavior(self):
555        """Check that fs behaves as non-root user regardless of actual
556        user rights.
557        """
558        self.fs.is_windows_fs = False
559        dir_path = "/foo/bar"
560        self.fs.create_dir(dir_path, perm_bits=0o555)
561        file_path = dir_path + "baz"
562        with self.assertRaises(OSError):
563            self.fs.create_file(file_path)
564
565        file_path = "/baz"
566        self.fs.create_file(file_path)
567        os.chmod(file_path, 0o400)
568        with self.assertRaises(OSError):
569            open(file_path, "w", encoding="utf8")
570
571
572class PauseResumeTest(fake_filesystem_unittest.TestCase):
573    def setUp(self):
574        self.setUpPyfakefs()
575
576    def test_pause_resume(self):
577        fake_temp_file = tempfile.NamedTemporaryFile()
578        self.assertTrue(self.fs.exists(fake_temp_file.name))
579        self.assertTrue(os.path.exists(fake_temp_file.name))
580        self.pause()
581        self.assertTrue(self.fs.exists(fake_temp_file.name))
582        self.assertFalse(os.path.exists(fake_temp_file.name))
583        real_temp_file = tempfile.NamedTemporaryFile()
584        self.assertFalse(self.fs.exists(real_temp_file.name))
585        self.assertTrue(os.path.exists(real_temp_file.name))
586        self.resume()
587        self.assertFalse(os.path.exists(real_temp_file.name))
588        self.assertTrue(os.path.exists(fake_temp_file.name))
589
590    def test_pause_resume_fs(self):
591        fake_temp_file = tempfile.NamedTemporaryFile()
592        self.assertTrue(self.fs.exists(fake_temp_file.name))
593        self.assertTrue(os.path.exists(fake_temp_file.name))
594        # resume does nothing if not paused
595        self.fs.resume()
596        self.assertTrue(os.path.exists(fake_temp_file.name))
597        self.fs.pause()
598        self.assertTrue(self.fs.exists(fake_temp_file.name))
599        self.assertFalse(os.path.exists(fake_temp_file.name))
600        real_temp_file = tempfile.NamedTemporaryFile()
601        self.assertFalse(self.fs.exists(real_temp_file.name))
602        self.assertTrue(os.path.exists(real_temp_file.name))
603        # pause does nothing if already paused
604        self.fs.pause()
605        self.assertFalse(self.fs.exists(real_temp_file.name))
606        self.assertTrue(os.path.exists(real_temp_file.name))
607        self.fs.resume()
608        self.assertFalse(os.path.exists(real_temp_file.name))
609        self.assertTrue(os.path.exists(fake_temp_file.name))
610
611    def test_pause_resume_contextmanager(self):
612        fake_temp_file = tempfile.NamedTemporaryFile()
613        self.assertTrue(self.fs.exists(fake_temp_file.name))
614        self.assertTrue(os.path.exists(fake_temp_file.name))
615        with Pause(self):
616            self.assertTrue(self.fs.exists(fake_temp_file.name))
617            self.assertFalse(os.path.exists(fake_temp_file.name))
618            real_temp_file = tempfile.NamedTemporaryFile()
619            self.assertFalse(self.fs.exists(real_temp_file.name))
620            self.assertTrue(os.path.exists(real_temp_file.name))
621        self.assertFalse(os.path.exists(real_temp_file.name))
622        self.assertTrue(os.path.exists(fake_temp_file.name))
623
624    def test_pause_resume_fs_contextmanager(self):
625        fake_temp_file = tempfile.NamedTemporaryFile()
626        self.assertTrue(self.fs.exists(fake_temp_file.name))
627        self.assertTrue(os.path.exists(fake_temp_file.name))
628        with Pause(self.fs):
629            self.assertTrue(self.fs.exists(fake_temp_file.name))
630            self.assertFalse(os.path.exists(fake_temp_file.name))
631            real_temp_file = tempfile.NamedTemporaryFile()
632            self.assertFalse(self.fs.exists(real_temp_file.name))
633            self.assertTrue(os.path.exists(real_temp_file.name))
634        self.assertFalse(os.path.exists(real_temp_file.name))
635        self.assertTrue(os.path.exists(fake_temp_file.name))
636
637    def test_pause_resume_without_patcher(self):
638        fs = fake_filesystem.FakeFilesystem()
639        with self.assertRaises(RuntimeError):
640            fs.resume()
641
642    def test_that_tempfile_is_patched_after_resume(fs):
643        """Regression test for #1098"""
644        fs.pause()
645        fs.resume()
646        with tempfile.NamedTemporaryFile():
647            pass
648
649
650class PauseResumePatcherTest(fake_filesystem_unittest.TestCase):
651    def test_pause_resume(self):
652        with Patcher() as p:
653            fake_temp_file = tempfile.NamedTemporaryFile()
654            self.assertTrue(p.fs.exists(fake_temp_file.name))
655            self.assertTrue(os.path.exists(fake_temp_file.name))
656            p.pause()
657            self.assertTrue(p.fs.exists(fake_temp_file.name))
658            self.assertFalse(os.path.exists(fake_temp_file.name))
659            real_temp_file = tempfile.NamedTemporaryFile()
660            self.assertFalse(p.fs.exists(real_temp_file.name))
661            self.assertTrue(os.path.exists(real_temp_file.name))
662            p.resume()
663            self.assertFalse(os.path.exists(real_temp_file.name))
664            self.assertTrue(os.path.exists(fake_temp_file.name))
665        real_temp_file.close()
666
667    def test_pause_resume_contextmanager(self):
668        with Patcher() as p:
669            fake_temp_file = tempfile.NamedTemporaryFile()
670            self.assertTrue(p.fs.exists(fake_temp_file.name))
671            self.assertTrue(os.path.exists(fake_temp_file.name))
672            with Pause(p):
673                self.assertTrue(p.fs.exists(fake_temp_file.name))
674                self.assertFalse(os.path.exists(fake_temp_file.name))
675                real_temp_file = tempfile.NamedTemporaryFile()
676                self.assertFalse(p.fs.exists(real_temp_file.name))
677                self.assertTrue(os.path.exists(real_temp_file.name))
678            self.assertFalse(os.path.exists(real_temp_file.name))
679            self.assertTrue(os.path.exists(fake_temp_file.name))
680        real_temp_file.close()
681
682
683class TestPyfakefsTestCase(unittest.TestCase):
684    def setUp(self):
685        class TestTestCase(fake_filesystem_unittest.TestCase):
686            def runTest(self):
687                pass
688
689        self.test_case = TestTestCase("runTest")
690
691    def test_test_case_type(self):
692        self.assertIsInstance(self.test_case, unittest.TestCase)
693
694        self.assertIsInstance(self.test_case, fake_filesystem_unittest.TestCaseMixin)
695
696
697class TestTempDirCreation(fake_filesystem_unittest.TestCase):
698    """Test that the temp directory exists at test start."""
699
700    def setUp(self):
701        self.setUpPyfakefs()
702
703    def test_tempdir_exists(self):
704        self.assertTrue(os.path.exists(tempfile.gettempdir()))
705
706    @unittest.skipIf(sys.platform == "win32", "POSIX only test")
707    def test_tmp_exists(self):
708        # directory or link under Linux, link under macOS
709        self.assertTrue(os.path.exists("/tmp"))
710
711
712class TestTempFileReload(unittest.TestCase):
713    """Regression test for #356 to make sure that reloading the tempfile
714    does not affect other tests."""
715
716    def test_fakefs(self):
717        with Patcher() as patcher:
718            patcher.fs.create_file("/mytempfile", contents="abcd")
719
720    def test_value(self):
721        v = multiprocessing.Value("I", 0)
722        self.assertEqual(v.value, 0)
723
724
725class TestPyfakefsTestCaseMixin(
726    unittest.TestCase, fake_filesystem_unittest.TestCaseMixin
727):
728    def test_set_up_pyfakefs(self):
729        self.setUpPyfakefs()
730
731        self.assertTrue(hasattr(self, "fs"))
732        self.assertIsInstance(self.fs, fake_filesystem.FakeFilesystem)
733
734
735class TestShutilWithZipfile(fake_filesystem_unittest.TestCase):
736    """Regression test for #427."""
737
738    def setUp(self):
739        self.setUpPyfakefs()
740        self.fs.create_file("foo/bar")
741
742    def test_a(self):
743        shutil.make_archive("archive", "zip", root_dir="foo")
744
745    def test_b(self):
746        # used to fail because 'bar' could not be found
747        shutil.make_archive("archive", "zip", root_dir="foo")
748
749
750if sys.version_info < (3, 12):
751
752    class TestDistutilsCopyTree(fake_filesystem_unittest.TestCase):
753        """Regression test for #501."""
754
755        def setUp(self):
756            self.setUpPyfakefs()
757            self.fs.create_dir("./test/subdir/")
758            self.fs.create_dir("./test/subdir2/")
759            self.fs.create_file("./test2/subdir/1.txt")
760
761        def test_file_copied(self):
762            copy_tree("./test2/", "./test/")
763            remove_tree("./test2/")
764
765            self.assertTrue(os.path.isfile("./test/subdir/1.txt"))
766            self.assertFalse(os.path.isdir("./test2/"))
767
768        def test_file_copied_again(self):
769            # used to fail because 'test2' could not be found
770            self.assertTrue(os.path.isfile("./test2/subdir/1.txt"))
771
772            copy_tree("./test2/", "./test/")
773            remove_tree("./test2/")
774
775            self.assertTrue(os.path.isfile("./test/subdir/1.txt"))
776            self.assertFalse(os.path.isdir("./test2/"))
777
778
779class PathlibTest(TestCase):
780    """Regression test for #527"""
781
782    @patchfs
783    def test_cwd(self, fs):
784        """Make sure fake file system is used for os in pathlib"""
785        is_windows = sys.platform.startswith("win")
786        root_dir = "C:" + os.path.sep if is_windows else os.path.sep
787        self.assertEqual(root_dir, str(pathlib.Path.cwd()))
788        dot_abs = pathlib.Path(".").absolute()
789        self.assertEqual(root_dir, str(dot_abs))
790        self.assertTrue(dot_abs.exists())
791
792
793class TestDeprecationSuppression(fake_filesystem_unittest.TestCase):
794    def test_no_deprecation_warning(self):
795        """Ensures that deprecation warnings are suppressed during module
796        lookup, see #542.
797        """
798
799        from pyfakefs.tests.fixtures.deprecated_property import (  # noqa: F401
800            DeprecationTest,
801        )
802
803        with warnings.catch_warnings(record=True) as w:
804            warnings.simplefilter("error", DeprecationWarning)
805            self.setUpPyfakefs()
806            self.assertEqual(0, len(w))
807
808
809def load_configs(configs):
810    """Helper code for patching open_code in auto mode, see issue #554."""
811    retval = []
812    for config in configs:
813        if len(config) > 3 and config[-3:] == ".py":
814            retval += runpy.run_path(config)
815        else:
816            retval += runpy.run_module(config)
817    return retval
818
819
820@unittest.skipIf(sys.version_info < (3, 8), "open_code new in Python 3.8")
821class AutoPatchOpenCodeTestCase(fake_filesystem_unittest.TestCase):
822    """Test patching open_code in auto mode, see issue #554."""
823
824    def setUp(self):
825        self.setUpPyfakefs(patch_open_code=PatchMode.AUTO)
826
827        self.configpy = "configpy.py"
828        self.fs.create_file(self.configpy, contents="configurable_value='yup'")
829        self.config_module = "pyfakefs.tests.fixtures.config_module"
830
831    def test_both(self):
832        load_configs([self.configpy, self.config_module])
833
834    def test_run_path(self):
835        load_configs([self.configpy])
836
837    def test_run_module(self):
838        load_configs([self.config_module])
839
840    def import_foo(self):
841        spec = importlib.util.spec_from_file_location("bar", "/foo/bar.py")
842        mod = importlib.util.module_from_spec(spec)
843        spec.loader.exec_module(mod)
844
845    def test_exec_module_in_fake_fs(self):
846        self.fs.create_file("/foo/bar.py", contents="print('hello')")
847        with redirect_stdout(StringIO()) as stdout:
848            self.import_foo()
849        assert stdout.getvalue() == "hello\n"
850
851
852class TestOtherFS(fake_filesystem_unittest.TestCase):
853    def setUp(self):
854        self.setUpPyfakefs()
855
856    @mock.patch.dict(os.environ, {"HOME": "/home/john"})
857    def test_real_file_with_home(self):
858        """Regression test for #558"""
859        self.fs.is_windows_fs = os.name != "nt"
860        if self.fs.is_windows_fs:
861            self.fs.is_macos = False
862        self.fs.add_real_file(__file__)
863        with open(__file__, encoding="utf8") as f:
864            self.assertTrue(f.read())
865        home = Path.home()
866        os.chdir(home)
867        with open(__file__, encoding="utf8") as f:
868            self.assertTrue(f.read())
869
870    def test_windows(self):
871        self.fs.os = OSType.WINDOWS
872        path = r"C:\foo\bar"
873        self.assertEqual(path, os.path.join("C:\\", "foo", "bar"))
874        self.assertEqual(("C:", r"\foo\bar"), os.path.splitdrive(path))
875        self.fs.create_file(path)
876        self.assertTrue(os.path.exists(path))
877        self.assertTrue(os.path.exists(path.upper()))
878        self.assertTrue(os.path.ismount(r"\\share\foo"))
879        self.assertTrue(os.path.ismount(r"C:"))
880        self.assertEqual("\\", os.sep)
881        self.assertEqual("\\", os.path.sep)
882        self.assertEqual("/", os.altsep)
883        self.assertEqual(";", os.pathsep)
884        self.assertEqual("\r\n", os.linesep)
885        self.assertEqual("NUL", os.devnull)
886
887    def test_linux(self):
888        self.fs.os = OSType.LINUX
889        path = "/foo/bar"
890        self.assertEqual(path, os.path.join("/", "foo", "bar"))
891        self.assertEqual(("", "C:/foo/bar"), os.path.splitdrive("C:/foo/bar"))
892        self.fs.create_file(path)
893        self.assertTrue(os.path.exists(path))
894        self.assertFalse(os.path.exists(path.upper()))
895        self.assertTrue(os.path.ismount("/"))
896        self.assertFalse(os.path.ismount("//share/foo"))
897        self.assertEqual("/", os.sep)
898        self.assertEqual("/", os.path.sep)
899        self.assertEqual(None, os.altsep)
900        self.assertEqual(":", os.pathsep)
901        self.assertEqual("\n", os.linesep)
902        self.assertEqual("/dev/null", os.devnull)
903
904    def test_macos(self):
905        self.fs.os = OSType.MACOS
906        path = "/foo/bar"
907        self.assertEqual(path, os.path.join("/", "foo", "bar"))
908        self.assertEqual(("", "C:/foo/bar"), os.path.splitdrive("C:/foo/bar"))
909        self.fs.create_file(path)
910        self.assertTrue(os.path.exists(path))
911        self.assertTrue(os.path.exists(path.upper()))
912        self.assertTrue(os.path.ismount("/"))
913        self.assertFalse(os.path.ismount("//share/foo"))
914        self.assertEqual("/", os.sep)
915        self.assertEqual("/", os.path.sep)
916        self.assertEqual(None, os.altsep)
917        self.assertEqual(":", os.pathsep)
918        self.assertEqual("\n", os.linesep)
919        self.assertEqual("/dev/null", os.devnull)
920
921    def test_drivelike_path(self):
922        self.fs.os = OSType.LINUX
923        folder = Path("/test")
924        file_path = folder / "C:/testfile"
925        file_path.parent.mkdir(parents=True)
926        file_path.touch()
927        os.chdir(folder)
928        self.assertTrue(os.path.exists(str(file_path.relative_to(folder))))
929
930    @unittest.skipIf(sys.platform != "win32", "Windows-specific test")
931    def test_tempfile_access(self):
932        # regression test for #912
933        self.fs.os = OSType.LINUX
934        tmp_file = tempfile.TemporaryFile()
935        assert tmp_file
936
937
938@unittest.skipIf(sys.platform != "win32", "Windows-specific behavior")
939class TestAbsolutePathOnWindows(fake_filesystem_unittest.TestCase):
940    @patchfs
941    def test_is_absolute(self, fs):
942        # regression test for #673
943        self.assertTrue(pathlib.Path(".").absolute().is_absolute())
944
945
946@unittest.skipIf(sys.version_info < (3, 8), "Not available before Python 3.8")
947class TestClassSetup(fake_filesystem_unittest.TestCase):
948    @classmethod
949    def setUpClass(cls):
950        cls.setUpClassPyfakefs()
951        cls.fake_fs().create_file("foo/bar", contents="test")
952
953    def test_using_fs_functions(self):
954        self.assertTrue(os.path.exists("foo/bar"))
955        with open("foo/bar", encoding="utf8") as f:
956            contents = f.read()
957        self.assertEqual("test", contents)
958
959    def test_using_fakefs(self):
960        self.assertTrue(self.fs.exists("foo/bar"))
961        f = self.fs.get_object("foo/bar")
962        self.assertEqual("test", f.contents)
963
964
965class TestTempPathCreation(fake_filesystem_unittest.TestCase):
966    """Regression test for #965. Checks that the temp file system
967    is properly created with a root-owned root path.
968    """
969
970    def setUp(self):
971        self.setUpPyfakefs()
972
973    def check_write_tmp_after_reset(self, os_type):
974        self.fs.os = os_type
975        # Mark '/' to be modifiable by only root
976        os.chown("/", 0, 0)
977        os.chmod("/", 0b111_101_101)
978        with tempfile.TemporaryFile("wb") as f:
979            assert f.write(b"foo") == 3
980
981    def test_write_tmp_linux(self):
982        self.check_write_tmp_after_reset(OSType.LINUX)
983
984    def test_write_tmp_macos(self):
985        self.check_write_tmp_after_reset(OSType.MACOS)
986
987    def test_write_tmp_windows(self):
988        self.check_write_tmp_after_reset(OSType.WINDOWS)
989
990
991@unittest.skipIf(sys.version_info < (3, 8), "Not available before Python 3.8")
992class FakeImportTest(fake_filesystem_unittest.TestCase):
993    """Checks that a fake module can be imported in AUTO patch mode."""
994
995    def setUp(self):
996        self.setUpPyfakefs(patch_open_code=PatchMode.AUTO)
997
998    def test_simple_fake_import(self):
999        fake_module_path = Path("/") / "site-packages" / "fake_module.py"
1000        self.fs.create_file(fake_module_path, contents="number = 42")
1001        sys.path.insert(0, str(fake_module_path.parent))
1002        module = importlib.import_module("fake_module")
1003        del sys.path[0]
1004        assert module.__name__ == "fake_module"
1005        assert module.number == 42
1006
1007    def test_fake_import_dotted_module(self):
1008        fake_pkg_path = Path("/") / "site-packages"
1009        self.fs.create_file(fake_pkg_path / "fakepkg" / "__init__.py")
1010        fake_module_path = fake_pkg_path / "fakepkg" / "fake_module.py"
1011        self.fs.create_file(fake_module_path, contents="number = 42")
1012        sys.path.insert(0, str(fake_pkg_path))
1013        module = importlib.import_module("fakepkg.fake_module")
1014        del sys.path[0]
1015        assert module.__name__ == "fakepkg.fake_module"
1016        assert module.number == 42
1017
1018    def test_fake_relative_import(self):
1019        fake_module_path = Path("site-packages") / "fake_module.py"
1020        self.fs.create_file(fake_module_path, contents="number = 42")
1021        sys.path.insert(0, str(fake_module_path.parent))
1022        module = importlib.import_module("fake_module")
1023        del sys.path[0]
1024        assert module.__name__ == "fake_module"
1025        assert module.number == 42
1026
1027
1028if __name__ == "__main__":
1029    unittest.main()
1030