EE308_Lab11 Unittest

MOMOWHITE_ECHO 2021-12-17 19:59:49

 

The Link Your Class

https://bbs.csdn.net/forums/MUEE308FZ

The Aim of This Assignment

Software Testing

MU STU ID and FZU STU ID

19104413_831901105

Preparation

Learn related knowledge about Junit Test for Java and Unittest for python. You can finish the following assignment or test Your Project.

 

Task

  1. Here are Junit Test task and Unittest task for choose. If you are good at Java , we suggest you choose the first one, if you are good at Python, then, the latter one.
  2. Follow the requests and tips, complete the test task .

 

Requirements

  1. You should be familiar with Junit Test or Unittest and the usage of these tools.Such as ‘assert, suite, timeout’, check problems for detail.
  2. Fix the missing codes according to requirement for every problem.

 

Unittest assert test

related knowledge: 

assertEqual(first, second, msg=None): return False if first not equals second, msg could be anything you want if exception be triggered.

similar method:

assertEqual(first, second, msg=None): check first == second

assertNotEqual(first, second, msg=None): check first != second

assertIn(member, container, msg=None): check member in container or not

assertNotIn(member, container, msg=None):check  member not in container or yes

assertTrue(expr, msg=None): expr is True

assertFalse(expr, msg=None): expr is False

assertIsNone(self, obj, msg=None): None, obj is None

assertIsNotNone(self, obj, msg=None): None, obj is not None

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):
        # fix missing three lines of codes below ‘try’, test if b-a equals res or not
        try:
            a, b = 1, 2
            res = 0
            self.assertNotEqual((b - a), (res), 'assert failed!,%s - %s != %s' % (b, a, 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(type(x), y, "Not an Instance")
        except AssertionError as e:
            print(e)
 
if __name__ == '__main__':
    # run unittest
    unittest.main()

Unittest test groups

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):
    # fix a line of codes to test c.sub(self, a, *b) method
        self.assertTrue(self.c.sub(4, 1, 2, 3) == -2)
    def test_mul(self):
    # fix a line of codes to test c.mul(self, *b) method
        self.assertTrue(self.c.mul(3, 4) == 12)
    def test_div(self):
    # fix a line of codes to test c.div(self, a, *b) method
        self.assertTrue(self.c.div(4, 2) == 2)
    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)
    # put more test class into suite
    suite3 = unittest.TestLoader().loadTestsFromTestCase(TestDictValueFormatFunctions)
    # 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)

U

目录

Preparation

Task

Requirements

 

Unittest assert test

Unittest test groups

Unittest skip test

Unittest Run test under numerical order or alpha order

Unittest Time Test


nittest 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))
 
    # add a line of annotation that skip this method if a>5
    @unittest.skipIf(a > 5,"skip this method if a>5")
    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)
 
    # add a line of annotation that skip if not in linux platform
    @unittest.skipIf(sys.platform!='linux', "Require for linux")
    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)

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_a_add(self):
        print("run add()")
        self.assertEqual(self.c.add(1, 2, 12), 15, 'test add fail')
 
    def test_b_sub(self):
        print("run sub()")
        self.assertEqual(self.c.sub(2, 1, 3), -2, 'test sub fail')
 
    def test_c_mul(self):
        print("run mul()")
        self.assertEqual(Calc.mul(self,2, 3, 5), 30, 'test mul fail')
 
    def test_d_div(self):
        print("run div()")
        self.assertEqual(Calc.div(self,8, 2, 4), 1, 'test div fail')
 
 
if __name__ == '__main__':
    unittest.main()

Unittest Time Test

Related Knowledge:import time_decorator and use it before test methods

import sys
import time
import unittest
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()

 

 

 

 

...全文
225 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
代码转载自:https://pan.quark.cn/s/a4b39357ea24 自动驾驶是当前科技界高度关注的研究方向,其研究范畴涵盖了人工智能、计算机视觉、机器学习以及传感器融合等多个重要学科。这份题为"自动驾驶论文"的资料,无疑为人们提供了一个深入了解这一复杂系统的机会。以下是基于其标题和描述所呈现的一些关键知识点的详细阐述: 1. **自动驾驶技术**:自动驾驶指的是车辆在无需人类驾驶员参与的情况下,借助各类传感器和智能算法来感知周围环境,制定行驶路线,并执行驾驶行为。这种技术的核心宗旨在于提升交通安全性、缓解交通压力,并改善出行体验。 2. **Python编程语言**:Python是一种在数据处理和科学计算领域得到广泛应用的高级编程语言,由于其语法简洁且拥有丰富的库支持,经常被应用于自动驾驶领域的数据处理、模型构建和系统集成。 3. **源代码分析**:论文中提供的源代码可能包含了自动驾驶算法的实现细节,可能涵盖环境感知模块(包括图像处理、激光雷达数据解读)、决策模块(涉及路径规划、行为分析)、控制模块(涵盖车辆动力学建模、控制策略设计)等,这些代码可作为学习和研究自动驾驶算法的实践范例。 4. **计算机视觉**:自动驾驶系统中的计算机视觉技术主要用于识别道路标识、行人、其他车辆等,这通常涉及图像分类、目标识别和语义分割等任务,常见的技术包括卷积神经网络(CNN)、区域提议网络(RPN)、YOLO、Faster R-CNN等。 5. **机器学习**:机器学习是自动驾驶技术的核心,用于训练模型以理解和预测复杂的驾驶情境。深度学习,特别是深度强化学习,在决策制定和控制策略方面已取得显著进展。 6. **传感器融合**:自动驾驶汽车通常装备多种传...
内容概要:本文提出了一种改进的多旋翼无人机动态模拟的模块化仿真环境,基于Matlab/Simulink平台实现。该仿真环境通过模块化设计,集成了无人机的气动模型、动力系统模型、传感器模型及控制算法等多个关键子系统,能够精确模拟多旋翼无人机在复杂飞行条件下的动态响应特性。系统改进之处在于增强了模型的真实性和可扩展性,优化了仿真计算效率,并支持硬件在环(HIL)测试,便于控制算法的快速原型验证与迭代开发。该环境不仅可用于无人机飞控算法的设计与验证,也可服务于飞行器性能评估、故障诊断与容错控制等研究。; 适合人群:具备一定控制理论基础和Matlab/Simulink使用经验的高校研究生、科研机构研究人员及无人机相关领域的工程技术人员。; 使用场景及目标:①用于多旋翼无人机飞行动力学建模与仿真分析;②支持先进飞行控制算法(如PID、LQR、MPC、自适应控制等)的开发与验证;③作为教学工具帮助学生理解无人机系统构成与控制原理;④为无人机产品开发提供前期仿真测试平台,降低实飞风险与研发成本。; 阅读建议:建议读者结合Matlab/Simulink环境动手实践,逐步搭建并调试各个模块,重点关注各子系统间的接口关系与数据交互逻辑。同时可参考文中提供的仿真案例,深入理解参数设置对系统动态性能的影响,进而开展个性化功能扩展与算法创新。

183

社区成员

发帖
与我相关
我的任务
社区描述
福州大学 梅努斯国际工程学院 软件工程 教学
软件工程 高校
社区管理员
  • 单步调试
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧