Im trying to make a function that gives a word, reverses it then sees if it has correctly reversed it. If so it prints "TEST PASSED" but I cannot get the last part to work. the code is:
def back_it_up(any_word):
reverse = any_word[::-1]
print(any_word)
print(reverse)
test = reverse[::-1]
if any_word == test:
return True
else:
return False
def test_back_it_up():
print("")
print("Back It Up Unit Test...")
print("")
if back_it_up("book") == "koob":
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("college") == "egelloc":
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("dog") == "god":
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("code") == "edoc":
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("") == "Empty String":
print("TEST PASSED")
else:
print("TEST FAILED")
There are a couple of issues with your code...
First, the reverse function is not returning a string but a boolean. This will make your unit test to fail since you're trying to check if the return value is the reversed string. A simple solution for this is changing the function to:
def back_it_up(any_word: str) -> str:
reverse = any_word[::-1]
print(any_word)
print(reverse)
return reverse
Second, this change will solve all the testing cases but the last one. This happen because you're trying to compare an empty string ""
with a string that have contents "Empty String"
. This can be solved in one of two ways:
"Empty String"
by ""
on the test suite.Simply replace all the lines that say == 'string'
to == True
. After doing this your code ran successfully.
def back_it_up(any_word):
reverse = any_word[::-1]
print(any_word)
print(reverse)
test = reverse[::-1]
if any_word == test:
return True
else:
return False
def test_back_it_up():
print("")
print("Back It Up Unit Test...")
print("")
if back_it_up("book") == True:
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("college") == True:
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("dog") == True:
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("code") == True:
print("TEST PASSED")
else:
print("TEST FAILED")
if back_it_up("") == True:
print("TEST PASSED")
else:
print("TEST FAILED")
test_back_it_up()
Note: I did not fully understand what if back_it_up("") == "Empty String":
meant, so I just set it to True
as well. Make an edit if you need. Output:
Back It Up Unit Test...
book
koob
TEST PASSED
college
egelloc
TEST PASSED
dog
god
TEST PASSED
code
edoc
TEST PASSED
TEST PASSED
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.