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""" 14Example module that is used for testing modules that import file system modules 15to be patched under another name. 16""" 17import os as my_os 18import pathlib 19import sys 20from builtins import open as bltn_open 21from io import open as io_open 22from os import path 23from os import stat 24from os import stat as my_stat 25from os.path import exists 26from os.path import exists as my_exists 27from pathlib import Path 28 29 30def check_if_exists1(filepath): 31 # test patching module imported under other name 32 return my_os.path.exists(filepath) 33 34 35def check_if_exists2(filepath): 36 # tests patching path imported from os 37 return path.exists(filepath) 38 39 40def check_if_exists3(filepath): 41 # tests patching Path imported from pathlib 42 return Path(filepath).exists() 43 44 45def check_if_exists4(filepath, file_exists=my_os.path.exists): 46 return file_exists(filepath) 47 48 49def check_if_exists5(filepath): 50 # tests patching `exists` imported from os.path 51 return exists(filepath) 52 53 54def check_if_exists6(filepath): 55 # tests patching `exists` imported from os.path as other name 56 return my_exists(filepath) 57 58 59def check_if_exists7(filepath): 60 # tests patching pathlib 61 return pathlib.Path(filepath).exists() 62 63 64def file_stat1(filepath): 65 # tests patching `stat` imported from os 66 return stat(filepath) 67 68 69def file_stat2(filepath): 70 # tests patching `stat` imported from os as other name 71 return my_stat(filepath) 72 73 74def system_stat(filepath): 75 if sys.platform == 'win32': 76 from nt import stat as system_stat 77 else: 78 from posix import stat as system_stat 79 return system_stat(filepath) 80 81 82def file_contents1(filepath): 83 with bltn_open(filepath) as f: 84 return f.read() 85 86 87def file_contents2(filepath): 88 with io_open(filepath) as f: 89 return f.read() 90 91 92def exists_this_file(): 93 """Returns True in real fs only""" 94 return exists(__file__) 95 96 97def open_this_file(): 98 """Works only in real fs""" 99 with open(__file__): 100 pass 101 102 103def return_this_file_path(): 104 """Works only in real fs""" 105 return Path(__file__) 106 107 108class TestDefaultArg: 109 def check_if_exists(self, filepath, file_exists=my_os.path.exists): 110 # this is a similar case as in the tempfile implementation under Posix 111 return file_exists(filepath) 112