EE308 Lab11 Unittest

ZL_Chen_19105843 2021-12-16 16:13:42
The Link Your Class
https://bbs.csdn.net/forums/MUEE308FZ?category=0

The Link of Requirement of This Assignment

https://bbs.csdn.net/topics/603748107
The Aim of This AssignmentSoftware Testing-Unittest
MUID&FZUID19105843 & 831901123
Name

Zhongliang Chen

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.

 

Tips:

  • We list ‘related knowledge’ for some problems, read it very carefully.

 

  1. 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 = 1 
self.assertNotEqual(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.assertlsInstance(x, y, "%s and %s are not same "%(x, y))
        except AssertionError as e:
            print (e)

if __name__ == '__main__':
    # run unittest
    unittest.main()

2. 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(10,4,3,2)==1)
 
    def test_mul(self):
        # fix a line of codes to test c.mul(self, *b) method
self.assertTrue(self.c.mul(1,2,3,4)==24)
 
    def test_div(self):
        # fix a line of codes to test c.div(self, a, *b) method
 		self.assertTrue(self.c.div(24,4,3,2)==1)
    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)
  1. 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))
 
      # add a line of annotation that skip this method if a>5
  @unittest.skipIf(a > 5, "condition is not satisfied!")
      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.skipUnless(sys.platform.startswith("Linux"), "requires 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)

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

3.unittest Time Test

Related Knowledge:import time_decorator and use it before test methods

import time
import timeout_decorator

class timeoutTest(unittest.TestCase):

# set a time decorator(annotation) which will be triggered after 5s’ running
@timeout_decorator.timeout(seconds=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()

 

...全文
177 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文基于Matlab/Simulink平台,对电励磁同步电机在异步牵入、稳态运行及能耗制动三个阶段的全周期动态特性进行建模仿真与系统研究。研究构建了完整的电机数学模型与仿真系统,重点分析了电机从异步启动到同步运行的过渡过程、稳态运行时的电磁与机械性能,以及执行能耗制动时的减速特性与能量耗散机理。通过仿真,揭示了励磁电流、负载转矩与转速在不同工况下的动态响应规律与耦合关系,为电机的控制策略设计与性能优化提供了理论依据和数据支持。; 适合人群:具备电机学、电力电子与电力拖动基础知识的电气工程及相关专业的研究生、科研人员与工程技术人员。; 使用场景及目标:①研究电励磁同步电机的启动特性,解决异步牵入过程不稳定或失败的问题;②分析电机在不同负载下的稳态运行性能,优化运行效率;③设计和验证能耗制动策略,精确控制制动过程的减速时间和能量消耗。; 阅读建议:在学习过程中,应结合电机的基本原理,深入理解仿真模型中各模块(如电机本体、励磁控制、负载模型)的搭建逻辑,并通过调整仿真参数(如励磁电压、负载大小)来观察和分析系统动态响应,以加深对电机全周期运行特性的理解。
内容概要:通过介绍短时倒谱(Cepstrogram)计算方法,开展时-倒频分析研究,深入探讨倒谱分析机理、短时倒谱构建逻辑及时-倒频分析的内涵。文中系统对比了时-倒频分析与全局倒谱、传统时频分析方法的差异,阐明其在卷积特征解耦、非平稳信号跟踪、微弱周期特征增强及多维特征融合方面的技术优势,并分析其在语音识别、机械故障诊断、音频处理和非平稳时序信号分析中的典型应用,同时指出其在分辨率、计算复杂度等方面的局限性并提出优化方向。; 适合人群:具备一定信号处理或数据分析基础,从事机械、通信、声学或自动化等领域研究的研发人员及研究生。; 使用场景及目标:① 掌握短时倒谱与时-倒频分析的理论基础与实现方法;② 应用于语音信号处理、机械设备故障诊断、音频相似性检测等工程实践;③ 对比传统方法,提升对复杂非平稳信号中隐含周期特征的识别能力; 阅读建议:此资源以Matlab代码实现为核心,强调理论与实践结合,建议读者在理解核心算法原理的基础上,动手运行代码并调试参数,结合具体应用场景深化对方法适用性与局限性的认识。

183

社区成员

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

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