blob: 0cce1db92db8d77e230820da197fef6a65c9168a [file] [log] [blame]
emartin03e058d2020-03-25 10:05:35 +00001# ============LICENSE_START===================================================
2# Copyright (C) 2020 Nordix Foundation.
3# ============================================================================
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16# SPDX-License-Identifier: Apache-2.0
17# ============LICENSE_END=====================================================
18import os
19import signal
20import threading
21import time
22from unittest import TestCase
23from unittest.mock import patch, Mock, MagicMock
24
25import pmsh_service_main
26from mod.exit_handler import ExitHandler
27from mod.pmsh_utils import PeriodicTask
28from mod.subscription import AdministrativeState
29
30
31class ExitHandlerTests(TestCase):
32
33 @patch('pmsh_service_main.ConfigHandler')
34 @patch('pmsh_service_main.create_app')
35 @patch('pmsh_service_main.db')
36 @patch('pmsh_service_main.aai.get_pmsh_subscription_data')
37 @patch('pmsh_service_main.AppConfig')
38 @patch('pmsh_service_main.Subscription')
39 @patch('pmsh_service_main.launch_api_server')
40 @patch('pmsh_service_main.SubscriptionHandler')
41 @patch.object(PeriodicTask, 'start')
42 @patch.object(PeriodicTask, 'cancel')
43 def test_terminate_signal_success(self, mock_task_cancel, mock_task_start, mock_sub_handler,
44 mock_launch_api_server, mock_sub, mock_app_conf, mock_aai,
45 mock_db, mock_app, mock_config_handler):
46 pid = os.getpid()
47 mock_aai.return_value = [Mock(), Mock()]
48 mock_db.get_app.return_value = Mock()
49
50 mock_sub.administrativeState = AdministrativeState.UNLOCKED.value
51 mock_sub.process_subscription = Mock()
52 mock_sub_handler_instance = MagicMock(execute=Mock(), current_sub=mock_sub)
53 mock_sub_handler.side_effect = [mock_sub_handler_instance]
54
55 def mock_api_server_run(param):
56 while mock_sub.administrativeState == AdministrativeState.UNLOCKED.value:
57 time.sleep(1)
58
59 mock_launch_api_server.side_effect = mock_api_server_run
60
61 def trigger_signal():
62 time.sleep(1)
63 os.kill(pid, signal.SIGTERM)
64
65 thread = threading.Thread(target=trigger_signal)
66 thread.start()
67
68 pmsh_service_main.main()
69
70 self.assertEqual(3, mock_task_cancel.call_count)
71 self.assertTrue(ExitHandler.shutdown_signal_received)
72 self.assertEqual(1, mock_sub.process_subscription.call_count)
73 self.assertEqual(mock_sub.administrativeState, AdministrativeState.LOCKED.value)