def testInvalidFriendSearch(monkeypatch): # todo: fix (broke because of change in findUser function) monkeypatch.setattr("sys.stdin", StringIO("2\n")) settings.currentState = states.userSearch connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first", "last", 0, "01/01/2020")
def manageMessage(self, msg): content_type, chat_type, chat_id = telepot.glance(msg) self.chat_id = chat_id # mensaje del usuario self.message = msg # guardamos el usuario en la bdd si no está user = [[chat_id, msg['from']['first_name']]] database.insertUser(user) # llamamos a dialogflow intent, entities = self.eatBotConversation.checkMessage( self.message['text']) # gestionamos el mensaje self.eatBotRules.reset() # declaramos los hechos para las reglas, los intent y las entities if intent != '': self.eatBotRules.declare(Fact(intent=intent)) for k, v in entities.items(): f = Fact() f[k] = v if k != '' and v != '': self.eatBotRules.declare(f) print(self.eatBotRules.facts) # ejecutamos el motor de reglas self.eatBotRules.run()
def testCreateUser(): # todo: potentially change this test to utilize createUser function from main program instead connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() # Initialize database and run insert function db.initTables(cursor) db.insertUser(cursor, "username", "password", "first", "last", 0, "01/01/2020") assert db.getUserByName(cursor, "username") # Check successful insert connection.close()
def testValidJobPost(monkeypatch): monkeypatch.setattr("sys.stdin", StringIO("Title\nDescription\nEmpName\nLocation\n1")) connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first", "last", 0, "01/01/2020") settings.signedInUname = "username1" jobs.postJob(cursor, connection) out = db.getJobByTitle(cursor, "Title") # Confirms that job has been added into DB correctly assert out is not None
def testMaxAccountsCreated(monkeypatch, capfd): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() db.initTables(cursor) for i in range(10): db.insertUser(cursor, f"username{i}", "password", f"first{i}", f"last{i}", 0, "01/01/2020") users.createUser(cursor, connection) out, err = capfd.readouterr() # Output should display max users created assert out == "All permitted accounts have been created, please come back later\n" assert db.getNumUsers(cursor) == 10
def testInvalidUserLogin(monkeypatch, capfd): monkeypatch.setattr("sys.stdin", StringIO("username1\npassword\nusername2\npassword\n")) #invalid credentials first, valid credentials second connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() db.initTables(cursor) db.insertUser(cursor, "username2", "password", "first", "last", 0, "01/01/2020") settings.signedIn = False # fix users.loginUser(cursor, connection) # Fails because it gets trapped in while loop out, err = capfd.readouterr() assert "Enter your password: Incorrect" in out assert settings.signedIn
def testValidUserLogin(monkeypatch, capfd): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first", "last", 0, "01/01/2020") db.insertUserSettings(cursor, "username1", "*****@*****.**", "123-123-1234", 0, "English") monkeypatch.setattr("sys.stdin", StringIO("username1\npassword\n")) # Patch in user input users.loginUser(cursor, connection) out, err = capfd.readouterr() # Output should display successfully sign in and state change assert "You have successfully logged in." in out assert settings.signedIn
def testSendFriendRequest(monkeypatch): monkeypatch.setattr("sys.stdin", StringIO("A\nfirst2 last2\nY\n")) connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "2020-01-01 12:30:00") db.insertUser(cursor, "username2", "password", "first2", "last2", 0, "2020-01-01 12:30:00") settings.signedInUname = "username1" settings.signedIn = True settings.currentState = states.userSearch users.findUser(cursor, connection) assert len(db.getUserFriendRequests(cursor, "username2")) == 1
def start(bot, update): """Conversation logic for when the user first starts talking to the bot, called when the user uses the "/start" command. @param {Bot} bot @param {update} update""" insertUser(update.message.chat.id, update.message.chat.first_name, update.message.chat.last_name) insertMessage(update.message.chat.id, update.message.text, time(), 0, contexts['InitialUserRegistration'], None, 1) genres_keyboard = botAssets.genresKeyboard() reply_markup = telegram.ReplyKeyboardMarkup(genres_keyboard) bot.send_message(chat_id=update.message.chat_id, text="Hey {}! Thanks for talking to me, I haven't spoken to anyone in a while!".format(update.message.chat.first_name)) bot.send_message(chat_id=update.message.chat_id, text="""I'm really interested in films. My favourite genre is comedy, what's yours?""", reply_markup=reply_markup)
def testUserAlreadyExists(monkeypatch, capfd): monkeypatch.setattr("sys.stdin", StringIO("username1\nusername2\nPassword1!\nfname\nlname\nN\n")) #after username1 is taken, pick a different uname and exit menu connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS user_settings") cursor.execute("DROP TABLE IF EXISTS profile_page") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first", "last", 0, "01/01/2020") users.createUser(cursor, connection) out, err = capfd.readouterr() assert "Sorry, that username has already been taken" in out assert settings.currentState == states.loggedOut
def testFavoriteAJob(monkeypatch): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS favorited_jobs") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "2020-01-01 12:30:00") db.insertUser(cursor, "username2", "password", "first2", "last2", 0, "2020-01-01 12:30:00") db.insertJob(cursor, "title1", "desc1", "emp1", "loc1", "sal1", "first1 last1") selectedJob = db.getAllJobs(cursor)[0] settings.signedInUname = "username2" monkeypatch.setattr("sys.stdin", StringIO("b\nz\n")) jobs.viewJobDetails(cursor, connection, selectedJob) assert len(db.getFavoriteJobsByUser(cursor, "username2")) == 1
def testApplyForJob(monkeypatch): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS user_job_applications") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "01/01/2020") db.insertUser(cursor, "username2", "password", "first2", "last2", 0, "01/01/2020") db.insertJob(cursor, "title1", "desc1", "emp1", "loc1", "sal1", "first1 last1") selectedJob = db.getAllJobs(cursor)[0] settings.signedInUname = "username2" monkeypatch.setattr("sys.stdin", StringIO("1\n01/01/1234\n01/02/1234\ncredentials\n")) jobs.applyForJob(cursor, connection, selectedJob) assert len(db.getAppliedJobs(cursor, "username2")) == 1
def testCreateMaxJobPosts(capfd): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS jobs") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "01/01/2020") for _ in range(10): db.insertJob(cursor, "title", "desc", "emp", "loc", "sal", "username1") jobs.postJob(cursor, connection) out, err = capfd.readouterr() assert "All permitted jobs have been created, please come back later.\n" in out assert db.getNumJobs(cursor) == 10 assert settings.currentState == states.jobMenu
def testImportantLinks(monkeypatch, capfd): monkeypatch.setattr("sys.stdin", StringIO("f\nz\nz\nz\n")) settings.signedInUname = "username1" connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS profile_page") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "2020-01-01 12:30:00") db.insertProfilePage(cursor, "username1", "major", "university", "about") settings.currentState = states.mainMenu ui.enterMainMenu(cursor, connection) out, err = capfd.readouterr() assert "Important Links" in out
def testViewFriendList(monkeypatch, capfd): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times db.initTables(cursor) db.insertUser(cursor, "uname", "password", "first", "last", 0, "01/01/2020") db.insertUser(cursor, "friend_uname", "password", "first2", "last2", 0, "01/01/2020") db.insertUserFriend(cursor, "uname", "friend_uname") settings.currentState = states.friendsMenu settings.signedInUname = "uname" monkeypatch.setattr("sys.stdin", StringIO("Z\n")) ui.enterFriendsMenu(cursor, connection) out, err = capfd.readouterr() assert out is not None assert settings.currentState == states.mainMenu assert db.getUserFriendsByName(cursor, "uname") is not None
def testDeleteJobPost(monkeypatch): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "2020-01-01 12:30:00") db.insertUser(cursor, "username2", "password", "first2", "last2", 0, "2020-01-01 12:30:00") settings.signedInUname = "username1" db.insertJob(cursor, "title1", "desc1", "emp1", "loc1", "sal1", "first1 last1") db.insertJob(cursor, "title2", "desc2", "emp2", "loc2", "sal2", "first1 last1") assert db.getNumJobs(cursor) == 2 db.insertUserJobApplication(cursor, "username2", "title1", "01/01/1243", "01/02/1243", "credentials", "2020-01-01 12:30:00") monkeypatch.setattr("sys.stdin", StringIO("1\nN\n")) jobs.enterDeleteAJobMenu(cursor, connection) assert db.getNumJobs(cursor) == 1 assert len(db.getAppliedJobs(cursor, "username2")) == 0
def testRemoveFriend(monkeypatch): monkeypatch.setattr("sys.stdin", StringIO("A\n1\nZ\n")) connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS user_friends") db.initTables(cursor) db.insertUser(cursor, "uname", "password", "first", "last", 0, "01/01/2020") db.insertUser(cursor, "friend_uname", "password", "first2", "last2", 0, "01/01/2020") db.insertUserFriend(cursor, "uname", "friend_uname") db.insertUserFriend(cursor, "friend_uname", "uname") settings.currentState = states.friendsMenu settings.signedInUname = "uname" ui.enterFriendsMenu(cursor, connection) assert settings.currentState == states.mainMenu assert len(db.getUserFriendsByName(cursor, "uname")) == 0
def testProfileAddFourJobs(monkeypatch, capfd): connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS profile_jobs") db.initTables(cursor) db.insertUser(cursor, "uname", "password", "first", "last", 0, "01/01/2020") db.insertProfilePage(cursor, "uname", "major", "university", "about") for _ in range(3): # add 3 jobs db.insertProfileJob(cursor, "uname", "title", "employer", "date_start", "date_end", "location", "job_description") settings.currentState = states.profilePage #settings needed for enterProfilePageMenu to work settings.signedInUname = "uname" monkeypatch.setattr("sys.stdin", StringIO("a\nd\nz\nz\n")) #navigate menu. pressing d tries to add a new job which should fail profiles.enterProfilePageMenu(cursor, connection) out, err = capfd.readouterr() assert out is not None assert len(db.getProfileJobs(cursor, settings.signedInUname)) == 3 assert settings.currentState == states.mainMenu
def testAcceptFriendRequest(monkeypatch): monkeypatch.setattr("sys.stdin", StringIO("A\n")) connection = sqlite3.connect("incollege_test.db") cursor = connection.cursor() cursor.execute("DROP TABLE IF EXISTS Users") #delete tables to make sure no conflicts when running test multiple times cursor.execute("DROP TABLE IF EXISTS friend_requests") cursor.execute("DROP TABLE IF EXISTS user_friends") db.initTables(cursor) db.insertUser(cursor, "username1", "password", "first1", "last1", 0, "01/01/2020") db.insertUser(cursor, "username2", "password", "first2", "last2", 0, "01/01/2020") db.insertFriendRequest(cursor, "username1", "username2") settings.signedInUname = "username2" utils.handleUserFriendRequests(cursor, connection, settings.signedInUname) assert len(db.getUserFriendsByName(cursor, "username1")) == 1 assert len(db.getUserFriendsByName(cursor, "username2")) == 1 assert ((db.getUserFriendsByName(cursor, "username1"))[0])[0] == "username2" assert ((db.getUserFriendsByName(cursor, "username2"))[0])[0] == "username1"
def home(): netid = CASClient().authenticate().strip('\n') print(netid) insertUser(netid) # find particular entry of user user = entryInfo.entryInfo() # cas client appends a new line so get rid of it user.setNetid(netid.strip('\n')) # search for user in database entry = searchEntry(user) userEntry = entryInfo.entryInfo() if (len(entry) > 1): raise Exception('Only one entry per user') elif (len(entry) == 1): userEntry = entry[0] # If userEntry exists puts in string elements of each field # If it doesn't each get statement is '' and we pass in '' for each name-value pair name = userEntry.getName(), phone = userEntry.getPhone() email = userEntry.getEmail() description = userEntry.getDescription() city = userEntry.getCity() address = userEntry.getAddress() # each field is part of the user entry so it displays in the submit form markersData = getAll() #getting all the user info html = render_template('home.html', netid=netid, name=name, phone=phone, email=email, description=description, address=address, city=city, markersData=json.dumps(markersData)) response = make_response(html) return response
def inputAPIUsers(dbCursor, dbConnection): today = date.today() # Get today's date date_format = "%m/%d/%Y" todayDate = today.strftime(date_format) # Format date mm/dd/yyyy currentDate = datetime.strptime(todayDate, date_format) # Today's date as a string user_count = db.getNumUsers(dbCursor) student_accounts = API.createStudentAccounts() if student_accounts: for obj in student_accounts: # only create up to 10 accounts, don't recreate accounts if user_count < 10 and db.getUserByFullName( dbCursor, obj.first_name, obj.last_name) is None: db.insertUser(dbCursor, obj.username, obj.password, obj.first_name, obj.last_name, obj.plus_member, currentDate) db.insertUserSettings(dbCursor, obj.username, settings.emailNotif, settings.smsNotif, settings.targetAdvert, settings.language) db.insertProfilePage(dbCursor, obj.username, "", "", "") user_count += 1 dbConnection.commit()
def cadastrarUser(): body = request.get_json() if ("name" not in body): return getResponse(400, "name is required") if ("email" not in body): return getResponse(400, "email is required") if ("password" not in body): return getResponse(400, "password is required") user = insertUser(body["name"], body["email"], body["password"]) return getResponse(200, "Created user", "user", user)
def insert_user(): if not request.is_json: return jsonify(msg="Missing JSON in request"), 400 uname = request.json.get('username', None) passwd = request.json.get('password', None) level = request.json.get('level', None) if not uname or not passwd: return jsonify(msg="Missing UserName and Password"), 400 if not level: level = 1 if not insertUser(uname, passwd, level): return jsonify(msg="insert user failed"), 400 return jsonify(msg='insert user success'), 200
#import database.py from database import userExists, deleteUser, insertUser, getMainPage print('userExists("adducin")=' + str(userExists('adducin'))) print('userExists("test2")=' + str(userExists('test2'))) print('trying to delete user "test2"') deleteUser('test2') print('userExists("test2")=' + str(userExists('test2'))) print('trying to insert user "test2"') insertUser('test2', 'test2Pass', 'Test', '2', 'Test User 2 Desc', 'Hello World.pdf') print('userExists("test2")=' + str(userExists('test2'))) print('Database contents:') getMainPage()
socket_cliente.send(info.encode('utf-8')) # Envia resposta else: logado = True idUsuario = info2[0] info = ('\n========== Você está logado no BIRD ==========\n') socket_cliente.send(info.encode('utf-8')) print("Login Efetuado com Sucesso") #socket_cliente.send(info1.encode('utf-8')) # Envia mensagem #print(info1) #login = socket_cliente.recv(1024) #senha = socket_cliente.recv(1024) #print(type(login)) #print(senha) if '2' == valor[0]: # cadastrando usuario info2 = database.insertUser(valor[1], valor[2], valor[3], valor[4]) info = ("\n Dados cadastrados com sucesso\n") socket_cliente.send(info.encode('utf-8')) # Envia mensagem if '3' == valor[0]: # listar todos os usuarios info3 = str(database.listarUsuarios()) dic = str([info3]) socket_cliente.sendall(dic.encode()) #socket_cliente.send(info3.encode()) # Envia mensagem if '4' == valor[0]: # listar um usuario especifico info3 = str(database.listarUnicoUsuario( valor[1])) #valor[1] recebe o nome do usuario socket_cliente.send(info3.encode('utf-8')) # Envia mensagem #print(info3)
def createUser(dbCursor, connection): if db.getNumUsers( dbCursor ) >= constants.MAX_USER_ACCOUNTS: # checks if number of accounts in database is at max limit print( "All permitted accounts have been created, please come back later") settings.currentState = states.loggedOut # returns to main() w/ currentState = loggedOut return print( "Enter desired account credentials, or only press enter at any time to cancel account creation." ) uname = input("Enter your desired username: "******"": print("Account creation canceled.") settings.currentState = states.loggedOut return while db.getUserByName(dbCursor, uname): print("Sorry, that username has already been taken.") uname = input("Enter your desired username: "******"": print("Account creation canceled.") settings.currentState = states.loggedOut return pword = input("Enter your desired password: "******"": print("Account creation canceled.") settings.currentState = states.loggedOut return while not utils.validatePassword(pword): print( "Invalid password. Must be length 8-12 characters, contain one digit, one uppercase character, and one non-alphanumeric." ) pword = input("Enter your desired password: "******"": print("Account creation canceled.") settings.currentState = states.loggedOut return fname = input("Enter your first name: ") if fname == "": print("Account creation canceled.") settings.currentState = states.loggedOut return lname = input("Enter your last name: ") if lname == "": print("Account creation canceled.") settings.currentState = states.loggedOut return plusMember = input( "Sign up for InCollege-Plus membership? (Enter Y for Plus, N for Standard): " ) while True: if plusMember.upper() == "Y": plusMember = 1 break elif plusMember.upper() == "N": plusMember = 0 break else: print(constants.INVALID_INPUT) plusMember = input( "Sign up for InCollege-Plus membership? (Enter Y for Plus, N for Standard): " ) today = date.today() # Get today's date date_format = "%m/%d/%Y" todayDate = today.strftime(date_format) # Format date mm/dd/yyyy currentDate = datetime.strptime(todayDate, date_format) # Today's date as a string db.insertUser(dbCursor, uname, pword, fname, lname, plusMember, currentDate) db.insertUserSettings(dbCursor, uname, settings.emailNotif, settings.smsNotif, settings.targetAdvert, settings.language) db.insertProfilePage(dbCursor, uname, "", "", "") # add notification to let other users know a new student has joined other_users = db.getAllOtherUsers(dbCursor, uname) if len(other_users) > 0: for user in other_users: db.insertNotification(dbCursor, "new_student", fname + " " + lname, user[0]) connection.commit( ) # commits the new account and settings to the database (ensures account and settings are saved) API.outputUsers(dbCursor) API.outputProfiles(dbCursor) settings.currentState = states.loggedOut # returns to main() w/ currentState = loggedOut print("Account has been created.")