Esempio n. 1
0
    def setUp(self):
        """Sets up testing variables.

        Test data using test API query outputs for location and poi searches.
        """
        # used in test_location_search and test_get_poi
        self.test1: TripAdvisorApi = TripAdvisorApi(
            ["Lima", "Peru"], ["Lima", "Peru"])
        self.test2: TripAdvisorApi = TripAdvisorApi(
            ["fake_reg", "fake_country"], ["fake_city", "fake_country"])
        self.data: list = JsonHandler.read_json(
            "tests/resources/test-loc-data.json")
        self.poidata: list = JsonHandler.read_json(
            "tests/resources/test-poi-data.json")

        # used in test_poi_search
        self.region_info1: dict = {
            "name": "Victoria",
            "location_id":
            "255098"
            }
        self.poi_info1: dict = {
            'errors': [{
                'type': 'BadRequestException',
                'message': 'Cannot view this connection at this level.',
                'code': '120'}]
                }
        self.region_info2: dict = {
            'name': 'Melbourne',
            'location_id': '255100',
            'description': 'Some description about Melbourne'
            }
        self.poi_info2: list = JsonHandler.read_json(
            "tests/resources/test-poi-search.json")
Esempio n. 2
0
    def test_read_and_write_json(self):
        """Tests modules in the JsonHandler class.

        Asserts presence/absence of data in self.text_from_json and
        self.text_from_blank; Appends new data to self.text_from_json and
        save to a new file ("test2.json"). Tests original and new files for
        new data and length; Deletes test2.json when completed.
        """
        self.assertIsNotNone(self.text_from_json)
        self.assertEqual(self.text_from_blank, [])
        self.text_from_json.append({
            "city": "Dhaka",
            "city_ascii": "Dhaka",
            "lat": "23.7231",
            "lng": "90.4086",
            "country": "Bangladesh",
            "iso2": "BD",
            "iso3": "BGD",
            "admin_name": "Dhaka",
            "capital": "primary",
            "population": "12797394",
            "id": "1050529279"
        })
        JsonHandler.write_json("test2.json", self.text_from_json)
        original_list: list = JsonHandler.read_json("test.json")
        test2_list: list = JsonHandler.read_json("test2.json")
        self.assertEqual("Dhaka", test2_list[7]["city"])
        self.assertEqual(len(test2_list), 8)
        self.assertEqual(len(original_list), 7)
        TestFile.delete_test_file("test2.json")
Esempio n. 3
0
    def setUp(self):
        """Sets up test variables for testing of the file_handler module.

        Sets up test variables from both csv and json sources.
        """
        TestFile.create_file()
        self.test_list = CsvHandler.read_csv("tests/test.csv")
        self.test_list_2 = CsvHandler.read_csv("")
        FileConverter.save_csv_as_json("tests/test.csv", "test.json")
        self.text_from_json = JsonHandler.read_json("test.json")
        self.text_from_blank = JsonHandler.read_json("fake.json")
Esempio n. 4
0
 def wrapper(*args, **kwargs):
     func_value = func(*args, **kwargs)
     print("Saving data")
     content: list = JsonHandler.read_json(func_value[1])
     content.append(func_value[0])
     JsonHandler.write_json(func_value[1], content)
     print("Data saved")
     print("Making it presentable.....\n\n\n")
     display_content: Display = Display(content[0])
     display_content.display_saved_data()
     return func_value
Esempio n. 5
0
    def tearDown(self):
        """Remove test files + search_history created during setUp/testing."""

        try:
            TestFile.delete_test_file(
                "tests/resources/test/Melbourne-Australia.json")
        except FileNotFoundError:
            pass

        try:
            content: list = self.test_file4.past_searches
            content.remove(["Melbourne", "Australia"])
            JsonHandler.write_json(
                f"{self.test_file4.path}search_history.json", content)
        except ValueError:
            print("['Melbourne', 'Australia'] removed.")
Esempio n. 6
0
    def __init__(self, region: list, path: str):
        """Initialises UserFile object with four instance attributes.

        Args:
            region (list): Generated by the select_region() method from
                a Places object.
            path (str): Defined in the User object's path attribute.
        """
        #: str:  defines path to folder where search results are saved
        # and retrieved. Creates directory if it does not already exist
        # in the defined file path
        self.path: str = path
        if not os.path.exists(self.path):
            os.makedirs(self.path)

        #: list: region as selected using the select_region method in a
        # Places object
        self.region: list = region

        #: city: city as selected using the select_city method in a
        # Places object
        self.city: list = []

        #: list of [region, country] or [city, country] saved from past
        # searches. Retrieved from the
        # resources/<user.name>/search_history file.
        self.past_searches: list = JsonHandler.read_json(
            f"{self.path}search_history.json")

        #: str: defined externally as the level of search(region/city) is made.
        # Determines the file name for lookup and/or save.
        self.searchfile: str = ""
Esempio n. 7
0
 def setUp(self):
     """Sets up variables for object creation and testing."""
     self.place_info1: dict = {
         'name': 'Melbourne',
         'location_id': '255100',
         'description': 'Some description about Melbourne'
     }
     self.poi_results1: list = JsonHandler.read_json(
         "tests/resources/test-poi-search.json")
Esempio n. 8
0
    def __init__(self, places_file: str = 'resources/worldcities.json'):
        """Initialises Database object with two instance attributes.

        Using data from places_file (list of cities in json format), the
        cities_db dictionary is created using the create_cities_db()
        method and stored as an instance attribute.

        Args:
            places_file (str, optional): file path pointing to json
                file for data lookup and extraction during instantiation.
                Defaults to 'resources/worldcities.json'.
        """
        self.places: list = JsonHandler.read_json(places_file)
        self.cities_db: dict = self.create_cities_db()
Esempio n. 9
0
    def read_flag_and_save(self, data: dict, flag: str) -> tuple:
        """Saves formatted content into a location file for future lookup.

        Formats retrieved location data into a uniform format and save it
        in a predefined file name for future lookup.
        User's past searches list (json file) updated with the latest
        location search.

        Args:
            data (dict): processed location data from city_info attribute
                from a PoiData object. This is obtained after running the
                extract() and consolidate_categories() methods on the
                PoiData instance.
            flag (str): obtained from the output of the get_poi method of a
                TripadvisorApi instance. Informs on the level of search
                (region/city) that was conducted during the API search.

        Returns:
            tuple: returns final formatted content and file path for
            save_and_display_data decorator to perform
            save and display of data.
        """
        if flag == "region":
            final_format: dict = {"Region": self.region, "Data": data}
            file_path: str = (
                f"{self.path}{self.region[0]}-{self.region[1]}.json")
            self.past_searches.append(self.region)
            JsonHandler.write_json(f"{self.path}search_history.json",
                                   self.past_searches)
        elif flag == "city":
            final_format = {"City": self.city, "Data": data}
            file_path = f"{self.path}{self.city[0]}-{self.city[1]}.json"
            self.past_searches.append(self.city)
            JsonHandler.write_json(f"{self.path}search_history.json",
                                   self.past_searches)
        return final_format, file_path
Esempio n. 10
0
    def retrieve_saved(self, place: list, file_path: str) -> dict:
        """Retrieves content of a previously saved places file.

        Args:
            place (list): [region, country] or [city, country] depending
                on the level of the search.
            file_path (str): defines path to folder within which search
                results are retrieved.

        Returns:
            dict: raw content from location save file.
        """
        print("Retrieving saved data")
        content: list = JsonHandler.read_json(file_path)
        retrieved: dict = {}
        for item in content:
            if "City" in item and item["City"] == place:
                retrieved = item
            if "Region" in item and item["Region"] == place:
                retrieved = item
        return retrieved