Пример #1
0
def get_socket(host, is_ssl=False, is_blocking=True):
    """Retrieves a socket connection to host.

    :param host: Host to connect to.
    :param is_ssl: Determines if SSL connection should be established.
    :param is_blocking: Determines if socket should be blocking.
    :return: Socket or SSLSocket.
    """
    try:
        if is_ssl:
            # If SSL is necessary then wrap socket in SSLContext object.
            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            s = context.wrap_socket(
                socket.socket(socket.AF_INET, socket.SOCK_STREAM))
            s.setblocking(is_blocking)
            s.connect((host, 443))
            return s
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setblocking(is_blocking)
            s.connect((host, 80))
            return s
    except BlockingIOError as error:
        # Output expected BlockingIOErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #2
0
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)
Пример #3
0
def main():
    try:
        host = 'airbrake.io'

        Logging.line_separator('AIRBRAKE.IO HTTP REQUEST', 60)
        s = get_socket(host, False)
        get_socket_response(s,
                            f'GET / HTTP/1.1\r\nHost: {host}\r\n\r\n'.encode())

        Logging.line_separator('AIRBRAKE.IO HTTPS REQUEST', 60)
        s = get_socket(host, True)
        get_socket_response(s,
                            f'GET / HTTP/1.1\r\nHost: {host}\r\n\r\n'.encode())

        Logging.line_separator('AIRBRAKE.IO HTTP REQUEST w/o BLOCKING', 60)
        s = get_socket(host, False, False)
        get_socket_response(s,
                            f'GET / HTTP/1.1\r\nHost: {host}\r\n\r\n'.encode())

        Logging.line_separator('AIRBRAKE.IO HTTPS REQUEST w/o BLOCKING', 60)
        s = get_socket(host, True, False)
        get_socket_response(s,
                            f'GET / HTTP/1.1\r\nHost: {host}\r\n\r\n'.encode())
    except BlockingIOError as error:
        # Output expected BlockingIOErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #4
0
def main():
    try:
        # Increment local count.
        increment_local_count()

        # Set local book title.
        set_local_book_title("The Silmarillion")

        # Set global book title.
        set_global_book_title("The Silmarillion")

        # Disassemble functions.
        Logging.line_separator("DISASSEMBLY OF increment_count.", 60)
        disassemble_object(increment_local_count)

        Logging.line_separator("DISASSEMBLY OF set_local_book_title.", 60)
        disassemble_object(set_local_book_title)

        Logging.line_separator("DISASSEMBLY OF set_global_book_title.", 60)
        disassemble_object(set_global_book_title)
    except NameError as error:
        # Output expected NameErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #5
0
def main():
    try:
        # Create Book.
        book = Book("The Hobbit", "J.R.R. Tolkien", 366, datetime.date(1937, 9, 15))

        # Log book object.
        Logging.line_separator("log_object(book)", 60)
        log_object(book)

        # Log invalid object.
        Logging.line_separator("log_invalid_object(book)", 60)
        log_invalid_object(book)

        # Disassemble both log_ functions.
        Logging.line_separator("DISASSEMBLY OF log_object()", 60)
        disassemble_object(log_object)

        Logging.line_separator("DISASSEMBLY OF log_invalid_object()", 60)
        disassemble_object(log_invalid_object)
    except NameError as error:
        # Output expected NameErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #6
0
def divide(numerator, denominator, lib: NumberType = NumberType.INTEGER):
    """Get result of division of numerator and denominator, using passed numeric type or library.

    :param numerator: Numerator.
    :param denominator: Denominator.
    :param lib: Type of numeric value or library to use for calculation.
    :return: Division result.
    """
    try:
        if lib == NumberType.INTEGER:
            # Divide using standard integer.
            return numerator / denominator
        elif lib == NumberType.FLOAT:
            # Convert to floats before division.
            return float(numerator) / float(denominator)
        elif lib == NumberType.DECIMAL:
            # Divide the decimal.Decimal value.
            return decimal.Decimal(numerator) / decimal.Decimal(denominator)
        elif lib == NumberType.MPMATH:
            # Divide using the mpmath.mpf (real float) value.
            return mpf(numerator) / mpf(denominator)
        else:
            # Divide using standard integer (default).
            return numerator / denominator
    except ZeroDivisionError as error:
        # Output expected ZeroDivisionErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #7
0
def main():
    try:
        name = 'Alice
    except SyntaxError as error:
        # Output expected SyntaxErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #8
0
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)
Пример #9
0
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)
Пример #10
0
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)
Пример #11
0
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)
Пример #12
0
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)
Пример #13
0
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)
Пример #14
0
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)
Пример #15
0
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)
Пример #16
0
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)
Пример #17
0
def buffer_test():
    try:
        # Create byte array with string 'Hello'.
        array = io.BytesIO(b'Hello')
        # Create a read-write copy of the bytearray.
        view = array.getbuffer()
        # Output copied memory view.
        output_buffer(view)
        # Add string ' world!' to existing bytearray.
        array.write(b' world!')
    except BufferError as error:
        # Output expected BufferErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)
Пример #18
0
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)
Пример #19
0
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)
Пример #20
0
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)
Пример #21
0
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)
Пример #22
0
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)
Пример #23
0
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)
Пример #24
0
def get_pi(precision, lib: PiLibType = PiLibType.INTEGER):
    """Get value of pi with the specified level of precision, using passed numeric or library.

    :param precision: Precision to retrieve.
    :param lib: Type of numeric value or library to use for calculation.
    :return: Pi value with specified precision.
    """
    try:
        if lib == PiLibType.INTEGER:
            return pi_using_integer(precision)
        elif lib == PiLibType.FLOAT:
            return pi_using_float(precision)
        elif lib == PiLibType.DECIMAL:
            return pi_using_decimal_lib(precision)
        elif lib == PiLibType.MPMATH:
            return pi_using_mpmath_lib(precision)
    except OverflowError as error:
        # Output expected OverflowErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output expected Exceptions.
        Logging.log_exception(exception, False)
Пример #25
0
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)
Пример #26
0
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)