Search code examples
pythonunit-testingparsingcommand-linenose

Can not run nosetests when i use argparse in my python code


In my main code I have this:

  #comp.py
  parser = ArgumentParser()
  parser.add_argument("-n", dest="deg", default=100,type=int, help="setup value of deg")
  parser.add_argument("-k", dest="k", default=25, type=float, help="setup value of k")
  parser.add_argument("-l", dest="l", default=0, type=int, help="setup value of l")
  args = parser.parse_args()

  def afunc(x):
      ...
      #do something with k, l, deg and the return the result
      ...
      return result

and my testing file verify.py:

  #verify.py
  import unittest
  import comp
  class TestFuncs(unittest.TestCase):
      def test_afunc(self):
          self.assertEqual(afunc(0), 0)
          self.assertEqual(afunc(1), 0)
          self.assertEqual(afunc(1), 1)
          self.assertEqual(afunc(3.2), 1)
...

And when I tried to run nosetests for testing results of function afunc(...), I got this error:

machine:project user$ nosetests verify
usage: nosetests [-h] [-n DEG] [-k K] [-l L]
nosetests: error: unrecognized arguments: verify

How to solve this problem?


Solution

  • Ok, I just solved the problem by adding a few lines of if else condition.

    It seems to be my test file (verify.py) can not manage value assignment on the parser section in comp.py. So, I just add some condition below to assign the values of deg, k, l in case that comp.py doesn't run as a main function.

    #comp.py
    if __name__ == "__main__":
        parser = ArgumentParser()
        parser.add_argument("-n", dest="deg", default=100,type=int, help="setup value of deg")
        parser.add_argument("-k", dest="k", default=25, type=float, help="setup value of k")
        parser.add_argument("-l", dest="l", default=0, type=int, help="setup value of l")
        args = parser.parse_args()
    else:
        deg=100
        k=25
        l=0
    
    def afunc(x):
        ...
        #do something with k, l, deg and the return the result
        ...
        return result