Coverage for tests/utils/string_utils.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 19:49 +0000

1from abc import ABC 

2from typing import Any 

3from json import loads, dumps 

4from secrets import token_hex 

5 

6 

7class StringUtils(ABC): 

8 """General string utilities.""" 

9 

10 @classmethod 

11 def get_percentage(cls, n: int, m: int, precision: int = 2) -> str: 

12 """Get percentage in readable format. 

13 

14 :param int n: steps completed. 

15 :param int m: total steps. 

16 :param int precision: percentage precision. 

17 :returns str: percentage in readable format. 

18 """ 

19 # calculate percentage from steps 

20 r: float = (n / m)*100 

21 return cls.get_percentage_float(r, precision) 

22 

23 @classmethod 

24 def get_percentage_float(cls, n: float, precision: int = 2) -> str: 

25 """Get percentage in readable format. 

26 

27 :param float n: percentage value. 

28 :param int precision: percentage precision. 

29 :returns str: percentage in readable format. 

30 """ 

31 # set precision 

32 return f"{round(n, precision)}%" 

33 

34 @classmethod 

35 def get_random_string(cls, n: int = 25) -> str: 

36 """Generate random string. 

37 

38 :param int n: length of the random string to generate (default `25`). 

39 :returns str: random string. 

40 """ 

41 # generate random string 

42 return token_hex(n) 

43 

44 @classmethod 

45 def prettify(cls, json_str: str) -> str: 

46 """Pretty-print a JSON string with indentation. 

47 

48 :param str json_str: JSON string to pretty-print. 

49 :returns str: the pretty-printed JSON string. 

50 """ 

51 parsed_obj: Any = loads(json_str) 

52 return dumps(parsed_obj, indent=1)