I am new to python..
In my test function I am passing some text data which considers "invalid password".
In such case I return Data_Check as "invalid password" but now client as asked if "invalid password" is more than once in data variable then only return "INVALID PASSWORD" otherwise it should return "VALID" itself.
please tell me in below function what changes can be done.
def test(data):
Data_Check = 'VALID'
if (data.lower()).find('invalid password') >= 1:
Data_Check = 'INVALID PASSWORD'
return Data_Check
s.find(t) will tell you the position of t in s, not how often t occurs in s.
Your want http://docs.python.org/library/stdtypes.html#str.count
if data.lower().count('invalid password') > 1:
# do something
Improvement on your solution:
if data.lower().count('invalid password') > 1:
return 'INVALID PASSWORD'
return 'VALID'
One-liner solution:
return 'VALID' if data.lower().count('invalid password') <= 1 else 'INVALID PASSWORD'
And on a side note, you should separate your if's "do something" block onto a new line.
Related
I'm new to Selenium /Python, I have Login validation. when user try to login, if password is Invalid or expired it will display 2 error message with different location. data is coming from excel with for loop. (Data driven framework).
If login password is expired it is working fine. the its moving to next, if password is invalid still its checking password expired condition only and exist the loop and give 'error'. It's not going through elif or else.
print("Login Pass")
else:
time.sleep(5)
try:
if (self.driver.find_element_by_xpath(
self.lp.textbox_ConfirmPassword_xpath).is_displayed() == True) \
or (self.lp.verifyInvalidPasswordIsDisplay() == "Invalid username or password"):
if self.driver.find_element_by_xpath(self.lp.textbox_ConfirmPassword_xpath).is_displayed():
self.driver.find_element_by_xpath(self.lp.textbox_ConfirmPassword_xpath).click()
print("expired")
XLUtils.writeData(self.path, 'Sheet2', r, 6, 'Expired password')
elif self.lp.verifyInvalidPasswordIsDisplay() == "Invalid username or password":
print("invalid")
XLUtils.writeData(self.path, 'Sheet2', r, 3, 'Invalid username or password')
else:
XLUtils.writeData(self.path, 'Sheet2', r, 4, 'Error')
else:
print("error")
except NoSuchElementException:
XLUtils.writeData(self.path, 'Sheet2', r, 4, 'Error')
print(self.user)
print("login fail")
self.driver.close()
If it's not going through elif self.lp.verifyInvalidPasswordIsDisplay() == "Invalid username or password":
nor the else, is because in all conditions, the first nested if (the one statement which only checks the self.driver.find_element_by_xpath(self.lp.textbox_ConfirmPassword_xpath).is_displayed()) is True and it won't go through other elif nor else statements.
The first if (which contains the if-elif-else statements) ,has a condition like this:
self.driver.find_element_by_xpath(
self.lp.textbox_ConfirmPassword_xpath).is_displayed() == True
However it is followed by the other condition with or but it seems in all situations the textbox_ConfirmPassword_xpath is True.
Since this condition is exactly repeated in the first nested if, and therefore the condition of this if statement is always True and it won't let other conditions to be checked.
First of all, in my opinion the first if is not necessary and you could just do the work without it, like this:
print("Login Pass")
else:
time.sleep(5)
try:
if self.driver.find_element_by_xpath(self.lp.textbox_ConfirmPassword_xpath).is_displayed():
self.driver.find_element_by_xpath(self.lp.textbox_ConfirmPassword_xpath).click()
print("expired")
XLUtils.writeData(self.path, 'Sheet2', r, 6, 'Expired password')
elif self.lp.verifyInvalidPasswordIsDisplay() == "Invalid username or password":
print("invalid")
XLUtils.writeData(self.path, 'Sheet2', r, 3, 'Invalid username or password')
else:
XLUtils.writeData(self.path, 'Sheet2', r, 4, 'Error')
print('error')
except NoSuchElementException:
XLUtils.writeData(self.path, 'Sheet2', r, 4, 'Error')
print(self.user)
print("login fail")
self.driver.close()
Secondly, you should choose a better condition for the first if instead of self.driver.find_element_by_xpath(self.lp.textbox_ConfirmPassword_xpath).is_displayed(), since as I said before, apparently in all cases this condition is True.
Moreover, I suggest to use Constants to check the equality of error messages, for example:
Instead of "Invalid username or password" string, do this:
INVALID_USERNAME_PASS = "Invalid username or password"
.
.
.
self.lp.verifyInvalidPasswordIsDisplay() == INVALID_USERNAME_PASS:
# DO STUFF
Because, in this way it's more maintainable and it's not hard coded any more.
database=[['username1','password1'],['username2','password2']]
def check_match():
check_username()
check_password()
for pair in database:
if check_username==pair[0]:
if check_password==pair[1]:
print('login succesful!')
return
else:
print('login failed')
return
This is the code I have currently to check if index 0 of a list matches index 1 of the same list, It's not working though. check_username() and check_password() hold the contents of a list based on user input.
I realized I called the incorrect functions in the given function, that's my bad, thanks for the help though!
Here is a simple answer. You can modify it accordingly but i made it to satisfy the basic needs;
database=[['username1','password1'],['username2','password2']]
username = 'username1'
password = 'password2'
def login(username, password):
for i in range(len(database)):
if username == database[i][0] and password == database[i][1]:
print("login successfull")
return
print("invalid credentials")
login(username, password)
username and password can be taken from the user.
This is a really newbie question.
So, I am trying to code a login system in Python, where it asks for an username (only 1 username available), if the username typed in is incorrect, it says the username is invalid, if it is correct, it asks for a password, if the password is incorrect, it says incorrect password and proceeds to ask for the password once again, and if the password typed in is correct, it just says logged in.
What I've been able to do so far is:
a = 0
while a < 1:
print ('Username:')
name = input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
a = a + 1
password = input()
b = 0
while b < 1:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
b = b + 1
continue
else:
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
break
This works, although it does something I don't want if the user types in the incorrect password. If the user types in the incorrect password, I wanted the program to tell the user 'Incorrect password' and proceed to ask for it once again, but it doesn't do that, it just prints 'Incorrect password', and then it terminates. It works 100% on the part where it asks for the username, though.
It's a little thing I am missing. How can I fix this?
Thanks a lot!
The statement b = b + 1 is terminating your while loop every time the user enters an incorrect password. There is really no need for it.
You can alternatively just wrap your password prompt in a while loop:
while input("Enter password") != "1234":
print("Password incorrect")
There is no need for the + 1 when checking for the password. That just breaks you out of the loop.
Instead, try:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
continue
A much better solution, instead of using +1 and <1 to break out of loops is to use booleans.
Sample:
userCorrect = False
while not userCorrect:
print ('Username:')
name = raw_input()
if name != 'Teodor': #checks the username typed in
print ('Invalid username.')
continue
else:
print ('Hello, Teodor.')
print ('Password:')
userCorrect = True
password = raw_input()
passCorrect = False
while not passCorrect:
if password != '1234': #checks the password typed in
print ('Password incorrect.')
print ('Password:')
password = raw_input()
else:
passCorrect = True
# Since password is correct, continue.
print ('Password correct.')
print ('Logging in...')
print ('Logged in.')
This loop (while b < 1:) terminates the moment an invalid password is entered.
Look at
> if password != '1234': #checks the password typed in
> print ('Password incorrect.')
> b = b + 1
> continue
The line of code b = b + 1 makes it such that while b < 1: becomes false, thus ending the loop and terminating your program.
As others have already pointed out, the problem lies is b = b + 1 breaking the condition while b < 1:, causing it not to ask for another password. Simple delete the line b = b + 1
Want to make it better?
Avoid the 'over-the-shoulder' attack with getpass() instead of input(). Your password input is masked as ****
ex.
from getpass import getpass
password = getpass()
Cryptify
Well, apart from sounding cool, this doesn't really stop somebody from modifying the code to skip past the password phase -but it can stop them from seeing the raw password in the code.
this post has a good example using passlib
This helps protect non-unique/sensitive passwords (like the password you use for 5x other things, or your mother's maiden name... lets not drag her into this)
Can you tell me the input so that the check statement is passed along with the try..except of the input pin
#!/usr/bin/python
# Secure Pin system
import sys
users = {'admin': '<REDACTED>'}
def register(username, password):
if username in users:
return "User already exits."
users[username] = password
return "Registered Successfully."
def login(username, password):
if username not in users:
return "Wrong pin/password"
if password != users[username]:
return "Wrong pin/password"
if username == "admin":
return "The FLAG is what you entered in the \"Pin\" field to get here!"
return "You must login as admin to get the flag"
def handle_command(command):
if command not in ["REG", "LOGIN"]:
return "Invalid Command!"
print "Username:",
sys.stdout.flush()
username = raw_input()
try:
print "Pin ([0-9]+):",
sys.stdout.flush()
password = input() # we only support numbers in password
except:
return "Please enter a valid password. Pin can only contain digits."
if command == 'REG':
return register(username, password)
if command == 'LOGIN':
return login(username, password)
if __name__=="__main__":
print "Hey welcome to the admin panel"
print "Commands: REG, LOGIN"
try:
print ">",
sys.stdout.flush()
command = raw_input()
print handle_command(command)
sys.stdout.flush()
except:
pass
The code is all right but the only thing is to bypass the input check
There is a bug that is to be identified
If you want to check whether the input from user only has numbers, then you can use the method - str.isnumeric() , to check whether the string only contains numbers.
Example -
>>> "123".isnumeric()
True
>>> "123.21".isnumeric()
False
>>> "abcd".isnumeric()
False
You can do this check instead of a try/except block (since you do not really use the password as a number after this block).
To ensure the user enters a number, you could convert the script to use a function as follows:
def get_input_number(prompt):
while True:
try:
user_num = int(raw_input(prompt))
return user_num
except ValueError:
print "Please enter a valid password. Pin can only contain digits."
password = get_input_number("Pin ([0-9]+): ")
This would then keep prompting until a number is entered.
If I first enter data that is valid it works fine, but if I enter invalid data, then valid data, None is returned. Here is an example of the problem:
code:
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
enterPasswords()
else:
return True
def passwordMatch(password, password2):
if password != password2:
print("Error from server: Your passwords don't match.")
enterPasswords()
else:
return True
def enterPasswords():
password = input("Message from server: Please enter your desired password: ")
if passwordLength(password):
password2 = input("Message from server: Please re-enter your password: ")
print(password, password2)
if passwordMatch(password, password2):
print(password)
return password
password = enterPasswords()
print(password)
Your problem is that you are not using recursion properly. Take the example of non-matching passwords: hello and hello1.
Your function will be fine until if passwordMatch(password, password2):. At this point, passwordMatch returns None. That is because in passwordMatch you do not say return enterPasswords(), so the return value defaults to None, NOT the return value of the new call to enterPasswords.
if password != password2:
print("Error from server: Your passwords don't match.")
enterPasswords() # Doesn't return anything, so it defaults to None
If you were to use the function like so then you wouldn't have an issue.
def passwordMatch(password, password2):
if password != password2:
print("Error from server: Your passwords don't match.")
return enterPasswords()
else:
return True
Please notice that you have the same problem in passwordLength.
So what happens is that if you first enter invalid data (let's say an invalid password length), you call enterPasswords() again from the passwordLength() function. That prompts you for another password. This time you enter valid input. You get down to where you should return the password, and you return it. The problem is, on the stack, you are returning to where you called enterPasswords() from the passwordLength() function. That is where you are returning the valid password to. It doesn't do anything with it, execution is returned to the original call to enterPasswords() (where the input was invalid) and you're going to return None from there.
A visualization:
enterPasswords() called
prompted for input, give string of length 3
passwordLength(password) called
Invalid string length, print an error and then call enterPasswords()
prompted for input, give valid string
passwordLength(password) called
valid length, return true
prompted for input for second password
passwordMatch(password, password2) called
passwords match, return True
print password
return password to the first passwordLength() call
nothing else to do here, pop the stack and return to the first enterPasswords()
nothing else to do here, pop the stack
print(password), but password is None here