使用python对已编写的函数进行测试
一般格式为:
import unittest
from ModuleName import FunctionName
class testcase(unittest.TestCase):
def test_FunctionName(self):
var=FunctionName(INPUT)
self.assertEqual(var,OUTPUT)
unittest.main()
但是在实际的操作中(例为使用jupyter notebook的情况),却可能会出现这样的情况:
import unittest
def greet(name):
greeting=name+",hello"
return greeting
class testcase(unittest.TestCase):
def test_greet(self):
greetin=greet("java")
self.assertEqual(greetin,"java,hello")
unittest.main()
E
====================================================================== ERROR:
C:\Users\Administrator\AppData\Roaming\jupyter\runtime\kernel-8daecc65-9072-4330-a105-1d1794e47be6
(unittest.loader._FailedTest)
AttributeError: module ‘main’ has no attribute
‘C:\Users\Administrator\AppData\Roaming\jupyter\runtime\kernel-8daecc65-9072-4330-a105-1d1794e47be6’---------------------------------------------------------------------- Ran 1 test in 0.001s
FAILED (errors=1) An exception has occurred, use %tb to see the full
traceback.SystemExit: True
D:\1984096375\anaconda\lib\site-packages\IPython\core\interactiveshell.py:2969:
UserWarning: To exit: use ‘exit’, ‘quit’, or Ctrl-D. warn(“To exit:
use ‘exit’, ‘quit’, or Ctrl-D.”, stacklevel=1)
在查阅了资料之后发现这个测试方法适用于使用命令行模式对函数进行测试,使用命令行:
如图,显示的是正常的结果