You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

74 lines
2.5 KiB

  1. from .._events import *
  2. from .._state import *
  3. from .._connection import *
  4. def get_all_events(conn):
  5. got_events = []
  6. while True:
  7. event = conn.next_event()
  8. if event in (NEED_DATA, PAUSED):
  9. break
  10. got_events.append(event)
  11. if type(event) is ConnectionClosed:
  12. break
  13. return got_events
  14. def receive_and_get(conn, data):
  15. conn.receive_data(data)
  16. return get_all_events(conn)
  17. # Merges adjacent Data events, converts payloads to bytestrings, and removes
  18. # chunk boundaries.
  19. def normalize_data_events(in_events):
  20. out_events = []
  21. for event in in_events:
  22. if type(event) is Data:
  23. event.data = bytes(event.data)
  24. event.chunk_start = False
  25. event.chunk_end = False
  26. if out_events and type(out_events[-1]) is type(event) is Data:
  27. out_events[-1].data += event.data
  28. else:
  29. out_events.append(event)
  30. return out_events
  31. # Given that we want to write tests that push some events through a Connection
  32. # and check that its state updates appropriately... we might as make a habit
  33. # of pushing them through two Connections with a fake network link in
  34. # between.
  35. class ConnectionPair:
  36. def __init__(self):
  37. self.conn = {CLIENT: Connection(CLIENT), SERVER: Connection(SERVER)}
  38. self.other = {CLIENT: SERVER, SERVER: CLIENT}
  39. @property
  40. def conns(self):
  41. return self.conn.values()
  42. # expect="match" if expect=send_events; expect=[...] to say what expected
  43. def send(self, role, send_events, expect="match"):
  44. if not isinstance(send_events, list):
  45. send_events = [send_events]
  46. data = b""
  47. closed = False
  48. for send_event in send_events:
  49. new_data = self.conn[role].send(send_event)
  50. if new_data is None:
  51. closed = True
  52. else:
  53. data += new_data
  54. # send uses b"" to mean b"", and None to mean closed
  55. # receive uses b"" to mean closed, and None to mean "try again"
  56. # so we have to translate between the two conventions
  57. if data:
  58. self.conn[self.other[role]].receive_data(data)
  59. if closed:
  60. self.conn[self.other[role]].receive_data(b"")
  61. got_events = get_all_events(self.conn[self.other[role]])
  62. if expect == "match":
  63. expect = send_events
  64. if not isinstance(expect, list):
  65. expect = [expect]
  66. assert got_events == expect
  67. return data