Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.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,我有以下测试 from unittest.mock import ANY try: from unittest import mock # python 3.3+ except ImportError: import mock # python 2.6-3.2 import pytest from data_cleaning import __main__ as data_cleaning @mock.patch('Repositories.repository.R

我有以下测试

from unittest.mock import ANY

try:
    from unittest import mock  # python 3.3+
except ImportError:
    import mock  # python 2.6-3.2

import pytest

from data_cleaning import __main__ as data_cleaning


@mock.patch('Repositories.repository.Repository.delete')
@pytest.mark.parametrize("argv", [
    (['-t', 'signals']),
    (['-t', 'signals', 'visualizations']),
    (['-t', 'signals', 'visualizations']),
    (['-d', '40', '--processes', 'historicals'])])
def test_get_from_user(mock_delete, argv):
    with mock.patch('data_cleaning.__main__.sys.argv', [''] + argv):
        data_cleaning.main()

    mock_delete.assert_has_calls([ANY])


pytest.main('-x ../data_cleaning'.split())
它试图覆盖以下代码

import argparse
import logging
import sys

from Repositories import repository
from common import config

_JSONCONFIG = config.config_json()
config.initial_configuration_for_logging()


def parse_args(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--days', help='Dias de datos que se quiere mantener.',
                        required=False, type=int, default=30)
    parser.add_argument('-p', '--processes', help='Tablas a procesar.',
                        required=True, nargs='+', choices=['signals', 'not_historicals', 'historicals'])
    return parser.parse_args(args)


def main():
    args = parse_args(sys.argv[1:])
    try:
        repo = repository.Repository()
        for process in args.processes:
            if process == 'signals':
                tables_with_column = get_tables_with_column(_JSONCONFIG['SIGNAL_TABLES'])
                for table, column in tables_with_column:
                    repo.delete(column, table, args.days)
            elif process == 'not_historicals':
                tables_with_column = get_tables_with_column(_JSONCONFIG['NOT_HISTORICALS_TABLES'])
                for table, column in tables_with_column:
                    repo.delete(column, table, args.days)
            elif process == 'historicals':
                tables_with_column = get_tables_with_column(_JSONCONFIG['HISTORICAL_TABLES'])
                for table, column in tables_with_column:
                    repo.delete(column, table, args.days)
                    repo.execute_copy_table_data_from(table, 'historica')

    except AttributeError as error:
        logging.exception(f'AttributeError: {repr(error)}')
    except KeyError as error:
        logging.exception(f'KeyError: {repr(error)}')
    except TypeError as error:
        logging.exception(f'TypeError: {repr(error)}')
    except Exception as error:
        logging.exception(f'Exception: {repr(error)}')


def get_tables_with_column(json_object):
    tables_with_column = convert_values_to_pairs_from(json_object, 'table_name', 'column_name')
    return tables_with_column


def convert_values_to_pairs_from(obj: [dict], ket_to_key: str, key_to_value: str) -> [tuple]:
    return [(item[ket_to_key], item[key_to_value]) for item in obj]
如何通过测试覆盖100%的代码?指定其实现程度的测试用例是什么?我必须在测试中涵盖哪些内容才能完全涵盖本模块

我应该如何涵盖此代码的测试?我开始进行单元测试,但已经两个多月了,我很难理解应该测试什么。

您可以使用函数断言是否调用了该特定方法

在您的情况下,这可能看起来像这样:

@mock.patch('Repositories.repository.repository'))
@pytest.mark.parametrize(“argv”,…)
def test_get_from_user(模拟存储库,argv):
使用mock.patch('data\u cleaning.\u main\u.sys.argv',['']+argv):
data_cleaning.main()
mock_repository.delete.assert_调用_once()

FAILURES,AssertionError:预期已调用一次“delete”。打了0次电话。这是对
aseert\u called\u once的调用的返回,我得到了一个提示,但显然它应该模拟方法而不是类,为什么?尝试使用assert\u called()而不是assert\u called\u once(),因为在main()函数中多次调用delete()函数。您的答案有帮助,但不正确,由于
@moc.path
应该应用于
方法
,而不是
,因此我进行了此更改,并最终使其生效。但现在还没有涵盖整个问题。是的,没错。谢谢你的投票,我会尽力把剩下的事情都讲清楚。