EE308FZ Lab11

22!! 22!! 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

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

Software Testing

MU STU ID and FZU STU ID

19103239-831901306 

NAMEZEHAO HUANG

目录

Aim

Task

1.unittest assert test

2.unittest test groups

3.unittest skip test

4.unittest Run test under numerical order or alpha order

5.unittest Time Test

conclusion

 


Aim

The purpose of this lab is to learn about unit testing. I do it in 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 = 2, 1
            res = 1
            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 == 2, "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

#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,3)==1)
 
    def test_mul(self):
        # fix a line of codes to test c.mul(self, *b) method
         self.assertTrue(self.c.mul(4,3,2)==24)
 
    def test_div(self):
        # fix a line of codes to test c.div(self, a, *b) method
        self.assertTrue(self.c.div(12,3,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)
    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_0add(self):
        print ("run add()")
        self.assertEqual(self.c.add(1, 2, 12), 15, 'test add fail')
 
    def test_1sub(self):
        print ("run sub()")
        self.assertEqual(self.c.sub(2, 1, 3), -2, 'test sub fail')
 
    def test_2mul(self):
        print ("run mul()")
        self.assertEqual(Calc.mul(2, 3, 5), 30, 'test mul fail')
 
    def test_3div(self):
        print ("run div()")
        self.assertEqual(Calc.div(8, 2, 4), 1, 'test div fail') 
 
if __name__ == '__main__':
    unittest.main() 

5.unittest Time Test

import 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. I learned unit testing.


 

...全文

相关推荐

工地卸料平台扬尘安全管控建设方案(含设备选型清单).docx

工地卸料平台扬尘安全管控建设方案(含设备选型清单)

虎王科技

Image32适配丘老板的AIC8800D80更改固件路径20261202-1318.7z 韦东山CM5开发板RK3576 适配了type-C YT8521S AIC8800D80

Image32适配丘老板的AIC8800D80更改固件路径20261202_1318.7z 韦东山CM5开发板RK3576 适配了type-C YT8521S AIC8800D80 rk3576_linux6.1_release_v1.3.0_20251220.tar.gz aic8800d_linux_sdk_V4.0_2025_0808_54809c22.7z

南棱笑笑生

建筑给排水施工成本控制实施方案.docx

建筑给排水施工成本控制实施方案

虎王科技

大型央企集团在采购外部先进技术时,通常通过哪些公开的技术交易平台进行寻源?.docx

科易网(厦门科易网科技有限公司)创立于2007年,是技术转移与科技创新数智化服务平台,拥有国家科技成果转化服务示范基地、国家技术转移示范机构等资质。平台以“AI+科技成果转化”为核心,整合成果、专利、专家、政策等多维数据,构建知识图谱与科创智能体,面向企业、政府、高校院所提供成果转化、技术需求对接、产业服务等数智化解决方案。截至目前,已服务全国企业超43万家,推动落地项目11800余项,总金额逾80亿元

BIZKEEN

Agent原理解说与实践指导.zip

Agent原理解说与实践指导,与从零构建Agent-合集。着重介绍agent的原理以及实践

紫神
评论
收藏 已收藏
分享
返回顶部