When running the tests I get "NameError: name 'script_id' is not defined". I'm running all this in PyCharm 2024. Tests are kept in .\test\ tools are kept in .\tools. I've had this working with other tests on another project. test_utils.py (I have tried naming this file conftest.py): import pytest from time import time from os import path, remove from tools import log_tools # From Windows Copilot - "pycharm: i have a function to test that has a logging function how can I deal with log file creation in my tests" @pytest.fixture(scope="session", autouse=True) def setup_logging(): # Set up the logging configuration log_tools.script_id = "AutoInvest_test" log_tools.run_date = time.strftime('%d-%m-%Y', time.localtime()) file_name = f'logs\\{log_tools.script_id}_log_{log_tools.run_date}.txt' log_tools.initialize(False) yield # Remove the log file after each test if path.exists(file_name): remove(file_name) test_tools.py: from tools.file import check_for_backup from os import path, remove from datetime import datetime def create_file(a_path: str, data: list) -> None: if not path.exists(a_path): with open(a_path, 'w') as f: f.writelines(data) def clear_datetime_stamps(a_list: list) -> None: for x in range(len(a_list)): if len(a_list[x]) >= 18: try: datetime.strptime(a_list[x][:19], '%d-%m-%Y %H:%M:%S') a_list[x] = a_list[x][22:] except ValueError: pass def clean_print_capture(capture: str) -> list: output = capture.split("\n") clear_datetime_stamps(output) return output[:-1] def test_check_for_backup(capsys): data_path = '.\\test_data\\testfile.txt' filename = 'Test' check_for_backup(filename, data_path) assert clean_print_capture(capsys.readouterr().out) == [f"{filename} file ({path.abspath(data_path)}) empty or corrupt.", f"No backup {filename} file found."] create_file(data_path[:-3] + "old", ["hello"]) check_for_backup(filename, data_path) assert clean_print_capture(capsys.readouterr().out) == [f"{filename} file ({path.abspath(data_path)}) empty or corrupt.", "Backup file (.old) is present.", "\t\tIt is likely you have suffered some data loss.\t\tConsider renaming old file to JSON."] remove(data_path[:-3] + 'old') create_file(data_path[:-3] + "old2", ["hello", "file2"]) check_for_backup(filename, data_path) assert clean_print_capture(capsys.readouterr().out) == [f"{filename} file ({path.abspath(data_path)}) empty or corrupt.", "Backup file (.old2) is present.", "\t\tIt is highly likely you have suffered some data loss.\t\tConsider renaming old2 file to JSON."] remove(data_path[:-3] + 'old2') file.py from os import path from tools import log_tools def check_for_backup(name: str, file_path: str) -> None: log_tools.tprint(f'{name} file ({path.abspath(file_path)}) empty or corrupt.') if path.isfile(file_path[:-3] + 'old'): log_tools.tprint("Backup file (.old) is present.") print("\t\tIt is likely you have suffered some data loss.\t\tConsider renaming old file to JSON.") else: if path.isfile(file_path[:-3] + 'old2'): log_tools.tprint("Backup file (.old2) is present.") print("\t\tIt is highly likely you have suffered some data loss.\t\tConsider renaming old2 file to JSON.") else: log_tools.tprint(f"No backup {name} file found.") log_tools.py from time import strftime, localtime global run_date, script_id, html_output_file, log_file_name def initialize(enable_html: bool = True) -> None: if enable_html: global html_output_file html_output_file = list() from os import path if not path.isdir(r'./logs'): from os import makedirs makedirs('./logs') tprint("Log directory created.\n") del makedirs del path '''Print a string with a timestamp''' def tprint(*args: str, html: bool = False, **kwargs: str) -> None: if len(kwargs) == 0: kwargs = {'sep': '', 'end': '\n'} else: if 'sep' not in kwargs: kwargs['sep'] = '' if 'end' not in kwargs: kwargs['end'] = '\n' output = strftime('%d-%m-%Y %H:%M:%S', localtime()) + " - " for x in args: output += x add_to_txt_log(output + kwargs['end']) if html: add_to_html_log(output + kwargs['end']) print(output, sep=kwargs['sep'], end=kwargs['end']) def add_to_txt_log(string: str, add_date: bool = False) -> None: if string[-1] != '\n': string += '\n' if not script_id or script_id == '': f_txt_log = open('logs\\log_{}.txt'.format(run_date), 'a', encoding="utf-8") else: f_txt_log = open('logs\\{}_log_{}.txt'.format(script_id, run_date), 'a', encoding="utf-8") if add_date: string = "{} - {}".format(strftime('%d-%m-%Y %H:%M:%S', localtime()), string) try: f_txt_log.write(string) except UnicodeEncodeError: print("Error with line writing line:\n" + string) finally: f_txt_log.close() '''Convert screen outputs from tprint into html for log file''' def add_to_html_log(string: str) -> None: output = string.split('\n') list_length = len(output) superfluous = list() for x in countup(list_length): if len(output[x]) == 0: superfluous.append(x) superfluous_length = len(superfluous) for i in countdown(superfluous_length - 1): output.pop(superfluous) list_length -= superfluous_length for x in countup(list_length): html_output_file.append(output[x] + '<br>') I've set up test in similarly in another project and it worked fine. Continue reading...