Coverage for suhteita/__init__.py: 98.61%

58 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-04 22:42:46 +00:00

1"""Relationships (Finnish: suhteita) maintained across distances as load test core.""" 

2 

3import datetime as dti 

4import logging 

5import os 

6import pathlib 

7import platform 

8import secrets 

9import uuid 

10from typing import Tuple, no_type_check 

11 

12# [[[fill git_describe()]]] 

13__version__ = '2023.6.18+parent.b59b2bfe' 

14# [[[end]]] (checksum: 2ff08a325317e78f9992a600ae7274f6) 

15__version_info__ = tuple( 

16 e if '-' not in e else e.split('-')[0] for part in __version__.split('+') for e in part.split('.') if e != 'parent' 

17) 

18 

19APP_ALIAS = str(pathlib.Path(__file__).parent.name) 

20APP_ENV = APP_ALIAS.upper() 

21APP_NAME = locals()['__doc__'] 

22DEBUG = bool(os.getenv(f'{APP_ENV}_DEBUG', '')) 

23VERBOSE = bool(os.getenv(f'{APP_ENV}_VERBOSE', '')) 

24QUIET = False 

25STRICT = bool(os.getenv(f'{APP_ENV}_STRICT', '')) 

26ENCODING = 'utf-8' 

27ENCODING_ERRORS_POLICY = 'ignore' 

28DEFAULT_CONFIG_NAME = f'.{APP_ALIAS}.json' 

29 

30NODE_INDICATOR = str(uuid.uuid3(uuid.NAMESPACE_DNS, platform.node())) 

31STORE = os.getenv(f'{APP_ENV}_STORE', '') # default 'store' per argparse 

32 

33USER = os.getenv(f'{APP_ENV}_USER', '') 

34TOKEN = os.getenv(f'{APP_ENV}_TOKEN', '') 

35BASE_URL = os.getenv(f'{APP_ENV}_BASE_URL', '') 

36IS_CLOUD = bool(os.getenv(f'{APP_ENV}_IS_CLOUD', '')) 

37PROJECT = os.getenv(f'{APP_ENV}_PROJECT', '') 

38IDENTITY = os.getenv(f'{APP_ENV}_IDENTITY', '') # default 'adhoc' per argparse 

39WORDS = os.getenv(f'{APP_ENV}_WORDS', '/usr/share/dict/words') 

40 

41 

42log = logging.getLogger() # Module level logger is sufficient 

43LOG_FOLDER = pathlib.Path('logs') 

44LOG_FILE = f'{APP_ALIAS}.log' 

45LOG_PATH = pathlib.Path(LOG_FOLDER, LOG_FILE) if LOG_FOLDER.is_dir() else pathlib.Path(LOG_FILE) 

46LOG_LEVEL = logging.INFO 

47 

48TS_FORMAT_LOG = '%Y-%m-%dT%H:%M:%S' 

49TS_FORMAT_PAYLOADS = '%Y-%m-%d %H:%M:%S.%f UTC' 

50 

51Clocking = Tuple[str, float, str] 

52 

53 

54def two_sentences(word_count: int = 4) -> Tuple[str, str]: 

55 """DRY.""" 

56 with open(WORDS, 'rt', encoding=ENCODING) as handle: 

57 words = [word.strip() for word in handle] 

58 wun = ' '.join(secrets.choice(words) for _ in range(word_count)) 

59 two = ' '.join(secrets.choice(words) for _ in range(word_count)) 

60 del words 

61 return wun, two 

62 

63 

64@no_type_check 

65def extract_fields(data, fields): 

66 """DRY.""" 

67 return {field: data[field] for field in fields} 

68 

69 

70@no_type_check 

71def formatTime_RFC3339(self, record, datefmt=None): 

72 """HACK A DID ACK we could inject .astimezone() to localize ...""" 

73 return dti.datetime.fromtimestamp(record.created, dti.timezone.utc).isoformat() 

74 

75 

76@no_type_check 

77def init_logger(name=None, level=None): 

78 """Initialize module level logger""" 

79 global log # pylint: disable=global-statement 

80 

81 log_format = { 

82 'format': '%(asctime)s %(levelname)s [%(name)s]: %(message)s', 

83 'datefmt': TS_FORMAT_LOG, 

84 # 'filename': LOG_PATH, 

85 'level': LOG_LEVEL if level is None else level, 

86 } 

87 logging.Formatter.formatTime = formatTime_RFC3339 

88 logging.basicConfig(**log_format) 

89 log = logging.getLogger(APP_ENV if name is None else name) 

90 log.propagate = True 

91 

92 

93init_logger(name=APP_ENV, level=logging.DEBUG if DEBUG else None)