import unittest from importlib import reload from unittest.mock import patch import pytest from fargate_tools.cli import create_task_definition class TestCreateTaskDefinition: """Test create_task_definition.py.""" mock_register_new_task_definition_response = { 'taskDefinition': { 'taskDefinitionArn': 'arn:aws:ecs:us-east-1:123456789012:task-definition/test_task_family:1', 'revision': 1 } } output_file_path = 'test_output_file.json' @pytest.mark.parametrize('create_output_file', ['false', 'true']) @patch('logging.info') @patch('fargate_tools.cli.deploy.create_new_task_definition') @patch('fargate_tools.cli.deploy.register_new_task_definition') @patch('boto3.client') def test_main(self, mock_boto_client, mock_register_new_task_definition, mock_create_new_task_definition, mock_logging_info, create_output_file): """Test main function.""" env_vars = { 'Environment': 'test', 'AWS_REGION': 'us-east-1', 'SERVICE_NAME': 'test_service', 'TASK_FAMILY': 'test_task_family' } if create_output_file == 'true': env_vars['OUTPUT_FILE_PATH'] = self.output_file_path with patch.dict('os.environ', env_vars, clear=True): # Need to reload import as env vars now set reload(create_task_definition) # Must be patched after reload with patch('fargate_tools.cli.create_task_definition.write_json_output_file') as mock_write_json_output_file: mock_ecs_client = mock_boto_client.return_value mock_create_new_task_definition.return_value = ({}, 'new_task_def') mock_register_new_task_definition.return_value = self.mock_register_new_task_definition_response create_task_definition.main() mock_logging_info.assert_called_with( 'Created arn:aws:ecs:us-east-1:123456789012:task-definition/test_task_family:1') mock_boto_client.assert_called_once_with('ecs', region_name='us-east-1') mock_create_new_task_definition.assert_called_once_with(mock_ecs_client, 'test_task_family') if create_output_file == 'true': mock_write_json_output_file.assert_called_once_with( self.mock_register_new_task_definition_response, self.output_file_path) else: mock_write_json_output_file.assert_not_called() @patch('builtins.open', new_callable=unittest.mock.mock_open) @patch('json.dumps') @patch('logging.info') def test_write_json_output_file(self, mock_logging_info, mock_json_dumps, mock_open): """Test write_json_output_file function.""" create_task_definition.write_json_output_file(self.mock_register_new_task_definition_response, self.output_file_path) mock_json_dumps.assert_called_once_with({ 'arn': 'arn:aws:ecs:us-east-1:123456789012:task-definition/test_task_family:1', 'revision': 1 }, indent=2) mock_open.assert_called_once_with(self.output_file_path, 'w') mock_open().write.assert_called_once_with(mock_json_dumps.return_value) mock_logging_info.assert_called_with(f'Wrote task definition to {self.output_file_path}')