Coverage for .nox/test-3-12/lib/python3.12/site-packages/nskit/mixer/components/file.py: 94%

47 statements  

« prev     ^ index     » next       coverage.py v7.3.3, created at 2023-12-19 17:42 +0000

1"""File component.""" 

2from pathlib import Path 

3from typing import Any, Dict, Optional, Union 

4 

5from pydantic import Field 

6 

7from nskit.mixer.components.filesystem_object import FileSystemObject 

8from nskit.mixer.utilities import JINJA_ENVIRONMENT_FACTORY, Resource 

9 

10 

11class File(FileSystemObject): 

12 """File component.""" 

13 

14 content: Union[Resource, str, bytes, Path] = Field('', description='The file content') 

15 

16 def render_content(self, context: Dict[str, Any]): # pylint: disable=arguments-differ 

17 """Return the rendered content using the context and the Jinja environment.""" 

18 if isinstance(self.content, Resource): 

19 content = self.content.load() 

20 elif isinstance(self.content, Path): 

21 with open(self.content) as f: 

22 content = f.read() 

23 else: 

24 content = self.content 

25 if isinstance(content, str): 

26 # If it is a string, we render the content 

27 content = JINJA_ENVIRONMENT_FACTORY.environment.from_string(content).render(**context) 

28 return content 

29 

30 def write(self, base_path: Path, context: Dict[str, Any], override_path: Optional[Path] = None): 

31 """Write the rendered content to the appropriate path within the ``base_path``.""" 

32 file_path = self.get_path(base_path, context, override_path) 

33 content = self.render_content(context) 

34 if isinstance(content, str): 

35 open_str = 'w' 

36 elif isinstance(content, bytes): 

37 open_str = 'wb' 

38 with file_path.open(open_str) as output_file: 

39 output_file.write(content) 

40 return {file_path: content} 

41 

42 def dryrun(self, base_path: Path, context: Dict[str, Any], override_path: Optional[Path] = None): 

43 """Preview the file contents using the context.""" 

44 file_path = self.get_path(base_path, context, override_path) 

45 result = {file_path: self.render_content(context)} 

46 return result 

47 

48 def validate(self, base_path: Path, context: Dict[str, Any], override_path: Optional[Path] = None): 

49 """Validate the output against expected.""" 

50 missing = [] 

51 errors = [] 

52 ok = [] 

53 path = self.get_path(base_path, context, override_path) 

54 if not path.exists(): 

55 missing.append(path) 

56 else: 

57 content = self.render_content(context) 

58 if isinstance(content, bytes): 

59 read_str = 'rb' 

60 else: 

61 read_str = 'r' 

62 with open(path, read_str) as f: 

63 if f.read() != self.render_content(context): 

64 errors.append(path) 

65 else: 

66 ok.append(path) 

67 return missing, errors, ok