gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:45:49 24 4
gpt4 key购买 nike

我有以下测试

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% 的代码?指定实现情况的测试用例是什么?我必须在测试中涵盖哪些内容才能完全涵盖该模块?

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

最佳答案

您可以使用 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()

关于Python如何通过单元测试检查内部功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62035145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com