猿问

Python unittest正确设置全局变量

我有一个简单的方法,可以根据方法参数将全局变量设置为 True 或 False。


这个全局变量被调用feedback并且有一个默认值False。


当我调用setFeedback('y')全局变量时,将更改为feedback = True. 当我调用setFeedback('n')全局变量时,将更改为feedback = False.


现在我正在尝试在 Python 中使用 unittest 进行测试:


class TestMain(unittest.TestCase):


    def test_setFeedback(self):


        self.assertFalse(feedback)

        setFeedback('y')

        self.assertTrue(feedback)

当我运行此测试时,我收到以下错误:AssertionError: False is not true.


由于我知道该方法可以正常工作,因此我假设全局变量以某种方式被重置。但是,由于我对 Python 环境还很陌生,所以我不知道自己做错了什么。


我已经在这里阅读了一篇关于 mocking 的文章,但是由于我的方法更改了一个全局变量,我不知道 mocking 是否可以解决这个问题。


我将不胜感激。


这是代码:


主要.py:


#IMPORTS

from colorama import init, Fore, Back, Style

from typing import List, Tuple


#GLOBAL VARIABLE

feedback = False


#SET FEEDBACK METHOD

def setFeedback(feedbackInput):

    """This methods sets the feedback variable according to the given parameter.

       Feedback can be either enabled or disabled.


    Arguments:

        feedbackInput {str} -- The feedback input from the user. Values = {'y', 'n'}

    """


    #* ACCESS TO GLOBAL VARIABLES

    global feedback


    #* SET FEEDBACK VALUE

    # Set global variable according to the input

    if(feedbackInput == 'y'):


        feedback = True

        print("\nFeedback:" + Fore.GREEN + " ENABLED\n" + Style.RESET_ALL)

        input("Press any key to continue...")


        # Clear the console

        clearConsole()


    else:

        print("\nFeedback:" + Fore.GREEN + " DISABLED\n" + Style.RESET_ALL)

        input("Press any key to continue...")


        # Clear the console

        clearConsole()

test_main.py:


import unittest

from main import *


class TestMain(unittest.TestCase):


    def test_setFeedback(self):


        self.assertFalse(feedback)

        setFeedback('y')

        self.assertTrue(feedback)



if __name__ == '__main__':

    unittest.main()


杨__羊羊
浏览 378回答 2
2回答

千巷猫影

你的测试有两个问题。首先,你input在你的feedback函数中使用,这将停止测试,直到你输入一个键。你可能应该嘲笑input. 此外,您可能会认为调用input不属于setFeedback(参见@chepner 的评论)。其次,from main import *在这里不起作用(除了样式不好),因为这样您在测试模块中创建全局变量的副本 - 变量本身的更改不会传播到副本。您应该改为导入模块,以便访问模块中的变量。第三(这取自@chepner 的答案,我错过了),您必须确保变量在测试开始时处于已知状态。这是应该工作的:import unittestfrom unittest import mockimport main  # importing the module lets you access the original global variableclass TestMain(unittest.TestCase):    def setUp(self):        main.feedback = False  # make sure the state is defined at test start    @mock.patch('main.input')  # patch input to run the test w/o user interaction    def test_setFeedback(self, mock_input):        self.assertFalse(main.feedback)        main.setFeedback('y')        self.assertTrue(main.feedback)

郎朗坤

你不需要嘲笑任何东西;您只需要在运行每个测试之前确保全局变量处于已知状态即可。此外, using在您的测试模块中from main import *创建一个新的全局命名,与修改不同。feedbackmain.feedbacksetFeedbackimport mainclass TestMain(unittest.TestCase):    def setUp(self):        main.feedback = False    def test_setFeedback(self):        self.assertFalse(feedback)        main.setFeedback('y')        self.assertTrue(feedback)
随时随地看视频慕课网APP

相关分类

Python
我要回答