EE308_Lab11

sazic sazic 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
The Link Your Classhttps://bbs.csdn.net/forums/MUEE308FZ?category=0
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/603748107
The Aim of This AssignmentUnit Test Tutorial (for python)
MU STU ID and FZU STU ID19104073_831901119

Aim

This lab is aim to learn something about unit test. This lab contains task of python and java. I choose python with the toolbox called unittest which is already inside 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):
        pass
        
# 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 = 4, 2
            res = 2
            self.assertNotEqual(a - b, 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, "True 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, "y is not an instance of x")
        except AssertionError as e:
            print (e)

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

The only confusing thing is the function call "assertIsInstance", the relation between them needs to check on the datasheet.

2.unittest test groups

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

*d means the following values will all be concreted into a array of d

TestCalc.py

# 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, 1, 2, 3, 4) == 0)

    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, 1, 2, 3, 4) == 1)

    def tearDown(self):
        print("test completed!")

    def tearDown(self):
        print("tearDown completed")


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

unittest_suite.py

# 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)

If you need to create a empty function, just fill the function with a "pass".

A suite test is to test multi tests at one time.

3.unittest skip test

# encoding=utf-8

import random, sys, unittest, platform


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, "skipping for 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.skipUnless(platform.system().lower() == 'linux', "skipping for 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)

@unittest.skip("skipping") skip the following block

@unittest.skipIf(a>5, "skipping for a>5") skip for some reason (like a>5, a bool check)

@unittest.skipUnless(platform.system().lower() == 'linux', "skipping for linux platform") skip for some reason, if the bool check is 0, skip.

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_add(self):
        print("run add()")
        self.assertEqual(self.c.add(1, 2, 12), 15, 'test add fail')

    def test_sub(self):
        print("run sub()")
        self.assertEqual(self.c.sub(2, 1, 3), -2, 'test sub fail')

    def test_mul(self):
        print("run mul()")
        self.assertEqual(Calc.mul(1, 2, 3, 5), 30, 'test mul fail')

    def test_div(self):
        print("run div()")
        self.assertEqual(Calc.div(1, 8, 2, 4), 1, 'test div fail')


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

5.unittest Time Test

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

In lack of the module "timeout_decorator", we can not execute the code correctly.

Conclusion

In this lab I learned how to test Python code. Unit test can save a lot of time for us, it is very useful for use to test in our projects.

...全文

相关推荐

EE-308 LAB4 final version.7z

这是本次实验的压缩包

晨起剪桃花

EE308-Lab11-Software Testing

unittest for Python

调参侠鱼尾

高校技术转移办公室人员如何精准识别高质量可转化专利?.docx

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

BIZKEEN

chromedriver-win64-159.0.8137.0(Canary).zip

chromedriver-win64-159.0.8137.0(Canary).zip

LCG元

风光储协同并网发电系统仿真(Simulink仿真实现)

内容概要:本文系统介绍了风光储协同并网发电系统的Simulink仿真资源,聚焦于风力、光伏与储能系统在交直流微电网环境下的集成建模与一体化协调控制策略仿真。内容涵盖MPPT最大功率点跟踪、储能变流器(PCS)控制、下垂控制、虚拟同步机(VSG)技术、并网PQ控制、孤岛运行、能量管理及混合储能(如蓄电池与超级电容)的功率分配等关键技术模块。资源提供完整的Simulink模型文件、详细的说明文档、参考文献及SCI论文复现资料,支持从理论建模到仿真验证的全流程科研实践,适用于微电网并网特性分析、系统稳定性研究与先进控制算法验证。; 适合人群:电力系统、新能源发电、微电网控制及相关方向的研究生、科研人员和工程技术人员,尤其适合具备MATLAB/Simulink操作基础和电力电子、自动控制背景的专业人士; 使用场景及目标:①开展风光储多能互补系统的建模与仿真研究;②完成学术论文复现、课程设计或学位课题开发;③深入掌握微电网中储能协调控制、并网逆变器控制、VSG动态响应等核心技术的实现机制; 阅读建议:建议结合所提供的参考文献与建模报告,按照资源目录顺序循序渐进地学习,优先运行仿真模型并调整关键控制参数,通过对比不同工况下的系统响应,深入理解控制逻辑与动态性能,全面提升科研仿真能力与工程应用水平。

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