1# Licensed under the Apache License, Version 2.0 (the "License"); 2# you may not use this file except in compliance with the License. 3# You may obtain a copy of the License at 4# 5# http://www.apache.org/licenses/LICENSE-2.0 6# 7# Unless required by applicable law or agreed to in writing, software 8# distributed under the License is distributed on an "AS IS" BASIS, 9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10# See the License for the specific language governing permissions and 11# limitations under the License. 12 13""" 14Tests for patching modules loaded after `setUpPyfakefs()`. 15""" 16import pathlib 17import unittest 18 19from pyfakefs import fake_filesystem_unittest 20 21 22class TestPyfakefsUnittestBase(fake_filesystem_unittest.TestCase): 23 def setUp(self): 24 """Set up the fake file system""" 25 self.setUpPyfakefs() 26 27 28class DynamicImportPatchTest(TestPyfakefsUnittestBase): 29 def __init__(self, methodName="runTest"): 30 super(DynamicImportPatchTest, self).__init__(methodName) 31 32 def test_os_patch(self): 33 import os 34 35 os.mkdir("test") 36 self.assertTrue(self.fs.exists("test")) 37 self.assertTrue(os.path.exists("test")) 38 39 def test_os_import_as_patch(self): 40 import os as _os 41 42 _os.mkdir("test") 43 self.assertTrue(self.fs.exists("test")) 44 self.assertTrue(_os.path.exists("test")) 45 46 def test_os_path_patch(self): 47 import os.path 48 49 os.mkdir("test") 50 self.assertTrue(self.fs.exists("test")) 51 self.assertTrue(os.path.exists("test")) 52 53 def test_shutil_patch(self): 54 import shutil 55 56 self.fs.set_disk_usage(100) 57 self.assertEqual(100, shutil.disk_usage("/").total) 58 59 def test_pathlib_path_patch(self): 60 file_path = "test.txt" 61 path = pathlib.Path(file_path) 62 with path.open("w") as f: 63 f.write("test") 64 65 self.assertTrue(self.fs.exists(file_path)) 66 file_object = self.fs.get_object(file_path) 67 self.assertEqual("test", file_object.contents) 68 69 70if __name__ == "__main__": 71 unittest.main() 72