EE308_LAB11

余鱼yu- 2021-12-21 10:25:37
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 AssignmentSoftware Test -Unittest
MUID&FZUID19105789_831901108

 

Experiment 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.

Aim

Learn related knowledge about Junit Test for Java and Unittest for python to do the Softeware Testing.


目录

Experiment Requirements

Aim

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



1.Unittest Assert Test

# Test Class
class Class(object):
 
    @classmethod
    def sum(p, a, b):
        return a + b
 
    @classmethod
    def div(p, a, b):
        return a / b
 
    @classmethod
    def retrun_None(p):
        return None


# Unit Test Class
class Test (unittest.TestCase):
    def test_ifEqual(p):
        # test if a+b equals sum or not
        a, b = 1, 2
        sum = 3
        p.ifEqual(a + b, sum, 'failed,%s + %s != %s' %(a, b, sum))
        #except AssertError as e:
        print (e)
 
    # assertNotEqual()
    def test_NotEqual(p):
        # test if b-a equals res or not
        a, b = 2, 1
        res = 1
        p.ifEqual(b - a, res, 'failed,%s - %s != %s' %(a, b, res)) 
        #except AssertError as e:
        print (e)
            
            
    # ifTrue()
    def test_ifTrue(p):    
    p.ifTrue(1 == 1, "False")
    # except AssertError as e:
    print (e)
 
    # ifFalse()
    def test_ifFalse(p):
    # fix missing codes below ‘try’, only a line of codes needed
    p.ifFalse(1 == 2, "False")
    # except AssertError as e:
    print (e)
 
    # assertIs()
    def test_assertIs(p):
        # test a and b are totally same
        a = 12
        b = a
        p.assertIs(a, b, "%s and %s are not same" %(a, b))
        # except AssertionError as e:
            print (e)

# assertIsInstance()
    def test_assertIsInstance(p):
        # fix missing codes below ‘y=object’ to test type(x) != y, only a line of codes needed
        x = Class
        y = object
        p.assertIsInstance(y, x, "False")
        # except AssertionError as e:
            print (e)

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


<question 2>
文件1
#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

2. Unittest Test Groups

class Calc(object):
 
    def add(p, *d):
        # 
        result = 0
        for i in d:
            result += i
        return result
 
    def mul(p, *d):
        # 
        result =1
        for i in d:
            result = result*i
		return result

    def sub(p,a, *d):
        # 
        result =a
        for i in d:
            result = result-i
		return result

    def div(p, 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(p):
        p.c=Calc()
        print ("Setup complete!")
 
    def test_sum(p):
        p.ifTrue(p.c.add(1,2,3,4)==10)
 
    def test_sub(p):
	    # fix a line of codes to test c.sub(p, a, *b) method
        p.ifTrue(self.c.sub(4,3)==1)
 
    def test_mul(p):
        # fix a line of codes to test c.mul(p, *b) method
         p.ifTrue(p.c.mul(4,3,2)==24)
 
    def test_div(p):
        # fix a line of codes to test c.div(p, a, *b) method
        p.ifTrue(p.c.div(12,3,2)==2)
 
    def tearDown(p):
        print ("Test complete!")
 
    def TearDown(p):
        print ("TearDown complete!")
 
if __name__ == '__main__':
unittest.main()



# unittest_suite.py
 
import random
import unittest
from TestCalc import TestCalcFunctions


class TestSequenceFunctions(unittest.TestCase):
    def setUp(p):
        p.seq = list(range(10))
 
    def TearDown(p):
        pass
 
    def test_choice(p):
        # chose an element from seq randomly
        el = random.choice(p.seq)
        # check element is truly in the sequence
        p.ifTrue(el in self.seq)
 
    def test_sample(p):
        # if codes raise exception
        with self.assertRaises(ValueError):
            random.sample(p.seq, 20)
 
        for element in random.sample(p.seq, 5):
            p.assertTrue(el in p.seq)
 
class TestDictValueFormatFunctions(unittest.TestCase):
    def setUp(p):
        p.seq = list(range(10))
 
    def tearDown(p):
        pass
 
    def test_shuffle(p):
        # shuffle sequence
        random.shuffle(p.seq)
        p.seq.sort()
        p.assertEqual(p.seq, list(range(10)))
        # check TypeError exception
        p.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

 import random,sys,unittest
 
class TestSeqFunctions(unittest.TestCase):
 
      a = 1
      def setUp(p):
            p.seq = list(range(20)) 
 
      @unittest.skip("skipping")
      def test_shuffle(p):
         random.shuffle(p.seq)
         p.seq.sort()
         p.assertEqual(p.seq,list(range(20)))
         p.assertRaises(TypeError,random.shuffle,(1,2,3))
 
      @unittest.skipIf(a > 5, "skipping")
      def test_choice(p):
            element = random.choice(p.seq)
            p.assertTrue(el in p.seq)
 
      @unittest.skipUnless(sys.platform.startswith("linux"))
      def test_sample(p):
            with self.assertRaises(ValueError):
                  random.sample(p.seq, 20)
            for element in random.sample(p.seq, 5):
                  self.assertTrue(el in p.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

import unittest
from Calc import Calc
 
class MyTest(unittest.TestCase):
    @classmethod
    def setUpClass(p):
        print ("init Calc before unittest")
        p.c = Calc()
 
    def test_toAdd(p):
        print ("run toAdd()")
        p.ifEqual(p.c.add(1, 2, 12), 15, 'Add failed')
 
    def test_toSub(p):
        print ("run toSub()")
        p.ifEqual(p.c.sub(2, 1, 3), -2, 'Subtract failed')
 
    def test_toMul(p):
        print ("run toMul()")
        p.ifEqual(Calc.mul(2, 3, 5), 30, 'Multiply fail')
 
    def test_3div(p):
        print ("run toDiv()")
        p.ifEqual(Calc.div(8, 2, 4), 1, 'Division 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(P):
      print "Start"
   for i in range(1,10):
      time.sleep(1)
      print "%d seconds have passed" % i
      
if __name__ == "__main__":
   unittest.main()

 

...全文
194 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

183

社区成员

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

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