python - 当我在 python 代码中使用 argparse 时无法运行 nosetests

标签 python unit-testing parsing command-line nose

在我的主要代码中我有这个:

  #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

和我的测试文件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)
...

当我尝试运行 nosetests 来测试函数 afunc(...) 的结果时,我得到了这个错误:

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

如何解决这个问题?

最佳答案

好吧,我只是通过添加几行 if else 条件解决了这个问题。

这似乎是我的测试文件 (verify.py) 无法管理 comp.py 中解析器部分的赋值。所以,我只是在下面添加一些条件来分配 degkl 的值,以防 comp.py 不作为主函数运行。

#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

关于python - 当我在 python 代码中使用 argparse 时无法运行 nosetests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24397258/

相关文章:

python - libxml 解决 python 的 utf 编码问题还是我的问题?

python - 根据索引列表从numpy数组中获取和替换值

python - 在 Python 中还有哪些其他方法可以编写 if x==1 or x==5 or x==10...?

javascript - Angular - 提交时测试服务订阅

java - 从字符串(使用 Scanne.next() 从文件中获取)中修剪/删除不需要的简单值,以使用 Double.parseDouble() 解析 double

ios - 使用文件内容解析 NSData

python - Sendmail Errno[61] 连接被拒绝

Python:最好对数组的公共(public)元素使用字典或 HashMap

unit-testing - Tibco 单元测试工具

unit-testing - 使用Visual Studio Online构建服务器发现xUnit.net测试的异常