"""Test run controller logic.""" from unittest.mock import Mock, patch from royalties.constants.constants import ACCOUNTING_PERIOD_STATUSES, CONTRACT_TYPES from royalties.constants.error import ERROR_ALREADY_EXISTS from royalties.logic import run_controller as logic from royalties.tests.utils.factories import ( AccountingPeriodFactory, RunControllerFactory, ) @patch('royalties.logic.run_controller.models.RunController') class TestRunControllerLogic: """Run controller logic tests.""" def test_create_run_controller_failure(self, mock_model): """Try to create a run controller that exists.""" name = 'Important' contract_type = CONTRACT_TYPES.DISTRIBUTION mock_model.find_by_name.return_value = '' response = logic.create_run_controller(name, contract_type) mock_model.find_by_name.assert_called_once_with(name) mock_model.create.assert_not_called() assert response.status == 400 assert response.errors['message'] == ERROR_ALREADY_EXISTS.format( object_type='run controller' ) def test_create_run_controller_success(self, mock_model, test_app_request): """Create a run controller successfully.""" name = 'Important' contract_type = CONTRACT_TYPES.DISTRIBUTION mock_model.find_by_name.return_value = None created = Mock() created.run_controller_id = 23 created.run_controller_name = name created.contract_type = contract_type mock_model.build.return_value = created response = logic.create_run_controller(name, contract_type) mock_model.find_by_name.assert_called_once_with(name) mock_model.build.assert_called_once_with( run_controller_name=name, contract_type=contract_type ) mock_model.commit_changes.assert_called_once() assert response.status == 201 assert response.message == { 'run_controller_id': 23, 'run_controller_name': name, 'contract_type': contract_type, } @patch('royalties.logic.run_controller.models') def test_add_run_controller_to_acct_period(mock_models, test_app_request): """Test given run controller is added to an open accounting period.""" run_controller = RunControllerFactory.build() open_period = AccountingPeriodFactory.build( accounting_period_status=ACCOUNTING_PERIOD_STATUSES.OPEN, closed_date=None ) mock_models.AccountingPeriod.get_current_period.return_value = open_period logic.add_run_controller_to_acct_period(run_controller) mock_models.AccountingRun.create.assert_called_with( accounting_period=open_period, run_controller=run_controller ) @patch('royalties.logic.run_controller.models') def test_add_run_controller_to_acct_period_for_closed_statements( mock_models, test_app_request ): """Test add_run_controller_to_acct_period function when all statement periods are closed.""" run_controller = RunControllerFactory.build() mock_models.StatementPeriod.get_current_statement_period.return_value = [] logic.add_run_controller_to_acct_period(run_controller) mock_models.AccountingPeriod.get_current_period.assert_not_called()