import json import os import random import string from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Optional from urllib.parse import urlunparse from loguru import logger from pytest_abra.dir_manager import DirManager @dataclass class BaseUrl: """utility class to create a url string with urllib""" netloc: str scheme: str = "https" path: str = "" params: str = "" query: str = "" fragment: str = "" def get(self, path: str = ""): return urlunparse((self.scheme, self.netloc, path, self.params, self.query, self.fragment)) def get_datetime_string() -> str: current_datetime = datetime.now() return current_datetime.strftime("%Y-%m-%d-%H-%M-%S") def rmtree(root_dir: Path) -> None: """removes a folder with content recursively""" if not root_dir.is_dir(): return for child in root_dir.iterdir(): if child.is_dir(): rmtree(child) else: child.unlink() root_dir.rmdir() def generate_random_string(length: int, punctuation=False) -> str: """returns a random string of the given length""" characters = string.ascii_letters + string.digits if punctuation: characters += string.punctuation random_string = "".join(random.choice(characters) for _ in range(length)) return random_string def load_json_to_environ(cred_file: Path) -> None: """Load the contents of a json file directly into os.environ. Variable names are inherited""" if not cred_file.is_file(): logger.warning(f"{cred_file} could not be found, no credentials loaded") return with open(cred_file, "r") as f: CREDENTIALS = json.load(f) for key, value in CREDENTIALS.items(): os.environ[key] = value def get_session_id(args_output_dir: Path, args_resume: bool, args_session_id: Optional[str]) -> str: """converts the cli arguments to the correct session_id""" session_id = args_session_id if not session_id: session_id = "test-" + get_datetime_string() if args_resume: latest_session_id = DirManager.get_latest_session_id(args_output_dir) if latest_session_id: session_id = latest_session_id return session_id def files_are_same(file1: Path, file2: Path) -> bool: with open(file1, "r") as f1, open(file2, "r") as f2: return f1.read() == f2.read()