1# Copyright 2014 Altera Corporation. All Rights Reserved. 2# Author: John McGehee 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16""" 17Test the :py:class`pyfakefs.example` module to demonstrate the usage of the 18:py:class`pyfakefs.fake_filesystem_unittest.TestCase` base class. 19 20Fake filesystem functions like `create_file()`, `create_dir()` or 21`create_symlink()` are often used to set up file structures at the beginning 22of a test. 23While you could also use the familiar `open()`, `os.mkdirs()` and similar 24functions, these functions can make the test code shorter and more readable. 25`create_file()` is particularly convenient because it creates all parent 26directories and allows you to specify the contents or the size of the file. 27""" 28 29import io 30import os 31import sys 32import unittest 33 34from pyfakefs import fake_filesystem_unittest 35from pyfakefs.legacy_packages import scandir 36from pyfakefs.tests import example # The module under test 37 38 39# Work around pyupgrade auto-rewriting `io.open()` to `open()`. 40io_open = io.open 41 42 43def load_tests(loader, tests, ignore): 44 """Load the pyfakefs/example.py doctest tests into unittest.""" 45 return fake_filesystem_unittest.load_doctests(loader, tests, ignore, example) 46 47 48class TestExample(fake_filesystem_unittest.TestCase): # pylint: disable=R0904 49 """Test the example module. 50 The os and shutil modules have been replaced with the fake modules, 51 so that all of the calls to os and shutil in the tested example code 52 occur in the fake filesystem. 53 """ 54 55 def setUp(self): 56 """Invoke the :py:class:`pyfakefs.fake_filesystem_unittest.TestCase` 57 `self.setUp()` method. This defines: 58 59 * Attribute `self.fs`, an instance of 60 :py:class:`pyfakefs.fake_filesystem.FakeFilesystem`. This is useful 61 for creating test files. 62 * Attribute `self.stubs`, an instance of 63 :py:class:`pyfakefs.mox3_stubout.StubOutForTesting`. Use this if 64 you need to define additional stubs. 65 """ 66 67 # This is before setUpPyfakefs(), so still using the real file system 68 self.filepath = os.path.realpath(__file__) 69 with io_open(self.filepath, "rb") as f: 70 self.real_contents = f.read() 71 72 self.setUpPyfakefs() 73 74 def tearDown(self): 75 # No longer need self.tearDownPyfakefs() 76 pass 77 78 def test_create_file(self): 79 """Test example.create_file() which uses `open()` 80 and `file.write()`. 81 """ 82 self.assertFalse(os.path.isdir("/test")) 83 os.mkdir("/test") 84 self.assertTrue(os.path.isdir("/test")) 85 86 self.assertFalse(os.path.exists("/test/file.txt")) 87 example.create_file("/test/file.txt") 88 self.assertTrue(os.path.exists("/test/file.txt")) 89 90 def test_delete_file(self): 91 """Test example.delete_file() which uses `os.remove()`.""" 92 self.fs.create_file("/test/full.txt", contents="First line\nSecond Line\n") 93 self.assertTrue(os.path.exists("/test/full.txt")) 94 example.delete_file("/test/full.txt") 95 self.assertFalse(os.path.exists("/test/full.txt")) 96 97 def test_file_exists(self): 98 """Test example.path_exists() which uses `os.path.exists()`.""" 99 self.assertFalse(example.path_exists("/test/empty.txt")) 100 self.fs.create_file("/test/empty.txt") 101 self.assertTrue(example.path_exists("/test/empty.txt")) 102 103 def test_get_globs(self): 104 """Test example.get_glob().""" 105 self.assertFalse(os.path.isdir("/test")) 106 self.fs.create_dir("/test/dir1/dir2a") 107 self.assertTrue(os.path.isdir("/test/dir1/dir2a")) 108 # os.mkdirs() works, too. 109 os.makedirs("/test/dir1/dir2b") 110 self.assertTrue(os.path.isdir("/test/dir1/dir2b")) 111 112 self.assertEqual(example.get_glob("/test/dir1/nonexistent*"), []) 113 is_windows = sys.platform.startswith("win") 114 matching_paths = sorted(example.get_glob("/test/dir1/dir*")) 115 if is_windows: 116 self.assertEqual(matching_paths, [r"/test/dir1\dir2a", r"/test/dir1\dir2b"]) 117 else: 118 self.assertEqual(matching_paths, ["/test/dir1/dir2a", "/test/dir1/dir2b"]) 119 120 def test_rm_tree(self): 121 """Test example.rm_tree() using `shutil.rmtree()`.""" 122 self.fs.create_dir("/test/dir1/dir2a") 123 # os.mkdirs() works, too. 124 os.makedirs("/test/dir1/dir2b") 125 self.assertTrue(os.path.isdir("/test/dir1/dir2b")) 126 self.assertTrue(os.path.isdir("/test/dir1/dir2a")) 127 128 example.rm_tree("/test/dir1") 129 self.assertFalse(os.path.exists("/test/dir1")) 130 131 def test_os_scandir(self): 132 """Test example.scandir() which uses `os.scandir()`. 133 134 The os module has been replaced with the fake os module so the 135 fake filesystem path entries are returned instead of `os.DirEntry` 136 objects. 137 """ 138 self.fs.create_file("/test/text.txt") 139 self.fs.create_dir("/test/dir") 140 self.fs.create_file("/linktest/linked") 141 self.fs.create_symlink("/test/linked_file", "/linktest/linked") 142 143 entries = sorted(example.scan_dir("/test"), key=lambda e: e.name) 144 self.assertEqual(3, len(entries)) 145 self.assertEqual("linked_file", entries[1].name) 146 self.assertTrue(entries[0].is_dir()) 147 self.assertTrue(entries[1].is_symlink()) 148 self.assertTrue(entries[2].is_file()) 149 150 @unittest.skipIf(scandir is None, "Testing only if scandir module is installed") 151 def test_scandir_scandir(self): 152 """Test example.scandir() which uses `scandir.scandir()`. 153 154 The scandir module has been replaced with the fake_scandir module so 155 the fake filesystem path entries are returned instead of 156 `scandir.DirEntry` objects. 157 """ 158 self.fs.create_file("/test/text.txt") 159 self.fs.create_dir("/test/dir") 160 161 entries = sorted(example.scan_dir("/test"), key=lambda e: e.name) 162 self.assertEqual(2, len(entries)) 163 self.assertEqual("text.txt", entries[1].name) 164 self.assertTrue(entries[0].is_dir()) 165 self.assertTrue(entries[1].is_file()) 166 167 def test_real_file_access(self): 168 """Test `example.file_contents()` for a real file after adding it using 169 `add_real_file()`.""" 170 with self.assertRaises(OSError): 171 example.file_contents(self.filepath) 172 self.fs.add_real_file(self.filepath) 173 self.assertEqual(example.file_contents(self.filepath), self.real_contents) 174 175 176if __name__ == "__main__": 177 unittest.main() 178