我想将单元测试添加到我的高中编程课程的评估中。
如果我有二十份提交的文件看起来像这样:
def calculateReturn(principle, rate, freq, time):
final = principle * (1 + (rate/freq)) ** (freq * time)
return final
我可以使用这样的测试用例吗?
import unittest
class test(unittest.TestCase):
def test1(self):
value = calculateReturn(5000, 0.05, 12, 11)
self.assertAlmostEqual(value, 8235.05, 2)
if __name__ == '__main__':
unittest.main()
如何在20个模块上运行这个简单的测试?
更多信息
为了进行测试,我创建了三个"提交内容#34;所有这些都显示了计算x ^ y的不同方式。
submission1.py:
from math import pow
def powerFunction(base, power):
result = pow(base, power)
return result
submission2.py:
def powerFunction(base, power):
result = base ** power
return result
submission3.py:
def powerFunction(base, power):
result = 1
for i in range(power):
result = result * base
return result
测试代码是:
import unittest
import importlib
class MyTest(unittest.TestCase):
def setUp(self):
pass
def test_power_3_4(self):
self.assertEqual(module.powerFunction(2, 3), 8)
files = ['submission1', 'submission2', 'submission3']
for file in files:
module = importlib.import_module(file)
print module
unittest.main()
如果运行测试代码,则控制台输出仅显示正在测试的submission1:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
/Users/staff/PycharmProjects/UnitTest/powerTest.py
<module 'submission1' from '/Users/staff/PycharmProjects/UnitTest/
submission1.pyc'>
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Process finished with exit code 0
有趣的是,如果我不使用单元测试,我可以使用这种方法正确导入和测试:
import importlib
files = ['submission1', 'submission2', 'submission3']
for file in files:
module = importlib.import_module(file)
print module
print module.powerFunction(2,3)
这里的控制台输出是:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/
python2.7 /Users/staff/PycharmProjects/UnitTest/importlib1.py
<module 'submission1' from '/Users/staff/PycharmProjects/UnitTest/
submission1.pyc'>
8.0
<module 'submission2' from '/Users/staff/PycharmProjects/UnitTest/
submission2.pyc'>
8
<module 'submission3' from '/Users/staff/PycharmProjects/UnitTest/
submission3.pyc'>
8
Process finished with exit code 0
单元测试模块可能不是最好的方法,但我仍然对如何实现它感兴趣。