Esempio n. 1
0
class TestList(unittest.TestCase):
    """ Submodule for unittests, derives from unittest.TestCase. """
    first_node_value = "one"
    second_node_value = "two"
    third_node_value = "three"
    fourth_node_value = "four"
    test_list1 = [5, 3, 4, 1, 2]
    test_list2 = ["a", "d", "b", "e", "c"]
    test_list3 = ["a", 5, 3, "e", 1, "abc", 10, 6]
    test_list1_sorted = [1, 2, 3, 4, 5]
    test_list2_sorted = ["a", "b", "c", "d", "e"]
    test_list3_sorted = [1, 3, 5, 6, 10, 'a', 'abc', 'e']

    def setUp(self):
        """ Create object for all tests """
        # Arrange
        self.list = UnorderedList()

    def tearDown(self):
        """ Remove dependencies after test """
        self.list = None

    def test_list_append(self):
        """Test append node."""
        self.list.append(TestList.first_node_value)
        self.assertIsInstance(self.list.head, Node)
        self.list.append(TestList.second_node_value)
        self.assertIsInstance(self.list.tail, Node)
        self.assertEqual(
            self.list.head.data,
            TestList.first_node_value,
            msg='Head.data: {0}'.format(self.list.head.data)
        )
        self.assertEqual(self.list.tail.data, TestList.second_node_value)
        self.assertIs(self.list.head.next, self.list.tail)

    def test_list_set_valid(self):
        """Test set node with valid index."""
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        self.list[0] = TestList.fourth_node_value
        self.assertEqual(
            self.list.head.data,
            TestList.fourth_node_value,
            msg='Head.data: {0}'.format(self.list.head.data)
        )
        # self.assertEqual(self.list.tail.data, TestList.second_node_value)

    def test_list_set_invalid(self):
        """Test set node with invalid index."""
        with self.assertRaises(ListIndexError) as _:
            self.list[0] = TestList.first_node_value
        self.list.append(TestList.first_node_value)
        with self.assertRaises(ListIndexError) as _:
            self.list[1] = ""

    def test_list_get(self):
        """Test get node."""
        with self.assertRaises(ListIndexError) as _:
            print(self.list[0])
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        with self.assertRaises(ListIndexError) as _:
            print(self.list[3])
        self.assertEqual(self.list[2], TestList.third_node_value)

    def test_list_index_of(self):
        """Test index_of."""
        with self.assertRaises(ListValueError) as _:
            self.list.index_of("a")
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        self.assertEqual(self.list.index_of(TestList.third_node_value), 2)
        with self.assertRaises(ListValueError) as _:
            self.list.index_of("a")

    def test_list_remove(self):
        """Test remove element."""
        with self.assertRaises(ListIndexError) as _:
            self.list.remove("a")
        self.list.append(TestList.first_node_value)
        self.list.append(TestList.second_node_value)
        self.list.append(TestList.third_node_value)
        # remove middle value and test if shifted to the left
        self.list.remove(TestList.second_node_value)
        self.assertEqual(self.list.index_of(TestList.third_node_value), 1)
        with self.assertRaises(ListValueError) as _:
            self.list.remove(TestList.second_node_value)
        # test adding again (had problem with it before)
        self.list.append(TestList.fourth_node_value)
        self.assertEqual(self.list.index_of(TestList.fourth_node_value), 2)

    def test_list_insertionsort_all_numeric(self):
        """test_list_insertionsort_all_numeric"""
        for node in self.test_list1:
            self.list.append(node)
        self.list.insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list1_sorted, res_list)

    def test_list_insertionsort_all_strings(self):
        """test_list_insertionsort_all_strings"""
        for node in self.test_list2:
            self.list.append(node)
        self.list.insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list2_sorted, res_list)

    def test_list_insertionsort_mixed(self):
        """test_list_insertionsort_mixed"""
        for node in self.test_list3:
            self.list.append(node)
        self.list.insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list3_sorted, res_list)

    def test_list_recursive_insertionsort_all_numeric(self):
        """test_list_recursive_insertionsort_all_numeric"""
        for node in self.test_list1:
            self.list.append(node)
        self.list.recursive_insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list1_sorted, res_list)

    def test_list_recursive_insertionsort_all_strings(self):
        """test_list_recursive_insertionsort_all_strings"""
        for node in self.test_list2:
            self.list.append(node)
        self.list.recursive_insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list2_sorted, res_list)

    def test_list_recursive_insertionsort_mixed(self):
        """test_list_recursive_insertionsort_mixed"""
        for node in self.test_list3:
            self.list.append(node)
        self.list.recursive_insertionsort()
        res_list = []
        for i in range(len(self.list)):
            res_list.append(self.list[i])
        self.assertEqual(self.test_list3_sorted, res_list)
Esempio n. 2
0
class Handler:
    """ Handler class """

    _OPTIONS = {
        "1": "append",
        "2": "set",
        "3": "size",
        "4": "get",
        "5": "index_of",
        "6": "print_list",
        "7": "remove",
        "8": "sort",
        "9": "recursive_sort",
        "a": "recursive_bubblesort",
        "f": "gen_test_list",
        "q": "quit"
    }
    # test_list = [5, 3, 4, 1, 2]
    # test_list = ["a", "d", "b", "e", "c"]
    test_list = ["a", 5, 3, "e", 1, "abc", 10, 6]

    def __init__(self):
        """ Initialize class """
        self.list = UnorderedList()
        self.start()

    def _get_method(self, method_name):
        """
        Uses function getattr() to dynamically get value of an attribute.
        """
        return getattr(self, self._OPTIONS[method_name])

    def _print_menu(self):
        """
        Use docstring from methods to print options for the program.
        """
        menu = ""

        for key in sorted(self._OPTIONS):
            method = self._get_method(key)
            docstring = inspect.getdoc(method)

            menu += "{choice}: {explanation}\n".format(choice=key,
                                                       explanation=docstring)

        print(chr(27) + "[2J" + chr(27) + "[;H")
        print(menu)

    def append(self):
        """Adds a node to the list."""
        value = input("\nAdd a value: \n>>> ")
        if value.isnumeric():
            value = int(value)
        else:
            try:
                value = float(value)
            except ValueError:
                pass
        self.list.append(value)
        print(f"{value} has been added.")
        # print("Head.data: '" + self.list.head.data + "'")

    def set(self):
        """Replace value (data) for the node on the index place."""
        index = input("\nIndex: ")
        value = input("Value: ")
        try:
            self.list.set(index, value)
            print(f"{value} has been changed.")
        except ListIndexError as e:
            print(f"Error: {e}")

    def size(self):
        """ Shows the list length. """
        print(self.list.size())

    def get(self):
        """Get data on the index position."""
        index = input("\nEnter index value: ")
        try:
            print(self.list.get(index))
        except ListIndexError as e:
            print(f"Error: {e}")

    def index_of(self):
        """Get the first index of the data."""
        value = input("\nEnter data value: ")
        try:
            print(self.list.index_of(value))
        except ListValueError as e:
            print(f"Error: {e}")

    def print_list(self):
        """Print all nodes in the list."""
        print(self.list.print_list())

    def remove(self):
        """ Removes the first node from the list. """
        value = input("\nEnter data value: ")
        try:
            self.list.remove(value)
            print(f"{value} has been removed.")
        except (ListIndexError, ListValueError) as e:
            print(f"Error: {e}")

    def sort(self):
        """Sort list (insert)."""
        print("Sorted list: ")
        print(self.list.insertionsort())

    def recursive_sort(self):
        """Sort list Recursively (insert)."""
        print(self.list)
        print("Recursively sorted list: ")
        print(self.list.recursive_insertionsort())

    def recursive_bubblesort(self):
        """Bubblesort list Recursively."""
        print(self.list)
        print("Recursively bubblesorted list: ")
        print(self.list.recursive_bubblesort())

    def gen_test_list(self):
        """Generate test list."""
        if len(self.list) > 0:
            for i in range(len(self.list) - 1, -1, -1):
                self.list.remove(self.list[i])
        for node in self.test_list:
            self.list.append(node)
        print("Generated list: ", self.list)

    @staticmethod
    def quit():
        """ Quit the program """
        sys.exit()

    def start(self):
        """ Start method """
        while True:
            self._print_menu()
            choice = input("Enter menu selection:\n-> ")

            try:
                self._get_method(choice.lower())()
            except KeyError:
                print("Invalid choice!")

            input("\nPress any key to continue ...")