Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我的单元测试是否正确编写以测试代码函数_Python_Unit Testing_Pytest - Fatal编程技术网

Python 我的单元测试是否正确编写以测试代码函数

Python 我的单元测试是否正确编写以测试代码函数,python,unit-testing,pytest,Python,Unit Testing,Pytest,尝试编写单元测试来测试我的Python代码项目 我有一个gestioner.py文件,用于检查用户输入,并查看它们是否有效(从允许列表中)或无效(从“危险列表中”) 然后还检查输入的命令是否输入了任何可疑字符,以防止安全攻击 现在,我想将单元测试添加到Gestioner.py中的函数代码中 以下是Stackoverflow问题中的书面说明: 然后是py.test文档() 我编写了以下test_gestioner.py来开始我的单元测试,如下所示: 而我的三次测试似乎一直在进行。但是我怀疑我的这些

尝试编写单元测试来测试我的Python代码项目

我有一个gestioner.py文件,用于检查用户输入,并查看它们是否有效(从允许列表中)或无效(从“危险列表中”) 然后还检查输入的命令是否输入了任何可疑字符,以防止安全攻击

现在,我想将单元测试添加到Gestioner.py中的函数代码中

以下是Stackoverflow问题中的书面说明:

然后是py.test文档()

我编写了以下test_gestioner.py来开始我的单元测试,如下所示:

而我的三次测试似乎一直在进行。但是我怀疑我的这些测试是否真的正确地测试了我的代码,因为当我期望测试失败时,测试还是通过了

我是否正确地进行了代码的单元测试? 在我看来,我不是,所以请建议我在单元测试中犯了什么错误

这是我的主要脚本,Gestioner.py



import sys
import re


class CmdGestioner:
    _allowed_list = ['fichier', 'binfile', 'prep', 'rep' ]
    _danger_list = ['gen', 'regen'] 

    def __init__(self):
        None

    def chk_cmds(self, mycmd):
        print('chk_cmds: lets look term at {}'.format(mycmd))
        regex = re.compile(r'[&`%;$><!#]')
        msg = bool(regex.search(mycmd))
        print('My command: ' +mycmd)
        if msg is True:
            print(msg)
            print('Found a suspicious entry in the command : {}'.format(mycmd))
            return -1
        else:
            print('Command seems clean {}'.format(mycmd))
            return 0


    def is_valid(self, in_command):
        valid = True


        cmd_mtg_str = ''.join(str(elem) for elem in in_command)



        for term in cmd_mtg_str.split():

            if term.strip('--') not in self._allowed_list:
                if term.strip('--') in self._forbidden_list:
                    valid = False
                    print('Found a forbidden Sec_Service command '+term)
                else:
                    print ('%s not found in list so need to runs checks on this!' % (term))
                    checkResult = self.chk_cmds(term)
                    if checkResult == -1:
                        valid = False
            else:
                print ('Found in list so term %s is valid' % (term))
        return valid




test_command = ' '.join(str(elem) for elem in sys.argv[1:])
cmd = CmdGestioner()

status = cmd.is_valid(test_command)
print ('\nStatus for command: %s is %s' % (test_command,status))

import sys
import re
import unittest
import pytest
from gestioner import CmdGestioner

cmd = CmdGestioner()


def test_chk_cmds_valid():
    mycmd = "--binfile testbinfile"
    cmd.chk_cmds(mycmd)
    assert 'Status for command: ' +mycmd +' is True'


def test_chk_cmds_danger():
    mycmd = "--gen genf"
    cmd.chk_cmds(mycmd)
    assert 'Status for command: ' +mycmd +' is False'


def test_chk_cmds_attacks():
    mycmd = ";ls"
    cmd.chk_cmds(mycmd)
    assert 'Found a suspicious entry in the command : ' .format(mycmd)
    assert 'Status for command: ' +mycmd +' is False


正在执行的我的单元测试:

PS C:\Work\Questions_forums\SecService_messaging> py.test -v                                                                                                                                                                                       ================================================================================== test session starts =============================================================================================================================
platform win32 -- Python 3.7.4, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- c:\users\SecUser\appdata\local\programs\python\python37\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.7.4', 'Platform': 'Windows-10-10.0.18362-SP0', 'Packages': {'pytest': '5.0.1', 'py': '1.8.0', 'pluggy': '0.12.0'}, 'Plugins': {'html': '1.21.1', 'metadata': '1.8.0'}}
rootdir: C:\Work\Questions_forums\SecService_messaging
plugins: html-1.21.1, metadata-1.8.0
collected 3 items

test_gestioner.py::test_chk_cmds_valid PASSED                                                                                                                                                                                                                           [ 33%]
test_gestioner.py::test_chk_cmds_danger PASSED                                                                                                                                                                                                                          [ 66%]
test_gestioner.py::test_chk_cmds_attacks PASSED                                                                                                                                                                                                                         [100%]

========================================================================================================================== 3 passed in 0.03 seconds ==========================================================================================================================

不,您的单元测试编写不正确。chk_cmd方法不返回字符串,它打印到标准输出,但是您的断言语句正在查找chk_cmd的结果是否等于打印的结果。相反,assert语句检查字符串是否等于true,一个或多个特许的任何字符串都被视为true,因此这些测试应该始终通过。要使assert语句在编写时正常工作,您需要从chk_cmd方法返回预期的字符串,或者测试其他内容。比如说

assert cmd.是否有效('rep')
assert cmd.chk_cmds(mycmd)=-1
assert cmd.chk\u cmd(mycmd)=0
看起来您可能来自具有-1和0返回值的C编程背景。如果您将这些值重写为True和False,则会改进代码和断言。以下重构:

class cmdgestoner:
_允许的_列表=['fichier'、'binfile'、'prep'、'rep']
_危险列表=['gen','regen']
def chk_cmds(自我,mycmd):
regex=re.compile(r'[&`%;$>

您当前的断言方式应该始终为true,因为您正在检查字符串而不是标准输出。

您似乎没有断言任何有关
cmd.chk\u cmds(mycmd)
返回值的内容。谢谢infosmith,非常简单。