Exemple #1
0
def test_get_list_of_dicts_duplicates():
    """
    Tests getting a list of dictionary duplicates.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'get_list_of_dicts_duplicates'.
        ValueError: A failure occurred in section 1.1 while testing the function 'get_list_of_dicts_duplicates'.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: get_list_of_dicts_duplicates')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Sets sample list
    sample_list_dictionary = [{
        'key1': 'ValueA'
    }, {
        'key1': 'ValueA'
    }, {
        'key1': 'ValueA'
    }, {
        'key1': 'ValueB'
    }, {
        'key1': 'ValueB'
    }]
    # Tests finding duplicate values for key (key1).
    check_all = get_list_of_dicts_duplicates('key1', sample_list_dictionary)
    # Return length should equal 5.
    # Expected Return: [{'index': 0, 'value': 'ValueA'}, {'index': 1, 'value': 'ValueA'}, {'index': 2, 'value': 'ValueA'}, {'index': 3, 'value': 'ValueB'}, {'index': 4, 'value': 'ValueB'}]
    if len(check_all) != 5:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'get_list_of_dicts_duplicates\'.',
            'expected_result': 5,
            'returned_result': len(check_all),
        }
        raise FValueError(exc_args)

    # ========Tests for a successful output return.========
    # Tests finding duplicate values for key (key1).
    check_all = get_list_of_dicts_duplicates('key1', sample_list_dictionary,
                                             True)
    # Return length should equal 2.
    # Expected Return: {'ValueA': [{'index': 0, 'value': 'ValueA'}, {'index': 1, 'value': 'ValueA'}, {'index': 2, 'value': 'ValueA'}], 'ValueB': [{'index': 3, 'value': 'ValueB'}, {'index': 4, 'value': 'ValueB'}]}
    if len(check_all) != 2:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.1 while testing the function \'get_list_of_dicts_duplicates\'.',
            'expected_result': 2,
            'returned_result': len(check_all),
        }
        raise FValueError(exc_args)
Exemple #2
0
def test_remove_duplicate_dict_values_in_list():
    """
    This tests removing duplicate dictionary values in a list.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'remove_duplicate_dict_values_in_list' using a full check.
        ValueError: A failure occurred in section 1.1 while testing the function 'remove_duplicate_dict_values_in_list' using an index.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: remove_duplicate_dict_values_in_list')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Sets sample list
    sample_list_dictionary = list([{
        'search_entry': '|Error|',
        'found_entry': 'the entry found'
    }, {
        'search_entry': '|Warning|',
        'found_entry': 'the entry found'
    }])
    # Tests removing duplicate dictionary entries.
    check_all = remove_duplicate_dict_values_in_list(sample_list_dictionary)
    # Return length should equal 2.
    # Expected Return: [{'search_entry': '|Error|', 'found_entry': 'the entry found'}, {'search_entry': '|Warning|', 'found_entry': 'the entry found'}]
    if len(check_all) != 2:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'remove_duplicate_dict_values_in_list\' using a full check.',
            'expected_result': 2,
            'returned_result': len(check_all),
        }
        raise FValueError(exc_args)

    # ========Tests for a successful output return.========
    # Tests removing duplicates from index 1 of each dictionary entry.
    check_index = remove_duplicate_dict_values_in_list(sample_list_dictionary,
                                                       1)
    # Return length should equal 1.
    # Expected Return: [{'search_entry': '|Error|', 'found_entry': 'the entry found'}]
    if len(check_index) != 1:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.1 while testing the function \'remove_duplicate_dict_values_in_list\' using an index.',
            'expected_result': 1,
            'returned_result': len(check_index),
        }
        raise FValueError(exc_args)
Exemple #3
0
def test_find_longest_common_substring():
    """
    Tests finding a common grouping substring.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function \'find_longest_common_substring\'. The test did return the correct common substring.
        ValueError: A failure occurred in section 2.0 while testing the function \'find_longest_common_substring\'. The test did not fail when sending a non-string parameter.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: find_longest_common_substring')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    common_substring = find_longest_common_substring('mysamplechangeshere',
                                                     'mysampleneverchanges')
    # Checks if the return substring is not equal the expected result.
    if not common_substring == 'mysample':
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'find_longest_common_substring\'. The test did return the correct common substring.',
            'expected_result': 'mysample',
            'returned_result': common_substring,
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 2 (Error/Catch Value Checking)######
    # ############################################################
    # ========Tests for an incorrectly sent config format.========
    try:

        common_substring = find_longest_common_substring(
            'mysamplechangeshere', ['INCORRECT or EMPTY DATA TEST'])
    except Exception as error:
        if """The value '['INCORRECT or EMPTY DATA TEST']' is not in <class 'str'> format.""" not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 2.0 while testing the function \'find_longest_common_substring\'. The test did not fail when sending a non-string parameter.',
                'expected_result': 'non-string parameter error',
                'returned_result': error,
            }
            raise FValueError(exc_args)
Exemple #4
0
def test_clean_non_word_characters():
    """
    Tests cleaning non-word characters.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function \'clean_non_word_characters\'. The test did return the correct cleaned substring.
        ValueError: A failure occurred in section 2.0 while testing the function \'clean_non_word_characters\'. The test did not fail when sending a non-string parameter.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: clean_non_word_characters')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    cleaned_string = clean_non_word_characters('BTW-N5K\x06')
    # Checks if the return substring is not equal the expected result.
    if not cleaned_string == 'BTW-N5K':
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'clean_non_word_characters\'. The test did return the correct cleaned substring.',
            'expected_result': 'BTW-N5K',
            'returned_result': cleaned_string,
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 2 (Error/Catch Value Checking)######
    # ############################################################
    # ========Tests for an incorrectly sent config format.========
    try:

        cleaned_string = clean_non_word_characters(
            ['INCORRECT or EMPTY DATA TEST'])
    except Exception as error:
        if """The value '['INCORRECT or EMPTY DATA TEST']' is not in <class 'str'> format.""" not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 2.0 while testing the function \'clean_non_word_characters\'. The test did not fail when sending a non-string parameter.',
                'expected_result': 'non-string parameter error',
                'returned_result': error,
            }
            raise FValueError(exc_args)
def test_start_subprocess():
    """
    Tests starting a subprocess.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'start_subprocess'. The subprocess did not return any output.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: start_subprocess')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Sample sub processing args
    processing_args = ['ipconfig', '/all']

    output = start_subprocess(processing_args)

    # Expected Return: ['', 'Windows IP Configuration', '', '   Host Name . . . . . . . . . . . . : Test-PC-1', '   Primary Dns Suffix  . . . . . . . : test.site.org', ' ...............---> continued']
    if not output.stdout:
        exc_args = {
            'main_message': 'A failure occurred in section 1.0 while testing the function \'start_subprocess\'. The subprocess did not return any output.',
        }
        raise FValueError(exc_args)
Exemple #6
0
def test_start_function_thread():
    """
    Tests starting a function thread.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'start_function_thread'. The function did not start a new thread. No 'sample_test_thread' detected.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: start_function_thread')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Gets the programs root directory.
    preset_root_directory = os.path.dirname(os.path.realpath(__file__))

    # Sets the sample file path.
    sample_file_path = os.path.abspath(f'{preset_root_directory}\\setup.py')

    # Uses sample time.sleep (separate function) to wait 5 seconds. This allows the sleep to run as a separate thread but sleep so that the validation check can detect the separate thread.
    start_function_thread(partial(time.sleep, 5), 'sample_test_thread', False)

    # Checks if the thread is not running
    if 'sample_test_thread' not in str(threading.enumerate()):
        exc_args = {
            'main_message': 'A failure occurred in section 1.0 while testing the function \'start_function_thread\'. The function did not start a new thread. No \'sample_test_thread\' detected.',
        }
        raise FValueError(exc_args)
Exemple #7
0
def test_convert_relative_to_full_path():
    """
    Tests converting a relative path to a full path.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'convert_relative_to_full_path'. The full path did not return correctly.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: convert_relative_to_full_path')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    full_path = convert_relative_to_full_path("mytest\\sample.txt")

    if '\\mytest\\sample.txt' not in full_path:
        exc_args = {
            'main_message': 'A failure occurred in section 1.0 while testing the function \'convert_relative_to_full_path\'. The full path did not return correctly.',
        }
        raise FValueError(exc_args)
Exemple #8
0
def test_write_file():
    """
    Tests writing a file.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'write_file'. The test did not write.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: get_list_duplicates')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Gets the programs root directory.
    preset_root_directory = os.path.dirname(os.path.realpath(__file__))

    # Sets the sample save file path.
    # No return value. Throws an exception if the file does not write.
    sample_write_file_path = os.path.abspath(f'{preset_root_directory}\\temp_pytest_read_write.py')

    try:
        # Writes to file.
        # This temp file is used for additional tests in other functions.
        write_file(sample_write_file_path, 'testing line1')
        write_file(sample_write_file_path, 'testing line2')
        write_file(sample_write_file_path, 'testing line3')
    except Exception as exc:
        exc_args = {
            'main_message': 'A failure occurred in section 1.0 while testing the function \'write_file\'. The test did not write.',
            'expected_result': 'non-list error',
            'returned_result': exc,
        }
        raise FValueError(exc_args)
Exemple #9
0
def test_string_grouper():
    """
    Tests grouping strings.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'string_grouper'.
        ValueError: A failure occurred in section 1.1 while testing the function 'string_grouper'. The first entries in the list do not match.
        ValueError: A failure occurred in section 2.0 while testing the function 'string_grouper'.
        ValueError: A failure occurred in section 2.1 while testing the function 'string_grouper'. The first entries in the list do not match.
        ValueError: A failure occurred in section 3.0 while testing the function 'string_grouper'.
        ValueError: A failure occurred in section 3.1 while testing the function 'string_grouper'. The first entries in the list do not match.
        ValueError: A failure occurred in section 4.0 while testing the function 'string_grouper'.
        ValueError: A failure occurred in section 4.1 while testing the function 'string_grouper'. The first entries in the list do not match.
        ValueError: A failure occurred in section 5.0 while testing the function 'string_grouper'.
        ValueError: A failure occurred in section 5.1 while testing the function 'string_grouper'. The first entries in the list do not match.
        ValueError: A failure occurred in section 6.0 while testing the function 'string_grouper'.
        ValueError: A failure occurred in section 6.1 while testing the function 'string_grouper'. The first entries in the list do not match.
        ValueError: A failure occurred in section 7.0 while testing the function 'string_grouper'. The test did not fail when sending a non-list of strings.
        ValueError: A failure occurred in section 7.1 while testing the function 'string_grouper'. The test did not fail when sending a non-string.
        ValueError: A failure occurred in section 7.2 while testing the function 'string_grouper'. The test did not fail when sending a non-int.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: string_grouper')
    print('-' * 65)
    print('-' * 65)
    print('')

    # List of sample switch names for multiple sites. Case insensitive testing.
    list_of_strings = [
        "JJ-MDF-9200-1_2",
        "KV-MDF-9200-1_2",
        "KV-MDF1-9200-1_2",
        "KZV-MDF1-9200-1_2",
        "kv-IDF1-9200-1_2",
        "KV-IDF2-9200-1_2",
        "TI-IDF1-9200-1_2",
        "TI-IDF2-9200-1_2",
    ]

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return for case insensitive.========
    # Tests finding duplicate values in the list.
    group_check = string_grouper(list_of_strings, '-', 1, True)

    # Return length should equal 5.
    # Expected Return: [{'group_identifier': 'JJ', 'grouping': ['JJ-MDF-9200-1_2']},
    #                   {'group_identifier': 'KV', 'grouping': ['kv-IDF1-9200-1_2, 'KV-IDF2-9200-1_2', 'KV-MDF-9200-1_2', 'KV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'KZV', 'grouping': ['KZV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'TI', 'grouping': ['TI-IDF1-9200-1_2', 'TI-IDF2-9200-1_2']}]
    if len(group_check) != 4:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'string_grouper\'.',
            'expected_result': 4,
            'returned_result': len(group_check),
        }
        raise FValueError(exc_args)

    # Gets first list return values from the two dictionary entries.
    group_identifier = group_check[0].get('group_identifier')
    grouping = group_check[0].get('grouping')
    # Checks if the values are not equal to the expected return output.
    if (group_identifier != 'JJ' or grouping != ['JJ-MDF-9200-1_2']):
        exc_args = {
            'main_message':
            'A failure occurred in section 1.1 while testing the function \'string_grouper\'s. The first entries in the list do not match.',
            'expected_result':
            'group_identifier != JJ -- or --  grouping != [\'JJ-MDF-9200-1_2\']',
            'returned_result':
            f'roup_identifier != {group_identifier} -- or -- grouping != {grouping}',
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 2 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return for case insensitive.========
    # Tests finding duplicate values in the list.
    group_check = string_grouper(list_of_strings, 2, 2, True)

    # Return length should equal 4.
    # Expected Return: [{'group_identifier': 'JJ', 'grouping': ['JJ-MDF-9200-1_2']},
    #                   {'group_identifier': 'KV', 'grouping': ['kv-IDF1-9200-1_2', 'KV-IDF2-9200-1_2', 'KV-MDF-9200-1_2', 'KV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'KZV', 'grouping': ['KZV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'TI', 'grouping': ['TI-IDF1-9200-1_2', 'TI-IDF2-9200-1_2']}]
    if len(group_check) != 4:
        exc_args = {
            'main_message':
            'A failure occurred in section 2.0 while testing the function \'string_grouper\'.',
            'expected_result': 4,
            'returned_result': len(group_check),
        }
        raise FValueError(exc_args)

    # Gets first list return values from the two dictionary entries.
    group_identifier = group_check[0].get('group_identifier')
    grouping = group_check[0].get('grouping')
    # Checks if the values are not equal to the expected return output.
    if (group_identifier != 'JJ' or grouping != ['JJ-MDF-9200-1_2']):
        exc_args = {
            'main_message':
            'A failure occurred in section 2.1 while testing the function \'string_grouper\'s. The first entries in the list do not match.',
            'expected_result':
            'group_identifier != JJ -- or --  grouping != [\'JJ-MDF-9200-1_2\']',
            'returned_result':
            f'roup_identifier != {group_identifier} -- or -- grouping != {grouping}',
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 3 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Currently option 3 does not support case insensitive. Leaving test to add once option 3 is setup.
    # Tests finding duplicate values in the list.
    group_check = string_grouper(list_of_strings, None, 3)

    # Return length should equal 5.
    # Expected Return: [{'group_identifier': 'JJ-MDF-9200-1_2', 'grouping': ['JJ-MDF-9200-1_2']},
    #                   {'group_identifier': 'KV-IDF', 'grouping': ['KV-IDF1-9200-1_2', 'KV-IDF2-9200-1_2']},
    #                   {'group_identifier': 'KV-MDF', 'grouping': ['KV-MDF-9200-1_2', 'KV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'KZV-MDF1-9200-1_2', 'grouping': ['KZV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'TI-IDF', 'grouping': ['TI-IDF1-9200-1_2', 'TI-IDF2-9200-1_2']}]
    if len(group_check) != 5:
        exc_args = {
            'main_message':
            'A failure occurred in section 3.0 while testing the function \'string_grouper\'.',
            'expected_result': 5,
            'returned_result': len(group_check),
        }
        raise FValueError(exc_args)

    # Gets first list return values from the two dictionary entries.
    group_identifier = group_check[0].get('group_identifier')
    grouping = group_check[0].get('grouping')
    # Checks if the values are not equal to the expected return output.
    if (group_identifier != 'JJ-MDF-9200-1_2'
            or grouping != ['JJ-MDF-9200-1_2']):
        exc_args = {
            'main_message':
            'A failure occurred in section 3.1 while testing the function \'string_grouper\'s. The first entries in the list do not match.',
            'expected_result':
            'group_identifier != JJ-MDF-9200-1_2 -- or --  grouping != [\'JJ-MDF-9200-1_2\']',
            'returned_result':
            f'roup_identifier != {group_identifier} -- or -- grouping != {grouping}',
        }
        raise FValueError(exc_args)

    # List of sample switch names for multiple sites. All upper testing.
    list_of_strings = [
        "JJ-MDF-9200-1_2",
        "KV-MDF-9200-1_2",
        "KV-MDF1-9200-1_2",
        "KZV-MDF1-9200-1_2",
        "KV-IDF1-9200-1_2",
        "KV-IDF2-9200-1_2",
        "TI-IDF1-9200-1_2",
        "TI-IDF2-9200-1_2",
    ]

    # ############################################################
    # ######Section Test Part 4 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Tests finding duplicate values in the list.
    group_check = string_grouper(list_of_strings, '-', 1)

    # Return length should equal 4.
    # Expected Return: [{'group_identifier': 'JJ', 'grouping': ['JJ-MDF-9200-1_2']},
    #                   {'group_identifier': 'KV', 'grouping': ['KV-IDF1-9200-1_2', 'KV-IDF2-9200-1_2', 'KV-MDF-9200-1_2', 'KV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'KZV', 'grouping': ['KZV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'TI', 'grouping': ['TI-IDF1-9200-1_2', 'TI-IDF2-9200-1_2']}]
    if len(group_check) != 4:
        exc_args = {
            'main_message':
            'A failure occurred in section 4.0 while testing the function \'string_grouper\'.',
            'expected_result': 4,
            'returned_result': len(group_check),
        }
        raise FValueError(exc_args)

    # Gets first list return values from the two dictionary entries.
    group_identifier = group_check[0].get('group_identifier')
    grouping = group_check[0].get('grouping')
    # Checks if the values are not equal to the expected return output.
    if (group_identifier != 'JJ' or grouping != ['JJ-MDF-9200-1_2']):
        exc_args = {
            'main_message':
            'A failure occurred in section 4.1 while testing the function \'string_grouper\'s. The first entries in the list do not match.',
            'expected_result':
            'group_identifier != JJ -- or --  grouping != [\'JJ-MDF-9200-1_2\']',
            'returned_result':
            f'roup_identifier != {group_identifier} -- or -- grouping != {grouping}',
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 5 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Tests finding duplicate values in the list.
    group_check = string_grouper(list_of_strings, 2, 2)

    # Return length should equal 4.
    # Expected Return: [{'group_identifier': 'JJ', 'grouping': ['JJ-MDF-9200-1_2']},
    #                   {'group_identifier': 'KV', 'grouping': ['KV-IDF1-9200-1_2', 'KV-IDF2-9200-1_2', 'KV-MDF-9200-1_2', 'KV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'KZV', 'grouping': ['KZV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'TI', 'grouping': ['TI-IDF1-9200-1_2', 'TI-IDF2-9200-1_2']}]
    if len(group_check) != 4:
        exc_args = {
            'main_message':
            'A failure occurred in section 5.0 while testing the function \'string_grouper\'.',
            'expected_result': 4,
            'returned_result': len(group_check),
        }
        raise FValueError(exc_args)

    # Gets first list return values from the two dictionary entries.
    group_identifier = group_check[0].get('group_identifier')
    grouping = group_check[0].get('grouping')
    # Checks if the values are not equal to the expected return output.
    if (group_identifier != 'JJ' or grouping != ['JJ-MDF-9200-1_2']):
        exc_args = {
            'main_message':
            'A failure occurred in section 5.1 while testing the function \'string_grouper\'s. The first entries in the list do not match.',
            'expected_result':
            'group_identifier != JJ -- or --  grouping != [\'JJ-MDF-9200-1_2\']',
            'returned_result':
            f'roup_identifier != {group_identifier} -- or -- grouping != {grouping}',
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 6 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Tests finding duplicate values in the list.
    group_check = string_grouper(list_of_strings, None, 3)

    # Return length should equal 5.
    # Expected Return: [{'group_identifier': 'JJ-MDF-9200-1_2', 'grouping': ['JJ-MDF-9200-1_2']},
    #                   {'group_identifier': 'KV-IDF', 'grouping': ['KV-IDF1-9200-1_2', 'KV-IDF2-9200-1_2']},
    #                   {'group_identifier': 'KV-MDF', 'grouping': ['KV-MDF-9200-1_2', 'KV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'KZV-MDF1-9200-1_2', 'grouping': ['KZV-MDF1-9200-1_2']},
    #                   {'group_identifier': 'TI-IDF', 'grouping': ['TI-IDF1-9200-1_2', 'TI-IDF2-9200-1_2']}]
    if len(group_check) != 5:
        exc_args = {
            'main_message':
            'A failure occurred in section 6.0 while testing the function \'string_grouper\'.',
            'expected_result': 5,
            'returned_result': len(group_check),
        }
        raise FValueError(exc_args)

    # Gets first list return values from the two dictionary entries.
    group_identifier = group_check[0].get('group_identifier')
    grouping = group_check[0].get('grouping')
    # Checks if the values are not equal to the expected return output.
    if (group_identifier != 'JJ-MDF-9200-1_2'
            or grouping != ['JJ-MDF-9200-1_2']):
        exc_args = {
            'main_message':
            'A failure occurred in section 6.1 while testing the function \'string_grouper\'s. The first entries in the list do not match.',
            'expected_result':
            'group_identifier != JJ-MDF-9200-1_2 -- or --  grouping != [\'JJ-MDF-9200-1_2\']',
            'returned_result':
            f'roup_identifier != {group_identifier} -- or -- grouping != {grouping}',
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 7 (Error/Catch Value Checking)######
    # ############################################################
    # ========Tests for an incorrectly sent list format.========
    try:
        # Tests finding duplicate values in the list.
        group_check = string_grouper('INCORRECT or EMPTY DATA TEST', '-', 1)
    except Exception as error:
        if """The value 'INCORRECT or EMPTY DATA TEST' is not in <class 'list'> format""" not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 7.0 while testing the function \'string_grouper\'. The test did not fail when sending a non-list of strings.',
                'expected_result': 'non-list error',
                'returned_result': error,
            }
            raise FValueError(exc_args)

    # ========Tests for an incorrectly sent string format.========
    # Tests finding duplicate values in the list.
    try:
        group_check = string_grouper(['ONE ENTRY1', 'ONE ENTRY2'], 3, 1)
    except Exception as error:
        if 'The grouping_value sent for the grouping is not a string' not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 7.2 while testing the function \'string_grouper\'. The test did not fail when sending a non-string.',
                'expected_result': 'non-string error',
                'returned_result': error,
            }
            raise FValueError(exc_args)

    # ========Tests for an incorrectly sent int format.========
    # Tests finding duplicate values in the list.
    try:
        group_check = string_grouper(['ONE ENTRY1', 'ONE ENTRY2'], 'T', 2)
    except Exception as error:
        if 'The grouping_value sent for the grouping is not a int' not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 7.3 while testing the function \'string_grouper\'. The test did not fail when sending a non-int.',
                'expected_result': 'non-int error',
                'returned_result': error,
            }
            raise FValueError(exc_args)
def test_feed():
    """
    This test currently tests encrypting a message or info.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'test_feed'. The message is not in bytes format.
        ValueError: A failure occurred in section 1.1 while testing the function 'test_feed'. The message returned the wrong result.
        ValueError: A failure occurred in section 2.0 while testing the function 'test_feed'. The test did not fail when not sending a incorrect convert_option value.
        ValueError: A failure occurred in section 2.1 while testing the function 'test_feed'. The test did not fail when not sending a incorrect data value.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: feed')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    parser = HTMLConverter()

    data = """
        <ol>
        <li>Coffee</li>
        <li>Tea</li>
        <li>Milk</li>
        </ol>

        <ul>
        <li>Coffee</li>
        <li>Tea</li>
        <li>Milk</li>
        </ul>
    """
    parser.feed(data, 'text')
    converted_html = parser.output
    if '- Coffee' not in converted_html:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.1 while testing the function \'test_feed\'. The message returned the wrong result.',
            'expected_result': '- Coffee',
            'returned_result': converted_html,
        }
        raise FValueError(exc_args)

    # ############################################################
    # ######Section Test Part 2 (Error/Catch Value Checking)######
    # ############################################################
    # ========Tests for incorrect value checks.========
    try:
        parser = HTMLConverter()

        parser.feed(data, 'image')
    except FValueError as error:
        if 'The HTML output could not be converted because the conversion option is not valid' not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 2.0 while testing the function \'test_feed\'. The test did not fail when not sending a incorrect convert_option value.',
                'expected_result': 'A value error',
                'error': error
            }
            raise FValueError(exc_args)

    # ========Tests for incorrect value checks.========
    try:
        parser = HTMLConverter()

        parser.feed(1, 'text')
    except FTypeError as error:
        if """The value '1' is not in <class 'str'> format""" not in str(
                error):
            exc_args = {
                'main_message':
                'A failure occurred in section 2.1 while testing the function \'test_feed\'. The test did not fail when not sending a incorrect data value.',
                'expected_result': 'A value error',
                'error': error
            }
            raise FValueError(exc_args)
Exemple #11
0
def test_search_file():
    """
    Tests searching a file.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'search_file'. The function did not return a type 'list'.
        ValueError: A failure occurred in section 1.1 while testing the function 'search_file'. The returned search list length should have equaled 1.
        ValueError: A failure occurred in section 1.2 while testing the function 'search_multiple_files' with a single search value against multiple paths.. The function did not return a type \'list\'.
        ValueError: A failure occurred in section 1.3 while testing the function 'search_multiple_files' with a single search value against multiple paths. The returned search list length should have equaled 2.
        ValueError: A failure occurred in section 1.4 while testing the function 'search_multiple_files' with multiple search values against multiple paths. The function did not return a type \'list\'.
        ValueError: A failure occurred in section 1.5 while testing the function 'search_multiple_files' with multiple search values against multiple paths. The returned search list length should have equaled 2.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: search_file')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Gets the programs root directory.
    preset_root_directory = os.path.dirname(os.path.realpath(__file__))
    # Sets the sample file path.
    sample_file_path = os.path.abspath(f'{preset_root_directory}\\temp_pytest_read_write.py')
    found_value = search_file(sample_file_path, 'line1')

    try:
        type_check(found_value, list)
    except FTypeError as exc:
        exc_args = {
            'main_message': 'A failure occurred in section 1.0 while testing the function \'search_file\'. The function did not return a type \'list\'.',
            'expected_result': 'non-list error',
            'returned_result': exc,
        }
        raise FValueError(exc_args)

    # Return length should equal 1.
    # Expected Return: [{'search_entry': 'line1', 'found_entry': 'testing line1'}]
    if len(found_value) != 1:
        exc_args = {
            'main_message': 'A failure occurred in section 1.1 while testing the function \'search_file\'. The returned search list length should have equaled 1.',
        }
        raise FValueError(exc_args)

    # ========Tests for a successful output return.========
    # Gets the programs root directory.
    preset_root_directory = os.path.dirname(os.path.realpath(__file__))

    # Sets the sample file path.
    sample_file_path = os.path.abspath(f'{preset_root_directory}\\temp_pytest_read_write.py')

    # Single search value against the same path twice.
    found_value = search_file(list([sample_file_path, sample_file_path]), 'line1')

    try:
        type_check(found_value, list)
    except FTypeError as exc:
        exc_args = {
            'main_message': 'A failure occurred in section 1.2 while testing the function \'search_multiple_files\' with a single search value against multiple paths.. The function did not return a type \'list\'.',
            'expected_result': 'non-list error',
            'returned_result': exc,
        }
        raise FValueError(exc_args)

    # Return length should equal 2.
    # Expected Return: [{'search_entry': 'line1', 'found_entry': 'testing line1'}, {'search_entry': 'line1', 'found_entry': 'testing line1'}]
    if len(found_value) != 2:
        exc_args = {
            'main_message': 'A failure occurred in section 1.3 while testing the function \'search_multiple_files\' with a single search value against multiple paths. The returned search list length should have equaled 2.',
        }
        raise FValueError(exc_args)

    # ========Tests for a successful output return.========
    # Multi search value against the same path twice.
    found_value = search_file(list([sample_file_path, sample_file_path]), list(['line1', 'line2']))

    try:
        type_check(found_value, list)
    except FTypeError as exc:
        exc_args = {
            'main_message': 'A failure occurred in section 1.4 while testing the function \'search_multiple_files\' with multiple search values against multiple paths. The function did not return a type \'list\'.',
            'expected_result': 'non-list error',
            'returned_result': exc,
        }
        raise FValueError(exc_args)

    # Return length should equal 2.
    # Expected Return: [{'search_entry': ['line1', 'line2'], 'found_entry': 'testing line1'}, {'search_entry': ['line1', 'line2'], 'found_entry': 'testing line2'}]
    if len(found_value) != 2:
        exc_args = {
            'main_message': 'A failure occurred in section 1.5 while testing the function \'search_multiple_files\' with multiple search values against multiple paths. The returned search list length should have equaled 2.',
        }
        raise FValueError(exc_args)

    # Removes the testing file once the test is complete.
    os.remove(sample_file_path)
Exemple #12
0
def test_decrypt_info():
    """
    This test currently tests decryptting a message or info.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'decrypt_info'. The message is not in bytes format.
        ValueError: A failure occurred in section 1.1 while testing the function 'decrypt_info'. The message returned the wrong result.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: decrypt_info')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ####Section Test Part 1 (Successful Decryption Checking)####
    # ############################################################
    # ========Tests for a successful decryption.========
    message_encryption_password = '******'
    message_encryption_random_salt = b'ChangeME'

    # Sets the sample message.
    encoded_message = b'gAAAAABgW0PuVC2XK6QXtpD44P2pHnvAvwSXSV0Ulj8TBzJLHfrvQZF4eFkF22TdOynRx9eMPb7n_dRULQmZWcEz-g85nXK3yg=='
    decrypted_message = decrypt_info(encoded_message,
                                     message_encryption_password,
                                     message_encryption_random_salt)
    try:
        type_check(decrypted_message, str)
    except FTypeError as exc:
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'decrypt_info\'. The message is not in bytes format.',
            'original_error': exc,
        }
        raise FTypeError(exc_args)

    # ========Tests for a successful decryption.========
    message_encryption_password = '******'
    message_encryption_random_salt = b'ChangeME'

    # Sets the sample message.
    encoded_message = b'gAAAAABgW0PuVC2XK6QXtpD44P2pHnvAvwSXSV0Ulj8TBzJLHfrvQZF4eFkF22TdOynRx9eMPb7n_dRULQmZWcEz-g85nXK3yg=='
    decrypted_message = decrypt_info(encoded_message,
                                     message_encryption_password,
                                     message_encryption_random_salt)

    # Expected Return: b'pytest sample'
    if decrypted_message != 'pytest sample':
        exc_args = {
            'main_message':
            'A failure occurred in section 1.1 while testing the function \'decrypt_info\'. The message returned the wrong result.',
            'expected_result': 'b\'pytest sample\'',
            'returned_result': decrypted_message,
        }
        raise FValueError(exc_args)

    # ========Tests for a successful decryption.========
    message_encryption_password = '******'
    message_encryption_random_salt = str(b'ChangeME')

    # Sets the sample message.
    encoded_message = b'gAAAAABgW0PuVC2XK6QXtpD44P2pHnvAvwSXSV0Ulj8TBzJLHfrvQZF4eFkF22TdOynRx9eMPb7n_dRULQmZWcEz-g85nXK3yg=='
    decrypted_message = decrypt_info(encoded_message,
                                     message_encryption_password,
                                     message_encryption_random_salt)

    # Expected Return: b'pytest sample'
    if decrypted_message != 'pytest sample':
        exc_args = {
            'main_message':
            'A failure occurred in section 1.1 while testing the function \'decrypt_info\'. The message returned the wrong result.',
            'expected_result': 'b\'pytest sample\'',
            'returned_result': decrypted_message,
        }
        raise FValueError(exc_args)
def test_create_logger():
    """
    This tests creating a logger.

    Raises:
        ValueError: A failure occurred in section 1.0 while testing the function 'create_logger'. No logger was setup during pytest.
    """
    print('')
    print('-' * 65)
    print('-' * 65)
    print('Testing Function: create_logger')
    print('-' * 65)
    print('-' * 65)
    print('')

    # ############################################################
    # ######Section Test Part 1 (Successful Value Checking)#######
    # ############################################################
    # ========Tests for a successful output return.========
    # Gets the programs root directory.
    preset_root_directory = os.path.dirname(os.path.realpath(__file__))

    # Sets the temp log file name.
    log_name = 'temp_pytest_read_write.py'

    # Sets the logger name.
    logger_name = 'pytest_logger'

    # Sets logging format option
    # Option 1 = Default
    # Options:
    #   1 - '%(asctime)s|%(levelname)s|%(message)s (Module:%(module)s, Function:%(funcName)s,  Line:%(lineno)s)',datefmt='%Y-%m-%d %H:%M:%S'
    #   2 - '%(message)s'
    #   '%(asctime)s|%(levelname)s|%(funcName)s|%(message)s' - Manual Entry
    logging_format_option = 1
    # Sets handler option
    # Option 1 = Default
    #   1 - Both
    #   2 - File Handler
    #   3 - Console Handler
    logging_handler_option = 1
    # Sets backup copy count
    logging_backup_log_count = 3
    # Sets logging level
    # Configure based on the LoggingHandlerOption option
    # Options:
    #   - NOTSET
    #   - DEBUG
    #   - INFO
    #   - WARNING
    #   - ERROR
    #   - CRITICAL
    file_log_level = 'DEBUG'
    console_log_level = 'INFO'
    # Sets max log size in bytes
    # Used for issue tracking and program log
    # Default 1000000 Byltes (1 Megabyte)
    max_log_file_size = 1000000
    # Rolling over log file on startup
    rollover = False

    # Gets/Sets the logger for the docker container.
    #
    # These settings are hardcoded and not user programable in the YAML.
    #
    logger_settings = {
        'save_path': preset_root_directory,  # Sets the log save path.
        'logger_name': logger_name,  # Sets the name of the logger.
        'log_name': log_name,  # Set the name of the log file.
        'max_bytes': max_log_file_size,  # Sets the max log file size.
        'file_log_level':
        file_log_level,  # Sets the file log level. Use DEBUG to keep output from going to the console when using the create_logger function with the YAML logger import function (setup_logger_yaml).
        'console_log_level':
        console_log_level,  # Sets the console log level. Use DEBUG to keep output from going to the console when using the create_logger function with the YAML logger import function (setup_logger_yaml).
        'backup_count': logging_backup_log_count,  # Sets backup copy count
        'format_option':
        logging_format_option,  # Sets the log format based on a number option or manual.
        'handler_option': logging_handler_option,  # Sets handler option.
        'rollover': rollover,  # Sets rollover
    }
    # Calls function to setup logging and create the tracker logger.
    logger = create_logger(logger_settings)

    # Expected Return: <class 'logging.Logger'>
    if not isinstance(logger, type(logger)):
        exc_args = {
            'main_message':
            'A failure occurred in section 1.0 while testing the function \'create_logger\'. No logger was setup during pytest.',
            'expected_result': 'A logger',
            'returned_result': 'No logger was setup during pytest',
        }
        raise FValueError(exc_args)

    # Sets the sample file path.
    # Uses temp file from write_file test
    sample_file_path = os.path.abspath(
        f'{preset_root_directory}\\temp_pytest_read_write.py')

    # Gets all handlers.
    handlers = logger.handlers[:]
    for handler in handlers:

        # Closes and removes the handlers.
        handler.close()
        logger.removeHandler(handler)

    # Removes sample write/read file used in all the testing functions.
    # This line needs to be in the last tested function.
    if os.path.isfile(sample_file_path):
        os.remove(sample_file_path)
Exemple #14
0
    def feed(self, html_output: str, convert_option: str) -> str:
        """
        Main feed to convert HTML to text.

        Args:
            html_output (str):
            \t\\- HTML output requiring conversion.
            convert_option (str):
            \t\\- Conversion option.\\
            \t\\- Only 'text' is supported currently.

        Calling Example:
        \t\\- html_output = '<HTML as a string>'\\
        \t\\- convert_option = 'text

        Raises:
            FTypeError (fexception):
            \t\\- The value '{html_output}' is not in <class 'str'> format.
            FTypeError (fexception):
            \t\\- The value '{convert_option}' is not in <class 'str'> format.
            FValueError (fexception):
            \t\\- The HTML output could not be converted because the conversion option is not valid.
            FGeneralError (fexception):
            \t\\- A general failure occurred while converting HTML to text.

        Returns:
            str:
            \t\\- Converted HTML to text.
        """
        logger = logging.getLogger(__name__)
        logger.debug(f'=' * 20 + get_function_name() + '=' * 20)
        # Custom flowchart tracking. This is ideal for large projects that move a lot.
        # For any third-party modules, set the flow before making the function call.
        logger_flowchart = logging.getLogger('flowchart')
        # Deletes the flowchart log if one already exists.
        logger_flowchart.debug(
            f'Flowchart --> Function: {get_function_name()}')

        try:
            type_check(html_output, str)
            type_check(convert_option, str)
        except FTypeError:
            raise

        logger.debug(
            'Passing parameters:\n'
            f'  - html_output (str):\n        - {str(html_output)}\n'
            f'  - convert_option (str):\n        - {convert_option}\n')

        if not any(convert_option == c for c in (None, 'text')):
            exc_args = {
                'main_message':
                'The HTML output could not be converted because the conversion option is not valid.',
                'expected_result':
                'text',
                'returned_result':
                convert_option,
                'suggested_resolution':
                'Please verify you have sent a valid conversion option.',
            }
            raise FValueError(exc_args)

        try:
            self.output = ""
            super(HTMLConverter, self).feed(html_output)
            # Supports text conversion, but other conversions such as PDF, image, etc can be added in the future.
            if convert_option == 'text':
                logging.debug(
                    'The HTML was converted to text. Returning the output.')
                # Removes all html before the last "}". Some HTML can return additional style information with text output.
                self.output = str(self.output).split('}')[-1].strip()
        except Exception as exc:
            exc_args = {
                'main_message':
                'A general failure occurred while converting HTML to text.',
                'original_exception': exc,
            }
            raise FGeneralError(exc_args)
        else:
            return self.output