Python Selenium verify record is deleted - python

I have this code in python and selenium to find the deleted records and verify that the record is deleted.
def find_deleted_device(self, mac, serialno):
index = 0
loopNext = True
matched = False
while loopNext:
index = 0
if not element_locator.find_elements_by_css(driver_obj, self.no_device):
record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)
for facility_mac, serialnumber in zip(macaarray, serialnum):
if facility_mac.text == mac and serialnumber.text == serialno:
loopNext = False
matched = True
break
elif index == len(record) - 1:
if index >= 19:
next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
if next_page.is_enabled():
next_page.click()
else:
loopNext = False
index = index + 1
else:
loopNext = False
else:
print('No matching macaddress and serial number, No device message appears')
assert True
loopNext = False
if matched:
print "The mac and serial number matched, should have been deleted"
assert False
else:
print('No matching macaddress and serial number found')
assert True
sleep(2)
But the problem is there are two scenarios:
1) If only one record exists and we delete that then I get a message "No Records exist"
2) second scenario is a few records exists and I can loop through and verify that the record is deleted.
In case of scenario 1, it works fine.
In case of scenario 2 , it passes but with an error something like "1496424768.39". How do I escape this error.

I fixed my issue using the following alternative approach.
#This method is used to search deleted group
def find_deleted_device_with_paging(self, mac, serialno):
page_num = element_locator.find_element_by_css(driver_obj, ".test-grid-pagination-summary")
if page_num.text < 1:
print('No matching macaddress and serial number found')
assert True
else:
index = 0
loopNext = True
matched = False
print "The mac and serial number matched, should have been deleted"
while loopNext:
index = 0
record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)
for facility_mac, serialnumber in zip(macaarray, serialnum):
if facility_mac.text == mac and serialnumber.text == serialno:
loopNext = False
matched = True
break
elif index == len(record) - 1:
if index >= 19:
next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
if next_page.is_enabled():
next_page.click()
else:
loopNext = False
index = index + 1
else:
loopNext = False
if matched:
print "The mac and serial number matched, should have been deleted"
assert False
else:
print('No matching macaddress and serial number found')
assert True
So, Instead of verifying the message ,I am comparing the number of records that exist on that page for pagination purpose. This fixed my code.

Related

Why am I not getting four unique numbers returned?

I am trying to create a function that returns a 4 digit string which consists of 4 unique values.
I currently have the following code:
def generateNum():
ValidNum = False
while ValidNum == False:
RanNumber = random.randint(1000, 9999)
RanNumber = str(RanNumber)
for number in RanNumber:
if RanNumber.count(number) > 1:
ValidNum = False
else:
ValidNum = True
return RanNumber
print(generateNum())
Can someone explain what is wrong with this piece of code and what I can potentially do to fix it?
Thank you.
Following your logic, this is what would have worked:
def generateNum():
ValidNum = False
while True:
RanNumber = random.randint(1000, 9999)
RanNumber = str(RanNumber)
for number in RanNumber:
if RanNumber.count(number) == 1:
ValidNum = True
continue
else:
ValidNum = False
break
if not ValidNum:
continue
break
return RanNumber
import random
def generate_random():
num = ''
while len(num) < 4:
random_int = random.randint(0,9)
if str(random_int) in num:
pass
else:
num += str(random_int)
return num
print(generate_random())
This should work fine

CS50P PSETS 2, Vanity plates

I'm having some issues with the psets 2 of cs50p, precisely I'm talking about the "Vanity Plates" problem, where I fulfilled all requests except one, which said:
“Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.” Can you help me? Thank's
this is the code I wrote so far:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s.isalnum() | s[:2].isalpha() | 2 < len(s) < 6 | :
else:
return False
main()
you have to consider all the cases one by one, this is how I solved it:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if len(s) < 2 or len(s) > 6:
return False
elif not s[0].isalpha() or not s[1].isalpha():
return False
elif checkFirstZero(s):
return False
elif checkMiddleZero(s):
return False
elif last(s):
return False
elif worng(s):
return False
return True
def last(s):
isAlp = False
isNum = False
for w in s:
if not w.isalpha():
isNum = True
else:
if isNum:
return True
return False
def checkCuntuNNumber(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
def checkMiddleZero(s):
isFirstTry = True
isNum = False
for w in s:
if not w.isalpha():
if isFirstTry:
isNum = True
isFirstTry = False
if isNum and s[-1].isalpha():
return True
else:
return False
def checkFirstZero(s):
for w in s:
if not w.isalpha():
if int(w) == 0:
return True
else:
return False
def worng(s):
for w in s:
if w in [" ", ".", ","]:
return True
return False
main()
This is how I did it. I am sure there is an easier way to do it out there but hopefully this helps :)
characters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
numbers = ['1','2','3','4','5','6','7','8','9','0']
def main ():
plate = (input ("Plate: ")).upper()
if is_valid(plate):
print ('Valid')
else:
print ('Invalid')
def is_valid (s):
#Check whether length is between 2 and 6 included
if len(s) < 2 or len(s) > 6:
return False
elif char_check(s):
return False
elif char_start(s):
return False
elif zero_check(s):
return False
elif alpha_follow_check (s):
return False
else:
return True
#Check for valid characters
def char_check(s):
for i in s:
if not (i in characters or i in numbers):
return True
#Check whether first two are letters
def char_start (s):
for i in s[:2]:
if not i in characters:
return True
#Check if zero is first number listed
def zero_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_present = 0
zero_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i == '0':
zero_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [0:zero_position]:
if i in numbers:
number_present = 1
if number_present == 0:
return True
else:
return False
#Check alphabet follows numbers
def alpha_follow_check (plate_response):
length_string = len (plate_response)
letter_position = 0
number_position = None
if any (i in numbers for i in plate_response):
for i in plate_response [0:length_string]:
if i in numbers:
number_position = letter_position
break
letter_position = letter_position + 1
for i in plate_response [number_position:length_string]:
if i in characters:
return True
else:
return False
main ()
idk if will help, but the part that i've had the most difficulty in this problem was: "Numbers cannot be used in the middle of a plate; they must come at the end, AAA22A would not be acceptable", then i learned that you can create a full list from the plate that the user inputed, and how to actually use it, with the:
ls = list(s)
for i in range(len(ls)):
After that, we check when the first number appears. "if == '0'" ,then returns False to the function.
After that, if the first number isn't a 0, the program checks if the next item in that list is letter, and, if it is, also return False.
i < len(ls) -1 => this part guarantee that the program will not run in the last item of the list
ls[i+1].isalpha() => and this part check that, if the item on the list was a number, and then the next item is a letter, it returns False
I hope it helps someone, i've spend a lot of time trying to figure it out what to do, and then reached this solution: "for i in range(len(ls))".
Now my code is complete and working.
My code:
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if not s.isalnum():
return False
elif len(s) < 4 or len(s) > 7:
return False
elif s[0].isdigit()or s[1].isdigit():
return False
elif s[-1].isalpha() or s[-2].isalpha():
return False
else:
ls = list(s)
for i in range(len(ls)):
if ls[i].isdigit():
if ls[i] == '0':
return False
elif i < len(ls) -1 and ls[i+1].isalpha():
return False
else:
return True
main()

Binary Search to search a list

I have a code which first sorts the emails into alphabetical order and then attempts to use binary search to search a user inputted email from a list. However, I have been stuck on how to do this for so long and haven't found any solutions on the error I get and how to fix it. Here is my code
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,ItemSought):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint] == ItemSought:
ItemFound = True
print("Item Found")
break
elif logindata[Midpoint] > ItemSought:
Last = Midpoint - 1
else:
First = Midpoint + 1
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
ItemSought=input("Enter username")
BinarySearch(logindata,ItemSought)
The error I currently get is :
elif logindata[Midpoint] > ItemSought:
TypeError: unorderable types: list() > str()
You're comparing a username/password pair (e.g. ["tom#gmail.com","Password1"]) with a username (e.g. "tom#gmail.com").
You need to extract the username from logindata[Midpoint] before comparing it to ItemSought.

returning to the start of a while loop in a binary search

I have a binary search to search a list of emails from a user input. However when the user inputted email isnt found in the list I want the user to be able to enter another time. However I dont know how to return it to the start of the while loop again.
Here is my Code:
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,email):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint][0] == email:
ItemFound = True
print("Email Found")
break
elif logindata[Midpoint][0] > email:
Last = Midpoint - 1
print("Not Found")
else:
First = Midpoint + 1
print("Not Found")
return False
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
email=input("Enter username")
BinarySearch(logindata,email)
Just add the part you need to repeat in another while loop:
email=input("Enter username")
BinarySearch(logindata,email)
to:
while True:
email=input("Enter username")
res = BinarySearch(logindata,email)
if res:
break
print("Done")
and work with the return value of your BinarySearch function.
You also need to change the implementation of BinarySearch to return the appropriate values. Also, your condition is faulty, binary searching is ends when First <= Last, you can drop the other flags you're using:
def BinarySearch(logindata,email):
First=0
Last=len(logindata)-1
while First <= Last:
Midpoint = (First + Last) // 2
if logindata[Midpoint][0] == email:
print("Email Found")
return True
elif logindata[Midpoint][0] > email:
Last = Midpoint - 1
else:
First = Midpoint + 1
print("Not found")
return False
You shouldn't be printing Not Found whenever one of the else clause is executed, it hasn't been found yet since the search hasn't rerminated. Print that out in the end, after the while loop of BinarySearch has been exited.

Help! Key error in python

I keep getting this error:
MultiValueDictKeyError at /search/
"Key 'name' not found in <'QueryDict: {}>"
I just started learning programming two days ago, so can someone explain in layman's terms why there's a problem and how to solve it. Thanks!
Here is the section of programming:
def NameAndOrCity(request):
NoEntry = False
if 'name' in request.GET and request.GET['name']:
name = request.GET['name']
if len(Business.objects.filter(name__icontains=name)) > 0:
ByName = Business.objects.filter(name__icontains=name)
q = set(ByName)
del ByName
ByName = q
if 'city' in request.GET and request.GET['city']:
city = request.GET['city']
if len(Business.objects.filter(city__icontains=city)) > 0:
ByCity = Business.objects.filter(city__contains=city)
p = set(ByCity)
del ByCity
ByCity = p
if len(q) > 0 and len(p) > 0:
NameXCity = q & p
return render_to_response('search_results.html', {'businesses':NameXCity, 'query':name})
if len(q) > 0 and len(p) < 1:
return render_to_response('search_results.html', {'businesses':ByName, 'query':name})
if len(p) > 0 and len(q) < 1:
return render_to_response('search_results.html', {'businesses':ByCity, 'query':city})
else:
NoResults = True
return render_to_response('search_form.html', {'NoResults': NoResults})
else:
name = request.GET['name']
city = request.GET['city']
if len(name) < 1 and len(city) < 1:
NoEntry = True
return render_to_response('search_form.html', {'NoEntry': NoEntry})
EDIT
1) Business.object is my database of businesses. They are objects with attributes like name, city, etc. I'm trying to make a program that will search the businesses by their attribute(s)
2) not a duplicate post
3) how do I check to see if those keys exist before I try to use them?
It looks like the only place you could be getting this error is on this line:
name = request.GET['name']
You haven't checked if 'name' is in the request.GET dictionary before trying to access it like you did above so you will get a key error if that key doesn't exist in request.GET.
So it looks like you need to change the following section to check if the 'name' and 'city' keys exist in your request.GET dictionary before you try accessing the values:
name = request.GET['name']
city = request.GET['city']
if len(name) < 1 and len(city) < 1:
NoEntry = True
return render_to_response('search_form.html', {'NoEntry': NoEntry})

Categories

Resources