mardi 5 juillet 2016

Python: how to unittest a class that reads a command line arg?

I want to write unit tests for a Python script. The script itself runs correctly.

The script consists of one class, which reads a value from the command line into a class variable.

When I import the class into my test file, I get the error 'list index out of range' at the point where the class reads from sys.argv[].

I'm new to testing, in Python and in general. I've read a lot of doc and SO pages about this over the last couple of days.

Here's the code:

File bongo.py --

import sys

class Bongo:

    my_int = int(sys.argv[1])

    def __init__(self, n):
        self.n = n

    def get_sum(self):
        return self.n + Bongo.my_int

if __name__ == '__main__':
    bongo = Bongo(5)
    m = bongo.get_sum()
    print('bongo.get_sum() returns {}'.format(m))

File bongo_test.py --

import unittest
from bongo import Bongo

class TestBongoMethods(unittest.TestCase):

    def setUp(self):
        self.bongo = Bongo(10)
        self.bongo.my_int = 5

    def test_get_n(self):
        self.assertEqual(self.bongo.get_sum(), 15)

if __name__ == '__main__':
    unittest.main()

The output of running python bongo_test.py is

Traceback (most recent call last):
  File "bongo_test.py", line 2, in <module>
    from bongo import Bongo
  File "/home/me/class_for_testing/bongo.py", line 4, in <module>
    class Bongo:
  File "/home/me/class_for_testing/bongo.py", line 6, in Bongo
    my_int = int(sys.argv[1])
IndexError: list index out of range

I've tried just about everything I can think of; I've been using Py 2.7 in PyCharm Pro 2016.1, but the results are no different using Py 3.4 or running from the command line.

Can this be done using unittest? Or do I need something else?

Any help would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire