def setUpClass(self): """ Set up the unit test. """ self.db = DB() self.table = "TestingTable" cmd = ( "CREATE TABLE TestingTable (id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, " "name varchar(30), age INT(3));") self.db.insert_data(cmd)
def test_generate_json(self): db = DB(config.backend_db['engine']) projects = db.get_items(Project) categories = db.get_items(Category) tasks = db.get_items(Task) s = json.dumps(projects+categories+tasks, cls=ModelEncoder, separators=(',', ':')) self.assertIsNotNone(s) f = open(config.backend_json['filename'], 'w') f.write(s) f.close()
def initialize_components(self): self.__dbinstance = DB() self.__dbinstance.create() songpaths = self.__dbinstance.executeSelect('SELECT * FROM song') # Iniatializes Tk() for importing purposes self.__root = Tk() self.__root.withdraw() # adding songs from hard drive to objects for song in songpaths: self.__addSongToEnvironment(song) strError = 'The following files coudn\'t be found and therefore were excluded from your library: ' if len(self.songsMissing) != 0: for path in self.songsMissing: strError += '\n' + path + '\n' tkinter.messagebox.showinfo(title="Warning!", message=strError)
def setUpClass(self): """ Set up the unit test. """ self.db = DB() self.email = '*****@*****.**' self.password = '******' self.fullname = 'ABC' self.user = User(self.db) self.user.create_new_user(self.email, self.password, self.fullname) self.user_id = self.user.check_email_match(self.email) self.email_1 = '*****@*****.**' self.password_1 = 'klmno' self.fullname_1 = 'XYZ' self.user_1 = User(self.db) self.user_1.create_new_user(self.email_1, self.password_1, self.fullname_1) self.user_id_1 = self.user_1.check_email_match(self.email_1) self.fitness = Fitness(self.db, self.user_id) self.fitness_dict = {'WorkoutType': 'Running',\ 'Minutes': 10.0,\ 'CaloriesBurned': 100.9} self.fitness_1 = Fitness(self.db, self.user_id_1) self.fitness_dict_1 = {'WorkoutType': 'Sleeping',\ 'Minutes': 100.0,\ 'CaloriesBurned': 10.9} self.dt1 = datetime.utcnow() self.unix_time = round(time.time())
def setUpClass(self): """ Set up the unit test. """ self.db = DB() self.email = '*****@*****.**' self.password = '******' self.fullname = 'ABC' self.user = User(self.db) self.user.create_new_user(self.email, self.password, self.fullname) self.user_id = self.user.check_email_match(self.email)
def setUpClass(self): """ Set up the unit test. """ self.db = DB() self.email = '*****@*****.**' self.password = '******' self.fullname = 'ABC' self.user = User(self.db) self.user.create_new_user(self.email, self.password, self.fullname) self.user_id = self.user.check_email_match(self.email) self.email_1 = '*****@*****.**' self.password_1 = 'klmno' self.fullname_1 = 'XYZ' self.user_1 = User(self.db) self.user_1.create_new_user(self.email_1, self.password_1, self.fullname_1) self.user_id_1 = self.user_1.check_email_match(self.email_1) self.email_2 = '*****@*****.**' self.password_2 = 'qqq' self.fullname_2 = 'ASD' self.user_2 = User(self.db) self.user_2.create_new_user(self.email_2, self.password_2, self.fullname_2) self.user_id_2 = self.user_2.check_email_match(self.email_2) self.diet = Diet(self.db, self.user_id) self.diet_1 = Diet(self.db, self.user_id_1) self.diet_2 = Diet(self.db, self.user_id_2) self.diet_dict = {'Item': 'Apple',\ 'ServingSize': 1.0,\ 'Barcode': False,\ 'nutri_dict': {'Cals': 100.0,'Protein': 100.0, 'Carbs': 100.0, 'Fat': 100.0, 'Fiber': 100.0}} self.diet_dict_1 = {'Item': 'Orange',\ 'ServingSize': 2.0,\ 'Barcode': False,\ 'nutri_dict': {'Cals': 105.0,'Protein': 105.0, 'Carbs': 105.0, 'Fat': 105.0, 'Fiber': 105.0}} self.diet_dict_2 = {'Item': 'banana',\ 'ServingSize': 2.0,\ 'Barcode': False,\ 'nutri_dict': {'Cals': 101.0,'Protein': 101.0, 'Carbs': 101.0, 'Fat': 101.0, 'Fiber': 101.0}} self.dt1 = datetime.utcnow() self.unix_time = round(time.time())
def setUpClass(self): """ Set up the unittest. """ self.db = DB() self.email = '*****@*****.**' self.password = '******' self.fullname = 'ABC' self.user = User(self.db) self.user.create_new_user(self.email, self.password, self.fullname) self.user_id = self.user.check_email_match(self.email) self.email_1 = '*****@*****.**' self.password_1 = 'klmno' self.fullname_1 = 'XYZ' self.user_1 = User(self.db) self.user_1.create_new_user(self.email_1, self.password_1, self.fullname_1) self.user_id_1 = self.user_1.check_email_match(self.email_1) self.sleep = Sleep(self.db, self.user_id) self.sleep_1 = Sleep(self.db, self.user_id_1) self.sleep_time = datetime.utcnow() self.wakeup_time = datetime.utcnow() + timedelta(minutes=1) self.sleep_dict = {'Nap': False,\ 'SleepTime': self.sleep_time,\ 'WakeupTime': self.wakeup_time} self.sleep_time_1 = datetime.utcnow() self.wakeup_time_1 = datetime.utcnow() + timedelta(minutes=2) self.sleep_dict_1 = {'Nap': False,\ 'SleepTime': self.sleep_time_1,\ 'WakeupTime': self.wakeup_time_1} self.dt1 = datetime.utcnow() self.unix_time = round(time.time())
def setUpClass(self): """ Set up the unit test. """ self.db = DB() self.email = '*****@*****.**' self.password = '******' self.fullname = 'ABCD' self.user = User(self.db) self.user.create_new_user(self.email, self.password, self.fullname) self.user_id = self.user.check_email_match(self.email) self.goals = Goals(self.db, self.user_id) self.diet_goal_dict = {'Type': 'Calories', 'Value': 1000.0} self.fitness_goal_dict = {'Type': 'FitnessMinutes', 'Value': 100.0} self.sleep_goal_dict = {'Type': 'SleepHours', 'Value': 10.0} self.goals.set_goal(self.diet_goal_dict) self.goals.set_goal(self.fitness_goal_dict) self.goals.set_goal(self.sleep_goal_dict)
def drop_all_tables(db: DB) -> None: db.insert_data('drop table Sleep') db.insert_data('drop table Diet') db.insert_data('drop table Fitness') db.insert_data('drop table Goals') db.insert_data('drop table Users')
"(WorkoutType varchar(256), Minutes DOUBLE NOT NULL, CaloriesBurned DOUBLE NOT NULL, " "Datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UserID INT(11) UNSIGNED, FOREIGN KEY (UserID) " "REFERENCES Users(id));") goals = ("CREATE TABLE Goals " "(Type varchar(50), Value DOUBLE, " "Datetime TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UserID INT(11) UNSIGNED, FOREIGN KEY (UserID) " "REFERENCES Users(id));") def set_up_db(db: DB) -> None: db.insert_data(users) db.insert_data(sleep) db.insert_data(diet) db.insert_data(fitness) db.insert_data(goals) def drop_all_tables(db: DB) -> None: db.insert_data('drop table Sleep') db.insert_data('drop table Diet') db.insert_data('drop table Fitness') db.insert_data('drop table Goals') db.insert_data('drop table Users') db = DB(False) try: set_up_db(db) print("Production DB is set up.") except: pass
def set_up_db(db: DB) -> None: db.insert_data(users) db.insert_data(sleep) db.insert_data(diet) db.insert_data(fitness) db.insert_data(goals)
class TestDB(unittest.TestCase): """ Tests for db.py """ @classmethod def setUpClass(self): """ Set up the unit test. """ self.db = DB() self.table = "TestingTable" cmd = ( "CREATE TABLE TestingTable (id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, " "name varchar(30), age INT(3));") self.db.insert_data(cmd) def test_1_insert_cmd_success(self): """ Test for checking successful database insertion. """ cmd = (f"insert into {self.table} (name, age) values ('Naveena', 21);") self.db.insert_data(cmd) # this just asserts that we made it this far without an exception being thrown self.assertTrue(True) def test_2_select_no_results(self): """ Test for ensuring that an incorrect query returns an empty tuple. """ query = (f" select * from {self.table} where age = 100;") results = self.db.select_data(query) self.assertEqual(results, ()) def test_3_select_with_results(self): """ Test for fetching from the database, and compare against the orcale output. """ query = (f" select * from {self.table} where name = 'Naveena';") results = self.db.select_data(query) self.assertEqual(len(results), 1) expected = {'id': 1, 'name': 'Naveena', 'age': 21} self.assertDictEqual(results[0], expected) def test_4_select_fail(self): """ Test for query failure when the corresponding table does not exists. """ query = (f" select * from NotExistingTable;") with self.assertRaises(ProgrammingError): self.db.select_data(query) def test_5_insert_cmd_fail(self): """ Test for insertion failure when the table columns are incorrect. """ cmd = ( f"insert into {self.table} (name, age) values ('Naveena', 'string');" ) with self.assertRaises(DataError): self.db.insert_data(cmd) def test_6_insert_row(self): """ Test for inserting rows into the table using 'insert_row()'. """ data = {'name': "'Lily'", 'age': 1} self.db.insert_row(self.table, data) query = (f" select * from {self.table} where name = 'Lily';") results = self.db.select_data(query) self.assertEqual(len(results), 1) expected = {'id': 2, 'name': 'Lily', 'age': 1} self.assertDictEqual(results[0], expected) def test_7_insert_row_1(self): """ Test for inserting a row in the table using 'insert_row_1()' """ data = {'name': 'ABC', 'age': 10} self.db.insert_row_1(self.table, data) query = (f" select * from {self.table} where name = 'ABC';") results = self.db.select_data(query) self.assertEqual(len(results), 1) expected = {'id': 3, 'name': 'ABC', 'age': 10} self.assertDictEqual(results[0], expected) def test_8_insert_cmd_success_1(self): """ Test for checking successful database insertion using 'insert_data_1()' """ cmd = (f"insert into {self.table} (name, age) values (%s, %s);") self.db.insert_data_1(cmd, ('DEF', 11)) self.assertTrue(True) @classmethod def tearDownClass(self): """ Tear down method. """ cmd = "drop table TestingTable;" self.db.insert_data(cmd)
class ManagerController: def __init__(self): self.allSongs = [] self.allAlbums = [] self.allArtists = [] self.dictAlbums = {} self.dictArtists = {} self.dictSongs = {} self.__root = None self.__dbinstance = None self.songsMissing = [] def __addSongToEnvironment(self, song): # path is in 1 fields = retrieveFields(song[1]) if fields == -1: self.songsMissing.append(song[1]) self.__dbinstance.executeInsertUpdateDelete( 'DELETE FROM song WHERE id = ' + str(song[0])) return self.dictSongs[str(song[0])] = len( self.allSongs) # mapeando as musicas por ID self.allSongs.append( Music(song[0], song[1], fields['track'], fields['title'], fields['album'], fields['band'], fields['duration'])) # links the song to the album if fields['album'] in self.dictAlbums: # the album already exists, so adds the song to the album # fields['album'] is the album's name # albums[x] is the dictionary that converts the name to the respective index # self.allAlbums is the array of albums self.allAlbums[self.dictAlbums[fields['album']]].addSong(song[0]) else: # the album must be created and then the song linked index = len(self.allAlbums) self.dictAlbums[fields['album']] = index self.allAlbums.append(Album(fields['album'], fields['band'])) self.allAlbums[index].addSong(song[0]) # links the song to the artist if fields['band'] in self.dictArtists: self.allArtists[self.dictArtists[fields['band']]].addSong(song[0]) else: index = len(self.allArtists) self.dictArtists[fields['band']] = index self.allArtists.append(Artist(fields['band'])) self.allArtists[index].addSong(song[0]) def initialize_components(self): self.__dbinstance = DB() self.__dbinstance.create() songpaths = self.__dbinstance.executeSelect('SELECT * FROM song') # Iniatializes Tk() for importing purposes self.__root = Tk() self.__root.withdraw() # adding songs from hard drive to objects for song in songpaths: self.__addSongToEnvironment(song) strError = 'The following files coudn\'t be found and therefore were excluded from your library: ' if len(self.songsMissing) != 0: for path in self.songsMissing: strError += '\n' + path + '\n' tkinter.messagebox.showinfo(title="Warning!", message=strError) # if exists, return 1, else, save in DB and return the created entry in DB to save in Environment def __addSongToDatabase(self, filepath): if (self.__dbinstance.executeSelect('SELECT * FROM song WHERE ' 'filepath = "' + filepath + '"') != []): return 1 else: print('INSERT INTO song(filepath) VALUES ("' + filepath + '")') self.__dbinstance.executeInsertUpdateDelete( 'INSERT INTO song(filepath) VALUES ("' + filepath + '")') return self.__dbinstance.executeSelect('SELECT * FROM song WHERE ' 'filepath = "' + filepath + '"') # Must save in DB and in Environment, if it already exists, it's ignored def import_song(self): filenames = askopenfilenames(parent=self.__root, title='Choose your songs', defaultextension='.mp3', filetypes=[('MP3 File', '*.mp3')]) nErrors = 0 for filepath in filenames: song = self.__addSongToDatabase(filepath) if (song != 1): print(song[0]) self.__addSongToEnvironment(song[0]) else: nErrors += 1 msg = "" if (len(filenames) - nErrors) > 0: msg += str(len(filenames) - nErrors) + " songs were added succesfully!" if (nErrors > 0): msg += '\n' + str(nErrors) + " songs were already on the database." tkinter.messagebox.showinfo(title="Operation Result", message=msg)
class ManagerController: def __init__(self): self.allSongs = [] self.allAlbums = [] self.allArtists = [] self.dictAlbums = {} self.dictArtists = {} self.dictSongs = {} self.__root = None self.__dbinstance = None self.songsMissing = [] def __addSongToEnvironment(self, song): # path is in 1 fields = retrieveFields(song[1]) if fields == -1: self.songsMissing.append(song[1]) self.__dbinstance.executeInsertUpdateDelete('DELETE FROM song WHERE id = ' + str(song[0])) return self.dictSongs[str(song[0])] = len(self.allSongs) # mapeando as musicas por ID self.allSongs.append(Music(song[0], song[1], fields['track'], fields['title'], fields['album'], fields['band'], fields['duration'])) # links the song to the album if fields['album'] in self.dictAlbums: # the album already exists, so adds the song to the album # fields['album'] is the album's name # albums[x] is the dictionary that converts the name to the respective index # self.allAlbums is the array of albums self.allAlbums[self.dictAlbums[fields['album']]].addSong(song[0]) else: # the album must be created and then the song linked index = len(self.allAlbums) self.dictAlbums[fields['album']] = index self.allAlbums.append(Album(fields['album'], fields['band'])) self.allAlbums[index].addSong(song[0]) # links the song to the artist if fields['band'] in self.dictArtists: self.allArtists[self.dictArtists[fields['band']]].addSong(song[0]) else: index = len(self.allArtists) self.dictArtists[fields['band']] = index self.allArtists.append(Artist(fields['band'])) self.allArtists[index].addSong(song[0]) def initialize_components(self): self.__dbinstance = DB() self.__dbinstance.create() songpaths = self.__dbinstance.executeSelect('SELECT * FROM song') # Iniatializes Tk() for importing purposes self.__root = Tk() self.__root.withdraw() # adding songs from hard drive to objects for song in songpaths: self.__addSongToEnvironment(song) strError = 'The following files coudn\'t be found and therefore were excluded from your library: ' if len(self.songsMissing) != 0: for path in self.songsMissing: strError += '\n' + path + '\n' tkinter.messagebox.showinfo(title="Warning!", message=strError) # if exists, return 1, else, save in DB and return the created entry in DB to save in Environment def __addSongToDatabase(self, filepath): if (self.__dbinstance.executeSelect('SELECT * FROM song WHERE ' 'filepath = "' + filepath + '"') != [] ): return 1 else: print('INSERT INTO song(filepath) VALUES ("' + filepath + '")') self.__dbinstance.executeInsertUpdateDelete( 'INSERT INTO song(filepath) VALUES ("' + filepath + '")') return self.__dbinstance.executeSelect('SELECT * FROM song WHERE ' 'filepath = "' + filepath + '"') # Must save in DB and in Environment, if it already exists, it's ignored def import_song(self): filenames = askopenfilenames(parent=self.__root, title='Choose your songs', defaultextension='.mp3', filetypes=[('MP3 File', '*.mp3')]) nErrors = 0 for filepath in filenames: song = self.__addSongToDatabase(filepath) if (song != 1): print(song[0]) self.__addSongToEnvironment(song[0]) else: nErrors += 1 msg = "" if (len(filenames) - nErrors) > 0: msg += str(len(filenames) - nErrors) + " songs were added succesfully!" if (nErrors > 0): msg += '\n'+ str(nErrors) + " songs were already on the database." tkinter.messagebox.showinfo(title="Operation Result", message=msg)
Parameters ---------- token : str Unique user token. Returns ------- result : int If successful, returns user ID. Otherwise, returns -1. """ msg, code = USER.decode_token(token) if code != 200: return -1 return int(msg) if __name__ == '__main__': test = False try: test = sys.argv[1] test = bool(test) except: test = False print(test) DB_OBJECT = DB(test) USER = User(DB_OBJECT) app.run(host="0.0.0.0", port=5000, debug=False)
from backend.db import DB db = DB() print(db.get_station_types()) db.create_event(1,1,123123,12.1231232,324.2323123,1234.213124,2424.54545)
TOPIC = 'input10' WALKER_DISTANCE = 1600 WINDOW_SIZE = 300 consumer = KafkaConsumer( auto_offset_reset='latest', enable_auto_commit=False, bootstrap_servers=[BOOTSTRAP_SERVER], consumer_timeout_ms=2000, api_version=(0, 10, 1), value_deserializer=lambda m: json.loads(m.decode('ascii'))) partition = TopicPartition(TOPIC, 0) consumer.assign([partition]) clients = {} db = DB() patrols = db.get_station(1) offices = db.get_station(2) banks = db.get_station(3) first_time = datetime.datetime.now().timestamp() def mean(arr): speed_sum = 0 for x in arr: speed_sum += x[5] return speed_sum / len(arr)
from backend.db import DB from backend.setup.set_up_db import set_up_db db = DB() set_up_db(db) print("Test database has been set up")