EE308 LAB11

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

The Link of Requirement of This Assignment

https://bbs.csdn.net/topics/603748107
The Aim of This AssignmentUnit test for Python
MUID&FZUID19105941_831901112

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.

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):
        # fix missing three lines of codes below ‘try’, test if b-a equals res or not
        try:
            a,b=1,1
            sum=3
            self.assertNotEqual(a+b,sum, 'assert failed!,%s + %s == %s' %(a, b, sum))
        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.assertTrue(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(x,y, "%s and %s are 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,2,3,4)==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)

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))
 
      # add a line of annotation thatskip 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
      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 add(self):
        print ("run add()")
        self.assertEqual(self.c.add(1, 2, 12), 15, 'test add fail')
 
    def sub(self):
        print ("run sub()")
        self.assertEqual(self.c.sub(2, 1, 3), -2, 'test sub fail')
 
    def mul(self):
        print ("run mul()")
        self.assertEqual(Calc.mul(2, 3, 5), 30, 'test mul fail')
 
    def div(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
   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()

 

...全文

相关推荐

EE-308 LAB4 final version.7z

这是本次实验的压缩包

晨起剪桃花

EE308-Lab11-Software Testing

unittest for Python

调参侠鱼尾

文件夹文件清单一键导出Excel工具

这是一款文件夹文件清单一键导出 Excel 工具,选一个文件夹点一下,整棵目录树就列成一张 Excel 表。自带中文图形界面,双击启动.bat 即用。交付物包含主程序脚本、启动批处理、README 说明文档(md、html、pdf 三种版本)、示例目录和界面截图,解压即用。 功能上覆盖目录盘点的完整流程:选一个文件夹递归扫描所有子目录,文件按相对路径列进 Excel;每行带相对路径、文件名、类型、大小、创建时间和修改时间六项信息;末尾自动合计文件总数和总大小;可按扩展名过滤只保留指定类型的文件,可限制递归深度只扫顶层或指定层数。 几个实用细节:只读文件元数据不动你的原始文件,输出进独立目录同名自动加序号不覆盖;自动跳过隐藏文件和常见缓存目录如 git、node_modules;按钮运行时变灰防重复点击;同时保留命令行模式,脚本党也能直接用。 适合做交接盘点、资料报审、目录整理的行政、IT 和办公族,不用写代码。使用时双击启动.bat,选好要盘点的文件夹,按需填扩展名过滤和递归深度,点导出 Excel 清单,几秒钟后结果就在旁边的输出文件夹里,打开就能直接使用查看。第一次用建议先拿自带的示例目录跑一遍熟悉流程,再扫自己的正式文件夹。

小鹿( ﹡ˆoˆ﹡ )

政府科技管理者在推动科技成果转化时,如何解决技术供需匹配低效的问题?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

BIZKEEN

科技中介服务机构如何提升技术需求挖掘与服务推荐能力?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

BIZKEEN
评论
收藏 已收藏
分享
返回顶部