EE308_lab11

Huang_Junqi 2021-12-17 15:38:25
The Link Your Classhttps://bbs.csdn.net/forums/MUEE308FZ
The Link of Requirement of This AssignmentLAB 11 Software Testing-CSDN社区
The Aim of This Assignmentunitttest
MU STU ID and FZU STU ID19105169_831901316

Unittest

part 1

In the first part, we learned how to use assert

In assertion testing, only failed assertion tests are recorded.Attach the completed code.

import unittest, random


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 = 2, 2
            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.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(type(x), y, "given object is not a instance of class")

        except AssertionError as e:
            print(e)


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

part 2

 unittest test groups.

Use assertTure to unit test code from other Python files。

# 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, 2) == 8)

    # fix a line of codes to test c.sub(self, a, *b) method

    def test_mul(self):
        self.assertTrue(self.c.mul(11, 2) == 22)

    # fix a line of codes to test c.mul(self, *b) method

    def test_div(self):
        self.assertTrue(self.c.div(10,2) == 5)

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

part 3

unittest_suite

Use the test suite to drive a test set.The completed code is attached here


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)

part 4

In some cases, skip the 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, "skip if a>5")
    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    @unittest.skipIf(sys.platform != "linux", "skipping if system is 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)

part 5

In order for the test program to proceed in a certain order, we must rename the names of the test code segments in the order of ASCII.Here I use 1 2 3 4 as the order


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

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


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

part 6

unittest Time Test

import time
import unittest
import timeout_decorator


class timeoutTest(unittest.TestCase):

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

 

...全文
152 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文针对低温环境下微电网运行中电池寿命损耗加剧的问题,提出了一种考虑电池寿命的优化调度模型,并通过Matlab代码实现仿真验证。研究聚焦于低温导致电池性能下降、循环寿命缩短的技术挑战,结合分布式能源出力波动性与负荷需求变化,构建了融合经济性、可靠性与电池健康状态的多目标优化调度框架。通过引入电池老化成本模型,将寿命损耗量化为可调度变量,优化充放电策略以延长电池使用寿命并降低系统综合运行成本。文中详细阐述了目标函数设计、约束条件设定及求解方法,并通过算例分析验证了该策略在抑制深度充放电、均衡电池组使用、提升系统经济性等方面的有效性。; 适合人群:具备电力系统、新能源或优化算法基础知识的研究生、科研人员及从事微电网、储能系统相关工作的工程技术人员。; 使用场景及目标:①应用于高寒地区或冬季低温场景下的微电网能量管理系统设计;②为研究电池寿命与系统经济性之间的权衡关系提供建模思路;③作为Matlab优化工具箱(如Yalmip、CPLEX)在电力系统调度中应用的学习案例; 阅读建议:读者可结合文中提供的Matlab代码,复现仿真结果,深入理解电池老化模型与优化调度的耦合机制,并尝试在此基础上引入更多不确定性因素(如电价波动、负荷预测误差)进行扩展研究。
【电动汽车响应率】考虑的是针对电动汽车充放电调度问题,由于放电奖励不同导致部分车主不愿参与放电,设计出响应率计算方法(Matlab代码实现)内容概要:本文针对电动汽车充放电调度问题,由于放电奖励不同导致部分车主不愿参与放电的现象,提出了一种响应率计算方法,并通过Matlab代码实现。该方法旨在量化车主对放电调度指令的响应意愿,为优化调度策略提供数据支持。文中详细阐述了响应率模型的构建原理、关键构成要素及验证方法,并探讨了其在调度优化和激励机制设计中的应用前景。通过设置不同响应率水平(如36%、50%、80%、100%)进行仿真分析,评估其对系统运行效果的影响,从而为提升电动汽车参与度提供理论依据和技术手段。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的科研人员、研究生及从事新能源汽车与电网互动领域的工程技术人员。; 使用场景及目标:①用于研究电动汽车用户行为建模与响应特性分析;②支撑含高比例电动汽车的微电网或主动配电网优化调度研究;③辅助设计合理的充放电价激励机制以提高用户参与度;④为需求响应项目的可行性评估与效果预测提供工具支持。; 阅读建议:建议读者结合文中提供的Matlab代码,深入理解响应率计算逻辑与实现细节,重点关注不同参数设置对响应率结果的影响,并尝试将其集成到更复杂的电力系统优化模型中进行扩展研究。

183

社区成员

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

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