def main(): try: # Create list and populate with Books. books = list() books.append( Book("Shadow of a Dark Queen", "Raymond E. Feist", 497, datetime.date(1994, 1, 1))) books.append( Book("Rise of a Merchant Prince", "Raymond E. Feist", 479, datetime.date(1995, 5, 1))) books.append( Book("Rage of a Demon King", "Raymond E. Feist", 436, datetime.date(1997, 4, 1))) # Output Books in list, with and without index. Logging.line_separator('Books') log_list(books) Logging.line_separator('Books w/ index') log_list(books, True) # Output list element outside bounds. Logging.line_separator('books[len(books)]') Logging.log(f'books[{len(books)}]: {books[len(books)]}') except IndexError as error: # Output expected IndexErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def test_floating_point(): try: Logging.log(round(24.601 / 3.5, 4)) except FloatingPointError as exception: # Output expected FloatingPointErrors. Logging.log_exception(exception) except Exception as exception: # Output expected Exceptions. Logging.log_exception(exception, False)
def test_division_by_zero(): try: # Divide by zero. Logging.log(24 / 0) except FloatingPointError as exception: # Output expected FloatingPointErrors. Logging.log_exception(exception) except Exception as exception: # Output expected Exceptions. Logging.log_exception(exception, False)
def test_floating_point_division_by_zero(): try: # Divide by floating point zero and round. Logging.log(round(24.601 / 0.0, 4)) except FloatingPointError as exception: # Output expected FloatingPointErrors. Logging.log_exception(exception) except Exception as exception: # Output expected Exceptions. Logging.log_exception(exception, False)
def main(): try: Logging.log(sys.version) title = input("Enter a book title: ") author = input("Enter the book's author: ") Logging.log(f'The book you entered is \'{title}\' by {author}.') except EOFError as error: # Output expected EOFErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def log_invalid_object(value): """Attempts to log invalid object (valu) to console. :param value: Value intended to be logged, but which is instead ignored. :return: None """ try: Logging.log(valu) except NameError as error: # Output expected NameErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def log_object(value): """Logs passed value parameter to console. :param value: Value to be logged. :return: None """ try: Logging.log(value) except NameError as error: # Output expected NameErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def increment_local_count(): """Increment count by one and output new value. :return: None """ try: Logging.line_separator("Incrementing LOCAL count.", 60) count += 1 Logging.log("Count incremented to: {}".format(count)) except UnboundLocalError as error: # Output expected UnboundLocalErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def main(): try: today = datetime.datetime.now() Logging.log(f'Today is {today.strftime("%A, %B %d, %Y")}') Logging.log("Invoking: eval(TOMORROW_DEFINITION)") Logging.log(eval(TOMORROW_DEFINITION)) Logging.log("Invoking: eval(DAY_AFTER_TOMORROW_DEFINITION)") Logging.log(eval(DAY_AFTER_TOMORROW_DEFINITION)) except SyntaxError as error: # Output expected SyntaxErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def set_local_book_title(title): """Set title property of local book to passed value and output. :param title: Title to be set. :return: None """ try: Logging.line_separator( "Setting LOCAL book title to '{}'.".format(title), 60) book.title = title Logging.log(book) except UnboundLocalError as error: # Output expected UnboundLocalErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def get_socket_response(s, request, max_bytes=4096): """Retrieves and logs request response from passed socket, up to maximum bytes. :param s: Socket with which to send request. :param request: Request (as bytes). :param max_bytes: Maximum number of bytes to receive. :return: Response data (as bytearray). """ try: # Confirm that socket exists. if s is None: return None data = bytearray() # Send request. s.send(request) while True: # Get response and extend data array. response = s.recv(max_bytes) data.extend(response) # Break if no bytes, otherwise loop until max_bytes (or all available bytes) received. if len(response) == 0 or len(data) >= max_bytes or len( data) == len(response): break # Close socket. s.close() # Output decoded response. if data is not None: Logging.log(data.decode()) # Return data. return data except BlockingIOError as error: # Output expected BlockingIOErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def log_dict(collection, include_key=False): """Logs the each element in collection to the console. :param collection: Collection to be iterated and output. :param include_key: Determines if key should be output. :return: None """ try: # Iterate by getting collection of items. for key, item in collection.items(): if include_key: Logging.log(f'collection[{key}]: {item}') else: Logging.log(item) except KeyError as error: # Output expected KeyErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def log_list(collection, include_index=False): """Logs the each element in collection to the console. :param collection: Collection to be iterated and output. :param include_index: Determines if index is also output. :return: None """ try: # Iterate by converting to enumeration. for index, item in enumerate(collection): if include_index: Logging.log(f'collection[{index}]: {item}') else: Logging.log(item) except IndexError as error: # Output expected IndexErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def main(): try: Logging.log("Invoking: exec(DOUBLE_DEFINITION)") exec(DOUBLE_DEFINITION) Logging.log("Invoking: exec(DOUBLE_EXECUTOR)") exec(DOUBLE_EXECUTOR) Logging.log("Invoking: exec(TRIPLE_DEFINITION)") exec(TRIPLE_DEFINITION) Logging.log("Invoking: exec(TRIPLE_EXECUTOR)") exec(TRIPLE_EXECUTOR) except SyntaxError as error: # Output expected SyntaxErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def main(): try: # Create a dictionary and populate with Books. series = { 1: Book("The Name of the Wind", "Patrick Rothfuss", 662, datetime.date(2007, 3, 27)), 2: Book("The Wise Man's Fear", "Patrick Rothfuss", 994, datetime.date(2011, 3, 1)), 3: Book("Doors of Stone", "Patrick Rothfuss") } # Output Books in series dictionary, with and without index. Logging.line_separator('Series') log_dict(series) Logging.line_separator('Series w/ Order Index') log_dict(series, True) # Output book in series that doesn't exist. Logging.line_separator('series[len(series) + 1]') Logging.log(f'series[{len(series) + 1}]: {series[len(series) + 1]}') except KeyError as error: # Output expected KeyErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def divide_test(denominator, numerator): """Perform division tests using all different numeric types and mathematic libraries. :param denominator: Denominator. :param numerator: Numerator. """ Logging.line_separator('as int') Logging.log(divide(denominator, numerator)) Logging.line_separator('as float') Logging.log(divide(denominator, numerator, NumberType.FLOAT)) Logging.line_separator('as decimal.Decimal') Logging.log(divide(denominator, numerator, NumberType.DECIMAL)) Logging.line_separator('as mpmath.mpf') Logging.log(divide(denominator, numerator, NumberType.MPMATH))
def main(): try: Logging.log(sys.version) except ImportError as error: # Output expected ImportErrors. Logging.log_exception(error) # Include the name and path attributes in output. Logging.log(f'error.name: {error.name}') Logging.log(f'error.path: {error.path}') except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def test(): try: Logging.line_separator("CREATE BOOK", 50, '+') # Create and output book. book = Book("The Hobbit", "J.R.R. Tolkien", 366, datetime.date(1937, 9, 15)) Logging.log(book) # Output valid attributes. Logging.log(book.title) Logging.log(book.author) # Output invalid attribute (publisher). Logging.log(book.publisher) except AttributeError as error: # Output expected AttributeErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
def pi_test(precision): # Integer Logging.line_separator(f'PI WITH PRECISION OF {precision}, USING INTEGERS', 60) Logging.log(get_pi(precision)) # Float Logging.line_separator(f'PI WITH PRECISION OF {precision}, USING FLOATS', 60) Logging.log(get_pi(precision, PiLibType.FLOAT)) # Decimal Logging.line_separator(f'PI WITH PRECISION OF {precision}, DECIMAL LIB', 60) Logging.log(get_pi(precision, PiLibType.DECIMAL)) # MPMath # Set precision one higher to avoid rounding errors. Logging.line_separator(f'PI WITH PRECISION OF {precision + 1}, MPMATH LIB', 60) Logging.log(get_pi(precision + 1, PiLibType.MPMATH))
def check_equality(a, b): """Asserts the equivalent of the two passed objects. :param a: First object. :param b: Second object. :return: Indicates if assertion was successful. """ try: Logging.line_separator("ASSERTING EQUIVALENCE OF...") # Output objects using __str__ method. Logging.log(a) Logging.log(b) # Assert equivalence of objects, indicating inequality if failed. assert a == b, "The objects ARE NOT equal." # Indicate that assertion succeeded. Logging.log("The objects are equal.") return True except AssertionError as error: # Output expected AssertionErrors. Logging.log_exception(error) except Exception as exception: # Output unexpected Exceptions. Logging.log_exception(exception, False)
# exec_syntax_test.py from gw_utility.logging import Logging DOUBLE_DEFINITION = """ def double(x): return x * 2 """ DOUBLE_EXECUTOR = """ Logging.log(double(5)) """ TRIPLE_DEFINITION = """ def triple(x): return x * 3 """ TRIPLE_EXECUTOR = """ Logging.log(triple(5) """ def main(): try: Logging.log("Invoking: exec(DOUBLE_DEFINITION)") exec(DOUBLE_DEFINITION) Logging.log("Invoking: exec(DOUBLE_EXECUTOR)") exec(DOUBLE_EXECUTOR) Logging.log("Invoking: exec(TRIPLE_DEFINITION)") exec(TRIPLE_DEFINITION)
def output_buffer(view: memoryview): Logging.line_separator("BUFFER OUTPUT") Logging.log(f'tobytes(): {view.tobytes()}') Logging.log(f'tolist(): {view.tolist()}') Logging.log(f'hex(): {view.hex()}')