code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def remotely_pushed(self, pushed_headers: Iterable[Header]) -> tuple[list[Frame], list[Event]]:
"""
Mark this stream as one that was pushed by the remote peer. Must be
called immediately after initialization. Sends no frames, simply
updates the state machine.
"""
self.config.logger.debug("%r pushed by remote peer", self)
events = self.state_machine.process_input(
StreamInputs.RECV_PUSH_PROMISE,
)
self._authority = authority_from_headers(pushed_headers)
return [], events |
Mark this stream as one that was pushed by the remote peer. Must be
called immediately after initialization. Sends no frames, simply
updates the state machine.
| remotely_pushed | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def receive_headers(self,
headers: Iterable[Header],
end_stream: bool,
header_encoding: bool | str | None) -> tuple[list[Frame], list[Event]]:
"""
Receive a set of headers (or trailers).
"""
if is_informational_response(headers):
if end_stream:
msg = "Cannot set END_STREAM on informational responses"
raise ProtocolError(msg)
input_ = StreamInputs.RECV_INFORMATIONAL_HEADERS
else:
input_ = StreamInputs.RECV_HEADERS
events = self.state_machine.process_input(input_)
headers_event = cast(
"Union[RequestReceived, ResponseReceived, TrailersReceived, InformationalResponseReceived]",
events[0],
)
if end_stream:
es_events = self.state_machine.process_input(
StreamInputs.RECV_END_STREAM,
)
# We ensured it's not an information response at the beginning of the method.
cast(
"Union[RequestReceived, ResponseReceived, TrailersReceived]",
headers_event,
).stream_ended = cast("StreamEnded", es_events[0])
events += es_events
self._initialize_content_length(headers)
if isinstance(headers_event, TrailersReceived) and not end_stream:
msg = "Trailers must have END_STREAM set"
raise ProtocolError(msg)
hdr_validation_flags = self._build_hdr_validation_flags(events)
headers_event.headers = self._process_received_headers(
headers, hdr_validation_flags, header_encoding,
)
return [], events |
Receive a set of headers (or trailers).
| receive_headers | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def receive_continuation(self) -> None:
"""
A naked CONTINUATION frame has been received. This is always an error,
but the type of error it is depends on the state of the stream and must
transition the state of the stream, so we need to handle it.
"""
self.config.logger.debug("Receive Continuation frame on %r", self)
self.state_machine.process_input(
StreamInputs.RECV_CONTINUATION,
)
msg = "Should not be reachable" # pragma: no cover
raise AssertionError(msg) # pragma: no cover |
A naked CONTINUATION frame has been received. This is always an error,
but the type of error it is depends on the state of the stream and must
transition the state of the stream, so we need to handle it.
| receive_continuation | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def receive_alt_svc(self, frame: AltSvcFrame) -> tuple[list[Frame], list[Event]]:
"""
An Alternative Service frame was received on the stream. This frame
inherits the origin associated with this stream.
"""
self.config.logger.debug(
"Receive Alternative Service frame on stream %r", self,
)
# If the origin is present, RFC 7838 says we have to ignore it.
if frame.origin:
return [], []
events = self.state_machine.process_input(
StreamInputs.RECV_ALTERNATIVE_SERVICE,
)
# There are lots of situations where we want to ignore the ALTSVC
# frame. If we need to pay attention, we'll have an event and should
# fill it out.
if events:
assert isinstance(events[0], AlternativeServiceAvailable)
events[0].origin = self._authority
events[0].field_value = frame.field
return [], events |
An Alternative Service frame was received on the stream. This frame
inherits the origin associated with this stream.
| receive_alt_svc | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def reset_stream(self, error_code: ErrorCodes | int = 0) -> list[Frame]:
"""
Close the stream locally. Reset the stream with an error code.
"""
self.config.logger.debug(
"Local reset %r with error code: %d", self, error_code,
)
self.state_machine.process_input(StreamInputs.SEND_RST_STREAM)
rsf = RstStreamFrame(self.stream_id)
rsf.error_code = error_code
return [rsf] |
Close the stream locally. Reset the stream with an error code.
| reset_stream | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def acknowledge_received_data(self, acknowledged_size: int) -> list[Frame]:
"""
The user has informed us that they've processed some amount of data
that was received on this stream. Pass that to the window manager and
potentially return some WindowUpdate frames.
"""
self.config.logger.debug(
"Acknowledge received data with size %d on %r",
acknowledged_size, self,
)
increment = self._inbound_window_manager.process_bytes(
acknowledged_size,
)
if increment:
f = WindowUpdateFrame(self.stream_id)
f.window_increment = increment
return [f]
return [] |
The user has informed us that they've processed some amount of data
that was received on this stream. Pass that to the window manager and
potentially return some WindowUpdate frames.
| acknowledge_received_data | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _build_hdr_validation_flags(self, events: Any) -> HeaderValidationFlags:
"""
Constructs a set of header validation flags for use when normalizing
and validating header blocks.
"""
is_trailer = isinstance(
events[0], (_TrailersSent, TrailersReceived),
)
is_response_header = isinstance(
events[0],
(
_ResponseSent,
ResponseReceived,
InformationalResponseReceived,
),
)
is_push_promise = isinstance(
events[0], (PushedStreamReceived, _PushedRequestSent),
)
return HeaderValidationFlags(
is_client=self.state_machine.client or False,
is_trailer=is_trailer,
is_response_header=is_response_header,
is_push_promise=is_push_promise,
) |
Constructs a set of header validation flags for use when normalizing
and validating header blocks.
| _build_hdr_validation_flags | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _build_headers_frames(self,
headers: Iterable[Header],
encoder: Encoder,
first_frame: HeadersFrame | PushPromiseFrame,
hdr_validation_flags: HeaderValidationFlags) \
-> list[HeadersFrame | ContinuationFrame | PushPromiseFrame]:
"""
Helper method to build headers or push promise frames.
"""
# We need to lowercase the header names, and to ensure that secure
# header fields are kept out of compression contexts.
if self.config.normalize_outbound_headers:
# also we may want to split outbound cookies to improve
# headers compression
should_split_outbound_cookies = self.config.split_outbound_cookies
headers = normalize_outbound_headers(
headers, hdr_validation_flags, should_split_outbound_cookies,
)
if self.config.validate_outbound_headers:
headers = validate_outbound_headers(
headers, hdr_validation_flags,
)
encoded_headers = encoder.encode(headers)
# Slice into blocks of max_outbound_frame_size. Be careful with this:
# it only works right because we never send padded frames or priority
# information on the frames. Revisit this if we do.
header_blocks = [
encoded_headers[i:i+(self.max_outbound_frame_size or 0)]
for i in range(
0, len(encoded_headers), (self.max_outbound_frame_size or 0),
)
]
frames: list[HeadersFrame | ContinuationFrame | PushPromiseFrame] = []
first_frame.data = header_blocks[0]
frames.append(first_frame)
for block in header_blocks[1:]:
cf = ContinuationFrame(self.stream_id)
cf.data = block
frames.append(cf)
frames[-1].flags.add("END_HEADERS")
return frames |
Helper method to build headers or push promise frames.
| _build_headers_frames | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _process_received_headers(self,
headers: Iterable[Header],
header_validation_flags: HeaderValidationFlags,
header_encoding: bool | str | None) -> list[Header]:
"""
When headers have been received from the remote peer, run a processing
pipeline on them to transform them into the appropriate form for
attaching to an event.
"""
if self.config.normalize_inbound_headers:
headers = normalize_inbound_headers(
headers, header_validation_flags,
)
if self.config.validate_inbound_headers:
headers = validate_headers(headers, header_validation_flags)
if isinstance(header_encoding, str):
headers = _decode_headers(headers, header_encoding)
# The above steps are all generators, so we need to concretize the
# headers now.
return list(headers) |
When headers have been received from the remote peer, run a processing
pipeline on them to transform them into the appropriate form for
attaching to an event.
| _process_received_headers | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _initialize_content_length(self, headers: Iterable[Header]) -> None:
"""
Checks the headers for a content-length header and initializes the
_expected_content_length field from it. It's not an error for no
Content-Length header to be present.
"""
if self.request_method == b"HEAD":
self._expected_content_length = 0
return
for n, v in headers:
if n == b"content-length":
try:
self._expected_content_length = int(v, 10)
except ValueError as err:
msg = f"Invalid content-length header: {v!r}"
raise ProtocolError(msg) from err
return |
Checks the headers for a content-length header and initializes the
_expected_content_length field from it. It's not an error for no
Content-Length header to be present.
| _initialize_content_length | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _track_content_length(self, length: int, end_stream: bool) -> None:
"""
Update the expected content length in response to data being received.
Validates that the appropriate amount of data is sent. Always updates
the received data, but only validates the length against the
content-length header if one was sent.
:param length: The length of the body chunk received.
:param end_stream: If this is the last body chunk received.
"""
self._actual_content_length += length
actual = self._actual_content_length
expected = self._expected_content_length
if expected is not None:
if expected < actual:
raise InvalidBodyLengthError(expected, actual)
if end_stream and expected != actual:
raise InvalidBodyLengthError(expected, actual) |
Update the expected content length in response to data being received.
Validates that the appropriate amount of data is sent. Always updates
the received data, but only validates the length against the
content-length header if one was sent.
:param length: The length of the body chunk received.
:param end_stream: If this is the last body chunk received.
| _track_content_length | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _inbound_flow_control_change_from_settings(self, delta: int) -> None:
"""
We changed SETTINGS_INITIAL_WINDOW_SIZE, which means we need to
update the target window size for flow control. For our flow control
strategy, this means we need to do two things: we need to adjust the
current window size, but we also need to set the target maximum window
size to the new value.
"""
new_max_size = self._inbound_window_manager.max_window_size + delta
self._inbound_window_manager.window_opened(delta)
self._inbound_window_manager.max_window_size = new_max_size |
We changed SETTINGS_INITIAL_WINDOW_SIZE, which means we need to
update the target window size for flow control. For our flow control
strategy, this means we need to do two things: we need to adjust the
current window size, but we also need to set the target maximum window
size to the new value.
| _inbound_flow_control_change_from_settings | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _decode_headers(headers: Iterable[HeaderWeaklyTyped], encoding: str) -> Generator[HeaderTuple, None, None]:
"""
Given an iterable of header two-tuples and an encoding, decodes those
headers using that encoding while preserving the type of the header tuple.
This ensures that the use of ``HeaderTuple`` is preserved.
"""
for header in headers:
# This function expects to work on decoded headers, which are always
# HeaderTuple objects.
assert isinstance(header, HeaderTuple)
name, value = header
assert isinstance(name, bytes)
assert isinstance(value, bytes)
n = name.decode(encoding)
v = value.decode(encoding)
yield header.__class__(n, v) |
Given an iterable of header two-tuples and an encoding, decodes those
headers using that encoding while preserving the type of the header tuple.
This ensures that the use of ``HeaderTuple`` is preserved.
| _decode_headers | python | python-hyper/h2 | src/h2/stream.py | https://github.com/python-hyper/h2/blob/master/src/h2/stream.py | MIT |
def _secure_headers(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]:
"""
Certain headers are at risk of being attacked during the header compression
phase, and so need to be kept out of header compression contexts. This
function automatically transforms certain specific headers into HPACK
never-indexed fields to ensure they don't get added to header compression
contexts.
This function currently implements two rules:
- 'authorization' and 'proxy-authorization' fields are automatically made
never-indexed.
- Any 'cookie' header field shorter than 20 bytes long is made
never-indexed.
These fields are the most at-risk. These rules are inspired by Firefox
and nghttp2.
"""
for header in headers:
assert isinstance(header[0], bytes)
if header[0] in _SECURE_HEADERS or (header[0] in b"cookie" and len(header[1]) < 20):
yield NeverIndexedHeaderTuple(header[0], header[1])
else:
yield header |
Certain headers are at risk of being attacked during the header compression
phase, and so need to be kept out of header compression contexts. This
function automatically transforms certain specific headers into HPACK
never-indexed fields to ensure they don't get added to header compression
contexts.
This function currently implements two rules:
- 'authorization' and 'proxy-authorization' fields are automatically made
never-indexed.
- Any 'cookie' header field shorter than 20 bytes long is made
never-indexed.
These fields are the most at-risk. These rules are inspired by Firefox
and nghttp2.
| _secure_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def extract_method_header(headers: Iterable[Header]) -> bytes | None:
"""
Extracts the request method from the headers list.
"""
for k, v in headers:
if isinstance(v, bytes) and k == b":method":
return v
if isinstance(v, str) and k == ":method":
return v.encode("utf-8") # pragma: no cover
return None |
Extracts the request method from the headers list.
| extract_method_header | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def is_informational_response(headers: Iterable[Header]) -> bool:
"""
Searches headers list for a :status header to confirm that a given
collection of headers are an informational response. Assumes the header
are well formed and encoded as bytes: that is, that the HTTP/2 special
headers are first in the block, and so that it can stop looking when it
finds the first header field whose name does not begin with a colon.
:param headers: The HTTP/2 headers.
:returns: A boolean indicating if this is an informational response.
"""
for n, v in headers:
if not n.startswith(b":"):
return False
if n != b":status":
# If we find a non-special header, we're done here: stop looping.
continue
# If the first digit is a 1, we've got informational headers.
return v.startswith(b"1")
return False |
Searches headers list for a :status header to confirm that a given
collection of headers are an informational response. Assumes the header
are well formed and encoded as bytes: that is, that the HTTP/2 special
headers are first in the block, and so that it can stop looking when it
finds the first header field whose name does not begin with a colon.
:param headers: The HTTP/2 headers.
:returns: A boolean indicating if this is an informational response.
| is_informational_response | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def guard_increment_window(current: int, increment: int) -> int:
"""
Increments a flow control window, guarding against that window becoming too
large.
:param current: The current value of the flow control window.
:param increment: The increment to apply to that window.
:returns: The new value of the window.
:raises: ``FlowControlError``
"""
# The largest value the flow control window may take.
LARGEST_FLOW_CONTROL_WINDOW = 2**31 - 1 # noqa: N806
new_size = current + increment
if new_size > LARGEST_FLOW_CONTROL_WINDOW:
msg = f"May not increment flow control window past {LARGEST_FLOW_CONTROL_WINDOW}"
raise FlowControlError(msg)
return new_size |
Increments a flow control window, guarding against that window becoming too
large.
:param current: The current value of the flow control window.
:param increment: The increment to apply to that window.
:returns: The new value of the window.
:raises: ``FlowControlError``
| guard_increment_window | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def authority_from_headers(headers: Iterable[Header]) -> bytes | None:
"""
Given a header set, searches for the authority header and returns the
value.
Note that this doesn't use indexing, so should only be called if the
headers are for a client request. Otherwise, will loop over the entire
header set, which is potentially unwise.
:param headers: The HTTP header set.
:returns: The value of the authority header, or ``None``.
:rtype: ``bytes`` or ``None``.
"""
for n, v in headers:
if n == b":authority":
return v
return None |
Given a header set, searches for the authority header and returns the
value.
Note that this doesn't use indexing, so should only be called if the
headers are for a client request. Otherwise, will loop over the entire
header set, which is potentially unwise.
:param headers: The HTTP header set.
:returns: The value of the authority header, or ``None``.
:rtype: ``bytes`` or ``None``.
| authority_from_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def validate_headers(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Iterable[Header]:
"""
Validates a header sequence against a set of constraints from RFC 7540.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags.
"""
# This validation logic is built on a sequence of generators that are
# iterated over to provide the final header list. This reduces some of the
# overhead of doing this checking. However, it's worth noting that this
# checking remains somewhat expensive, and attempts should be made wherever
# possible to reduce the time spent doing them.
#
# For example, we avoid tuple unpacking in loops because it represents a
# fixed cost that we don't want to spend, instead indexing into the header
# tuples.
headers = _reject_empty_header_names(
headers, hdr_validation_flags,
)
headers = _reject_uppercase_header_fields(
headers, hdr_validation_flags,
)
headers = _reject_surrounding_whitespace(
headers, hdr_validation_flags,
)
headers = _reject_te(
headers, hdr_validation_flags,
)
headers = _reject_connection_header(
headers, hdr_validation_flags,
)
headers = _reject_pseudo_header_fields(
headers, hdr_validation_flags,
)
headers = _check_host_authority_header(
headers, hdr_validation_flags,
)
return _check_path_header(headers, hdr_validation_flags) |
Validates a header sequence against a set of constraints from RFC 7540.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags.
| validate_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _reject_empty_header_names(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if any header names are empty (length 0).
While hpack decodes such headers without errors, they are semantically
forbidden in HTTP, see RFC 7230, stating that they must be at least one
character long.
"""
for header in headers:
if len(header[0]) == 0:
msg = "Received header name with zero length."
raise ProtocolError(msg)
yield header |
Raises a ProtocolError if any header names are empty (length 0).
While hpack decodes such headers without errors, they are semantically
forbidden in HTTP, see RFC 7230, stating that they must be at least one
character long.
| _reject_empty_header_names | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _reject_uppercase_header_fields(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if any uppercase character is found in a header
block.
"""
for header in headers:
if UPPER_RE.search(header[0]):
msg = f"Received uppercase header name {header[0]!r}."
raise ProtocolError(msg)
yield header |
Raises a ProtocolError if any uppercase character is found in a header
block.
| _reject_uppercase_header_fields | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _reject_surrounding_whitespace(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if any header name or value is surrounded by
whitespace characters.
"""
# For compatibility with RFC 7230 header fields, we need to allow the field
# value to be an empty string. This is ludicrous, but technically allowed.
# The field name may not be empty, though, so we can safely assume that it
# must have at least one character in it and throw exceptions if it
# doesn't.
for header in headers:
if header[0][0] in _WHITESPACE or header[0][-1] in _WHITESPACE:
msg = f"Received header name surrounded by whitespace {header[0]!r}"
raise ProtocolError(msg)
if header[1] and ((header[1][0] in _WHITESPACE) or
(header[1][-1] in _WHITESPACE)):
msg = f"Received header value surrounded by whitespace {header[1]!r}"
raise ProtocolError(msg)
yield header |
Raises a ProtocolError if any header name or value is surrounded by
whitespace characters.
| _reject_surrounding_whitespace | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _reject_te(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if the TE header is present in a header block and
its value is anything other than "trailers".
"""
for header in headers:
if header[0] == b"te" and header[1].lower() != b"trailers":
msg = f"Invalid value for TE header: {header[1]!r}"
raise ProtocolError(msg)
yield header |
Raises a ProtocolError if the TE header is present in a header block and
its value is anything other than "trailers".
| _reject_te | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _reject_connection_header(headers: Iterable[Header], hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if the Connection header is present in a header
block.
"""
for header in headers:
if header[0] in CONNECTION_HEADERS:
msg = f"Connection-specific header field present: {header[0]!r}."
raise ProtocolError(msg)
yield header |
Raises a ProtocolError if the Connection header is present in a header
block.
| _reject_connection_header | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _assert_header_in_set(bytes_header: bytes,
header_set: set[bytes | str] | set[bytes] | set[str]) -> None:
"""
Given a set of header names, checks whether the string or byte version of
the header name is present. Raises a Protocol error with the appropriate
error if it's missing.
"""
if bytes_header not in header_set:
msg = f"Header block missing mandatory {bytes_header!r} header"
raise ProtocolError(msg) |
Given a set of header names, checks whether the string or byte version of
the header name is present. Raises a Protocol error with the appropriate
error if it's missing.
| _assert_header_in_set | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _reject_pseudo_header_fields(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if duplicate pseudo-header fields are found in a
header block or if a pseudo-header field appears in a block after an
ordinary header field.
Raises a ProtocolError if pseudo-header fields are found in trailers.
"""
seen_pseudo_header_fields = set()
seen_regular_header = False
method = None
for header in headers:
if header[0][0] == SIGIL:
if header[0] in seen_pseudo_header_fields:
msg = f"Received duplicate pseudo-header field {header[0]!r}"
raise ProtocolError(msg)
seen_pseudo_header_fields.add(header[0])
if seen_regular_header:
msg = f"Received pseudo-header field out of sequence: {header[0]!r}"
raise ProtocolError(msg)
if header[0] not in _ALLOWED_PSEUDO_HEADER_FIELDS:
msg = f"Received custom pseudo-header field {header[0]!r}"
raise ProtocolError(msg)
if header[0] in b":method":
method = header[1]
else:
seen_regular_header = True
yield header
# Check the pseudo-headers we got to confirm they're acceptable.
_check_pseudo_header_field_acceptability(
seen_pseudo_header_fields, method, hdr_validation_flags,
) |
Raises a ProtocolError if duplicate pseudo-header fields are found in a
header block or if a pseudo-header field appears in a block after an
ordinary header field.
Raises a ProtocolError if pseudo-header fields are found in trailers.
| _reject_pseudo_header_fields | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _validate_host_authority_header(headers: Iterable[Header]) -> Generator[Header, None, None]:
"""
Given the :authority and Host headers from a request block that isn't
a trailer, check that:
1. At least one of these headers is set.
2. If both headers are set, they match.
:param headers: The HTTP header set.
:raises: ``ProtocolError``
"""
# We use None as a sentinel value. Iterate over the list of headers,
# and record the value of these headers (if present). We don't need
# to worry about receiving duplicate :authority headers, as this is
# enforced by the _reject_pseudo_header_fields() pipeline.
#
# TODO: We should also guard against receiving duplicate Host headers,
# and against sending duplicate headers.
authority_header_val = None
host_header_val = None
for header in headers:
if header[0] == b":authority":
authority_header_val = header[1]
elif header[0] == b"host":
host_header_val = header[1]
yield header
# If we have not-None values for these variables, then we know we saw
# the corresponding header.
authority_present = (authority_header_val is not None)
host_present = (host_header_val is not None)
# It is an error for a request header block to contain neither
# an :authority header nor a Host header.
if not authority_present and not host_present:
msg = "Request header block does not have an :authority or Host header."
raise ProtocolError(msg)
# If we receive both headers, they should definitely match.
if authority_present and host_present and authority_header_val != host_header_val:
msg = (
"Request header block has mismatched :authority and "
f"Host headers: {authority_header_val!r} / {host_header_val!r}"
)
raise ProtocolError(msg) |
Given the :authority and Host headers from a request block that isn't
a trailer, check that:
1. At least one of these headers is set.
2. If both headers are set, they match.
:param headers: The HTTP header set.
:raises: ``ProtocolError``
| _validate_host_authority_header | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _check_host_authority_header(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises a ProtocolError if a header block arrives that does not contain an
:authority or a Host header, or if a header block contains both fields,
but their values do not match.
"""
# We only expect to see :authority and Host headers on request header
# blocks that aren't trailers, so skip this validation if this is a
# response header or we're looking at trailer blocks.
skip_validation = (
hdr_validation_flags.is_response_header or
hdr_validation_flags.is_trailer
)
if skip_validation:
return (h for h in headers)
return _validate_host_authority_header(headers) |
Raises a ProtocolError if a header block arrives that does not contain an
:authority or a Host header, or if a header block contains both fields,
but their values do not match.
| _check_host_authority_header | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _check_path_header(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raise a ProtocolError if a header block arrives or is sent that contains an
empty :path header.
"""
def inner() -> Generator[Header, None, None]:
for header in headers:
if header[0] == b":path" and not header[1]:
msg = "An empty :path header is forbidden"
raise ProtocolError(msg)
yield header
# We only expect to see :authority and Host headers on request header
# blocks that aren't trailers, so skip this validation if this is a
# response header or we're looking at trailer blocks.
skip_validation = (
hdr_validation_flags.is_response_header or
hdr_validation_flags.is_trailer
)
if skip_validation:
return (h for h in headers)
return inner() |
Raise a ProtocolError if a header block arrives or is sent that contains an
empty :path header.
| _check_path_header | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def utf8_encode_headers(headers: Iterable[HeaderWeaklyTyped]) -> list[Header]:
"""
Given an iterable of header two-tuples, rebuilds that as a list with the
header names and values encoded as utf-8 bytes. This function produces
tuples that preserve the original type of the header tuple for tuple and
any ``HeaderTuple``.
"""
encoded_headers: list[Header] = []
for header in headers:
h = (_to_bytes(header[0]), _to_bytes(header[1]))
if isinstance(header, HeaderTuple):
encoded_headers.append(header.__class__(h[0], h[1]))
else:
encoded_headers.append(h)
return encoded_headers |
Given an iterable of header two-tuples, rebuilds that as a list with the
header names and values encoded as utf-8 bytes. This function produces
tuples that preserve the original type of the header tuple for tuple and
any ``HeaderTuple``.
| utf8_encode_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _lowercase_header_names(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]:
"""
Given an iterable of header two-tuples, rebuilds that iterable with the
header names lowercased. This generator produces tuples that preserve the
original type of the header tuple for tuple and any ``HeaderTuple``.
"""
for header in headers:
if isinstance(header, HeaderTuple):
yield header.__class__(header[0].lower(), header[1])
else:
yield (header[0].lower(), header[1]) |
Given an iterable of header two-tuples, rebuilds that iterable with the
header names lowercased. This generator produces tuples that preserve the
original type of the header tuple for tuple and any ``HeaderTuple``.
| _lowercase_header_names | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _strip_surrounding_whitespace(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags | None) -> Generator[Header, None, None]:
"""
Given an iterable of header two-tuples, strip both leading and trailing
whitespace from both header names and header values. This generator
produces tuples that preserve the original type of the header tuple for
tuple and any ``HeaderTuple``.
"""
for header in headers:
if isinstance(header, HeaderTuple):
yield header.__class__(header[0].strip(), header[1].strip())
else:
yield (header[0].strip(), header[1].strip()) |
Given an iterable of header two-tuples, strip both leading and trailing
whitespace from both header names and header values. This generator
produces tuples that preserve the original type of the header tuple for
tuple and any ``HeaderTuple``.
| _strip_surrounding_whitespace | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def _check_sent_host_authority_header(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Raises an InvalidHeaderBlockError if we try to send a header block
that does not contain an :authority or a Host header, or if
the header block contains both fields, but their values do not match.
"""
# We only expect to see :authority and Host headers on request header
# blocks that aren't trailers, so skip this validation if this is a
# response header or we're looking at trailer blocks.
skip_validation = (
hdr_validation_flags.is_response_header or
hdr_validation_flags.is_trailer
)
if skip_validation:
return (h for h in headers)
return _validate_host_authority_header(headers) |
Raises an InvalidHeaderBlockError if we try to send a header block
that does not contain an :authority or a Host header, or if
the header block contains both fields, but their values do not match.
| _check_sent_host_authority_header | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def normalize_outbound_headers(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags | None,
should_split_outbound_cookies: bool=False) -> Generator[Header, None, None]:
"""
Normalizes a header sequence that we are about to send.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags.
:param should_split_outbound_cookies: boolean flag
"""
headers = _lowercase_header_names(headers, hdr_validation_flags)
if should_split_outbound_cookies:
headers = _split_outbound_cookie_fields(headers, hdr_validation_flags)
headers = _strip_surrounding_whitespace(headers, hdr_validation_flags)
headers = _strip_connection_headers(headers, hdr_validation_flags)
return _secure_headers(headers, hdr_validation_flags) |
Normalizes a header sequence that we are about to send.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags.
:param should_split_outbound_cookies: boolean flag
| normalize_outbound_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def normalize_inbound_headers(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Normalizes a header sequence that we have received.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags
"""
return _combine_cookie_fields(headers, hdr_validation_flags) |
Normalizes a header sequence that we have received.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags
| normalize_inbound_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def validate_outbound_headers(headers: Iterable[Header],
hdr_validation_flags: HeaderValidationFlags) -> Generator[Header, None, None]:
"""
Validates and normalizes a header sequence that we are about to send.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags.
"""
headers = _reject_te(
headers, hdr_validation_flags,
)
headers = _reject_connection_header(
headers, hdr_validation_flags,
)
headers = _reject_pseudo_header_fields(
headers, hdr_validation_flags,
)
headers = _check_sent_host_authority_header(
headers, hdr_validation_flags,
)
return _check_path_header(headers, hdr_validation_flags) |
Validates and normalizes a header sequence that we are about to send.
:param headers: The HTTP header set.
:param hdr_validation_flags: An instance of HeaderValidationFlags.
| validate_outbound_headers | python | python-hyper/h2 | src/h2/utilities.py | https://github.com/python-hyper/h2/blob/master/src/h2/utilities.py | MIT |
def window_consumed(self, size: int) -> None:
"""
We have received a certain number of bytes from the remote peer. This
necessarily shrinks the flow control window!
:param size: The number of flow controlled bytes we received from the
remote peer.
:type size: ``int``
:returns: Nothing.
:rtype: ``None``
"""
self.current_window_size -= size
if self.current_window_size < 0:
msg = "Flow control window shrunk below 0"
raise FlowControlError(msg) |
We have received a certain number of bytes from the remote peer. This
necessarily shrinks the flow control window!
:param size: The number of flow controlled bytes we received from the
remote peer.
:type size: ``int``
:returns: Nothing.
:rtype: ``None``
| window_consumed | python | python-hyper/h2 | src/h2/windows.py | https://github.com/python-hyper/h2/blob/master/src/h2/windows.py | MIT |
def window_opened(self, size: int) -> None:
"""
The flow control window has been incremented, either because of manual
flow control management or because of the user changing the flow
control settings. This can have the effect of increasing what we
consider to be the "maximum" flow control window size.
This does not increase our view of how many bytes have been processed,
only of how much space is in the window.
:param size: The increment to the flow control window we received.
:type size: ``int``
:returns: Nothing
:rtype: ``None``
"""
self.current_window_size += size
if self.current_window_size > LARGEST_FLOW_CONTROL_WINDOW:
msg = f"Flow control window mustn't exceed {LARGEST_FLOW_CONTROL_WINDOW}"
raise FlowControlError(msg)
self.max_window_size = max(self.current_window_size, self.max_window_size) |
The flow control window has been incremented, either because of manual
flow control management or because of the user changing the flow
control settings. This can have the effect of increasing what we
consider to be the "maximum" flow control window size.
This does not increase our view of how many bytes have been processed,
only of how much space is in the window.
:param size: The increment to the flow control window we received.
:type size: ``int``
:returns: Nothing
:rtype: ``None``
| window_opened | python | python-hyper/h2 | src/h2/windows.py | https://github.com/python-hyper/h2/blob/master/src/h2/windows.py | MIT |
def run_until_complete(self, *coroutines) -> None:
"""
Executes a set of coroutines that communicate between each other. Each
one is, in order, passed the output of the previous coroutine until
one is exhausted. If a coroutine does not initially yield data (that
is, its first action is to receive data), the calling code should prime
it by using the 'server' decorator on this class.
Once a coroutine is exhausted, the method performs a final check to
ensure that all other coroutines are exhausted. This ensures that all
assertions in those coroutines got executed.
"""
looping_coroutines = itertools.cycle(coroutines)
data = None
for coro in looping_coroutines:
try:
data = coro.send(data)
except StopIteration:
break
for coro in coroutines:
try:
next(coro)
except StopIteration:
continue
else:
pytest.fail(f"Coroutine {coro} not exhausted") |
Executes a set of coroutines that communicate between each other. Each
one is, in order, passed the output of the previous coroutine until
one is exhausted. If a coroutine does not initially yield data (that
is, its first action is to receive data), the calling code should prime
it by using the 'server' decorator on this class.
Once a coroutine is exhausted, the method performs a final check to
ensure that all other coroutines are exhausted. This ensures that all
assertions in those coroutines got executed.
| run_until_complete | python | python-hyper/h2 | tests/coroutine_tests.py | https://github.com/python-hyper/h2/blob/master/tests/coroutine_tests.py | MIT |
def build_headers_frame(self,
headers,
flags=None,
stream_id=1,
**priority_kwargs):
"""
Builds a single valid headers frame out of the contained headers.
"""
if flags is None:
flags = []
f = HeadersFrame(stream_id)
f.data = self.encoder.encode(headers)
f.flags.add("END_HEADERS")
for flag in flags:
f.flags.add(flag)
for k, v in priority_kwargs.items():
setattr(f, k, v)
return f |
Builds a single valid headers frame out of the contained headers.
| build_headers_frame | python | python-hyper/h2 | tests/helpers.py | https://github.com/python-hyper/h2/blob/master/tests/helpers.py | MIT |
def build_continuation_frame(self, header_block, flags=None, stream_id=1):
"""
Builds a single continuation frame out of the binary header block.
"""
if flags is None:
flags = []
f = ContinuationFrame(stream_id)
f.data = header_block
f.flags = set(flags)
return f |
Builds a single continuation frame out of the binary header block.
| build_continuation_frame | python | python-hyper/h2 | tests/helpers.py | https://github.com/python-hyper/h2/blob/master/tests/helpers.py | MIT |
def build_data_frame(self, data, flags=None, stream_id=1, padding_len=0):
"""
Builds a single data frame out of a chunk of data.
"""
flags = set(flags) if flags is not None else set()
f = DataFrame(stream_id)
f.data = data
f.flags = flags
if padding_len:
flags.add("PADDED")
f.pad_length = padding_len
return f |
Builds a single data frame out of a chunk of data.
| build_data_frame | python | python-hyper/h2 | tests/helpers.py | https://github.com/python-hyper/h2/blob/master/tests/helpers.py | MIT |
def test_sending_headers(self) -> None:
"""
Single headers frames are correctly encoded.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
# Clear the data, then send headers.
c.clear_outbound_data_buffer()
events = c.send_headers(1, self.example_request_headers)
assert not events
assert c.data_to_send() == (
b"\x00\x00\r\x01\x04\x00\x00\x00\x01"
b"A\x88/\x91\xd3]\x05\\\x87\xa7\x84\x87\x82"
) |
Single headers frames are correctly encoded.
| test_sending_headers | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_sending_data(self) -> None:
"""
Single data frames are encoded correctly.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
# Clear the data, then send some data.
c.clear_outbound_data_buffer()
events = c.send_data(1, b"some data")
assert not events
data_to_send = c.data_to_send()
assert (
data_to_send == b"\x00\x00\t\x00\x00\x00\x00\x00\x01some data"
)
buffer = h2.frame_buffer.FrameBuffer(server=False)
buffer.max_frame_size = 65535
buffer.add_data(data_to_send)
data_frame = next(iter(buffer))
sanity_check_data_frame(
data_frame=data_frame,
expected_flow_controlled_length=len(b"some data"),
expect_padded_flag=False,
expected_data_frame_pad_length=0,
) |
Single data frames are encoded correctly.
| test_sending_data | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_sending_data_with_padding(self) -> None:
"""
Single data frames with padding are encoded correctly.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
# Clear the data, then send some data.
c.clear_outbound_data_buffer()
events = c.send_data(1, b"some data", pad_length=5)
assert not events
data_to_send = c.data_to_send()
assert data_to_send == (
b"\x00\x00\x0f\x00\x08\x00\x00\x00\x01"
b"\x05some data\x00\x00\x00\x00\x00"
)
buffer = h2.frame_buffer.FrameBuffer(server=False)
buffer.max_frame_size = 65535
buffer.add_data(data_to_send)
data_frame = next(iter(buffer))
sanity_check_data_frame(
data_frame=data_frame,
expected_flow_controlled_length=len(b"some data") + 1 + 5,
expect_padded_flag=True,
expected_data_frame_pad_length=5,
) |
Single data frames with padding are encoded correctly.
| test_sending_data_with_padding | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_sending_data_with_zero_length_padding(self) -> None:
"""
Single data frames with zero-length padding are encoded
correctly.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
# Clear the data, then send some data.
c.clear_outbound_data_buffer()
events = c.send_data(1, b"some data", pad_length=0)
assert not events
data_to_send = c.data_to_send()
assert data_to_send == (
b"\x00\x00\x0a\x00\x08\x00\x00\x00\x01"
b"\x00some data"
)
buffer = h2.frame_buffer.FrameBuffer(server=False)
buffer.max_frame_size = 65535
buffer.add_data(data_to_send)
data_frame = next(iter(buffer))
sanity_check_data_frame(
data_frame=data_frame,
expected_flow_controlled_length=len(b"some data") + 1,
expect_padded_flag=True,
expected_data_frame_pad_length=0,
) |
Single data frames with zero-length padding are encoded
correctly.
| test_sending_data_with_zero_length_padding | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_sending_data_with_invalid_padding_length(self,
expected_error,
pad_length) -> None:
"""
``send_data`` with a ``pad_length`` parameter that is an integer
outside the range of [0, 255] throws a ``ValueError``, and a
``pad_length`` parameter which is not an ``integer`` type
throws a ``TypeError``.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
c.clear_outbound_data_buffer()
if expected_error is not None:
with pytest.raises(expected_error):
c.send_data(1, b"some data", pad_length=pad_length)
else:
c.send_data(1, b"some data", pad_length=pad_length) |
``send_data`` with a ``pad_length`` parameter that is an integer
outside the range of [0, 255] throws a ``ValueError``, and a
``pad_length`` parameter which is not an ``integer`` type
throws a ``TypeError``.
| test_sending_data_with_invalid_padding_length | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_closing_stream_sending_data(self, frame_factory) -> None:
"""
We can close a stream with a data frame.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
f = frame_factory.build_data_frame(
data=b"some data",
flags=["END_STREAM"],
)
# Clear the data, then send some data.
c.clear_outbound_data_buffer()
events = c.send_data(1, b"some data", end_stream=True)
assert not events
assert c.data_to_send() == f.serialize() |
We can close a stream with a data frame.
| test_closing_stream_sending_data | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_a_response(self, frame_factory) -> None:
"""
When receiving a response, the ResponseReceived event fires.
"""
config = h2.config.H2Configuration(header_encoding="utf-8")
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
# Clear the data
f = frame_factory.build_headers_frame(
self.example_response_headers,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 1
assert event.headers == self.example_response_headers |
When receiving a response, the ResponseReceived event fires.
| test_receiving_a_response | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_a_response_bytes(self, frame_factory) -> None:
"""
When receiving a response, the ResponseReceived event fires with bytes
headers if the encoding is set appropriately.
"""
config = h2.config.H2Configuration(header_encoding=False)
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
# Clear the data
f = frame_factory.build_headers_frame(
self.example_response_headers,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 1
assert event.headers == self.bytes_example_response_headers |
When receiving a response, the ResponseReceived event fires with bytes
headers if the encoding is set appropriately.
| test_receiving_a_response_bytes | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_a_response_change_encoding(self, frame_factory) -> None:
"""
When receiving a response, the ResponseReceived event fires with bytes
headers if the encoding is set appropriately, but if this changes then
the change reflects it.
"""
config = h2.config.H2Configuration(header_encoding=False)
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_headers_frame(
self.example_response_headers,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 1
assert event.headers == self.bytes_example_response_headers
c.send_headers(3, self.example_request_headers, end_stream=True)
c.config.header_encoding = "utf-8"
f = frame_factory.build_headers_frame(
self.example_response_headers,
stream_id=3,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 3
assert event.headers == self.example_response_headers |
When receiving a response, the ResponseReceived event fires with bytes
headers if the encoding is set appropriately, but if this changes then
the change reflects it.
| test_receiving_a_response_change_encoding | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cannot_send_headers_on_lower_stream_id(self) -> None:
"""
Once stream ID x has been used, cannot use stream ID y where y < x.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(3, self.example_request_headers, end_stream=False)
with pytest.raises(h2.exceptions.StreamIDTooLowError) as e:
c.send_headers(1, self.example_request_headers, end_stream=True)
assert e.value.stream_id == 1
assert e.value.max_stream_id == 3 |
Once stream ID x has been used, cannot use stream ID y where y < x.
| test_cannot_send_headers_on_lower_stream_id | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_pushed_stream(self, frame_factory) -> None:
"""
Pushed streams fire a PushedStreamReceived event, followed by
ResponseReceived when the response headers are received.
"""
config = h2.config.H2Configuration(header_encoding="utf-8")
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=False)
f1 = frame_factory.build_headers_frame(
self.example_response_headers,
)
f2 = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers,
flags=["END_HEADERS"],
)
f3 = frame_factory.build_headers_frame(
self.example_response_headers,
stream_id=2,
)
data = b"".join(x.serialize() for x in [f1, f2, f3])
events = c.receive_data(data)
assert len(events) == 3
stream_push_event = events[1]
response_event = events[2]
assert isinstance(stream_push_event, h2.events.PushedStreamReceived)
assert isinstance(response_event, h2.events.ResponseReceived)
assert stream_push_event.pushed_stream_id == 2
assert stream_push_event.parent_stream_id == 1
assert (
stream_push_event.headers == self.example_request_headers
)
assert response_event.stream_id == 2
assert response_event.headers == self.example_response_headers |
Pushed streams fire a PushedStreamReceived event, followed by
ResponseReceived when the response headers are received.
| test_receiving_pushed_stream | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_pushed_stream_bytes(self, frame_factory) -> None:
"""
Pushed headers are not decoded if the header encoding is set to False.
"""
config = h2.config.H2Configuration(header_encoding=False)
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=False)
f1 = frame_factory.build_headers_frame(
self.example_response_headers,
)
f2 = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers,
flags=["END_HEADERS"],
)
f3 = frame_factory.build_headers_frame(
self.example_response_headers,
stream_id=2,
)
data = b"".join(x.serialize() for x in [f1, f2, f3])
events = c.receive_data(data)
assert len(events) == 3
stream_push_event = events[1]
response_event = events[2]
assert isinstance(stream_push_event, h2.events.PushedStreamReceived)
assert isinstance(response_event, h2.events.ResponseReceived)
assert stream_push_event.pushed_stream_id == 2
assert stream_push_event.parent_stream_id == 1
assert (
stream_push_event.headers == self.bytes_example_request_headers
)
assert response_event.stream_id == 2
assert response_event.headers == self.bytes_example_response_headers |
Pushed headers are not decoded if the header encoding is set to False.
| test_receiving_pushed_stream_bytes | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cannot_receive_pushed_stream_when_enable_push_is_0(self,
frame_factory) -> None:
"""
If we have set SETTINGS_ENABLE_PUSH to 0, receiving PUSH_PROMISE frames
triggers the connection to be closed.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.local_settings.enable_push = 0
c.send_headers(1, self.example_request_headers, end_stream=False)
f1 = frame_factory.build_settings_frame({}, ack=True)
f2 = frame_factory.build_headers_frame(
self.example_response_headers,
)
f3 = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers,
flags=["END_HEADERS"],
)
c.receive_data(f1.serialize())
c.receive_data(f2.serialize())
c.clear_outbound_data_buffer()
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(f3.serialize())
expected_frame = frame_factory.build_goaway_frame(
0, h2.errors.ErrorCodes.PROTOCOL_ERROR,
)
assert c.data_to_send() == expected_frame.serialize() |
If we have set SETTINGS_ENABLE_PUSH to 0, receiving PUSH_PROMISE frames
triggers the connection to be closed.
| test_cannot_receive_pushed_stream_when_enable_push_is_0 | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_response_no_body(self, frame_factory) -> None:
"""
Receiving a response without a body fires two events, ResponseReceived
and StreamEnded.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_headers_frame(
self.example_response_headers,
flags=["END_STREAM"],
)
events = c.receive_data(f.serialize())
assert len(events) == 2
response_event = events[0]
end_stream = events[1]
assert isinstance(response_event, h2.events.ResponseReceived)
assert isinstance(end_stream, h2.events.StreamEnded) |
Receiving a response without a body fires two events, ResponseReceived
and StreamEnded.
| test_receiving_response_no_body | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_oversize_headers(self) -> None:
"""
Sending headers that are oversized generates a stream of CONTINUATION
frames.
"""
all_bytes = [chr(x).encode("latin1") for x in range(256)]
large_binary_string = b"".join(
random.choice(all_bytes) for _ in range(256)
)
test_headers = [
(":authority", "example.com"),
(":path", "/"),
(":method", "GET"),
(":scheme", "https"),
("key", large_binary_string),
]
c = h2.connection.H2Connection()
# Greatly shrink the max frame size to force us over.
c.max_outbound_frame_size = 48
c.initiate_connection()
c.send_headers(1, test_headers, end_stream=True)
# Use the frame buffer here, because we don't care about decoding
# the headers. Don't send all the data in because that will force the
# frame buffer to stop caching the CONTINUATION frames, so instead
# send all but one byte.
buffer = h2.frame_buffer.FrameBuffer(server=True)
buffer.max_frame_size = 65535
data = c.data_to_send()
buffer.add_data(data[:-1])
# Drain the buffer, confirming that it only provides a single frame
# (the settings frame)
assert len(list(buffer)) == 1
# Get the cached frames.
frames = buffer._headers_buffer
# Split the frames up.
headers_frame = frames[0]
continuation_frames = frames[1:]
assert isinstance(headers_frame, hyperframe.frame.HeadersFrame)
assert all(
(isinstance(f, hyperframe.frame.ContinuationFrame) for f in continuation_frames),
)
assert all(
(len(f.data) <= c.max_outbound_frame_size for f in frames),
)
assert frames[0].flags == {"END_STREAM"}
buffer.add_data(data[-1:])
headers = next(iter(buffer))
assert isinstance(headers, hyperframe.frame.HeadersFrame) |
Sending headers that are oversized generates a stream of CONTINUATION
frames.
| test_oversize_headers | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_handle_stream_reset(self, frame_factory) -> None:
"""
Streams being remotely reset fires a StreamReset event.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
c.clear_outbound_data_buffer()
f = frame_factory.build_rst_stream_frame(
stream_id=1,
error_code=h2.errors.ErrorCodes.STREAM_CLOSED,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.StreamReset)
assert event.stream_id == 1
assert event.error_code is h2.errors.ErrorCodes.STREAM_CLOSED
assert isinstance(event.error_code, h2.errors.ErrorCodes)
assert event.remote_reset |
Streams being remotely reset fires a StreamReset event.
| test_handle_stream_reset | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_handle_stream_reset_with_unknown_erorr_code(self, frame_factory) -> None:
"""
Streams being remotely reset with unknown error codes behave exactly as
they do with known error codes, but the error code on the event is an
int, instead of being an ErrorCodes.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
c.clear_outbound_data_buffer()
f = frame_factory.build_rst_stream_frame(stream_id=1, error_code=0xFA)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.StreamReset)
assert event.stream_id == 1
assert event.error_code == 250
assert not isinstance(event.error_code, h2.errors.ErrorCodes)
assert event.remote_reset |
Streams being remotely reset with unknown error codes behave exactly as
they do with known error codes, but the error code on the event is an
int, instead of being an ErrorCodes.
| test_handle_stream_reset_with_unknown_erorr_code | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_can_consume_partial_data_from_connection(self) -> None:
"""
We can do partial reads from the connection.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
assert len(c.data_to_send(2)) == 2
assert len(c.data_to_send(3)) == 3
assert 0 < len(c.data_to_send(500)) < 500
assert len(c.data_to_send(10)) == 0
assert len(c.data_to_send()) == 0 |
We can do partial reads from the connection.
| test_can_consume_partial_data_from_connection | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_settings_get_acked_correctly(self, frame_factory) -> None:
"""
When settings changes are ACKed, they contain the changed settings.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
new_settings = {
h2.settings.SettingCodes.HEADER_TABLE_SIZE: 52,
h2.settings.SettingCodes.ENABLE_PUSH: 0,
}
c.update_settings(new_settings)
f = frame_factory.build_settings_frame({}, ack=True)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.SettingsAcknowledged)
assert len(event.changed_settings) == len(new_settings)
for setting, value in new_settings.items():
assert event.changed_settings[setting].new_value == value |
When settings changes are ACKed, they contain the changed settings.
| test_settings_get_acked_correctly | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cannot_create_new_outbound_stream_over_limit(self, frame_factory) -> None:
"""
When the number of outbound streams exceeds the remote peer's
MAX_CONCURRENT_STREAMS setting, attempting to open new streams fails.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
f = frame_factory.build_settings_frame(
{h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 1},
)
c.receive_data(f.serialize())[0]
c.send_headers(1, self.example_request_headers)
with pytest.raises(h2.exceptions.TooManyStreamsError):
c.send_headers(3, self.example_request_headers) |
When the number of outbound streams exceeds the remote peer's
MAX_CONCURRENT_STREAMS setting, attempting to open new streams fails.
| test_cannot_create_new_outbound_stream_over_limit | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_can_receive_trailers(self, frame_factory) -> None:
"""
When two HEADERS blocks are received in the same stream from a
server, the second set are trailers.
"""
config = h2.config.H2Configuration(header_encoding="utf-8")
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
f = frame_factory.build_headers_frame(self.example_response_headers)
c.receive_data(f.serialize())
# Send in trailers.
trailers = [("content-length", "0")]
f = frame_factory.build_headers_frame(
trailers,
flags=["END_STREAM"],
)
events = c.receive_data(f.serialize())
assert len(events) == 2
event = events[0]
assert isinstance(event, h2.events.TrailersReceived)
assert event.headers == trailers
assert event.stream_id == 1 |
When two HEADERS blocks are received in the same stream from a
server, the second set are trailers.
| test_can_receive_trailers | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_reject_trailers_not_ending_stream(self, frame_factory) -> None:
"""
When trailers are received without the END_STREAM flag being present,
this is a ProtocolError.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
f = frame_factory.build_headers_frame(self.example_response_headers)
c.receive_data(f.serialize())
# Send in trailers.
c.clear_outbound_data_buffer()
trailers = [("content-length", "0")]
f = frame_factory.build_headers_frame(
trailers,
flags=[],
)
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(f.serialize())
expected_frame = frame_factory.build_goaway_frame(
last_stream_id=0, error_code=h2.errors.ErrorCodes.PROTOCOL_ERROR,
)
assert c.data_to_send() == expected_frame.serialize() |
When trailers are received without the END_STREAM flag being present,
this is a ProtocolError.
| test_reject_trailers_not_ending_stream | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_can_send_trailers(self, frame_factory) -> None:
"""
When a second set of headers are sent, they are properly trailers.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.clear_outbound_data_buffer()
c.send_headers(1, self.example_request_headers)
# Now send trailers.
trailers = [("content-length", "0")]
c.send_headers(1, trailers, end_stream=True)
frame_factory.refresh_encoder()
f1 = frame_factory.build_headers_frame(
self.example_request_headers,
)
f2 = frame_factory.build_headers_frame(
trailers,
flags=["END_STREAM"],
)
assert c.data_to_send() == f1.serialize() + f2.serialize() |
When a second set of headers are sent, they are properly trailers.
| test_can_send_trailers | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_trailers_must_have_end_stream(self, frame_factory) -> None:
"""
A set of trailers must carry the END_STREAM flag.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
# Send headers.
c.send_headers(1, self.example_request_headers)
# Now send trailers.
trailers = [("content-length", "0")]
with pytest.raises(h2.exceptions.ProtocolError):
c.send_headers(1, trailers) |
A set of trailers must carry the END_STREAM flag.
| test_trailers_must_have_end_stream | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_headers_are_lowercase(self, frame_factory) -> None:
"""
When headers are sent, they are forced to lower-case.
"""
weird_headers = [*self.example_request_headers, ("ChAnGiNg-CaSe", "AlsoHere"), ("alllowercase", "alllowercase"), ("ALLCAPS", "ALLCAPS")]
expected_headers = [*self.example_request_headers, ("changing-case", "AlsoHere"), ("alllowercase", "alllowercase"), ("allcaps", "ALLCAPS")]
c = h2.connection.H2Connection()
c.initiate_connection()
c.clear_outbound_data_buffer()
c.send_headers(1, weird_headers)
expected_frame = frame_factory.build_headers_frame(
headers=expected_headers,
)
assert c.data_to_send() == expected_frame.serialize() |
When headers are sent, they are forced to lower-case.
| test_headers_are_lowercase | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_outbound_cookie_headers_are_split(self) -> None:
"""
We should split outbound cookie headers according to
RFC 7540 - 8.1.2.5
"""
cookie_headers = [
HeaderTuple("cookie",
"username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC"),
("cookie", "path=1"),
("cookie", "test1=val1; test2=val2"),
]
expected_cookie_headers = [
HeaderTuple("cookie", "username=John Doe"),
HeaderTuple("cookie", "expires=Thu, 18 Dec 2013 12:00:00 UTC"),
("cookie", "path=1"),
("cookie", "test1=val1"),
("cookie", "test2=val2"),
]
client_config = h2.config.H2Configuration(
client_side=True,
header_encoding="utf-8",
split_outbound_cookies=True,
)
server_config = h2.config.H2Configuration(
client_side=False,
normalize_inbound_headers=False,
header_encoding="utf-8",
)
client = h2.connection.H2Connection(config=client_config)
server = h2.connection.H2Connection(config=server_config)
client.initiate_connection()
client.send_headers(1, self.example_request_headers + cookie_headers, end_stream=True)
e = server.receive_data(client.data_to_send())
cookie_fields = [(n, v) for n, v in e[1].headers if n == "cookie"]
assert cookie_fields == expected_cookie_headers |
We should split outbound cookie headers according to
RFC 7540 - 8.1.2.5
| test_outbound_cookie_headers_are_split | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_changing_max_frame_size(self, frame_factory, frame_size) -> None:
"""
When the user changes the max frame size and the change is ACKed, the
remote peer is now bound by the new frame size.
"""
# We need to refresh the encoder because hypothesis has a problem with
# integrating with py.test, meaning that we use the same frame factory
# for all tests.
# See https://github.com/HypothesisWorks/hypothesis-python/issues/377
frame_factory.refresh_encoder()
c = h2.connection.H2Connection()
c.initiate_connection()
# Set up the stream.
c.send_headers(1, self.example_request_headers, end_stream=True)
headers_frame = frame_factory.build_headers_frame(
headers=self.example_response_headers,
)
c.receive_data(headers_frame.serialize())
# Change the max frame size.
c.update_settings(
{h2.settings.SettingCodes.MAX_FRAME_SIZE: frame_size},
)
settings_ack = frame_factory.build_settings_frame({}, ack=True)
c.receive_data(settings_ack.serialize())
# Greatly increase the flow control windows: we're not here to test
# flow control today.
c.increment_flow_control_window(increment=(2 * frame_size) + 1)
c.increment_flow_control_window(
increment=(2 * frame_size) + 1, stream_id=1,
)
# Send one DATA frame that is exactly the max frame size: confirm it's
# fine.
data = frame_factory.build_data_frame(
data=(b"\x00" * frame_size),
)
events = c.receive_data(data.serialize())
assert len(events) == 1
assert isinstance(events[0], h2.events.DataReceived)
assert events[0].flow_controlled_length == frame_size
# Send one that is one byte too large: confirm a protocol error is
# raised.
data.data += b"\x00"
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(data.serialize()) |
When the user changes the max frame size and the change is ACKed, the
remote peer is now bound by the new frame size.
| test_changing_max_frame_size | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cookies_are_joined_on_push(self, frame_factory) -> None:
"""
RFC 7540 Section 8.1.2.5 requires that we join multiple Cookie headers
in a header block together when they're received on a push.
"""
# This is a moderately varied set of cookie headers: some combined,
# some split.
cookie_headers = [
("cookie",
"username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC"),
("cookie", "path=1"),
("cookie", "test1=val1; test2=val2"),
]
expected = (
"username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; "
"path=1; test1=val1; test2=val2"
)
config = h2.config.H2Configuration(header_encoding="utf-8")
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers + cookie_headers,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
e = events[0]
cookie_fields = [(n, v) for n, v in e.headers if n == "cookie"]
assert len(cookie_fields) == 1
_, v = cookie_fields[0]
assert v == expected |
RFC 7540 Section 8.1.2.5 requires that we join multiple Cookie headers
in a header block together when they're received on a push.
| test_cookies_are_joined_on_push | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cookies_arent_joined_without_normalization(self, frame_factory) -> None:
"""
If inbound header normalization is disabled, cookie headers aren't
joined.
"""
# This is a moderately varied set of cookie headers: some combined,
# some split.
cookie_headers = [
("cookie",
"username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC"),
("cookie", "path=1"),
("cookie", "test1=val1; test2=val2"),
]
config = h2.config.H2Configuration(
client_side=True,
normalize_inbound_headers=False,
header_encoding="utf-8",
)
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers + cookie_headers,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
e = events[0]
received_cookies = [(n, v) for n, v in e.headers if n == "cookie"]
assert len(received_cookies) == 3
assert cookie_headers == received_cookies |
If inbound header normalization is disabled, cookie headers aren't
joined.
| test_cookies_arent_joined_without_normalization | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_ignores_preamble(self) -> None:
"""
The preamble does not cause any events or frames to be written.
"""
c = h2.connection.H2Connection(config=self.server_config)
preamble = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
events = c.receive_data(preamble)
assert not events
assert not c.data_to_send() |
The preamble does not cause any events or frames to be written.
| test_ignores_preamble | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_drip_feed_preamble(self, chunk_size) -> None:
"""
The preamble can be sent in in less than a single buffer.
"""
c = h2.connection.H2Connection(config=self.server_config)
preamble = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
events = []
for i in range(0, len(preamble), chunk_size):
events += c.receive_data(preamble[i:i+chunk_size])
assert not events
assert not c.data_to_send() |
The preamble can be sent in in less than a single buffer.
| test_drip_feed_preamble | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_initiate_connection_sends_server_preamble(self, frame_factory) -> None:
"""
For server-side connections, initiate_connection sends a server
preamble.
"""
c = h2.connection.H2Connection(config=self.server_config)
expected_settings = frame_factory.build_settings_frame(
c.local_settings,
)
expected_data = expected_settings.serialize()
events = c.initiate_connection()
assert not events
assert c.data_to_send() == expected_data |
For server-side connections, initiate_connection sends a server
preamble.
| test_initiate_connection_sends_server_preamble | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_headers_event(self, frame_factory) -> None:
"""
When a headers frame is received a RequestReceived event fires.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
data = f.serialize()
events = c.receive_data(data)
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.RequestReceived)
assert event.stream_id == 1
assert event.headers == self.example_request_headers |
When a headers frame is received a RequestReceived event fires.
| test_headers_event | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_headers_event_bytes(self, frame_factory) -> None:
"""
When a headers frame is received a RequestReceived event fires with
bytes headers if the encoding is set appropriately.
"""
config = h2.config.H2Configuration(
client_side=False, header_encoding=False,
)
c = h2.connection.H2Connection(config=config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
data = f.serialize()
events = c.receive_data(data)
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.RequestReceived)
assert event.stream_id == 1
assert event.headers == self.bytes_example_request_headers |
When a headers frame is received a RequestReceived event fires with
bytes headers if the encoding is set appropriately.
| test_headers_event_bytes | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_data_event(self, frame_factory) -> None:
"""
Test that data received on a stream fires a DataReceived event.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f1 = frame_factory.build_headers_frame(
self.example_request_headers, stream_id=3,
)
f2 = frame_factory.build_data_frame(
b"some request data",
stream_id=3,
)
data = b"".join(f.serialize() for f in [f1, f2])
events = c.receive_data(data)
assert len(events) == 2
event = events[1]
assert isinstance(event, h2.events.DataReceived)
assert event.stream_id == 3
assert event.data == b"some request data"
assert event.flow_controlled_length == 17 |
Test that data received on a stream fires a DataReceived event.
| test_data_event | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_data_event_with_padding(self, frame_factory) -> None:
"""
Test that data received on a stream fires a DataReceived event that
accounts for padding.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f1 = frame_factory.build_headers_frame(
self.example_request_headers, stream_id=3,
)
f2 = frame_factory.build_data_frame(
b"some request data",
stream_id=3,
padding_len=20,
)
data = b"".join(f.serialize() for f in [f1, f2])
events = c.receive_data(data)
assert len(events) == 2
event = events[1]
assert isinstance(event, h2.events.DataReceived)
assert event.stream_id == 3
assert event.data == b"some request data"
assert event.flow_controlled_length == 17 + 20 + 1 |
Test that data received on a stream fires a DataReceived event that
accounts for padding.
| test_data_event_with_padding | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_ping_frame(self, frame_factory) -> None:
"""
Ping frames should be immediately ACKed.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
ping_data = b"\x01" * 8
sent_frame = frame_factory.build_ping_frame(ping_data)
expected_frame = frame_factory.build_ping_frame(
ping_data, flags=["ACK"],
)
expected_data = expected_frame.serialize()
c.clear_outbound_data_buffer()
events = c.receive_data(sent_frame.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.PingReceived)
assert event.ping_data == ping_data
assert c.data_to_send() == expected_data |
Ping frames should be immediately ACKed.
| test_receiving_ping_frame | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_settings_frame_event(self, frame_factory) -> None:
"""
Settings frames should cause a RemoteSettingsChanged event to fire.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_settings_frame(
settings=helpers.SAMPLE_SETTINGS,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.RemoteSettingsChanged)
assert len(event.changed_settings) == len(helpers.SAMPLE_SETTINGS) |
Settings frames should cause a RemoteSettingsChanged event to fire.
| test_receiving_settings_frame_event | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_basic_sending_ping_frame_logic(self, frame_factory) -> None:
"""
Sending ping frames serializes a ping frame on stream 0 with
appropriate opaque data.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
c.clear_outbound_data_buffer()
ping_data = b"\x01\x02\x03\x04\x05\x06\x07\x08"
expected_frame = frame_factory.build_ping_frame(ping_data)
expected_data = expected_frame.serialize()
events = c.ping(ping_data)
assert not events
assert c.data_to_send() == expected_data |
Sending ping frames serializes a ping frame on stream 0 with
appropriate opaque data.
| test_basic_sending_ping_frame_logic | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_ping_frame_opaque_data_must_be_length_8_bytestring(self,
frame_factory,
opaque_data) -> None:
"""
Sending a ping frame only works with 8-byte bytestrings.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
with pytest.raises(ValueError):
c.ping(opaque_data) |
Sending a ping frame only works with 8-byte bytestrings.
| test_ping_frame_opaque_data_must_be_length_8_bytestring | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_ping_acknowledgement(self, frame_factory) -> None:
"""
Receiving a PING acknowledgement fires a PingAckReceived event.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
ping_data = b"\x01\x02\x03\x04\x05\x06\x07\x08"
f = frame_factory.build_ping_frame(
ping_data, flags=["ACK"],
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.PingAckReceived)
assert event.ping_data == ping_data |
Receiving a PING acknowledgement fires a PingAckReceived event.
| test_receiving_ping_acknowledgement | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_stream_ended_remotely(self, frame_factory) -> None:
"""
When the remote stream ends with a non-empty data frame a DataReceived
event and a StreamEnded event are fired.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f1 = frame_factory.build_headers_frame(
self.example_request_headers, stream_id=3,
)
f2 = frame_factory.build_data_frame(
b"some request data",
flags=["END_STREAM"],
stream_id=3,
)
data = b"".join(f.serialize() for f in [f1, f2])
events = c.receive_data(data)
assert len(events) == 3
data_event = events[1]
stream_ended_event = events[2]
assert isinstance(data_event, h2.events.DataReceived)
assert isinstance(stream_ended_event, h2.events.StreamEnded)
stream_ended_event.stream_id == 3 |
When the remote stream ends with a non-empty data frame a DataReceived
event and a StreamEnded event are fired.
| test_stream_ended_remotely | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cannot_push_streams_when_disabled(self, frame_factory) -> None:
"""
When the remote peer has disabled stream pushing, we should fail.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_settings_frame(
{h2.settings.SettingCodes.ENABLE_PUSH: 0},
)
c.receive_data(f.serialize())
f = frame_factory.build_headers_frame(
self.example_request_headers,
)
c.receive_data(f.serialize())
with pytest.raises(h2.exceptions.ProtocolError):
c.push_stream(
stream_id=1,
promised_stream_id=2,
request_headers=self.example_request_headers,
) |
When the remote peer has disabled stream pushing, we should fail.
| test_cannot_push_streams_when_disabled | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_settings_remote_change_header_table_size(self, frame_factory) -> None:
"""
Acknowledging a remote HEADER_TABLE_SIZE settings change causes us to
change the header table size of our encoder.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
assert c.encoder.header_table_size == 4096
received_frame = frame_factory.build_settings_frame(
{h2.settings.SettingCodes.HEADER_TABLE_SIZE: 80},
)
c.receive_data(received_frame.serialize())[0]
assert c.encoder.header_table_size == 80 |
Acknowledging a remote HEADER_TABLE_SIZE settings change causes us to
change the header table size of our encoder.
| test_settings_remote_change_header_table_size | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_settings_local_change_header_table_size(self, frame_factory) -> None:
"""
The remote peer acknowledging a local HEADER_TABLE_SIZE settings change
does not cause us to change the header table size of our decoder.
For an explanation of why this test is this way around, see issue #37.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
assert c.decoder.header_table_size == 4096
expected_frame = frame_factory.build_settings_frame({}, ack=True)
c.update_settings(
{h2.settings.SettingCodes.HEADER_TABLE_SIZE: 80},
)
c.receive_data(expected_frame.serialize())
c.clear_outbound_data_buffer()
assert c.decoder.header_table_size == 4096 |
The remote peer acknowledging a local HEADER_TABLE_SIZE settings change
does not cause us to change the header table size of our decoder.
For an explanation of why this test is this way around, see issue #37.
| test_settings_local_change_header_table_size | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_restricting_outbound_frame_size_by_settings(self, frame_factory) -> None:
"""
The remote peer can shrink the maximum outbound frame size using
settings.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.initiate_connection()
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())
c.clear_outbound_data_buffer()
with pytest.raises(h2.exceptions.FrameTooLargeError):
c.send_data(1, b"\x01" * 17000)
received_frame = frame_factory.build_settings_frame(
{h2.settings.SettingCodes.MAX_FRAME_SIZE: 17001},
)
c.receive_data(received_frame.serialize())
c.send_data(1, b"\x01" * 17000)
assert c.data_to_send() |
The remote peer can shrink the maximum outbound frame size using
settings.
| test_restricting_outbound_frame_size_by_settings | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_restricting_inbound_frame_size_by_settings(self, frame_factory) -> None:
"""
We throw ProtocolErrors and tear down connections if oversize frames
are received.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
h = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(h.serialize())
c.clear_outbound_data_buffer()
data_frame = frame_factory.build_data_frame(b"\x01" * 17000)
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(data_frame.serialize())
expected_frame = frame_factory.build_goaway_frame(
last_stream_id=1, error_code=h2.errors.ErrorCodes.FRAME_SIZE_ERROR,
)
assert c.data_to_send() == expected_frame.serialize() |
We throw ProtocolErrors and tear down connections if oversize frames
are received.
| test_restricting_inbound_frame_size_by_settings | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cannot_receive_new_streams_over_limit(self, frame_factory) -> None:
"""
When the number of inbound streams exceeds our MAX_CONCURRENT_STREAMS
setting, their attempt to open new streams fails.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
c.update_settings(
{h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 1},
)
f = frame_factory.build_settings_frame({}, ack=True)
c.receive_data(f.serialize())
f = frame_factory.build_headers_frame(
stream_id=1,
headers=self.example_request_headers,
)
c.receive_data(f.serialize())
c.clear_outbound_data_buffer()
f = frame_factory.build_headers_frame(
stream_id=3,
headers=self.example_request_headers,
)
with pytest.raises(h2.exceptions.TooManyStreamsError):
c.receive_data(f.serialize())
expected_frame = frame_factory.build_goaway_frame(
last_stream_id=1, error_code=h2.errors.ErrorCodes.PROTOCOL_ERROR,
)
assert c.data_to_send() == expected_frame.serialize() |
When the number of inbound streams exceeds our MAX_CONCURRENT_STREAMS
setting, their attempt to open new streams fails.
| test_cannot_receive_new_streams_over_limit | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_can_receive_trailers(self, frame_factory) -> None:
"""
When two HEADERS blocks are received in the same stream from a
client, the second set are trailers.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())
# Send in trailers.
trailers = [("content-length", "0")]
f = frame_factory.build_headers_frame(
trailers,
flags=["END_STREAM"],
)
events = c.receive_data(f.serialize())
assert len(events) == 2
event = events[0]
assert isinstance(event, h2.events.TrailersReceived)
assert event.headers == trailers
assert event.stream_id == 1 |
When two HEADERS blocks are received in the same stream from a
client, the second set are trailers.
| test_can_receive_trailers | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_reject_trailers_not_ending_stream(self, frame_factory) -> None:
"""
When trailers are received without the END_STREAM flag being present,
this is a ProtocolError.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())
# Send in trailers.
c.clear_outbound_data_buffer()
trailers = [("content-length", "0")]
f = frame_factory.build_headers_frame(
trailers,
flags=[],
)
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(f.serialize())
expected_frame = frame_factory.build_goaway_frame(
last_stream_id=1, error_code=h2.errors.ErrorCodes.PROTOCOL_ERROR,
)
assert c.data_to_send() == expected_frame.serialize() |
When trailers are received without the END_STREAM flag being present,
this is a ProtocolError.
| test_reject_trailers_not_ending_stream | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_can_send_trailers(self, frame_factory) -> None:
"""
When a second set of headers are sent, they are properly trailers.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())
# Send headers.
c.clear_outbound_data_buffer()
c.send_headers(1, self.example_response_headers)
# Now send trailers.
trailers = [("content-length", "0")]
c.send_headers(1, trailers, end_stream=True)
frame_factory.refresh_encoder()
f1 = frame_factory.build_headers_frame(
self.example_response_headers,
)
f2 = frame_factory.build_headers_frame(
trailers,
flags=["END_STREAM"],
)
assert c.data_to_send() == f1.serialize() + f2.serialize() |
When a second set of headers are sent, they are properly trailers.
| test_can_send_trailers | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_trailers_must_have_end_stream(self, frame_factory) -> None:
"""
A set of trailers must carry the END_STREAM flag.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())
# Send headers.
c.send_headers(1, self.example_response_headers)
# Now send trailers.
trailers = [("content-length", "0")]
with pytest.raises(h2.exceptions.ProtocolError):
c.send_headers(1, trailers) |
A set of trailers must carry the END_STREAM flag.
| test_trailers_must_have_end_stream | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_can_send_goaway_repeatedly(self, frame_factory) -> None:
"""
We can send a GOAWAY frame as many times as we like.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
c.clear_outbound_data_buffer()
c.close_connection()
c.close_connection()
c.close_connection()
f = frame_factory.build_goaway_frame(last_stream_id=0)
assert c.data_to_send() == (f.serialize() * 3) |
We can send a GOAWAY frame as many times as we like.
| test_can_send_goaway_repeatedly | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_goaway_frame(self, frame_factory) -> None:
"""
Receiving a GOAWAY frame causes a ConnectionTerminated event to be
fired and transitions the connection to the CLOSED state, and clears
the outbound data buffer.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.initiate_connection()
c.receive_data(frame_factory.preamble())
f = frame_factory.build_goaway_frame(
last_stream_id=5, error_code=h2.errors.ErrorCodes.SETTINGS_TIMEOUT,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ConnectionTerminated)
assert event.error_code == h2.errors.ErrorCodes.SETTINGS_TIMEOUT
assert isinstance(event.error_code, h2.errors.ErrorCodes)
assert event.last_stream_id == 5
assert event.additional_data is None
assert c.state_machine.state == h2.connection.ConnectionState.CLOSED
assert not c.data_to_send() |
Receiving a GOAWAY frame causes a ConnectionTerminated event to be
fired and transitions the connection to the CLOSED state, and clears
the outbound data buffer.
| test_receiving_goaway_frame | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_multiple_goaway_frames(self, frame_factory) -> None:
"""
Multiple GOAWAY frames can be received at once, and are allowed. Each
one fires a ConnectionTerminated event.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.receive_data(frame_factory.preamble())
c.clear_outbound_data_buffer()
f = frame_factory.build_goaway_frame(last_stream_id=0)
events = c.receive_data(f.serialize() * 3)
assert len(events) == 3
assert all(
isinstance(event, h2.events.ConnectionTerminated)
for event in events
) |
Multiple GOAWAY frames can be received at once, and are allowed. Each
one fires a ConnectionTerminated event.
| test_receiving_multiple_goaway_frames | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_goaway_frame_with_additional_data(self, frame_factory) -> None:
"""
GOAWAY frame can contain additional data,
it should be available via ConnectionTerminated event.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.initiate_connection()
c.receive_data(frame_factory.preamble())
additional_data = b"debug data"
f = frame_factory.build_goaway_frame(last_stream_id=0,
additional_data=additional_data)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ConnectionTerminated)
assert event.additional_data == additional_data |
GOAWAY frame can contain additional data,
it should be available via ConnectionTerminated event.
| test_receiving_goaway_frame_with_additional_data | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_receiving_goaway_frame_with_unknown_error(self, frame_factory) -> None:
"""
Receiving a GOAWAY frame with an unknown error code behaves exactly the
same as receiving one we know about, but the code is reported as an
integer instead of as an ErrorCodes.
"""
c = h2.connection.H2Connection(config=self.server_config)
c.initiate_connection()
c.receive_data(frame_factory.preamble())
f = frame_factory.build_goaway_frame(
last_stream_id=5, error_code=0xFA,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ConnectionTerminated)
assert event.error_code == 250
assert not isinstance(event.error_code, h2.errors.ErrorCodes)
assert event.last_stream_id == 5
assert event.additional_data is None
assert c.state_machine.state == h2.connection.ConnectionState.CLOSED
assert not c.data_to_send() |
Receiving a GOAWAY frame with an unknown error code behaves exactly the
same as receiving one we know about, but the code is reported as an
integer instead of as an ErrorCodes.
| test_receiving_goaway_frame_with_unknown_error | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
def test_cookies_are_joined(self, frame_factory) -> None:
"""
RFC 7540 Section 8.1.2.5 requires that we join multiple Cookie headers
in a header block together.
"""
# This is a moderately varied set of cookie headers: some combined,
# some split.
cookie_headers = [
("cookie",
"username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC"),
("cookie", "path=1"),
("cookie", "test1=val1; test2=val2"),
]
expected = (
"username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; "
"path=1; test1=val1; test2=val2"
)
c = h2.connection.H2Connection(config=self.server_config)
c.initiate_connection()
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(
self.example_request_headers + cookie_headers,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
e = events[0]
cookie_fields = [(n, v) for n, v in e.headers if n == "cookie"]
assert len(cookie_fields) == 1
_, v = cookie_fields[0]
assert v == expected |
RFC 7540 Section 8.1.2.5 requires that we join multiple Cookie headers
in a header block together.
| test_cookies_are_joined | python | python-hyper/h2 | tests/test_basic_logic.py | https://github.com/python-hyper/h2/blob/master/tests/test_basic_logic.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.