sptps_basic.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env python3
  2. """Test basic SPTPS features."""
  3. import os
  4. import subprocess as subp
  5. import re
  6. from testlib import path, util, check
  7. from testlib.log import log
  8. port_re = re.compile(r"Listening on (\d+)\.\.\.")
  9. class Keypair:
  10. """Create public/private keypair using sptps_keypair."""
  11. private: str
  12. public: str
  13. def __init__(self, name: str) -> None:
  14. self.private = os.path.join(path.TEST_WD, f"{name}.priv")
  15. self.public = os.path.join(path.TEST_WD, f"{name}.pub")
  16. subp.run([path.SPTPS_KEYPAIR_PATH, self.private, self.public], check=True)
  17. log.info("generate keys")
  18. server_key = Keypair("server")
  19. client_key = Keypair("client")
  20. log.info("transfer random data")
  21. DATA = util.random_string(256).encode("utf-8")
  22. def run_client(port: int, key_priv: str, key_pub: str, *flags: str) -> None:
  23. """Start client version of sptps_test."""
  24. client_cmd = [
  25. path.SPTPS_TEST_PATH,
  26. "-4",
  27. "-q",
  28. *flags,
  29. key_priv,
  30. key_pub,
  31. "localhost",
  32. str(port),
  33. ]
  34. log.info('start client with "%s"', " ".join(client_cmd))
  35. subp.run(client_cmd, input=DATA, check=True)
  36. def get_port(server: subp.Popen) -> int:
  37. """Get port that sptps_test server is listening on."""
  38. assert server.stderr
  39. while True:
  40. line = server.stderr.readline().decode("utf-8")
  41. match = port_re.match(line)
  42. if match:
  43. return int(match[1])
  44. log.debug("waiting for server to start accepting connections")
  45. def test(key0: Keypair, key1: Keypair, *flags: str) -> None:
  46. """Run tests using the supplied keypair."""
  47. server_cmd = [path.SPTPS_TEST_PATH, "-4", *flags, key0.private, key1.public, "0"]
  48. log.info('start server with "%s"', " ".join(server_cmd))
  49. with subp.Popen(server_cmd, stdout=subp.PIPE, stderr=subp.PIPE) as server:
  50. assert server.stdout
  51. port = get_port(server)
  52. run_client(port, key1.private, key0.public, *flags)
  53. received = b""
  54. while len(received) < len(DATA):
  55. received += server.stdout.read()
  56. if server.returncode is None:
  57. server.kill()
  58. check.equals(DATA, received)
  59. def run_keypair_tests(*flags: str) -> None:
  60. """Run tests on all generated keypairs."""
  61. log.info("running tests with (client, server) keypair and flags %s", flags)
  62. test(server_key, client_key)
  63. log.info("running tests with (server, client) keypair and flags %s", flags)
  64. test(client_key, server_key)
  65. log.info("running tests in stream mode")
  66. run_keypair_tests()
  67. log.info("running tests in datagram mode")
  68. run_keypair_tests("-dq")