EE308_Lab11

厦大打工人 厦大打工人 墨衍会员 · 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 ID19105185_831901317

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

lab_11.py

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


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 = 4
            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(2 == 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 not same" % (type(x), y))
        except AssertionError as e:
            print(e)

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

The result of running through the code is:

💻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

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):
        self.assertTrue(self.c.sub(10, 3) == 7)
        # fix a line of codes to test c.sub(self, a, *b) method

    def test_mul(self):
        self.assertTrue(self.c.mul(3, 4) == 12)
        # fix a line of codes to test c.mul(self, *b) method

    def test_div(self):
        self.assertTrue(self.c.div(4, 2) == 2)
        # fix a line of codes to test c.div(self, a, *b) method

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

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

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

The result of running through the code is:

 lab11_3.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)

The result of running through the code is:

 📊3.unittest skip test

 lab11_4.py

# 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, "skip 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
    @unittest.skipIf(sys.platform != "Linux", "skip 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)

 The result of running through the code is:

💾4.unittest Run test under numerical order or alpha order

lab11_5.py
# 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 :
    # run add()
    # run sub()
    # run mul()
    # run div()

    # 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(self.c, 2, 3, 5), 30, 'test mul fail')

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


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

  The result of running through the code is:

📝5.unittest Time Test 

lab11_6.py

import time
import timeout_decorator
import unittest


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

There is no virtual machine on my computer, so I can't complete the last task. In lack of the module "timeout_decorator", we can not execute the code correctly.

🎆Conclusion

Through this experiment, I learned how to test Python code, and knew the importance and convenience of testing for code.

...全文

相关推荐

EE-308 LAB4 final version.7z

这是本次实验的压缩包

晨起剪桃花

EE308-Lab11-Software Testing

unittest for Python

调参侠鱼尾

EE308-Lab8-AlphaSprint Collection

EE308 Lab8 Alpha Sprint Collection1. Format Description2. 宁可累死自己,也要卷死同学 -Sprint Collection 1. Format Description The Link Your Class https://bbs.csdn.net/forums/MUEE308FZ The Link of Requirement of This Assignment https://bbs.csdn.net/topics/603251

调参侠鱼尾

【信息科学与工程学】【物理/化学科学和工程技术】知识体系073——电学基础04

​。

flyair_China

【锂电池管理系统】基于二阶RC模型与EKF的SOC估计精度对比:MATLAB仿真与多因素验证 MATLAB 锂电池SOC估计|二阶RC模型与EKF精度对比

内容概要:本文详细介绍了一种基于MATLAB的锂电池荷电状态(SOC)估计方法,采用二阶RC等效电路模型与扩展卡尔曼滤波(EKF)相结合的技术路线,旨在提高SOC估计的精度。文章首先介绍了项目背景,指出锂离子电池因其高能量密度和长循环寿命等特点,在新能源汽车、储能电站等多个领域得到广泛应用。然而,由于电池具有非线性、动态时变和多物理场耦合的特性,SOC的准确估计成为电池管理系统(BMS)中的关键技术难题。为此,本文提出了一种结合二阶RC模型与EKF的SOC估计方法,通过构建可解释的二阶RC电池动态模型,实现具有闭环修正能力的SOC估计。此外,项目还构建了可复现的多因素连续仿真数据,建立了完整的精度评价与工程验证体系,以确保所提方法的有效性和可靠性。 适合人群:具备一定编程基础,熟悉MATLAB编程语言,对电池管理系统有一定了解的研发人员和技术工程师。 使用场景及目标:①适用于新能源汽车、电化学储能电站、无人机与移动机器人、便携式设备与备用电源等领域,特别是在需要高精度SOC估计的应用场合;②目标在于通过二阶RC模型与EKF的结合,解决传统安时积分法存在的累计漂移问题,提高SOC估计的准确性,进而优化电池的使用效率和延长使用寿命。 其他说明:项目强调了数据生成的重要性,通过引入多种随机机制(如马尔可夫状态切换、随机脉冲组合等),构建了包含电流、端电压、温度、欧姆内阻和有效容量五项输入特征的五万组连续时序数据,确保了数据的真实性和多样性。同时,项目提出了多项评价指标(如均方根误差、平均绝对误差、最大绝对误差、末端漂移和误差标准差等),用于全面评估不同SOC估计方法的性能。此外,项目还讨论了电池模型非线性、参数时变与模型失配等挑战及其解决方案,强调了初始SOC偏差、噪声协方差整定与滤波收敛等关键因素对SOC估计精度的影响。最后,项目展望了未来的研究方向,包括在线参数辨识与自适应噪声调节、SOC与SOH联合估计、更强非线性滤波与多算法融合、温度场与迟滞效应增强等,旨在进一步提升SOC估计的鲁棒性和适应性。

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