예제 #1
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)
예제 #2
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)
예제 #3
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)
예제 #4
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)
예제 #5
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)
예제 #6
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)
예제 #7
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)
예제 #8
0
def main():
    Logging.line_separator("BOTH INCLUDE PUBLICATION DATES", 50, '+')
    # Create two Books with identical arguments.
    the_stand = Book("The Stand", "Stephen King", 1153,
                     datetime.date(1978, 1, 1))
    the_stand_2 = Book("The Stand", "Stephen King", 1153,
                       datetime.date(1978, 1, 1))

    # Check equivalency of Books.
    check_equality(the_stand, the_stand_2)

    Logging.line_separator("ONE MISSING PUBLICATION DATE", 50, '+')
    # Create two Books, one without publication_date argument specified.
    the_hobbit = Book("The Hobbit", "J.R.R. Tolkien", 366,
                      datetime.date(1937, 9, 15))
    the_hobbit_2 = Book("The Hobbit", "J.R.R. Tolkien", 366)

    # Check equivalency of Books.
    check_equality(the_hobbit, the_hobbit_2)
예제 #9
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)
예제 #10
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)
예제 #11
0
def main():
    Logging.line_separator("FLOATING POINT")
    test_floating_point()

    Logging.line_separator("DIVISION BY ZERO")
    test_division_by_zero()

    Logging.line_separator("FLOATING POINT DIVISION BY ZERO", 60)
    test_floating_point_division_by_zero()
예제 #12
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)
예제 #13
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)
예제 #14
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)
예제 #15
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)
예제 #16
0
def main():
    Logging.line_separator("FRACTION TEST", 40, '+')

    divide_test(5, 25)

    Logging.line_separator("WHOLE NUMBER TEST", 40, '+')

    divide_test(25, 5)

    Logging.line_separator("DIVIDE BY ZERO TEST", 40, '+')

    divide_test(5, 0)
예제 #17
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)
예제 #18
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)
예제 #19
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)
예제 #20
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)
예제 #21
0
def main():
    # Precision: 10
    pi_test(10)

    Logging.line_separator(None, 60, '_')

    # Precision: 25
    pi_test(25)

    Logging.line_separator(None, 60, '_')

    # Precision: 256
    pi_test(256)

    Logging.line_separator(None, 60, '_')

    # Precision: 300
    pi_test(300)
예제 #22
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)
예제 #23
0
# 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)
예제 #24
0
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))
예제 #25
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)
예제 #26
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)
예제 #27
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)
예제 #28
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)
예제 #29
0
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()}')
예제 #30
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)