1""" 2:module: tests.shell 3:synopsis: Common shell operations for testing. 4:author: [email protected] (Yesudeep Mangalapilly) 5:author: [email protected] (Mickaël Schoentgen) 6""" 7 8from __future__ import annotations 9 10import errno 11import os 12import os.path 13import shutil 14import tempfile 15import time 16 17 18def cd(path): 19 os.chdir(path) 20 21 22def pwd(): 23 return os.getcwd() 24 25 26def mkfile(path): 27 """Creates a file""" 28 with open(path, "ab"): 29 pass 30 31 32def mkdir(path, *, parents=False): 33 """Creates a directory (optionally also creates all the parent directories 34 in the path).""" 35 if parents: 36 try: 37 os.makedirs(path) 38 except OSError as e: 39 if not e.errno == errno.EEXIST: 40 raise 41 else: 42 os.mkdir(path) 43 44 45def rm(path, *, recursive=False): 46 """Deletes files or directories.""" 47 if os.path.isdir(path): 48 if recursive: 49 shutil.rmtree(path) 50 else: 51 raise OSError(errno.EISDIR, os.strerror(errno.EISDIR), path) 52 else: 53 os.remove(path) 54 55 56def touch(path, times=None): 57 """Updates the modified timestamp of a file or directory.""" 58 if os.path.isdir(path): 59 os.utime(path, times) 60 else: 61 with open(path, "ab"): 62 os.utime(path, times) 63 64 65def truncate(path): 66 """Truncates a file.""" 67 with open(path, "wb"): 68 os.utime(path, None) 69 70 71def mv(src_path, dest_path): 72 """Moves files or directories.""" 73 try: 74 os.rename(src_path, dest_path) 75 except OSError: 76 # this will happen on windows 77 os.remove(dest_path) 78 os.rename(src_path, dest_path) 79 80 81def mkdtemp(): 82 return tempfile.mkdtemp() 83 84 85def ls(path="."): 86 return os.listdir(path) 87 88 89def msize(path): 90 """Modify the file size without updating the modified time.""" 91 with open(path, "w") as w: 92 w.write("") 93 os.utime(path, (0, 0)) 94 time.sleep(0.4) 95 with open(path, "w") as w: 96 w.write("0") 97 os.utime(path, (0, 0)) 98 99 100def mount_tmpfs(path): 101 os.system(f"sudo mount -t tmpfs none {path}") 102 103 104def unmount(path): 105 os.system(f"sudo umount {path}") 106