def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.places  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.places  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Place with values
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places
    print("Test sorting - priority:")
    place_collection.sort("priority")
    print(place_collection)

    print("Test sorting - name:")
    place_collection.sort("name")
    print(place_collection)
Ejemplo n.º 2
0
def main():
    print('Travel Tracker 1.0 - by Shizheng Li')
    place_collection = PlaceCollection()
    place_collection.load_places("places.csv")
    rows = len(place_collection.places)
    print('{} places loaded from place.csv'.format(rows))

    while True:
        print('Menu:')
        print('L - List places')
        print('A - Add new place')
        print('M - Mark a place as visited')
        print('Q - Quit')
        choice = input().lower()
        if choice == 'l':
            display(place_collection)
        elif choice == 'a':
            add(place_collection)
        elif choice == 'm':
            mark(place_collection)
        elif choice == 'q':
            save(place_collection)
            return
        else:
            print('Invalid menu choice')
 def __init__(self, **kwargs):
     """Construct main app."""
     super().__init__(**kwargs)
     self.title = "Movies To Watch 2.0"
     self.collection = PlaceCollection()
     self.collection.load_places("places.csv")
     self.collection.sort("year")
     self.columns = ["Year", "Category", "Title", 'Watched']
Ejemplo n.º 4
0
 def __init__(self):
     """This method is automatically initialized when Place class is called."""
     self.data = []
     """this variable in Place that used for contain the data read from the csv files."""
     self.new_place = []
     """this variable in in Place that is used for contain correct user input that passed from main and give it to place collection that will be add later."""
     pc.read(self)
     """calling method in place collections for containing the data from csv files."""
Ejemplo n.º 5
0
 def __init__(self, **kwargs):
     """
     Construct main app
     """
     super(TravelTrackerApp, self).__init__(**kwargs)
     self.pc = PlaceCollection()
     self.pc.load_places()
     self.visited_status_text = "Places to visit: {}".format(
         self.pc.get_number_of_unvisited_places())
     self.input_data = []
 def __init__(self, **kwargs):
     """Initialise the instances"""
     super().__init__(**kwargs)
     self.place_collection = PlaceCollection(
     )  # get instance from PlaceCollection class
     self.place_collection.load_places(FILENAME)  # call load_places method
     self.places = {
         place.name: place
         for place in self.place_collection.places
     }
Ejemplo n.º 7
0
 def __init__(self, **kwargs):
     """Creat main app"""
     super().__init__(**kwargs)
     self.text_att = DICTIONARY
     self.sort_method = list(self.text_att.keys())
     self.sort_current = self.sort_method[0]
     self.places = PlaceCollection()
     self.places.load_places(DATA)
     self.information = WELCOME
     Window.size = (1000, 750)
Ejemplo n.º 8
0
    def build(self):
        '''build Kivy app from the kv file '''
        self.title = 'TravelTracker'
        self.root = Builder.load_file('app.kv')
        self.sort_by = SORT_FIELD.keys()
        self.current_sort = self.sort_by[0]
        self.root.ids.bar_bottom.text = 'Welcome to Travel Tracker 2.0'

        self.place_collection = PlaceCollection()
        self.place_collection.load_places(FILE_PATH)
        self.place_collection.sort(list(SORT_FIELD.values())[0])
        self.updateUnvisitedInfo()
        self.setupBtns()
        return self.root
Ejemplo n.º 9
0
def main():
    choice = input(MENU).upper()
    print(data)
    while choice != "Q":
        if choice == "L":
            listFunction(data, FILENAME)
        elif choice == "A":
            PlaceCollection.add_places(PlaceCollection)
        elif choice == "M":
            markFunction(PlaceCollection)
        else:
            print("Invalid menu choice")
        choice = input(MENU).upper()
    PlaceCollection.save_places(PlaceCollection)
Ejemplo n.º 10
0
 def __init__(self, **kwargs):
     """
     Initiate place_list to PlaceCollection class
     Initiate sort_choices as an array
     Initiate the current sorting option as "priority"
     Initiate the function load_places to load csv file
     :param kwargs:
     returns None
     """
     super(PlaceApp, self).__init__(**kwargs)
     self.place_list = PlaceCollection()
     self.sort_choices = ["name", "country", "priority", "is_visited"]
     self.current_sort = self.sort_choices[2]
     self.path = str(
         pathlib.Path(__file__).resolve().parent) + "\\places.csv"
     self.place_list.load_places(self.path)
Ejemplo n.º 11
0
    def build(self):
        """
        Build Kivy App
        :return: Reference to root Kivy widget
        """
        self.title = "TravelChecker"
        self.root = Builder.load_file('app.kv')
        Window.bind(on_request_close=self.save_to_csv)

        # Loading, sorting, and displaying places contained in .csv file
        self.PC = PlaceCollection()
        self.PC.load_places(FILE_LOCATION)
        self.set_sort_method('visited')
        self.update_widgets()

        return self.root
Ejemplo n.º 12
0
def main():
    """Run the whole process"""
    print("Travel Tracker 1.0 - by <Yudan Zhang>")
    place_collection = PlaceCollection()

    placs_list = place_collection.load_places('places.csv')

    while True:
        choice = read_menu()
        if choice == 'L':
            place_collection.list_places()

        elif choice == 'A':
            new_place = validate_new_places()
            place_collection.add_place(
                Place(new_place[0], new_place[1], new_place[2], new_place[3]))

        elif choice == 'M':
            mark_places(place_collection, placs_list)

        elif choice == 'Q':
            print("""{} places saved to places.csv
Have a nice day :)""".format(len(place_collection.places_list)))
            break

        else:
            print("Invalid menu choice")
Ejemplo n.º 13
0
class TravelTrackerApp(App):
    states = ListProperty()
    current_state = StringProperty()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.place_collection = PlaceCollection()
        self.place_collection.read_places('places.csv')

    def build(self):
        """build app"""
        self.title = "Travel Tracker"
        self.root = Builder.load_file("app.kv")
        return self.root

    def add_place(self):
        """add places"""
        add_name = self.root.ids.add_name.text
        add_country = self.root.ids.add_country.text
        add_priority = self.root.ids.add_priority.text

        if add_name.strip() == "" or add_country.strip(
        ) == "" or add_priority == "":
            end = "Cannot be blank!"
        else:
            if int(add_priority) <= 0:
                end = "priority must greater than 0 !"
            else:
                end = "{} ({}) with priority {}.".format(
                    add_name, add_country, add_priority)
                self.place_collection.list_data.append(
                    [add_name, add_country, add_priority], "n")
        self.root.ids.end.text = end

    def create_widgets(self, key="visited"):
        """add btn or other functions to app"""
        self.count_n()
        self.place_collection.s_places(key)

        for places in self.place_collection.list_data:
            if places[3] == "n":
                v = ""
            else:
                v = "(visited)"
            place_str = "{} ({}) with priority {} {}".format(
                places[0], places[1], places[2], v)
            btn = Button(id=places[0], text=place_str)
            self.root.ids.places_listed.add_widget(btn)

    def on_stop(self):
        """save csv file"""
        self.place_collection.s_places("places.csv")

    def count_n(self):
        n_place = self.place_collection.count_n()
        self.root.ids.count_n.text = "Places to visit: {}".format(n_place)
Ejemplo n.º 14
0
def main():
    """ Main function to run """
    print('Travel Checker 2.0 - Finley Sherwood')
    
    places = PlaceCollection()
    places.load_places(FILE_LOCATION)

    display_menu()
    method = input('>>> ').upper()
    while method != 'Q':
        if method == 'L':
            list_method(places)
        elif method == 'A':
            add_method(places)
        elif method == 'M':
            mark_method(places)
        else:
            print('Invalid menu choice')
        display_menu()
        method = input('>>> ').upper()
    quit_method(places)
Ejemplo n.º 15
0
    def main():
        """Run the whole process"""
        print("Travel Tracker 1.0 - by Xin Liu")
        place_collection = PlaceCollection()
        listed_places = place_collection.read_places("places.csv")

        while True:
            choice = get_menu()
            if choice == "L":
                place_collection.list_data
            elif choice == "A":
                add_places = add_place()
                place_collection.add_place(
                    Place(add_places[0], add_places[1], add_places[2],
                          add_places[3]))
            elif choice == "M":
                mark_places(place_collection, listed_places)

            elif choice == "Q":
                print("{} places saved to places.csv".format(
                    len(place_collection.list_data)))
                break
            else:
                print("Invalid menu choice")
Ejemplo n.º 16
0
def main():
    """main method"""
    """load the file"""
    filename = "places.csv"
    """create a places object and load a csv file"""
    places_obj = PlaceCollection()
    places_obj.load_places(filename)
    places = places_obj.places
    # print info
    print("Travel Tracker 1.0 - by Tong Wenlin")
    print("%d places loaded from places.csv" % len(places))
    """run the choice option"""
    loop = True
    while loop:
        display_main_menu()
        choice = input(">>> ").upper()

        if choice == "L":
            print(places)

        elif choice == "A":
            name = input("Name: ")
            country = input("Country: ")
            priority = int(input("Priority: "))
            place_obj = Place(name=name, country=country, priority=priority)
            places.append((place_obj.name, place_obj.country,
                           place_obj.priority, place_obj.is_visited))

        elif choice == "M":
            name = input("Input a place name:")
            for place in places:
                if place[0] == name:
                    place_obj = Place(name=place[0],
                                      country=place[1],
                                      priority=place[2],
                                      is_visited=place[3])
                    place_obj.mark_place_visited()
                    places.remove(place)
                    new_place = (place_obj.name, place_obj.country,
                                 place_obj.priority, place_obj.is_visited)
                    places.append(new_place)
                    print("add success")
                    break

        elif choice == "Q":
            places_obj.save_places()
            loop = False
            print("%d places saved to places.csv" % len(places))
            print("Have a nice day :)")

        else:
            print("Invalid menu choice")
Ejemplo n.º 17
0
def main():

    choice = input(MENU).upper()
    while choice != "Q":
        if choice == "L":
            PlaceCollection.print_place(PlaceCollection)
        elif choice == "A":
            PlaceCollection.add_places(PlaceCollection)
        elif choice == "M":
            print("Derp")


#            visit_place(Place, PlaceCollection)
        else:
            print("Invalid menu choice")
        choice = input(MENU).upper()
    PlaceCollection.save_places(PlaceCollection)
class TravelTrackerApp(App):
    collection: PlaceCollection
    current_key = StringProperty()
    columns = ListProperty()
    status_text = StringProperty()
    num_text = StringProperty()

    def __init__(self, **kwargs):
        """Construct main app."""
        super().__init__(**kwargs)
        self.title = "Movies To Watch 2.0"
        self.collection = PlaceCollection()
        self.collection.load_places("places.csv")
        self.collection.sort("year")
        self.columns = ["Year", "Category", "Title", 'Watched']

    def build(self):
        """Build an application"""
        # app title
        self.title = "TravelTrackerApp"
        self.root = Builder.load_file('app.kv')

        self.current_key = 'Year'
        # all the valid actions
        self.actions = ["Action", "Comedy", "Documentary", "Drama", "Fantasy", "Thriller"]
        # clear all widgets
        self.clear_all()
        # create widgets
        self.create_widgets()
        self.status_text = ""
        self.num_text = "To watch: {}. Watched: {}".format(self.collection.un_visited(),
                                                           self.collection.un_visited())
        return self.root

    def change_state(self, key):
        """Handle change of spinner selection, output result to label widget """
        index = self.columns.index(key)
        keys = ["year", "category", "title", "is_watched"]
        self.collection.sort(keys[index])
        self.clear_all()
        self.create_widgets()

    def create_widgets(self):
        """Create buttons from dictionary entries and add them to the GUI."""

        id = 0
        for places in self.collection.places:
            # create a button for each data entry, specifying the text and id
            name: str = "{} ({} from {})".format(places.name, places.country, places.visited)
            temp_button = Button(text=name, id=str(id), background_color=UNWATCHED_COLOR)
            if places.is_visited is True:
                temp_button = Button(text=name, id=str(id), background_color=WATCHED_COLOR)
            temp_button.bind(on_release=self.press_entry)
            # add the button to the "entries_box" layout widget
            self.root.ids.entries_box.add_widget(temp_button)
            id += 1

    def press_entry(self, instance):
        """Handle pressing entry buttons.
        :param instance: the Kivy button instance that was clicked"""

        # get name (dictionary key) from the id of Button we clicked on
        print(instance.id)
        index = int(instance.id)

        # update status text
        movie = self.collection.movies[index]
        if movie.is_watched:
            # if you have watched the movie, set it unwatched
            self.status_text = "You have watched {}".format(movie.title)
            movie.to_unwatch()
        else:
            # if you have not watch the movie, set it watched
            self.status_text = "You watched {}".format(movie.title)
            movie.to_watch()
        self.num_text = "To watch: {}. Watched: {}".format(self.collection.get_number_of_unwatched(),
                                                           self.collection.get_number_of_watched())
        self.clear_all()
        self.create_widgets()

    def clear_all(self):
        """Clear all of the widgets that are children of the "entries_box" layout widget."""
        self.root.ids.entries_box.clear_widgets()

    def clear_input(self):
        """Cleat the text input"""

        self.root.ids.title_input.text = ""
        self.root.ids.year_input.text = ""
        self.root.ids.category_input.text = ""
        self.status_text = ""

    def add_movie(self, title, year, category):
        """Add movie to the collection"""

        title = title.strip()
        year = year.strip()
        category = category.strip()
        if title == "" or year == "" or category == "":
            self.status_text = "All fields must be completed"
            return
        try:
            year = int(year)
        except:
            # if the year is not a number
            self.status_text = "Please enter a valid number"
            return
        if year < 0:
            # if year is not valid
            self.status_text = "Please enter a valid number"
            return
        if category not in self.actions:
            # if invalid category
            self.status_text = "·	The category must be one of the following: " \
                               "Action, Comedy, Documentary, Drama, Fantasy, Thriller"
            return
        place = place(title, year, category, False)
        self.collection.add(place)
        self.collection.sort("year")  # sort by year
        self.clear_all()  # redraw the widgets
        self.clear_input()
        self.create_widgets()

    def on_stop(self):
        """Exit event, save all the movies"""

        self.collection.save("places.csv")
Ejemplo n.º 19
0
def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.places  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.places  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Place with values
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places
    print("Test sorting - priority:")
    place_collection.sort("priority")
    print(place_collection)

    # TODO: Add more sorting tests
    # Test sorting places - country
    print("Test sorting - country:")
    place_collection.sort_places("country")
    print(place_collection)

    # Test sorting places - name
    print("Test sorting - name:")
    place_collection.sort_places("name")
    print(place_collection)

    # Test sorting places - visited
    print("Test sorting - visited:")
    place_collection.sort_places("visited")
    print(place_collection)

    # TODO: Test saving places (check CSV file manually to see results)
    place_collection.save_places('places.csv')
    # TODO: Add more tests, as appropriate, for each method
    # Test count number of unvisited places
    num = place_collection.num_nplaces()
    print(num)

    # Test listing places
    print("Test listing:")
    place_collection.list_places()
Ejemplo n.º 20
0
 def __init__(self, **kwargs):
     """Construct main app"""
     super().__init__(**kwargs)
     self.place_collection = PlaceCollection()
     self.place_collection.load_places('places.csv')
Ejemplo n.º 21
0
class TravelTrackerApp(App):
    """Create the application from App"""
    current_key = StringProperty()
    key_codes = ListProperty()

    def __init__(self, **kwargs):
        """Construct main app"""
        super().__init__(**kwargs)
        self.place_collection = PlaceCollection()
        self.place_collection.load_places('places.csv')

    def build(self):
        """Build the Kivy GUI"""
        self.title = "TravelTracker"
        self.root = Builder.load_file('app.kv')
        self.key_codes = KEYs.keys()
        self.current_key = self.key_codes[0]
        self.create_widgets()

        return self.root

    def change_key(self, key):
        """ handle change of spinner selection, output result to label widget """
        self.clear_all()
        # print('change to:',key, KEYs[key])
        self.create_widgets(key)

    def add_place(self):
        """Add new place to GUI"""
        new_name = self.root.ids.new_name.text
        new_country = self.root.ids.new_country.text
        new_priority = self.root.ids.new_priority.text

        if new_name.strip() == '' or new_country.strip(
        ) == '' or new_priority.strip() == '':
            terminal = 'All fields must be completed'
        else:
            try:
                new_priority = int(new_priority)
            except ValueError:
                terminal = 'Please enter a valid number'
            else:
                if int(new_priority) <= 0:
                    terminal = 'Priority must be > 0'
                else:
                    terminal = '{} in {}, priority {} added.'.format(
                        new_name, new_country, new_priority)
                    self.place_collection.places_list.append(
                        [new_name, new_country,
                         int(new_priority), 'n'])

                    # print(new_name, new_country, new_priority)
                    new_btn = Button(id=new_name,
                                     text='{} in {}, priority {} '.format(
                                         new_name, new_country,
                                         int(new_priority)))
                    self.root.ids.places_detail.add_widget(new_btn)
        self.root.ids.terminal.text = terminal
        self.clear_all()
        self.create_widgets()
        return self.place_collection.places_list

    def create_widgets(self, key='Visited'):
        """Create buttons from dictionary entries and add them to the GUI."""
        self.clear_all()
        self.place_collection.sort_places(key)
        self.num_nplaces()
        for places in self.place_collection.places_list:
            if places[3] == 'n':
                visit_status = ''
                bkcolor = (1, 0.61, 0.61, 1)
            else:
                visit_status = '(visited)'
                bkcolor = (0.3, 0.4, 0.4, 1)
            place_string = '{} in {}, priority {} {}'.format(
                places[0], places[1], places[2], visit_status)
            place_btn = Button(id=places[0],
                               text=place_string,
                               background_color=bkcolor)
            self.root.ids.places_detail.add_widget(place_btn)
            place_btn.bind(on_release=self.change_status)

    def clear_btn(self):
        """Bind to clear button, clear all input"""
        self.root.ids.new_name.text = ''
        self.root.ids.new_country.text = ''
        self.root.ids.new_priority.text = ''
        self.root.ids.terminal = ''

    def change_status(self, instance):
        """When press button of place, change it visit status"""
        for place in self.place_collection.places_list:
            placestring = '{} in {}, priority {}'.format(
                place[0], place[1], place[2])
            if placestring.strip() == instance.text.replace('(visited)',
                                                            '').strip():
                if place[3] == 'v':
                    if place[2] <= 2:
                        terminal = 'You need to visit {}. Get going!'.format(
                            place[0])
                    else:
                        terminal = 'You need to visit {}.'.format(place[0])
                    place[3] = 'n'
                else:
                    if place[2] <= 2:
                        terminal = 'You visited {}, Great travelling!'.format(
                            place[0])
                    else:
                        terminal = 'You visited {}.'.format(place[0])
                    place[3] = 'v'
                self.root.ids.terminal.text = terminal
            self.clear_all()
            self.create_widgets()

    def clear_all(self):
        """Clear all places buttons"""
        self.root.ids.places_detail.clear_widgets()

    def num_nplaces(self):
        """Return number of unvisited places"""
        n_place = self.place_collection.num_nplaces()
        self.root.ids.nplace.text = "Places to visit: {}".format(n_place)

    def on_stop(self):
        """Save all places when closing the app"""
        self.place_collection.save_places('places.csv')
Ejemplo n.º 22
0
class TravelTrackerApp(App):
    """..."""
    def __init__(self, **kwargs):
        """Creat main app"""
        super().__init__(**kwargs)
        self.text_att = DICTIONARY
        self.sort_method = list(self.text_att.keys())
        self.sort_current = self.sort_method[0]
        self.places = PlaceCollection()
        self.places.load_places(DATA)
        self.information = WELCOME
        Window.size = (1000, 750)

    def build(self):
        """Build the Kivy GUI."""
        self.title = "Places to Visit 2.0"
        self.source = Builder.load_file("app.kv")
        self.button_creat()

        return self.source

    def rank(self, text):
        """sort places"""
        attr = self.text_att[text]
        self.places.sort(attr)
        self.button_creat()

    def button_creat(self):
        """Clear all buttons"""
        self.source.ids.place_button.clear_widgets()
        for i, place in enumerate(self.places.places):
            temp_button = Button(id=str(i))
            temp_button.bind(on_release=self.place_button)
            name = place.name
            country = place.country
            priority = place.priority

            if place.is_visited:
                visited = " (visited)"
                temp_button.background_color = [0.5, 0.5, 1, 1]
            else:
                visited = ""
                temp_button.background_color = button_color
            text = " ''{}'' by {} ({}) {}".format(name, priority, country, visited)
            temp_button.text = text
            self.source.ids.place_button.add_widget(temp_button)

    def add_button(self):
        """Add place button"""
        name = self.source.ids.name.text
        country = self.source.ids.country.text
        priority = self.source.ids.priority.text

        if (name == "") | (country == "") | (priority == ""):
            self.information = "All fields must be completed"
            self.bottom_inf()
        else:
            try:
                priority = int(priority)
                if priority < 1:
                    # if the priority is < 1
                    self.information = "priority must be >=0"
                    self.bottom_inf()
                else:
                    place = Place(name, priority, country)
                    self.places.add_place(place)
                    self.all_inf()
            except ValueError:
                self.information = "Please enter a valid number"
                self.bottom_inf()

    def clear_button(self):
        """Clear button"""
        self.source.ids.name.text = ""
        self.source.ids.country.text = ""
        self.source.ids.priority.text = ""

    def place_button(self, instance):
        """Creat place button"""
        i = int(instance.id)
        place = self.places.places[i]
        if place.is_visited:
            place.unvisited()
            self.information = "You can visit {}".format(place.name)
        else:
            place.visit()
            self.information = "You have visited {}".format(place.name)
        self.all_inf()

    def top_inf(self):
        """Display the information on the top"""
        self.source.ids.top_message.text = "To visit: {}  visited: {}".format(self.places.unvisited_number(),
                                                                              self.places.visited_number())

    def bottom_inf(self):
        """Display the information of bottom"""
        self.source.ids.bottom_message.text = self.information

    def all_inf(self):
        """Display all information"""
        self.button_creat()
        self.top_inf()
        self.bottom_inf()

    def run_exit(self):
        self.places.save_places(DATA)
class TravelTrackerApp(App):
    """Travel Tracker's backstage and start code"""
    status_text = StringProperty()

    def __init__(self, **kwargs):
        """Constructor of all classes"""
        super().__init__(**kwargs)
        self.place_collection = PlaceCollection()
        self.place_collection.load_places('places.csv')

    def build(self):
        """Builder for kv code"""
        self.title = "Travel Tracker"
        self.root = Builder.load_file('app.kv')
        self.create_list()
        return self.root

    def get_name(self):
        """Check error of name input"""
        try:
            value = str(self.root.ids.input_name.text)
            return value
        except ValueError:
            return ''

    def get_country(self):
        """Check error for country input"""
        try:
            value = str(self.root.ids.input_country.text)
            return value
        except ValueError:
            return ''

    def get_priority(self):
        """Check error for priority input"""
        try:
            value = int(self.root.ids.input_priority.text)
            return value
        except ValueError:
            return 0

    def get_sort(self):
        """Check error for sort input(not necessary... just lazy to change)"""
        try:
            value = str(self.root.ids.input_sort.text)
            return value.upper()
        except ValueError:
            return ''

    def add_place(self):
        """add place in places list"""
        new_Place = Place(self.get_name(), self.get_country(),
                          self.get_priority())

        # if input are empty or error, change show board in front stage.
        if self.get_name() == '':
            self.root.ids.show_text.text = "All fields must be completed"
            return
        elif self.get_country() == '':
            self.root.ids.show_text.text = "All fields must be completed"
            return
        elif self.get_priority() == 0:
            self.root.ids.show_text.text = "Please enter a valid number"
            return
        else:
            self.place_collection.add_place(new_Place)
            self.clear_all()
            self.create_list()

    def clear(self):
        """clear all input field and show board """
        self.root.ids.input_name.text = ""
        self.root.ids.input_country.text = ""
        self.root.ids.input_priority.text = ""
        self.root.ids.show_text.text = ""

    def sort(self):
        """sort list for front stage"""
        self.place_collection.sort(self.get_sort())
        self.clear_all()
        self.create_list()

    def create_list(self):
        """make list to dynamic button for front stage"""
        self.place_collection.sort(self.get_sort())
        self.root.ids.show_unvisited_num.text = "Place to visit: {}".format(
            self.place_collection.get_num_of_unvisited())

        # give different color between visited and unvisited.
        for place in self.place_collection.places:
            if not place.visit:
                place_label = Button(text=str(place),
                                     id=place.name,
                                     background_color=(1, 0.61, 0.61, 1))
                place_label.bind(on_release=self.press_entry)
                self.root.ids.places_list.add_widget(place_label)
            else:
                place_label = Button(text=str(place), id=place.name)
                place_label.bind(on_release=self.press_entry)
                self.root.ids.places_list.add_widget(place_label)

    def press_entry(self, instance):
        """give functions when dynamic button be clicked"""
        for place in self.place_collection.places:
            # find place in list
            if str(place) == instance.text:
                # judge is place visited or not
                if place.visit:
                    # judge is place important or not
                    if place.is_important():
                        self.status_text = "You need to visit {}. Get going!".format(
                            place.name)
                        self.root.ids.show_text.text = self.status_text
                    else:
                        self.status_text = "You need to visit {}.".format(
                            place.name)
                        self.root.ids.show_text.text = self.status_text
                    place.visit = False
                elif not place.visit:
                    # same as top one
                    if place.is_important():
                        self.status_text = "You visited {}, Great travelling!".format(
                            place.name)
                        self.root.ids.show_text.text = self.status_text
                    else:
                        self.status_text = "You visited {}.".format(place.name)
                        self.root.ids.show_text.text = self.status_text
                    place.visit = True

                self.clear_all()
                self.create_list()
                self.root.ids.show_unvisited_num.text = "Place to visit: {}".format(
                    self.place_collection.get_num_of_unvisited())

    def clear_all(self):
        """clear all places list in front stage"""
        self.root.ids.places_list.clear_widgets()

    def on_stop(self):
        """save data when app is shutdown"""
        self.place_collection.save_places()
def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.places  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.places  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new Place with values
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places

    print("Test sorting - name:")
    place_collection.sort('name')
    print(place_collection)

    print("Test sorting - country")
    place_collection.sort('country')
    print(place_collection)

    print("Test sorting - priority:")
    place_collection.sort("priority")
    print(place_collection)

    print("Test sorting - visited")
    place_collection.sort('is_visited')
    print(place_collection)

    # Test saving places (check CSV file manually to see results)
    print("Test saving places")
    place_collection.save_places('places.csv')

    # Test get number of visited places
    print("Testing get number of visited places")
    print("Number of places visited: {}".format(
        place_collection.get_number_visited_places()))

    # Test get number of visited places
    print("Testing get number of visited places")
    print("Number of places unvisited: {}".format(
        place_collection.get_number_unvisited_places()))
Ejemplo n.º 25
0
def run_tests():
    """Test PlaceCollection class."""
    """Test empty PlaceCollection (defaults)"""
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.list_data  # an empty list is considered False
    """Test loading places"""
    print("Test loading places:")
    place_collection.read_places('places.csv')
    print(place_collection)
    assert place_collection.list_data  # assuming CSV file is non-empty, non-empty list is considered True
    """Test adding a new Place with values"""
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)
    """Test sorting - name:"""
    print("Test sorting - name:")
    place_collection.s_places("name")
    print(place_collection)
    """Test sorting - country:"""
    print("Test sorting - country:")
    place_collection.s_places("country")
    print(place_collection)
    """Test sorting places - priority"""
    print("Test sorting - priority:")
    place_collection.s_places("priority")
    print(place_collection)
    """Test sorting places - visited_status"""
    print("Test sorting - visited:")
    place_collection.s_places("visited")
    print(place_collection)
    """Test listing places"""
    print("Test listing:")
    place_collection.list_all_places()
def run_tests():
    """Test PlaceCollection class."""

    # Test empty PlaceCollection (defaults)
    print("Test empty PlaceCollection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.places  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    # assuming CSV file is non-empty, non-empty list is considered True
    assert place_collection.places

    # Test adding a new Place with values
    print("Test adding new place:")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places
    print("Test sorting - priority:")
    place_collection.sort("priority")
    print(place_collection)

    # TODO: Add more sorting tests
    print('Test sorting - is visited:')
    place_collection.sort('visited')
    print(place_collection)

    # TODO: Test saving places (check CSV file manually to see results)
    place_collection.save_place('place.csv')

    # TODO: Add more tests, as appropriate, for each method
    print('Test get_unvisited_number:')
    place_collection.add_place(Place())
    assert place_collection.get_unvisited_number() == 6
Ejemplo n.º 27
0
class TravelTrackerApp(App):
    """App constructor class, used for GUI"""
    current_selection = StringProperty()
    sort_by = ListProperty()
    places_to_visit = StringProperty()
    place_status = StringProperty()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.place_collection = PlaceCollection()
        self.place_collection.load_places(PLACES_FILE)

    def build(self):
        self.title = "Places To Visit 2.0"
        self.root = Builder.load_file('app.kv')
        self.sort_by = sorted(SORT_CATEGORIES.keys())
        self.current_selection = self.sort_by[0]
        self.places_to_visit = "Places to visit: {}".format(self.place_collection.get_unvisited())
        return self.root

    def create_buttons(self):
        """Creates buttons from MovieCollection for the GUI."""
        for place in self.place_collection.places:
            display_color = self.set_button_color(place)
            button = Button(text=self.display_visited(place), id=place.name, background_color=display_color)
            button.bind(on_release=self.handle_press_place)
            button.place = place
            self.root.ids.place_box.add_widget(button)

    @staticmethod
    def set_button_color(place):
        display_color = UNVISITED
        if place.is_visited:
            display_color = VISITED
        return display_color

    def handle_press_place(self, instance):
        if instance.place.is_visited:
            instance.place.mark_unvisited()
        else:
            instance.place.mark_visited()
        instance.background_color = self.set_button_color(instance.place)
        place_instance = 'need to visit'
        if instance.place.is_visited:
            place_instance = 'visited'
        self.place_status = "You {} {}.".format(place_instance, instance.place.name)
        instance.text = self.display_visited(instance.place)
        self.places_to_visit = "Places to visit: {}".format(self.place_collection.get_unvisited())

    @staticmethod
    def display_visited(instance):
        is_visited = '(visited)'
        if not instance.is_visited:
            is_visited = ''
        button_display_text = instance.text = "{} in {}, priority {} {}".format(instance.name, instance.country,
                                                                                instance.priority, is_visited)
        return button_display_text

    def new_spinner_selection(self, new_sort_by):
        self.current_selection = new_sort_by
        self.update_place_buttons()

    def update_place_buttons(self):
        self.place_collection.sort_places(SORT_CATEGORIES[self.current_selection])
        self.root.ids.place_box.clear_widgets()
        self.create_buttons()

    def handle_press_add(self, new_name, new_country, new_priority):
        if self.validate_input(new_name, new_country, new_priority):
            self.place_collection.add_place(Place(new_name, new_country, int(new_priority), False))
            button = Button(text='{} in {}, priority {} added'.format(new_name, new_country, new_priority), id=new_name,
                            background_color=UNVISITED)
            button.bind(on_release=self.handle_press_place)
            button.place = self.place_collection.places[-1]
            self.clear_fields()
            self.update_place_buttons()

    def validate_input(self, name, country, priority):
        input_fields = name, country, priority
        for field in input_fields:
            if field == '':
                self.place_status = "All fields must be completed"
                return False
        try:
            priority = int(priority)
        except ValueError:
            self.place_status = "Please enter a valid number"
            return False
        if not priority > 0:
            self.place_status = "Priority must be >0"
            return False
        return True

    def clear_fields(self):
        self.root.ids.new_name.text = ''
        self.root.ids.new_country.text = ''
        self.root.ids.new_priority.text = ''
        self.place_status = ''

    def on_stop(self):
        self.place_collection.boolean_to_string()
        self.place_collection.save_places(PLACES_FILE)
 def __init__(self, **kwargs):
     """Constructor of all classes"""
     super().__init__(**kwargs)
     self.place_collection = PlaceCollection()
     self.place_collection.load_places('places.csv')
Ejemplo n.º 29
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.place_collection = PlaceCollection()
     self.place_collection.load_places(PLACES_FILE)
def run_tests():
    """Test Collection class."""

    # Test empty Collection (defaults)
    print("Test empty Collection:")
    place_collection = PlaceCollection()
    print(place_collection)
    assert not place_collection.place  # an empty list is considered False

    # Test loading places
    print("Test loading places:")
    place_collection.load_places('places.csv')
    print(place_collection)
    assert place_collection.place_list  # assuming CSV file is non-empty, non-empty list is considered True

    # Test adding a new lace with values
    print("Test adding new place :")
    place_collection.add_place(Place("Smithfield", "Australia", 5, False))
    print(place_collection)

    # Test sorting places
    print("Test sorting - Priority:")
    sorted_list = place_collection.sort_place("priority ")
    print(place_collection.format_data(sorted_list))

    # Test sorting country
    print("Test sorting - country:")
    sorted_list_2 = place_collection.sort_place("country")
    print(place_collection.format_data(sorted_list_2))
    # test sorting name
    print("Test sorting - name:")
    sorted_list_3 = place_collection.sort_place("name")
    print(place_collection.format_data(sorted_list_3))
    #  Test saving places (check CSV file manually to see results)
    print("Test saving places:")
    place_collection.save_changes("places.csv")

    # Add more tests, as appropriate, for each method
    print("Test count learned places:")
    print(place_collection.count_learned())
    # Test count unlearned places
    print("Test count unlearned places:")
    print(place_collection.count_unlearned())