unit tests in python code example
Example 1: how to make a unit converter in python
num1 = input('Enter the value: ')
unit1 = input('Which unit do you want it converted from: ')
unit2 = input('Which unit do you want it converted to: ')
if unit1 == "cm" and unit2 == "m":
ans = float(num1)/100
print(ans)
elif unit1 == "mm" and unit2 == "cm":
ans = float(num1)/10
print(ans)
elif unit1 == "m" and unit2 == "cm":
ans = float(num1)*100
print(ans)
elif unit1 == "cm" and unit2 == "mm":
ans = float(num1)*10
print(ans)
elif unit1 == "mm" and unit2 == "m":
ans = float(num1)/1000
print(ans)
elif unit1 == "m" and unit2 == "mm":
ans = float(num1)*1000
print(ans)
elif unit1 == "km" and unit2 == "m":
ans = float(num1)*1000
print(ans)
elif unit1 == "m" and unit2 == "km":
ans = float(num1)/1000
print(ans)
elif unit1 == "mm" and unit2 == "km":
ans = float(num1)/1000000
print(ans)
elif unit1 == "ft" and unit2 == "cm":
ans = float(num1)*30.48
print(ans)
elif unit1 == "ft" and unit2 == "mm":
ans = float(num1)*304.8
print(ans)
elif unit1 == "ft" and unit2 == "inch":
ans = float(num1)*12
print(ans)
elif unit1 == "inch" and unit2 == "cm":
ans = float(num1)*2.54
elif unit1 == "inch" and unit2 == "mm":
ans = float(num1)*25.4
Example 2: format for unit test python
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
Example 3: python unittest setUpClass
class MyUnitTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
do_something_expensive_for_all_sets_of_tests()
class MyFirstSetOfTests(MyUnitTest):
@classmethod
def setUpClass(cls):
super(MyFirstSetOfTests, cls).setUpClass()
do_something_expensive_for_just_these_first_tests()
Example 4: python testing
>>> assert sum([1, 2, 3]) == 6, "Should be 6"
Example 5: self.assertequal python
'''
In other words, assertEquals is a function to check if two variables are equal, for purposes of automated testing:
'''
def assertEquals(var1, var2):
if var1 == var2:
return True
else:
return False