Best Python code snippet using prospector_python
test_ConsoleFormatter.py
Source:test_ConsoleFormatter.py
1import logging2import click3from esok.log.ConsoleFormatter import ConsoleFormatter4def test_notset_format():5 record_message = u"This is a test!"6 record = logging.makeLogRecord(7 {u"msg": record_message, u"levelno": logging.NOTSET, u"levelname": u"NOTSET"}8 )9 formatter = ConsoleFormatter()10 msg = formatter.format(record)11 prefix = click.style(u"[Notset] ", fg="blue")12 assert prefix + record_message == msg13def test_debug_format():14 record_message = u"This is a test!"15 record = logging.makeLogRecord(16 {u"msg": record_message, u"levelno": logging.DEBUG, u"levelname": u"DEBUG"}17 )18 formatter = ConsoleFormatter()19 msg = formatter.format(record)20 prefix = click.style(u"[Debug] ", fg="blue")21 assert prefix + record_message == msg22def test_info_format():23 record_message = u"This is a test!"24 record = logging.makeLogRecord({u"msg": record_message, u"levelno": logging.INFO})25 formatter = ConsoleFormatter()26 msg = formatter.format(record)27 assert record_message == msg28def test_warning_format():29 record_message = u"This is a test!"30 record = logging.makeLogRecord(31 {u"msg": record_message, u"levelno": logging.WARNING, u"levelname": u"WARNING"}32 )33 formatter = ConsoleFormatter()34 msg = formatter.format(record)35 prefix = click.style(u"[Warning] ", fg="yellow")36 assert prefix + record_message == msg37def test_error_format():38 record_message = u"This is a test!"39 record = logging.makeLogRecord(40 {u"msg": record_message, u"levelno": logging.ERROR, u"levelname": u"ERROR"}41 )42 formatter = ConsoleFormatter()43 msg = formatter.format(record)44 prefix = click.style(u"[Error] ", fg="red")45 assert prefix + record_message == msg46def test_critical_format():47 record_message = u"This is a test!"48 record = logging.makeLogRecord(49 {50 u"msg": record_message,51 u"levelno": logging.CRITICAL,52 u"levelname": u"CRITICAL",53 }54 )55 formatter = ConsoleFormatter()56 msg = formatter.format(record)57 prefix = click.style(u"[Critical] ", fg="red")58 assert prefix + record_message == msg59def test_error_format_with_traceback():60 record_message = u"This is a test!"61 record = logging.makeLogRecord(62 {63 u"msg": record_message,64 u"levelno": logging.ERROR,65 u"levelname": u"ERROR",66 u"exc_info": "Something",67 }68 )69 formatter = ConsoleFormatter()70 formatter.show_traceback = True71 tb_text = "Shitty traceback."72 formatter.formatException = lambda _: tb_text # Mock traceback text73 msg = formatter.format(record)74 prefix = click.style(u"[Error] ", fg="red")75 expected = u"{}{}\n{}".format(prefix, record_message, tb_text)76 assert expected == msg77def test_is_info_level():78 assert not ConsoleFormatter.is_info_level(logging.INFO - 1)79 assert ConsoleFormatter.is_info_level(logging.INFO)80 assert ConsoleFormatter.is_info_level(logging.WARNING - 1)81 assert not ConsoleFormatter.is_info_level(logging.WARNING)82def test_color_for_level():83 assert ConsoleFormatter.color_for_level(logging.CRITICAL) == "red"84 assert ConsoleFormatter.color_for_level(logging.ERROR) == "red"85 assert ConsoleFormatter.color_for_level(logging.WARNING) == "yellow"86 assert ConsoleFormatter.color_for_level(logging.INFO) == "white"87 assert ConsoleFormatter.color_for_level(logging.DEBUG) == "blue"...
formatter.py
Source:formatter.py
1import logging2from typing import List, Tuple3from urllib.parse import urlparse, parse_qs4from urllib.request import urlopen5import re6PATTERN = '\$\{\{(.+?)\}\}'7SEACH_CLASS_NAME = "LogSubstitutor"8def parse_url(pattern: str) -> Tuple[bool, str, dict]:9 try:10 result = urlparse(pattern)11 if any([result.scheme, result.netloc]):12 parsed_url = "{}://{}{}".format(result.scheme, result.netloc,13 result.path)14 parameters = parse_qs(result.query)15 return True, parsed_url, parameters16 except:17 return False, None, None18def execute_object(data: str, params: dict) -> str:19 exec(data, globals())20 class_repr = eval(SEACH_CLASS_NAME)21 result = str(class_repr(**params))22 return result23def check_substitute_pattern(record_message: str) -> str:24 compiled_re = re.compile(PATTERN)25 matched_iter = compiled_re.finditer(record_message)26 iter = 027 for match in matched_iter:28 found_str = match.group(1)29 try:30 ret, url, params = parse_url(found_str)31 if not ret:32 raise Exception()33 with urlopen(url, timeout=5) as response:34 eval_data = response.read()35 eval_result = execute_object(eval_data, params)36 record_message = re.sub(PATTERN, eval_result, record_message, iter)37 iter = iter + 138 except Exception as e:39 iter += 140 continue41 return record_message42class ShellishFormatter(logging.Formatter):43 def __init__(self):44 super(ShellishFormatter, self).__init__()45 def format(self, record: logging.LogRecord) -> str:46 # this is the default format function used by CPython's logging47 # library. We are retaining the same. But check_substitute_pattern48 # is called on the formatted string to make pattern substitution.49 record.message = record.getMessage()50 if self.usesTime():51 record.asctime = self.formatTime(record, self.datefmt)52 s = self.formatMessage(record)53 s = check_substitute_pattern(s)54 if record.exc_info:55 if not record.exc_text:56 record.exc_text = self.formatException(record.exc_info)57 if record.exc_text:58 if s[-1:] != "\n":59 s = s + "\n"60 s = s + record.exc_text61 if record.stack_info:62 if s[-1:] != "\n":63 s = s + "\n"64 s = s + self.formatStack(record.stack_info)...
PersistenceController.py
Source:PersistenceController.py
1import pickle2from os import remove3from models.Records import Records4from discord import File5async def load_Records(server):6 # If record doesn't exist7 if not server.record_Message:8 await save_Records({}, server)9 return {}10 11 file = await server.record_Message.attachments[0].to_file()12 file = file.fp13 data = pickle.load(file)14 records = Records(data['Records'], server)15 return records16async def save_Records(records, server):17 if server.record_Message:18 await server.record_Message.delete()19 data = {"Server_ID": server.ID, "Records": records}20 filepath = f"./{server.ID}"21 with open(filepath, mode="wb") as file:22 pickle.dump(data, file)23 file = File(filepath)24 await server.data_Channel.send(content=str(server.ID), file=file)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!