Python单元测试正确设置全局变量

CWh*_*ite 8 python unit-testing python-3.x python-unittest python-unittest.mock

我有一个简单的方法,根据方法参数将全局变量设置为 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)
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,出现以下错误:AssertionError: False is not true

因为我知道该方法工作正常,所以我假设全局变量以某种方式重置。然而,由于我对Python环境还很陌生,所以我不知道我到底做错了什么。

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

如果有建议,我将不胜感激。

这是代码:

主要.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()
Run Code Online (Sandbox Code Playgroud)

测试_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()
Run Code Online (Sandbox Code Playgroud)

MrB*_*men 10

你的测试有两个问题。

首先,您inputfeedback函数中使用,这将停止测试,直到您输入密钥。你可能应该嘲笑input. 另外,您可能会认为对的调用input不属于setFeedback(请参阅@chepner 的评论)。

其次,from main import *在这里不起作用(除了不好的风格之外),因为这样您可以在测试模块中创建全局变量的副本 - 变量本身的更改不会传播到副本。您应该导入模块,以便访问模块中的变量。

第三(这取自@chepner的答案,我错过了),你必须确保变量在测试开始时处于已知状态。

这是应该起作用的:

import unittest
from unittest import mock

import main  # importing the module lets you access the original global variable


class 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)
Run Code Online (Sandbox Code Playgroud)