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# Example for a test using a custom pytest fixture with an argument to Patcher 14# Needs Python >= 3.6 15 16import pytest 17 18import pyfakefs.pytest_tests.example as example 19from pyfakefs.fake_filesystem_unittest import Patcher 20 21 22@pytest.mark.xfail 23def test_example_file_failing(fs): 24 """Test fails because EXAMPLE_FILE is cached in the module 25 and not patched.""" 26 fs.create_file(example.EXAMPLE_FILE, contents='stuff here') 27 check_that_example_file_is_in_fake_fs() 28 29 30def test_example_file_passing_using_fixture(fs_reload_example): 31 """Test passes if using a fixture that reloads the module containing 32 EXAMPLE_FILE""" 33 fs_reload_example.create_file(example.EXAMPLE_FILE, contents='stuff here') 34 check_that_example_file_is_in_fake_fs() 35 36 37def test_example_file_passing_using_patcher(): 38 """Test passes if using a Patcher instance that reloads the module 39 containing EXAMPLE_FILE""" 40 with Patcher(modules_to_reload=[example]) as patcher: 41 patcher.fs.create_file(example.EXAMPLE_FILE, contents='stuff here') 42 check_that_example_file_is_in_fake_fs() 43 44 45def check_that_example_file_is_in_fake_fs(): 46 with open(example.EXAMPLE_FILE) as file: 47 assert file.read() == 'stuff here' 48 with example.EXAMPLE_FILE.open() as file: 49 assert file.read() == 'stuff here' 50 assert example.EXAMPLE_FILE.read_text() == 'stuff here' 51 assert example.EXAMPLE_FILE.is_file() 52