I'm student at QA and now I try to write a palindrome code in Python based on TDD and unittest.
I tried to write the code and it is functional but it doesn't work in according to assertTrue, also I checked assertEqual.
Python Code:
def PalindromTest(string):
return string == string[::-1]
while True:
stringul = input ("Enter a string or number:\n")
string = stringul.replace(" ", "").lower()
Test = PalindromTest(string)
if Test == True:
print (f'"{stringul} value is a palindrom"')
else:
print (f'"{stringul} value is not a palindrom"')
Test:
import unittest;
from Asignment_TDD import PalindromTest;
class MyPalindrome (unittest.TestCase):
def test_palindrome (self):
self.assertTrue (PalindromTest("civic"), "civic")
if __name__=='__main__':
unittest.main()
Help me please to write correct version of Unittest
Well, that code was clearly not written in TDD style :-)
A unit test needs to be automated, so neither the test nor the code under test should ask for input. (If the code under tests is poorly behaved and you cannot prevent it from asking, try to automatically feed it input. But this is probably too advanced yet.)
With that, I'd remove the
while True:loop asking for input, or move it elsewhere, or guard it with anif __name__=='__main__':check, like you have in the test case. That way it doesn't run just because some other programimports the code under test. You should probably always have thatif __name__=='__main__':unless you're writing a script that's not going to be reused elsewhere. Once you do that, your test runs and passes. I'd now add another test for a text that's not a palindrome and assert that the code correctly returnsFalse.Running:
Speaking of what I'd do: I'd also stick with Python naming conventions. It will make your code much easier to understand.