| 1 |
# Copyright 2020, TUF contributors |
| 2 |
# SPDX-License-Identifier: MIT OR Apache-2.0 |
| 3 |
|
| 4 |
""" |
| 5 |
<Program Name> |
| 6 |
test_utils.py |
| 7 |
|
| 8 |
<Author> |
| 9 |
Martin Vrachev. |
| 10 |
|
| 11 |
<Started> |
| 12 |
October 21, 2020. |
| 13 |
|
| 14 |
<Copyright> |
| 15 |
See LICENSE-MIT OR LICENSE for licensing information. |
| 16 |
|
| 17 |
<Purpose> |
| 18 |
Provide tests for some of the functions in utils.py module. |
| 19 |
""" |
| 20 |
|
| 21 |
import logging |
| 22 |
import os |
| 23 |
import socket |
| 24 |
import sys |
| 25 |
import unittest |
| 26 |
|
| 27 |
from tests import utils |
| 28 |
|
| 29 |
logger = logging.getLogger(__name__) |
| 30 |
|
| 31 |
|
| 32 |
def can_connect(port: int) -> bool: |
| 33 |
"""Check if a socket can connect on the given port""" |
| 34 |
try: |
| 35 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 36 |
sock.connect(("localhost", port)) |
| 37 |
return True |
| 38 |
except Exception: # noqa: BLE001 |
| 39 |
return False |
| 40 |
finally: |
| 41 |
# The process will always enter in finally even after return. |
| 42 |
if sock: |
| 43 |
sock.close() |
| 44 |
|
| 45 |
|
| 46 |
class TestServerProcess(unittest.TestCase): |
| 47 |
"""Test functionality provided in TestServerProcess from tests/utils.py.""" |
| 48 |
|
| 49 |
def test_simple_server_startup(self) -> None: |
| 50 |
# Test normal case |
| 51 |
server_process_handler = utils.TestServerProcess(log=logger) |
| 52 |
|
| 53 |
# Make sure we can connect to the server |
| 54 |
self.assertTrue(can_connect(server_process_handler.port)) |
| 55 |
server_process_handler.clean() |
| 56 |
|
| 57 |
def test_cleanup(self) -> None: |
| 58 |
# Test normal case |
| 59 |
server_process_handler = utils.TestServerProcess( |
| 60 |
log=logger, server=os.path.join(utils.TESTS_DIR, "simple_server.py") |
| 61 |
) |
| 62 |
|
| 63 |
server_process_handler.clean() |
| 64 |
|
| 65 |
# Check if the process has successfully been killed. |
| 66 |
self.assertFalse(server_process_handler.is_process_running()) |
| 67 |
|
| 68 |
def test_server_exit_before_timeout(self) -> None: |
| 69 |
with self.assertRaises(utils.TestServerProcessError): |
| 70 |
utils.TestServerProcess(logger, server="non_existing_server.py") |
| 71 |
|
| 72 |
# Test starting a server which immediately exits." |
| 73 |
with self.assertRaises(utils.TestServerProcessError): |
| 74 |
utils.TestServerProcess(logger, server="fast_server_exit.py") |
| 75 |
|
| 76 |
|
| 77 |
if __name__ == "__main__": |
| 78 |
utils.configure_test_logging(sys.argv) |
| 79 |
unittest.main() |