Python如何通过单元测试检查内部功能

时间:2020-05-27 03:53:46

标签: 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.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%的代码?指定了如何良好实施的测试用例?我必须在测试中涵盖什么内容才能完全涵盖该模块?

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

1 个答案:

答案 0 :(得分:1)

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

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

@mock.patch('Repositories.repository.Repository')
@pytest.mark.parametrize("argv", ...)
def test_get_from_user(mock_repository, argv):
    with mock.patch('data_cleaning.__main__.sys.argv', [''] + argv):
        data_cleaning.main()
        mock_repository.delete.assert_called_once()