Coverage for helpers.py: 15%

57 statements  

« prev     ^ index     » next       coverage.py v7.8.2, created at 2025-10-16 22:37 +0200

1import os 

2import textwrap 

3from pathlib import Path 

4 

5 

6def create_empty_file(filename: str | Path, create_folder: bool = False): 

7 """ 

8 A function and context manager to create an empty file with the given 

9 filename. When used as a function, the file needs to be removed explicitly 

10 with a call to `filename.unlink()` or `os.unlink(filename)`. 

11 

12 This function can be called as a context manager in which case the file will 

13 be removed when the context ends. 

14 

15 Returns: 

16 The filename as a Path. 

17 """ 

18 

19 class _ContextManager: 

20 def __init__(self, filename: str | Path, create_folder: bool): 

21 self.filename = Path(filename) 

22 

23 if self.filename.exists(): 

24 raise FileExistsError(f"The empty file you wanted to create already exists: {filename}") 

25 

26 if create_folder and not self.filename.parent.exists(): 

27 self.filename.parent.mkdir(parents=True) 

28 

29 with self.filename.open(mode="w"): 

30 pass 

31 

32 def __enter__(self): 

33 return self.filename 

34 

35 def __exit__(self, exc_type, exc_val, exc_tb): 

36 self.filename.unlink() 

37 

38 return _ContextManager(filename, create_folder) 

39 

40 

41def create_text_file(filename: str | Path, content: str, create_folder: bool = False): 

42 """ 

43 A function and context manager to create a text file with the given string 

44 as content. When used as a function, the file needs to be removed explicitly 

45 with a call to `filename.unlink()` or `os.unlink(filename)`. 

46 

47 This function can be called as a context manager in which case the file will 

48 be removed when the context ends. 

49 

50 >> with create_text_file("samples.txt", "A,B,C\n1,2,3\n4,5,6\n"): 

51 .. # do something with the file or its content 

52 

53 Returns: 

54 The filename as a Path. 

55 """ 

56 

57 class _ContextManager: 

58 def __init__(self, filename: str | Path, create_folder: bool): 

59 self.filename = Path(filename) 

60 

61 if self.filename.exists(): 

62 raise FileExistsError(f"The text file you wanted to create already exists: {filename}") 

63 

64 if create_folder and not self.filename.parent.exists(): 

65 self.filename.parent.mkdir(parents=True) 

66 

67 with self.filename.open(mode="w") as fd: 

68 fd.write(content) 

69 

70 def __enter__(self): 

71 return self.filename 

72 

73 def __exit__(self, exc_type, exc_val, exc_tb): 

74 self.filename.unlink() 

75 

76 return _ContextManager(filename, create_folder) 

77 

78 

79CSV_TEST_DATA = """\ 

80employee_id,first_name,last_name,department,position,salary,hire_date,is_active,email 

81# a comment line 

821001,John,Smith,Engineering,Software Engineer,75000,2022-03-15,TRUE,john.smith@company.com 

831002,Sarah,Johnson,Marketing,Marketing Manager,68000,2021-07-22,TRUE,sarah.johnson@company.com 

841003,Michael,Brown,Sales,Sales Representative,55000,2023-01-10,TRUE,michael.brown@company.com 

851004,Emily,Davis,Engineering,Senior Developer,85000,2020-11-05,TRUE,emily.davis@company.com 

861005,David,Wilson,HR,HR Specialist,62000,2022-09-18,TRUE,david.wilson@company.com 

871006,Lisa,Anderson,Finance,Financial Analyst,70000,2021-04-12,TRUE,lisa.anderson@company.com 

881007,Robert,Taylor,Engineering,DevOps Engineer,78000,2022-12-03,TRUE,robert.taylor@company.com 

891008,Jennifer,Thomas,Marketing,Content Creator,52000,2023-05-20,TRUE,jennifer.thomas@company.com 

901009,William,Jackson,Sales,Sales Manager,72000,2020-08-14,TRUE,william.jackson@company.com 

911010,Jessica,White,IT,System Administrator,65000,2021-10-30,FALSE,jessica.white@company.com 

921011,Christopher,Harris,Engineering,Junior Developer,58000,2023-08-07,TRUE,christopher.harris@company.com 

931012,Amanda,Martin,Finance,Accountant,61000,2022-02-28,TRUE,amanda.martin@company.com 

941013,James,Thompson,Sales,Sales Representative,54000,2023-03-16,TRUE,james.thompson@company.com 

951014,Michelle,Garcia,HR,Recruiter,59000,2021-12-08,TRUE,michelle.garcia@company.com 

961015,Daniel,Rodriguez,IT,Network Engineer,73000,2020-06-25,TRUE,daniel.rodriguez@company.com 

97""" 

98 

99 

100def create_test_csv_file(filename: str | Path, create_folder: bool = False): 

101 """ 

102 This file includes 15 employees with various data types that are useful for testing: 

103 

104 - Employee IDs (integers) 

105 - Names (text strings) 

106 - Departments (Engineering, Marketing, Sales, HR, Finance, IT) 

107 - Salaries (numeric values) 

108 - Hire dates (date format) 

109 - Active status (boolean TRUE/FALSE) 

110 - Email addresses (text with special characters) 

111 

112 The data includes different scenarios like active/inactive employees, various salary ranges, 

113 and different departments, making it great for testing data filtering, sorting, analysis, 

114 and visualization. 

115 

116 """ 

117 return create_text_file(filename, CSV_TEST_DATA, create_folder) 

118 

119 

120# Test the helper functions 

121 

122 

123def main(): 

124 print(f"cwd = {os.getcwd()}") 

125 

126 fn = Path("xxx.txt") 

127 

128 with create_empty_file(fn): 

129 assert fn.exists() 

130 assert not fn.exists() 

131 

132 create_empty_file(fn) 

133 assert fn.exists() 

134 fn.unlink() 

135 assert not fn.exists() 

136 

137 # Test the create_a_text_file() helper function 

138 

139 with create_text_file( 

140 fn, 

141 textwrap.dedent( 

142 """\ 

143 A,B,C,D 

144 1,2,3,4 

145 5,6,7,8 

146 """ 

147 ), 

148 ) as filename: 

149 assert fn.exists() 

150 assert filename == fn 

151 

152 print(fn.read_text()) 

153 

154 assert not fn.exists() 

155 

156 fn = Path("data/xxx.txt") 

157 

158 with create_empty_file(fn, create_folder=True): 

159 assert fn.exists() 

160 

161 assert not fn.exists() 

162 

163 

164if __name__ == "__main__": 164 ↛ 165line 164 didn't jump to line 165 because the condition on line 164 was never true

165 main()