def test_add_miles(self): """ Test whether the function add miles to exiting total miles """ d1 = Driver('Edison', 1.0, 1.000) d1.add_miles(35) self.assertEqual(36, d1.get_miles())
def test_add_hours(self): """ Test whether the function add hours to exiting total hours """ d1 = Driver('Edison', 1.0, 1.000) d1.add_hours(3.2) self.assertEqual(4.2, d1.get_hours())
def test_constructor(self): """ Test whether constructor sets correctly """ d1 = Driver('a', 0, 0) d2 = Driver('b', 0, 0) r = Report([d1, d2]) self.assertListEqual(r.output, [d1, d2])
def addDriver(self, id, name, phone, vehicle): driver = Driver() driver.setId(id) driver.setName(name) driver.setPhone(phone) driver.setVehicle(vehicle) UserService.driver_details[id] = driver return driver
def insert_profiles(base_url, db_path, driver_list, category): current_file = os.path.basename(__file__) current_file_name = os.path.splitext(current_file)[0] for driver_id in driver_list: url = base_url + "/" + current_file_name + "/" + str( driver_id) + "/" + category try: print(url) response = requests.get(url) except requests.exceptions.RequestException as e: print(e) sys.exit(1) if response.status_code == 200: doc = pq(response.text) connection = sqlite3.connect(db_path) try: if doc("main > div").eq(0).hasClass("profile"): # Header - Driver Info driver = Driver(doc, driver_id) connection.execute( '''INSERT INTO drivers (id,fullname,name,lastname,birthdate,deathdate,nationality,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?)''', driver.get_tuple()) # Starts-WRC for season in doc.items("h5.profile-season"): starts = season.nextAll('div.profile-starts').eq(0) for start in starts('div.profile-start-line').items(): result = Result(driver.id, season, start) connection.execute( '''INSERT INTO results (event_id,driver_id,codriver_id,season,car_number,car,plate,team,chassis,category,result,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', result.get_tuple()) connection.commit() except Exception as e: connection.rollback() raise e finally: connection.close()
def test_contructor(self): """ Tests whether the constructor sets values to an instance correctly """ self.d1 = Driver('Einstein', 0.0, 0.000) self.assertEqual('Einstein', self.d1.name) self.assertEqual(0.0, self.d1.total_hours) self.assertEqual(0.0, self.d1.total_miles)
def readDictFromJSON(modelType: str) -> Union[None, dict]: """ Returns a dictionary loaded directly from a JSON file. Package available method that returns a Python dictionary as defined in the relevant JSON file. The function will return either the dictionary converted into models or a directly loaded JSON dictionary. :param modelType: Type of model being loaded :type modelType: string :return: Dictionary if type is not a model :rtype: dictionary :return: None if type is a model :rtype: None """ JSONFile = __JSONFile(modelType) tempDict = json.load(JSONFile) JSONFile.close() if modelType.lower() in MODEL_TYPE_DICT.get('models').get('driverSubset'): for model in tempDict: Driver(tempDict[model]) return elif modelType.lower() in MODEL_TYPE_DICT.get('models').get('teamSubset'): for model in tempDict: Team(tempDict[model]) return elif modelType.lower() in MODEL_TYPE_DICT.get('miscSubset'): return tempDict
def process_command(self, parsed_line_list): # "Driver" command if parsed_line_list[0] == 'Driver': command, driver_name = tuple(parsed_line_list) # record new driver self.output.append(Driver(driver_name, 0.0, 0.000)) self.driver_to_idx[driver_name] = len( self.output) - 1 # record index # "Trip" command elif parsed_line_list[0] == 'Trip': command, driver_name, start_time, \ end_time, miles_driven = tuple(parsed_line_list) hours_driven = self.find_time_delta(start_time, end_time) # ignore trips with 0 travel time if hours_driven > 0: cur_mph = float(miles_driven) / hours_driven # ignore trips that are < 5 mph or > 100 mph if 5 <= cur_mph <= 100: # update the driver's info cur_driver = self.output[self.driver_to_idx[driver_name]] cur_driver.add_miles(float(miles_driven)) cur_driver.add_hours(hours_driven) # unknown command else: print("Error: Unknown input line format found.\n") sys.exit()
def import_data(car_instance_list: list, driver_instance_list: list) -> None: """ Import saved data into the respective instance lists Args: car_instance_list (list): Car instance list driver_instance_list (list): Driver instance list """ try: with open("data/cars.json", 'r') as cars_file: json_ = json.load(cars_file) cars_ = json_["cars"] for car_ in cars_: car_instance_list.append( Car(car_["id"], car_["reg"], car_["brand"], car_["hp"], car_["kms"])) except FileNotFoundError: from ui.console_messages import warning warning("cars.json doesn't exist! -> Cars not loaded") try: with open("data/drivers.json", 'r') as drivers_file: json_ = json.load(drivers_file) drivers_ = json_["drivers"] for driver_ in drivers_: car_for_driver = return_right_car(driver_["car_id"], car_instance_list) driver_instance_list.append( Driver(driver_["id"], driver_["name"], driver_["age"], car_for_driver)) except FileNotFoundError: from ui.console_messages import warning warning("drivers.json doesn't exist! -> Drivers not loaded loaded")
def insert_codrivers(base_url, db_path, codriver_list, category): current_file = os.path.basename(__file__) current_file_name = os.path.splitext(current_file)[0] for codriver_id in codriver_list: url = base_url + "/" + current_file_name + "/" + str( codriver_id) + "/" + category try: print(url) response = requests.get(url) except requests.exceptions.RequestException as e: print(e) sys.exit(1) if response.status_code == 200: doc = pq(response.text) connection = sqlite3.connect(db_path) try: if doc("main > div").eq(0).hasClass("profile"): # Header - Codriver Info codriver = Driver(doc, codriver_id) connection.execute( '''INSERT INTO codrivers (id,fullname,name,lastname,birthdate,deathdate,nationality,created_at,updated_at,deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?)''', codriver.get_tuple()) connection.commit() except Exception as e: connection.rollback() raise e finally: connection.close()
def __readModelListFromJSONFile( modelType: str, JSONFile: list) -> Union[None, List[Driver], List[Team]]: """ DEPRECATED: Returns a list of models from model list based on model type. Pseudo-private method that takes in a model type, reads each model from the model list and returns them in a list of relevant model objects. If the model list is empty, that means the list and subsequent file was just created; hence there is no data to read and the function returns nothing. :param modelType: Type of model being loaded :type modelType: string :param JSONFile: JSON file with models :type JSONFile: list :return: Models initialized as their relevant objects :rtype: list """ # There is no need for a validation message here as it is okay to not have data in the model list. if not JSONFile: return bar = __createProgressBar().start() i = 0 if modelType.lower() in MODEL_TYPE_DICT.get('models').get('driverSubset'): driverList = [] for tempDriver in JSONFile: print(tempDriver) driverList.append(Driver(tempDriver)) bar.update(i + 1) bar.finish() print() return driverList elif modelType.lower() in MODEL_TYPE_DICT.get('models').get('teamSubset'): teamList = [] for tempTeam in JSONFile: teamList.append(Team(tempTeam)) bar.update(i + 1) bar.finish() print() return teamList else: raise Exception("Incorrect model type!")
def test_print(self): """ Test both cases when output is empty and when it is not """ # output = [] r1 = Report([]) r1.print() out, err = self.capfd.readouterr() assert "No result." in out # output = [d1] d1 = Driver('a', 0, 0) r2 = Report([d1]) r2.print() out, err = self.capfd.readouterr() assert "No result." not in out
def convertCSVToJSON(modelType: str = None, filename: str = None) -> None: """ Imports lines from a CSV file as models and converts to JSON format :param modelType: Type of model being loaded :type modelType: string :param filename: If specified, the specific path to write the CSV file to :type filename: string :return: None :rtype: None """ CSVFile = __CSVFile(modelType, filename) reader = csv.DictReader(CSVFile) next(reader) # Skip the header lines for row in reader: Driver(row) CSVFile.close() print(f'CSV file converted from {CSVFile.name}')
def test_get_hours(self): """ Test whether the function returns the object's total hours """ d1 = Driver('Einstein', 0.0, 5.250) self.assertEqual(5.25, d1.get_hours())
def test_get_miles(self): """ Test whether the function returns the object's total miles """ d1 = Driver('Einstein', 100.2, 0.000) self.assertEqual(100.2, d1.get_miles())
def test_get_name(self): """ Test whether the function returns the object's name """ d1 = Driver('Einstein', 100.2, 0.000) self.assertEqual('Einstein', d1.get_name())
def handle_add_driver(driver_repo: Repo, parser: Parser, car_repo: Repo) -> None: """ Handle adding a driver Args: driver_repo (Repo): Driver repository parser (Parser): Input data parser car_repo (Repo): Car repository """ new_id = None new_name = "" new_age = None # Get driver id: done_id = False while not done_id: id_ = input( "Enter driver id (numeric), leave blank for autocomplete > ") if id_ == "": _, last_entity = driver_repo.get(mode="last") id_ = last_entity.id found = False while not found: id_ += 1 if not parser.check_if_already_exists(by_id=True, id=int(id_)): found = True new_id = int(id_) done_id = True print(f"\tAutocomplete succesfull, assigned id {new_id}") else: if not parser.check_if_already_exists(by_id=True, id=int(id_)): new_id = int(id_) done_id = True else: console.clear_console() olt.show( title="Info", message= "This id already exists, you might want to auto-complete, just press enter", go_back=False) # Get driver name: new_name = input("Enter the driver's name > ") # Get driver age: done_age = False while not done_age: age = input("Enter the driver's age (numeric) > ") try: new_age = int(age) done_age = True except ValueError: console.clear_console() olt.show(title="Info", message="The age must be a numeric value, ex: 45", go_back=False) # Deal with car assignment: if input("Do you want to assign a car now? y/n > ").lower() == "y": # Add car: print( "In order to assign a car to a driver you need it's ID, do you know it, or do you want to see all cars" ) input_ = input("Press enter to see all cars or enter an ID > ") if input_ == "": _, car_list = car_repo.get() if len(car_list) == 0 or car_list is None: olt.show( title="Something went wrong", message= "Either there are no cars at this moment or something else went wrong" ) else: table_data = [["ID", "Registration"]] for car in car_list: table_data.append([str(car.id), car.reg]) car_table = SingleTable(table_data, title="Cars") car_table.justify_columns = { 0: "left", 1: "center", } while True: console.clear_console() print(car_table.table) input_ = input("Type b or back to go back > ") if input_ == "b" or input_ == "back": break else: continue console.clear_console() input_ = input( "Enter car id or \"back\" if you want to leave it blank for now > " ) if input_ == "back": # Just add driver with no car assigned driver_repo.add(Driver(new_id, new_name, new_age, None)) else: try: new_car_id = int(input_) resp, car_ = car_repo.get(mode="single", entity_id=new_car_id) if resp == "found": # Add driver with respective car driver_repo.add( Driver(new_id, new_name, new_age, car_)) else: olt.show( title="Warning", message= "ID not found! Leaving blank for now, update via menu" ) driver_repo.add( Driver(new_id, new_name, new_age, None)) except ValueError: olt.show( title="Warning", message= "The id must be numeric. Leaving blank for now, update via menu" ) driver_repo.add(Driver(new_id, new_name, new_age, None)) else: # User gave manual id: try: new_car_id = int(input_) resp, car_ = car_repo.get(mode="single", entity_id=new_car_id) if resp == "found": # Add driver with respective car driver_repo.add(Driver(new_id, new_name, new_age, car_)) else: olt.show( title="Warning", message= "ID not found! Leaving blank for now, update via menu") driver_repo.add(Driver(new_id, new_name, new_age, None)) except ValueError: olt.show( title="Warning", message= "The id must be numeric. Leaving blank for now, update via menu" ) driver_repo.add(Driver(new_id, new_name, new_age, None)) else: # Just add driver with no car assigned driver_repo.add(Driver(new_id, new_name, new_age, None)) _, driver_instance_list = driver_repo.get() save_data(mode="single", only="drivers", driver_instance_list=driver_instance_list) olt.show(title="Success", message="The new driver was added succesfully")
def convertCSVToJSON(modelType: str) -> None: """ Converts the relevant CSV file to JSON format. Package available method that converts a CSV file into a JSON file. :param modelType: Type of model being loaded :type modelType: string :return: Dictionary of models :rtype: dictionary """ if modelType.lower() in MODEL_TYPE_DICT.get('models').get('driverSubset'): properHeader = [ 'Name', 'Age', 'Team Name', 'Contract Status', 'Car Number', 'Short Rating', 'Short Intermediate Rating', 'Intermediate Rating', 'Superspeedway Rating', 'Restrictor Plate Rating', 'Road Rating', 'Overall Rating', 'Potential' ] elif modelType.lower() in MODEL_TYPE_DICT.get('models').get('teamSubset'): properHeader = [ 'Name', 'Owner', 'Car Manufacturer', 'Equipment Rating', 'Team Rating', 'Race Rating' ] else: raise Exception('Incorrect model type!') csvHeader = [] CSVFile = __CSVFile(modelType) reader = csv.reader(CSVFile) header = next(reader) for column in header: csvHeader.append(column) # TODO: Refine error checking and display messages when the headers don't match up. headerDiffList = __headerDiff(properHeader, csvHeader) # Get the differences of the two lists; if they are not ordered correctly or have different column names, # don't do anything. if headerDiffList: raise Exception( "Seems like the header is messed up. Check the CSV and try again.") # itemCount = 0 # for item in headerDiffList: # if itemCount == 0 or itemCount % 2 == 0: # print("Expected:", headerDiffList[itemCount]) # print("Got:", headerDiffList[itemCount + 1]) # itemCount += 1 else: print("The header in both files match! Importing models now...") bar = __createProgressBar() bar.start() i = 0 if modelType.lower() in MODEL_TYPE_DICT.get('models').get( 'driverSubset'): for row in reader: Driver(row) bar.update(i + 1) writeDictToJSON(modelType, Driver.instances) elif modelType.lower() in MODEL_TYPE_DICT.get('models').get( 'teamSubset'): for row in reader: Team(row) bar.update(i + 1) writeDictToJSON(modelType, Team.instances) bar.finish() print() CSVFile.close()