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