I have written code but would not understand how to write test cases in python for below program. Can someone provide an example test case?
Thanks in advance. I have tried some samples but I do not understand what parts of the code should be tested as it only pick the company name related with highest price.
with open('/home/company_data.csv') as f:
reader = csv.reader(f)
tup = namedtuple('tup', ['price','year', 'month'])
d = OrderedDict()
names = next(reader)[2:]
for name in names:
d[name] = tup(0,'year', 'month')
for row in reader:
year, month = row[:2]
for name, price in zip(names, map(int, row[2:])):
if d[name].price < price:
d[name] = tup(price, year, month)
Test cases prove the correctness of your functions. How do you test correctness? By "proving" it. You therefore write test cases against your functions with predefined output so you can verify that it returns the expected result.
Example : Using python's unittest module, you can write a test for a function that adds two numbers like this:
import unittest
def my_adding_function(x,y):
return x+y
class TestMyFunction(unittest.TestCase):
def setUp(self):
pass
def test_my_function(self):
self.assertEqual(my_adding_function(3,4), 7)
if __name__ == '__main__':
unittest.main()
What you are doing here is saying when I call my_adding_function on 3 & 4, I should get 7. If your function is correct, the test will pass - and fail if not.
For your case, if you want to pick the company name with the highest price from a sample csv, something like this would do:
import unittest
def get_highest_valued_company(input_csv):
process[...]
return 'highest company name'
class TestMyFunction(unittest.TestCase):
def setUp(self):
pass
def test_my_csv_function(self):
self.assertTrue(get_highest_valued_company(csv)=='name_here')
if __name__ == '__main__':
unittest.main()