EE308_LAB11
| The Link Your Class | https://bbs.csdn.net/forums/MUEE308FZ |
|---|---|
| The Link of Requirement of This Assignment | https://bbs.csdn.net/topics/603748107 |
| The Aim of This Assignment | Unittest for python |
| MU STU ID and FZU STU ID | 19103832_831901226 |
Aim
This aim is ain to be familiar with Junit Test or Unittest and the usage of these tools.Such as ‘assert, suite, timeout’, check problems for detail. I choose python with the toolbox called unittest which is already inside python.
Task
1. unittest assert test
import unittest,random
# Test Class
class MyClass(object):
@classmethod
def sum(self, a, b):
return a + b
@classmethod
def div(self, a, b):
return a / b
@classmethod
def retrun_None(self):
return None
# Unit Test Class
class MyTest (unittest.TestCase):
# assertEqual()
def test_assertEqual(self):
# test if a+b equals sum or not
try:
a, b = 1, 2
sum = 3
self.assertEqual(a + b, sum, 'assert failed!,%s + %s != %s' %(a, b, sum))
except AssertionError as e:
print (e)
# assertNotEqual()
def test_assertNotEqual(self):
# test if b-a equals res or not
try:
a, b = 4, 2
res = 2
self.assertEqual(b - a, res, 'assert failed!,%s - %s != %s' %(a, b, res))
except AssertionError as e:
print (e)
# assertTrue()
def test_assertTrue(self):
try:
self.assertTrue(1 == 1, "False expression")
except AssertionError as e:
print (e)
# assertFalse()
def test_assertFalse(self):
# fix missing codes below ‘try’, only a line of codes needed
try:
self.assertFalse(1 != 1, "False expression")
except AssertionError as e:
print (e)
# assertIs()
def test_assertIs(self):
# test a and b are totally same
try:
a = 12
b = a
self.assertIs(a, b, "%s and %s are not same" %(a, b))
except AssertionError as e:
print (e)
# assertIsInstance()
def test_assertIsInstance(self):
# fix missing codes below ‘y=object’ to test type(x) != y, only a line of codes needed
try:
x = MyClass
y = object
self.assertIsInstance(y, x, "False expression")
except AssertionError as e:
print (e)
if __name__ == '__main__':
# run unittest
unittest.main()
2. unittest test groups
Calc.py
class Calc(object):
def add(self, *d):
#
result = 0
for i in d:
result += i
return result
def mul(self, *d):
#
result = 1
for i in d:
result = result * i
return result
def sub(self, a, *d):
#
result = a
for i in d:
result = result - i
return result
def div(self, a, *d):
#
result = a
for i in d:
result = result / i
return result
TestCalc.py
import unittest
import random
from Calc import Calc
class TestCalcFunctions(unittest.TestCase):
def setUp(self):
self.c = Calc()
print("setup completed!")
def test_sum(self):
self.assertTrue(self.c.add(1, 2, 3, 4) == 10)
def test_sub(self):
self.assertTrue(self.c.sub(9, 5) == 4)
# fix a line of codes to test c.sub(self, a, *b) method
def test_mul(self):
self.assertTrue(self.c.mul(2, 4) == 8)
# fix a line of codes to test c.mul(self, *b) method
def test_div(self):
self.assertTrue(self.c.div(4, 2) == 2)
# fix a line of codes to test c.div(self, a, *b) method
def tearDown(self):
print("test completed!")
def tearDown(self):
print("tearDown completed")
if __name__ == '__main__':
unittest.main()
unittest_suite.py
import random
import unittest
from TestCalc import TestCalcFunctions
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = list(range(10))
def tearDown(self):
pass
def test_choice(self):
# chose an element from seq randomly
element = random.choice(self.seq)
# check element is truly in the sequence
self.assertTrue(element in self.seq)
def test_sample(self):
# if codes raise exception
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
class TestDictValueFormatFunctions(unittest.TestCase):
def setUp(self):
self.seq = list(range(10))
def tearDown(self):
pass
def test_shuffle(self):
# shuffle sequence
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, list(range(10)))
# check TypeError exception
self.assertRaises(TypeError, random.shuffle, (1, 2, 3))
if __name__ == '__main__':
# get all test methods start with ‘test’ and return a suite
suite1 = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
# please fix another two suite, suite2 of TestCalcFunctions and suite3 of TestDictValueFormatFunctions
suite2 = unittest.TestLoader().loadTestsFromTestCase(TestCalcFunctions)
suite3 = unittest.TestLoader().loadTestsFromTestCase(TestDictValueFormatFunctions)
# put more test class into suite
# you can change suites’ order, like [suite1, suite2, suite3]
suite = unittest.TestSuite([suite2, suite1,suite3])
# set verbosity = 2 you could get more detailed information
unittest.TextTestRunner(verbosity = 2).run(suite)
3.unittest skip test
#encoding=utf-8
import random,sys,unittest
class TestSeqFunctions(unittest.TestCase):
a = 1
def setUp(self):
self.seq = list(range(20))
@unittest.skip("skipping") # skip this method anyway
def test_shuffle(self):
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq,list(range(20)))
self.assertRaises(TypeError,random.shuffle,(1,2,3))
@unittest.skipIf(a > 5, "skipping") # skip this method anyway
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
@unittest.skipUnless(sys.platform.startswith("linux"))# add a line of annotation that skip if not in linux platform
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__=="__main__":
# unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(TestSeqFunctions)
suite = unittest.TestSuite(suite)
unittest.TextTestRunner(verbosity = 2).run(suite)
4.unittest Run test under numerical order or alpha order
# encoding=utf-8
import unittest
from Calc import Calc
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(self):
print("init Calc before unittest")
self.c = Calc()
# rename the four methods bellow, make sure print queue will be :
# P.S.: test case must starts with ‘test’
def test_add(self):
print("run add()")
self.assertEqual(self.c.add(1, 2, 3), 7, 'test add fail')
def test_sub(self):
print("run sub()")
self.assertEqual(self.c.sub(2, 1, 2), -1, 'test sub fail')
def test_mul(self):
print("run mul()")
self.assertEqual(Calc.mul(1, 2, 3, 4), 24, 'test mul fail')
def test_div(self):
print("run div()")
self.assertEqual(Calc.div(1, 8, 2, 4), 1, 'test div fail')
if __name__ == '__main__':
unittest.main()
5.unittest Time Test
import time, unittest, sys, time
import timeout_decorator
class timeoutTest(unittest.TestCase):
# set a time decorator(annotation) which will be triggered after 5s’ running
@timeout_decorator.timeout(5)
def testtimeout(self):
print("Start")
for i in range(1, 10):
time.sleep(1)
print("%d seconds have passed" % i)
if __name__ == "__main__":
unittest.main()
Conclusion
In this lab I learned how to test Python code. Unit test can save a lot of time for us, it is very useful for use to test in our projects.
相关推荐
EE-308 LAB4 final version.7z
这是本次实验的压缩包
EE308-Lab11-Software Testing
unittest for Python
EE308-Lab8-AlphaSprint Collection
EE308 Lab8 Alpha Sprint Collection1. Format Description2. 宁可累死自己,也要卷死同学 -Sprint Collection 1. Format Description The Link Your Class https://bbs.csdn.net/forums/MUEE308FZ The Link of Requirement of This Assignment https://bbs.csdn.net/topics/603251
【信息科学与工程学】【物理/化学科学和工程技术】知识体系073——电学基础04
。
YOLO26算法煤气罐识别+训练好的模型+417张数据集+pyqt可视化界面.zip
附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[()] 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 97 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.8213** mAP50-95 | 0.6707 Precision | 0.8858 Recall | 0.7370 train/box_loss | 0.5927 train/cls_loss | 0.4692 val/box_loss | 0.7097 val/cls_loss | 0.8245 【训练过程分析】 训练过程中,模型在前几轮迅速收敛,loss 值从 0.5927 降到 0.7097,表明初期训练效果显著。loss 在第 10 轮降至最低点 0.5867,然后在接下来的 80 轮左右保持平稳,仅微幅波动在 0.5927 到 0.6000 之间,显示训练过程较为均衡,没有明显的过拟合迹象。整体来看,模型在训练后期趋于稳定,mAP50 从 0.6845 增长至 0.8213,提升较为平滑,显示出训练效果的稳健性。 模型在第 97 轮时,loss 稳定在较低水平,表明训练过程较为稳定,没有明显的过拟合迹象。从 PR 曲线可见,模型在检测精度和召回率方面表现均衡,特别是在高召回率时保持较高的精度。mAP50 为 0.8213,表明模型在中等难度的检测任务上表现良好。然而,mAP50-95 为 0.6707,说明在高难度检测任务... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。


