2020-10-28 13:11:49 +00:00
|
|
|
# Copyright 2020, TUF contributors
|
|
|
|
|
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
<Program Name>
|
|
|
|
|
test_utils.py
|
|
|
|
|
|
|
|
|
|
<Author>
|
|
|
|
|
Martin Vrachev.
|
|
|
|
|
|
|
|
|
|
<Started>
|
|
|
|
|
October 21, 2020.
|
|
|
|
|
|
|
|
|
|
<Copyright>
|
|
|
|
|
See LICENSE-MIT OR LICENSE for licensing information.
|
|
|
|
|
|
|
|
|
|
<Purpose>
|
|
|
|
|
Provide tests for some of the functions in utils.py module.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
import socket
|
|
|
|
|
import sys
|
2021-12-03 12:49:12 +00:00
|
|
|
import unittest
|
2020-10-28 13:11:49 +00:00
|
|
|
|
2020-11-19 12:45:09 +00:00
|
|
|
from tests import utils
|
2020-10-28 13:11:49 +00:00
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
2021-12-03 12:49:12 +00:00
|
|
|
def can_connect(port: int) -> bool:
|
|
|
|
|
"""Check if a socket can connect on the given port"""
|
2020-10-28 13:11:49 +00:00
|
|
|
try:
|
2021-12-03 12:49:12 +00:00
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
|
sock.connect(("localhost", port))
|
|
|
|
|
return True
|
2024-04-21 05:37:40 +00:00
|
|
|
except Exception: # noqa: BLE001
|
2021-12-03 12:49:12 +00:00
|
|
|
return False
|
2020-10-28 13:11:49 +00:00
|
|
|
finally:
|
2021-12-03 12:49:12 +00:00
|
|
|
# The process will always enter in finally even after return.
|
|
|
|
|
if sock:
|
|
|
|
|
sock.close()
|
2020-10-28 13:11:49 +00:00
|
|
|
|
|
|
|
|
|
2022-01-24 12:53:10 +00:00
|
|
|
class TestServerProcess(unittest.TestCase):
|
2021-12-03 12:49:12 +00:00
|
|
|
"""Test functionality provided in TestServerProcess from tests/utils.py."""
|
|
|
|
|
|
|
|
|
|
def test_simple_server_startup(self) -> None:
|
|
|
|
|
# Test normal case
|
|
|
|
|
server_process_handler = utils.TestServerProcess(log=logger)
|
|
|
|
|
|
|
|
|
|
# Make sure we can connect to the server
|
|
|
|
|
self.assertTrue(can_connect(server_process_handler.port))
|
|
|
|
|
server_process_handler.clean()
|
|
|
|
|
|
|
|
|
|
def test_cleanup(self) -> None:
|
|
|
|
|
# Test normal case
|
|
|
|
|
server_process_handler = utils.TestServerProcess(
|
|
|
|
|
log=logger, server="simple_server.py"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
server_process_handler.clean()
|
|
|
|
|
|
|
|
|
|
# Check if the process has successfully been killed.
|
|
|
|
|
self.assertFalse(server_process_handler.is_process_running())
|
|
|
|
|
|
|
|
|
|
def test_server_exit_before_timeout(self) -> None:
|
|
|
|
|
with self.assertRaises(utils.TestServerProcessError):
|
|
|
|
|
utils.TestServerProcess(logger, server="non_existing_server.py")
|
|
|
|
|
|
|
|
|
|
# Test starting a server which immediately exits."
|
|
|
|
|
with self.assertRaises(utils.TestServerProcessError):
|
|
|
|
|
utils.TestServerProcess(logger, server="fast_server_exit.py")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
utils.configure_test_logging(sys.argv)
|
|
|
|
|
unittest.main()
|