id stringlengths 20 30 | source stringclasses 1
value | chunk_index int64 0 520k | token_count int32 154 512 | content stringlengths 185 57.5k |
|---|---|---|---|---|
rust_dataset_chunk_400 | rust_dataset.txt | 400 | 512 | mut self.io).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_shut... |
rust_dataset_chunk_401 | rust_dataset.txt | 401 | 512 | ,
rc::Rc,
task::{Context, Poll},
};
use bytes::Bytes;
use crate::{body::MessageBody, Error};
/// Test body that yields fixed-size chunks for a configured number of polls.
pub(crate) struct ReadyChunkBody {
chunk_polls: Rc<Cell<usize>>,
remaining: usize,
chunk_len: usize,
}
impl ReadyChunkBody {
... |
rust_dataset_chunk_402 | rust_dataset.txt | 402 | 512 | !(assert_ready!(Pin::new(&mut body).poll_next(&mut cx)).is_none());
assert_eq!(chunk_polls.get(), 2);
}
}
--- FILE: actix-web/actix-http/src/test/test_buffer.rs ---
use std::{
cell::{Ref, RefCell, RefMut},
io::{self, Read, Write},
pin::Pin,
rc::Rc,
task::{Context, Poll},
};
use actix_... |
rust_dataset_chunk_403 | rust_dataset.txt | 403 | 512 | RefMut::map(self.write_buf.borrow_mut(), |b| b.as_mut())
}
#[allow(dead_code)]
pub(crate) fn take_write_buf(&self) -> Bytes {
self.write_buf.borrow_mut().split().freeze()
}
/// Add data to read buffer.
pub fn extend_read_buf<T: AsRef<[u8]>>(&mut self, data: T) {
self.re... |
rust_dataset_chunk_404 | rust_dataset.txt | 404 | 512 | mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
#[cfg(test)]
mod tests {
use std::{io, task::Context};
use futures_util::task::noop_waker_ref;
use tok... |
rust_dataset_chunk_405 | rust_dataset.txt | 405 | 512 | , &mut read_buf));
assert_eq!(read_buf.filled(), b"read");
let mut empty = TestBuffer::empty();
let mut read = [];
let mut read_buf = ReadBuf::new(&mut read);
assert_pending!(Pin::new(&mut empty).poll_read(&mut cx, &mut read_buf));
let mut error = TestBuffer::empty();
... |
rust_dataset_chunk_406 | rust_dataset.txt | 406 | 512 | 0).version = ver;
self
}
/// Set HTTP method of this request.
pub fn method(&mut self, meth: Method) -> &mut Self {
parts(&mut self.0).method = meth;
self
}
/// Set URI of this request.
///
/// # Panics
/// If provided URI is invalid.
pub fn uri(&mut self, p... |
rust_dataset_chunk_407 | rust_dataset.txt | 407 | 512 | ::with_payload(crate::h1::Payload::empty().into())
};
let head = req.head_mut();
head.uri = inner.uri;
head.method = inner.method;
head.version = inner.version;
head.headers = inner.headers;
req
}
}
#[inline]
fn parts(parts: &mut Option<Inner>) -> &mut Inne... |
rust_dataset_chunk_408 | rust_dataset.txt | 408 | 512 | add to the read buffer.
#[derive(Clone)]
pub struct TestSeqBuffer(Rc<RefCell<TestSeqInner>>);
impl TestSeqBuffer {
/// Create new `TestBuffer` instance with initial read buffer.
pub fn new<T>(data: T) -> Self
where
T: Into<BytesMut>,
{
Self(Rc::new(RefCell::new(TestSeqInner {
... |
rust_dataset_chunk_409 | rust_dataset.txt | 409 | 512 | >,
}
impl io::Read for TestSeqBuffer {
fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> {
let mut inner = self.0.borrow_mut();
if inner.read_buf.is_empty() {
if let Some(err) = inner.err.take() {
Err(err)
} else if inner.read_closed {
... |
rust_dataset_chunk_410 | rust_dataset.txt | 410 | 512 | };
use futures_util::task::noop_waker_ref;
use tokio_test::{assert_pending, assert_ready_err, assert_ready_ok};
use super::*;
#[test]
fn buffer_read_write() {
let mut buffer = TestSeqBuffer::new("read");
let clone = buffer.clone();
assert_eq!(buffer.read_buf().as_ref(), b... |
rust_dataset_chunk_411 | rust_dataset.txt | 411 | 512 | "));
let mut read = [];
let mut read_buf = ReadBuf::new(&mut read);
let error = assert_ready_err!(
Pin::new(&mut error).poll_read(&mut cx, &mut read_buf),
"expected a ready error"
);
assert_eq!(error.to_string(), "error");
let mut buffer = TestSeq... |
rust_dataset_chunk_412 | rust_dataset.txt | 412 | 512 | and returns a `200 OK` response.
pub(crate) fn drop_payload_service(
) -> impl Service<Request, Response = Response<&'static str>, Error = Error> {
fn_service(|mut req: Request| async move {
let _ = req.take_payload();
Ok::<_, Error>(Response::with_body(StatusCode::OK, "payload dropped"))
})
}
... |
rust_dataset_chunk_413 | rust_dataset.txt | 413 | 512 | BytesMut};
use bytestring::ByteString;
use tokio_util::codec::{Decoder, Encoder};
use super::{
frame::Parser,
proto::{CloseReason, OpCode},
ProtocolError,
};
/// A WebSocket message.
#[derive(Debug, PartialEq, Eq)]
pub enum Message {
/// Text message.
Text(ByteString),
/// Binary message.
... |
rust_dataset_chunk_414 | rust_dataset.txt | 414 | 512 | client mode.
///
/// By default decoder works in server mode.
#[must_use = "This returns the a new Codec, without modifying the original."]
pub fn client_mode(mut self) -> Self {
self.flags.remove(Flags::SERVER);
self
}
}
impl Default for Codec {
fn default() -> Self {
... |
rust_dataset_chunk_415 | rust_dataset.txt | 415 | 512 | ) {
Parser::write_message(
dst,
&data[..],
OpCode::Continue,
false,
!self.flags.contains(Flags::SERVER),
)
} els... |
rust_dataset_chunk_416 | rust_dataset.txt | 416 | 512 | Err(ProtocolError::ContinuationFragment(opcode))
}
};
}
match opcode {
OpCode::Continue => {
if self.flags.contains(Flags::CONTINUATION) {
self.flags.remove(Flags::CONTINUATION);
Ok(Some(... |
rust_dataset_chunk_417 | rust_dataset.txt | 417 | 512 | Dispatcher<S, T>
where
T: AsyncRead + AsyncWrite,
S: Service<Frame, Response = Message>,
S::Future: 'static,
S::Error: 'static,
{
pub fn new<F: IntoService<S, Frame>>(io: T, service: F) -> Self {
Dispatcher {
inner: inner::Dispatcher::new(Framed::new(io, Codec::new()), service),... |
rust_dataset_chunk_418 | rust_dataset.txt | 418 | 512 | : Encoder<I> + Decoder,
{
fn from(err: E) -> Self {
DispatcherError::Service(err)
}
}
impl<E, U, I> fmt::Debug for DispatcherError<E, U, I>
where
E: fmt::Debug,
U: Encoder<I> + Decoder,
<U as Encoder<I>>::Error: fmt::Debug,
<U as Decoder>::Err... |
rust_dataset_chunk_419 | rust_dataset.txt | 419 | 512 | Close,
}
pin_project! {
/// A future that reads frames from a [`Framed`] object and passes them to a [`Service`].
pub struct Dispatcher<S, T, U, I>
where
S: Service<<U as Decoder>::Item, Response = I>,
S::Error: 'static,
S::Future: 'static,
... |
rust_dataset_chunk_420 | rust_dataset.txt | 420 | 512 | Debug,
{
/// Create new `Dispatcher`.
pub fn new<F>(framed: Framed<T, U>, service: F) -> Self
where
F: IntoService<S, <U as Decoder>::Item>,
{
let (tx, rx) = mpsc::channel();
Dispatcher {
framed,
rx,
... |
rust_dataset_chunk_421 | rust_dataset.txt | 421 | 512 | match this.service.poll_ready(cx) {
Poll::Ready(Ok(_)) => {
let item = match this.framed.next_item(cx) {
Poll::Ready(Some(Ok(el))) => el,
Poll::Ready(Some(Err(err))) => {
*... |
rust_dataset_chunk_422 | rust_dataset.txt | 422 | 512 | => break,
Poll::Ready(Ok(_)) => {}
Poll::Ready(Err(err)) => {
debug!("Error sending data: {:?}", err);
*this.state = State::FramedError(DispatcherError::Encoder(err));
return true;
... |
rust_dataset_chunk_423 | rust_dataset.txt | 423 | 512 | CloseCode, CloseReason, OpCode},
ProtocolError,
};
/// A struct representing a WebSocket frame.
#[derive(Debug)]
pub struct Parser;
/// FIN bitmask (RFC 6455 §5.2).
const FIN_MASK: u8 = 0x80;
/// RSV1, RSV2, and RSV3 bitmask (RFC 6455 §5.2).
const RSV_MASK: u8 = 0b0111_0000;
/// OpCode 4-bit nibble mask (RFC 64... |
rust_dataset_chunk_424 | rust_dataset.txt | 424 | 512 | 5.2 defines the payload length as an unsigned 63-bit integer, so the most
/// significant bit must be zero.
fn payload_len_msb_set(len: u64) -> bool {
len > U64_PAYLOAD_MAX
}
impl Parser {
fn parse_metadata(
src: &[u8],
server: bool,
) -> Result<Option<(usize, bool, OpCode, usize, Option<[u... |
rust_dataset_chunk_425 | rust_dataset.txt | 425 | 512 | // the payload size limit that `Overflow` also documents.
return Err(ProtocolError::Overflow);
}
payload_len_to_usize(len)?
} else {
len as usize
};
let mask = if server {
if chunk_len < idx + MASK_LEN {
return O... |
rust_dataset_chunk_426 | rust_dataset.txt | 426 | 512 | match opcode {
OpCode::Ping | OpCode::Pong | OpCode::Close if length > MAX_CONTROL_FRAME_PAYLOAD => {
return Err(ProtocolError::InvalidLength(length));
}
_ => {}
}
// unmask
if let Some(mask) = mask {
apply_mask(&mut data, ... |
rust_dataset_chunk_427 | rust_dataset.txt | 427 | 512 | Error> {
// RFC 6455 §5.5.1 requires a two-byte status code when a close payload is not empty.
if payload.len() == 1 {
return Err(ProtocolError::InvalidLength(payload.len()));
}
if payload.len() >= 2 {
let raw_code = u16::from_be_bytes(
payload[..... |
rust_dataset_chunk_428 | rust_dataset.txt | 428 | 512 | two | payload_len as u8]);
} else if payload_len <= U16_PAYLOAD_MAX {
dst.reserve(p_len + 4);
dst.put_slice(&[one, two | EXT_LEN_U16]);
dst.put_u16(payload_len as u16);
} else {
dst.reserve(p_len + 10);
dst.put_slice(&[one, two | EXT_LEN_U64])... |
rust_dataset_chunk_429 | rust_dataset.txt | 429 | 512 | from(&[0x81u8, 127][..]);
buf.extend_from_slice(&(U64_PAYLOAD_MAX + 1).to_be_bytes());
assert!(
matches!(
Parser::parse(&mut buf, false, 1024),
Err(ProtocolError::Overflow)
),
"a 64-bit payload length with the MSB set must be rejected,... |
rust_dataset_chunk_430 | rust_dataset.txt | 430 | 512 | #[test]
fn test_parse_rejects_64_bit_length_beyond_addressable_range() {
let mut buf = BytesMut::from(&[0x81u8, 127][..]);
buf.extend_from_slice(&0x0000_0001_0000_0000u64.to_be_bytes());
buf.extend_from_slice(b"ABCD");
assert!(
matches!(
Parser::parse(&m... |
rust_dataset_chunk_431 | rust_dataset.txt | 431 | 512 | (&mut buf, false, 1024));
assert!(!frame.finished);
assert_eq!(frame.opcode, OpCode::Text);
assert!(frame.payload.is_empty());
}
#[test]
fn test_parse_length2() {
let mut buf = BytesMut::from(&[0b0000_0001u8, 126u8][..]);
assert!(is_none(&Parser::parse(&mut buf, fals... |
rust_dataset_chunk_432 | rust_dataset.txt | 432 | 512 | frame.opcode, OpCode::Text);
assert_eq!(frame.payload, Bytes::from(vec![1u8]));
}
#[test]
fn test_parse_frame_no_mask() {
let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]);
buf.extend([1u8]);
assert!(Parser::parse(&mut buf, true, 1024).is_err());
le... |
rust_dataset_chunk_433 | rust_dataset.txt | 433 | 512 | buf.extend([0b0000_0001u8, 0b0000_0010u8, 0b0000_0000u8, 0b0000_0000u8]);
// Next binary frame with length == 2 and payload == `[0x1111_1111u8, 0x1111_1111u8]`.
buf.extend([0b0000_0010u8, 0b0000_0010u8, 0b1111_1111u8, 0b1111_1111u8]);
assert_eq!(buf.len(), 8);
assert!(matches!(
... |
rust_dataset_chunk_434 | rust_dataset.txt | 434 | 512 | [..], &v[..]);
}
#[test]
fn test_empty_close_frame() {
let mut buf = BytesMut::new();
Parser::write_close(&mut buf, None, false);
assert_eq!(&buf[..], &vec![0x88, 0x00][..]);
}
#[test]
fn try_parse_close_payload_validates_payload() {
assert!(matches!(
... |
rust_dataset_chunk_435 | rust_dataset.txt | 435 | 512 | 0xff, 0xff, 0xff, 0xeb, 0x0e, 0x8f,
];
let mut buf = BytesMut::from(&buf[..]);
let result = Parser::parse(&mut buf, true, 65536);
// Opcode 0x0a is Pong. The length is rejected in `parse_metadata` before the frame can be
// buffered, so the header is reported as malformed rather ... |
rust_dataset_chunk_436 | rust_dataset.txt | 436 | 512 | _mut() {
*word ^= mask_u32;
}
apply_mask_fallback(suffix, mask_u32.to_ne_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_apply_mask() {
let mask = [0x6d, 0xb6, 0xb2, 0x80];
let unmasked = [
0xf3, 0x00, 0x01, 0x02, 0x03, 0x80, 0x81, 0x82, 0xff,... |
rust_dataset_chunk_437 | rust_dataset.txt | 437 | 512 | #[display("Received a masked frame from server")]
MaskedFrame,
/// Encountered invalid opcode.
#[display("Invalid opcode ({})", _0)]
InvalidOpcode(#[error(not(source))] u8),
// TODO(semver-major):
// /// Received a frame with non-zero reserved bits.
// #[display("Received a frame with ... |
rust_dataset_chunk_438 | rust_dataset.txt | 438 | 512 | /// WebSocket version header is not set.
#[display("WebSocket version header is required")]
NoVersionHeader,
/// Unsupported WebSocket version.
#[display("Unsupported WebSocket version")]
UnsupportedVersion,
/// WebSocket key is not set or wrong.
#[display("Unknown WebSocket key")]
Ba... |
rust_dataset_chunk_439 | rust_dataset.txt | 439 | 512 | .
pub fn handshake(req: &RequestHead) -> Result<ResponseBuilder, HandshakeError> {
verify_handshake(req)?;
Ok(handshake_response(req))
}
/// Verify WebSocket handshake request.
pub fn verify_handshake(req: &RequestHead) -> Result<(), HandshakeError> {
// WebSocket accepts only GET
if req.method != Meth... |
rust_dataset_chunk_440 | rust_dataset.txt | 440 | 512 | S)
.upgrade("websocket")
.insert_header((
header::SEC_WEBSOCKET_ACCEPT,
// key is known to be header value safe ascii
HeaderValue::from_bytes(&key).unwrap(),
))
.take()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{header, test::TestReq... |
rust_dataset_chunk_441 | rust_dataset.txt | 441 | 512 | from_static("websocket"),
))
.insert_header((
header::CONNECTION,
header::HeaderValue::from_static("upgrade"),
))
.insert_header((
header::SEC_WEBSOCKET_VERSION,
header::Header... |
rust_dataset_chunk_442 | rust_dataset.txt | 442 | 512 | );
}
#[test]
fn test_ws_error_http_response() {
let resp: Response<BoxBody> = HandshakeError::GetMethodRequired.into();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let resp: Response<BoxBody> = HandshakeError::NoWebsocketUpgrade.into();
assert_eq!(resp... |
rust_dataset_chunk_443 | rust_dataset.txt | 443 | 512 | impl From<OpCode> for u8 {
fn from(op: OpCode) -> u8 {
use self::OpCode::*;
match op {
Continue => 0,
Text => 1,
Binary => 2,
Close => 8,
Ping => 9,
Pong => 10,
Bad => {
tracing::error!("Attempted to... |
rust_dataset_chunk_444 | rust_dataset.txt | 444 | 512 | message
/// that violates its policy. This is a generic status code that can be returned when there is
/// no other more suitable status code (e.g., Unsupported or Size) or if there is a need to hide
/// specific details about the policy.
Policy,
/// Indicates that an endpoint is terminating the c... |
rust_dataset_chunk_445 | rust_dataset.txt | 445 | 512 | ,
1003 => Unsupported,
1006 => Abnormal,
1007 => Invalid,
1008 => Policy,
1009 => Size,
1010 => Extension,
1011 => Error,
1012 => Restart,
1013 => Again,
1015 => Tls,
_ => Other(code),
... |
rust_dataset_chunk_446 | rust_dataset.txt | 446 | 512 | s, unused_variables, dead_code)]
use super::*;
macro_rules! opcode_into {
($from:expr => $opcode:pat) => {
match OpCode::from($from) {
e @ $opcode => {}
e => unreachable!("{:?}", e),
}
};
}
macro_rules! opcode_from {
($fro... |
rust_dataset_chunk_447 | rust_dataset.txt | 447 | 512 | Code::Normal);
assert_eq!(CloseCode::from(1001u16), CloseCode::Away);
assert_eq!(CloseCode::from(1002u16), CloseCode::Protocol);
assert_eq!(CloseCode::from(1003u16), CloseCode::Unsupported);
assert_eq!(CloseCode::from(1006u16), CloseCode::Abnormal);
assert_eq!(CloseCode::from(100... |
rust_dataset_chunk_448 | rust_dataset.txt | 448 | 512 | Into::<u16>::into(CloseCode::Again));
assert_eq!(1015u16, Into::<u16>::into(CloseCode::Tls));
assert_eq!(2000u16, Into::<u16>::into(CloseCode::Other(2000)));
}
}
--- FILE: actix-web/actix-http-test/src/lib.rs ---
//! Various helpers for Actix applications to use during testing.
#) on an existing address binding.
pub async fn test_server_with_addr<F: ServerServiceFactory<TcpStream>>(
tcp: net::TcpListener,
factory: F,
) -> TestServer {
... |
rust_dataset_chunk_450 | rust_dataset.txt | 450 | 512 | (connector).finish()
};
TestServer {
server,
client,
system,
addr,
thread_stop_rx,
}
}
/// Test server controller
pub struct TestServer {
server: actix_server::ServerHandle,
client: awc::Client,
system: actix_rt::System,
addr: net::SocketAddr,
th... |
rust_dataset_chunk_451 | rust_dataset.txt | 451 | 512 | S) -> ClientRequest {
self.client.head(self.surl(path.as_ref()).as_str())
}
/// Create `PUT` request
pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.put(self.url(path.as_ref()).as_str())
}
/// Create HTTPS `PUT` request
pub fn sput<S: AsRef<str>>(&self... |
rust_dataset_chunk_452 | rust_dataset.txt | 452 | 512 | , path: S) -> ClientRequest {
self.client.request(method, path.as_ref())
}
pub async fn load_body<S>(
&mut self,
mut response: ClientResponse<S>,
) -> Result<Bytes, PayloadError>
where
S: Stream<Item = Result<Bytes, PayloadError>> + Unpin + 'static,
{
respons... |
rust_dataset_chunk_453 | rust_dataset.txt | 453 | 512 | pub fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)).unwrap();
socket.bind(&addr.into()).unwrap();
socket.set_reuse_address(true).unwrap();
let tcp = net::TcpListener::from(sock... |
rust_dataset_chunk_454 | rust_dataset.txt | 454 | 512 | .await;
let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success());
let request = srv.get("/").insert_header(("x-test", "111")).send();
let mut response = request.await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = respons... |
rust_dataset_chunk_455 | rust_dataset.txt | 455 | 512 | .h1(|req: Request| async move {
let (_, mut body) = req.into_parts();
let mut buf = Vec::new();
while let Some(Ok(chunk)) = body.next().await {
buf.extend_from_slice(&chunk);
}
let str = std::str::from_utf8(&buf).unwrap... |
rust_dataset_chunk_456 | rust_dataset.txt | 456 | 512 | h2(|_| async { Ok::<_, Error>(Response::ok()) })
.tcp()
})?
.run();
tx.send(srv.handle()).unwrap();
srv.await
})
});
let handle = rx.recv().unwrap();
let (sync_tx, rx) = std::sync::mpsc::sync_channel(1);
// use ... |
rust_dataset_chunk_457 | rust_dataset.txt | 457 | 512 | (1)
.listen("h2_ping_pong", lst, || {
HttpService::build()
.keep_alive(Duration::from_secs(30))
// set first request timeout to 5 seconds.
// this is the timeout used for http2 handshake.
... |
rust_dataset_chunk_458 | rust_dataset.txt | 458 | 512 | , BoxBody, SizedStream},
error::PayloadError,
header::{self, HeaderValue},
Error, HttpService, Method, Request, Response, StatusCode, TlsAcceptorConfig, Version,
};
use actix_http_test::test_server;
use actix_service::{fn_service, ServiceFactoryExt};
use bytes::{Bytes, BytesMut};
use derive_more::{Display, ... |
rust_dataset_chunk_459 | rust_dataset.txt | 459 | 512 | _| ready(Ok::<_, Error>(Response::ok())))
.openssl(tls_config())
.map_err(|_| ())
})
.await;
let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success());
Ok(())
}
#[tokio::test(flavor = "local")]
async fn h2_1() -> io::Result<()> {
let sr... |
rust_dataset_chunk_460 | rust_dataset.txt | 460 | 512 | ())
.map_err(|_| ())
})
.await;
static VALUE: HeaderValue = HeaderValue::from_static("0");
{
let req = srv.request(Method::HEAD, srv.surl("/0")).send();
actix_rt::time::timeout(Duration::from_secs(15), req)
.await
.expect("Request future stalled on r... |
rust_dataset_chunk_461 | rust_dataset.txt | 461 | 512 | TEST TEST TEST \
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \... |
rust_dataset_chunk_462 | rust_dataset.txt | 462 | 512 | ())
})
.await;
let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
}
#[tokio::test(flavor = "local")]
async fn h2_head_empty(... |
rust_dataset_chunk_463 | rust_dataset.txt | 463 | 512 | _LENGTH).unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
}
}
#[tokio::test(flavor = "local")]
async fn h2_body_length() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| async {
let body = once(async { Ok::<_, Infallible>(Bytes... |
rust_dataset_chunk_464 | rust_dataset.txt | 464 | 512 | }))
.openssl(tls_config())
.map_err(|_| ())
})
.await;
let response = srv.sget("/").send().await.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(
byt... |
rust_dataset_chunk_465 | rust_dataset.txt | 465 | 512 | ::pin,
sync::Arc,
task::Poll,
time::Duration,
};
use actix_http::{
body::{BodyStream, BoxBody, SizedStream},
error::PayloadError,
header::{self, HeaderName, HeaderValue},
Error, HttpService, Method, Request, Response, StatusCode, TlsAcceptorConfig, Version,
};
use actix_http_test::test_serv... |
rust_dataset_chunk_466 | rust_dataset.txt | 466 | 512 | config
}
fn tls_config() -> RustlsServerConfig {
tls_config_with_alpn(&[HTTP1_1_ALPN_PROTOCOL, H2_ALPN_PROTOCOL])
}
fn tls_config_h1() -> RustlsServerConfig {
tls_config_with_alpn(&[HTTP1_1_ALPN_PROTOCOL])
}
fn tls_config_h2() -> RustlsServerConfig {
tls_config_with_alpn(&[H2_ALPN_PROTOCOL])
}
fn h1... |
rust_dataset_chunk_467 | rust_dataset.txt | 467 | 512 | _client().get(srv.surl("/")).send().await.unwrap();
assert!(response.status().is_success());
srv.stop().await;
Ok(())
}
#[tokio::test(flavor = "local")]
async fn h2() -> io::Result<()> {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| ready(Ok::<_, Error>(Response::... |
rust_dataset_chunk_468 | rust_dataset.txt | 468 | 512 | ");
assert_eq!(req.version(), Version::HTTP_2);
ready(Ok::<_, Error>(Response::ok()))
})
.rustls_0_23(tls_config_h2())
})
.await;
let response = srv.squery("/").send().await.unwrap();
assert!(response.status().is_success());
srv.stop().await;
... |
rust_dataset_chunk_469 | rust_dataset.txt | 469 | 512 | {
let body = load_body(req.take_payload()).await?;
Ok::<_, Error>(Response::ok().set_body(body))
})
.rustls_0_23(tls_config_h2())
})
.await;
let response = srv.sget("/").send_body(data.clone()).await.unwrap();
assert!(response.status().is_success... |
rust_dataset_chunk_470 | rust_dataset.txt | 470 | 512 | .send();
let response = req.await.unwrap();
assert_eq!(response.headers().get(&header), None);
}
for &i in &[2, 3] {
let req = srv
.request(Method::GET, srv.surl(&format!("/{}", i)))
.send();
let response = req.await.unwra... |
rust_dataset_chunk_471 | rust_dataset.txt | 471 | 512 | Bytes::from(data2));
srv.stop().await;
}
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \
Hello World... |
rust_dataset_chunk_472 | rust_dataset.txt | 472 | 512 | ());
assert_eq!(response.version(), Version::HTTP_2);
{
let len = response
.headers()
.get(http::header::CONTENT_LENGTH)
.unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
}
// read response
let bytes = srv.load_body(response... |
rust_dataset_chunk_473 | rust_dataset.txt | 473 | 512 | 64, body)),
))
})
.rustls_0_23(tls_config_h2())
})
.await;
let response = srv.sget("/").send().await.unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from... |
rust_dataset_chunk_474 | rust_dataset.txt | 474 | 512 | (b"Error processing HTTP: failed to parse header value")
);
srv.stop().await;
}
#[derive(Debug, Display, Error)]
#[display("error")]
struct BadRequest;
impl From<BadRequest> for Response<BoxBody> {
fn from(_: BadRequest) -> Self {
Response::bad_request().set_body(BoxBody::new("error"))
}
}
#[... |
rust_dataset_chunk_475 | rust_dataset.txt | 475 | 512 | !(
get_negotiated_alpn_protocol(srv.addr(), CUSTOM_ALPN_PROTOCOL),
Some(CUSTOM_ALPN_PROTOCOL.to_vec())
);
let response = h1_client().get(srv.surl("/")).send().await.unwrap();
assert!(response.status().is_success());
srv.stop().await;
Ok(())
}
#[tokio::test(flavor = "local")]
async... |
rust_dataset_chunk_476 | rust_dataset.txt | 476 | 512 | /tests/test_server.rs ---
use std::{
convert::Infallible,
future::ready,
io::{Read, Write},
net,
pin::pin,
sync::{Arc, Mutex},
thread,
time::{Duration, Instant},
};
use actix_http::{
body::{self, BodyStream, BoxBody, SizedStream},
header, Error, HttpService, KeepAlive, Request, ... |
rust_dataset_chunk_477 | rust_dataset.txt | 477 | 512 | (flavor = "local")]
async fn h1_query() {
let mut srv = test_server(|| {
HttpService::build()
.h1(|req: Request| {
assert_eq!(req.method().as_str(), "QUERY");
ready(Ok::<_, Infallible>(Response::ok()))
})
.tcp()
})
.await;
let ... |
rust_dataset_chunk_478 | rust_dataset.txt | 478 | 512 | Service::build()
.expect(fn_service(|req: Request| {
sleep(Duration::from_millis(20)).then(move |_| {
if req.head().uri.query() == Some("yes=") {
ready(Ok(req))
} else {
ready(Err(ExpectFailed))
... |
rust_dataset_chunk_479 | rust_dataset.txt | 479 | 512 | unwrap();
let _ = stream.write_all(
b"POST /test HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\n\r\n",
);
for chunk_size in chunk_sizes.iter() {
let mut bytes = Vec::new();
let random_bytes = rand::rng()
.sample_iter(rand::distr:... |
rust_dataset_chunk_480 | rust_dataset.txt | 480 | 512 | _slice(last_chunk);
let smuggle_attempt = b"GET /smuggled-1 HTTP/1.1\r\nHost: localhost\r\n\r\n\
GET /smuggled-2 HTTP/1.1\r\nHost: localhost\r\n\r\n";
input.extend_from_slice(
format!(
"POST /front HTTP/1.1\r\n\
Host: localhost\r\n\
Conte... |
rust_dataset_chunk_481 | rust_dataset.txt | 481 | 512 | ()));
let mut srv = test_server({
let seen = seen.clone();
move || {
let seen = seen.clone();
HttpService::build()
.keep_alive(Duration::from_secs(30))
.h1(move |req: Request| {
seen.lock().unwrap().push(req.path().to_own... |
rust_dataset_chunk_482 | rust_dataset.txt | 482 | 512 | let _ = stream.write_all(b"GET /test HTTP/1.1\r\n");
let mut data = String::new();
let _ = stream.read_to_string(&mut data);
assert!(
data.starts_with("HTTP/1.1 408 Request Timeout"),
"response was not 408: {}",
data
);
let diff = start.elapsed();
if diff < Duration::f... |
rust_dataset_chunk_483 | rust_dataset.txt | 483 | 512 | (&data[..17], b"HTTP/1.1 200 OK\r\n");
srv.stop().await;
}
#[tokio::test(flavor = "local")]
async fn http1_keepalive_timeout() {
let mut srv = test_server(|| {
HttpService::build()
.keep_alive(Duration::from_secs(1))
.h1(|_| ready(Ok::<_, Infallible>(Response::ok())))
... |
rust_dataset_chunk_484 | rust_dataset.txt | 484 | 512 | spawn(move || {
let mut buf = Vec::new();
let mut chunk = [0u8; 256];
loop {
match stream.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => buf.extend_from_slice(&chunk[..n]),
}
}
let _ = tx.send(String::from_utf8_lossy... |
rust_dataset_chunk_485 | rust_dataset.txt | 485 | 512 | from_secs(30))
.client_request_timeout(Duration::from_secs(1))
.h1(|_| ready(Ok::<_, Infallible>(Response::ok())))
.tcp()
})
.await;
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream.write_all(b"GET /test HTTP/1.1\r\nHost: localhost\r\n\r... |
rust_dataset_chunk_486 | rust_dataset.txt | 486 | 512 | }
}
.timeout(Duration::from_secs(2))
.await
.expect("Request head deadline should not be renewed by incoming bytes");
assert!(response.starts_with("HTTP/1.1 408 Request Timeout"));
}
srv.stop().await;
}
/// Reads a complete response head from a service with an empty r... |
rust_dataset_chunk_487 | rust_dataset.txt | 487 | 512 | stream)
.await
.contains("200 OK"));
}
srv.stop().await;
}
#[tokio::test(flavor = "local")]
async fn http1_keepalive_pipelined_partial_head_uses_request_timeout() {
let mut srv = test_server(|| {
HttpService::build()
.keep_alive(Duration::from_millis(200))
... |
rust_dataset_chunk_488 | rust_dataset.txt | 488 | 512 | HttpService::build()
.h1(|_| ready(Ok::<_, Infallible>(Response::ok())))
.tcp()
})
.await;
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n");
let mut data = vec!... |
rust_dataset_chunk_489 | rust_dataset.txt | 489 | 512 | ()
.h1(|req: Request| {
let idx: usize = req.uri().path()[1..].parse().unwrap();
let statuses = [
StatusCode::NO_CONTENT,
StatusCode::CONTINUE,
StatusCode::SWITCHING_PROTOCOLS,
StatusCode::PROCESS... |
rust_dataset_chunk_490 | rust_dataset.txt | 490 | 512 | let addr = srv.addr();
let mut buf = [0; 12];
let mut conn = TcpStream::connect(&addr).await.unwrap();
conn.write_all(
b"POST /10000 HTTP/1.1\r\nHost: localhost\r\nContent-Length: 10000\r\n\r\ndata_truncated",
)
.await
.unwrap();
conn.shutdown().await.unwrap();
conn.read_exact(... |
rust_dataset_chunk_491 | rust_dataset.txt | 491 | 512 | TEST TEST TEST TEST TEST TEST TEST TEST TEST \
TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
));
}
ready(Ok::<_, Infallible>(builder.body(data.clone())))
})
.tcp()
})
.await;
let resp... |
rust_dataset_chunk_492 | rust_dataset.txt | 492 | 512 | async fn h1_head_empty() {
let mut srv = test_server(|| {
HttpService::build()
.h1(|_| ready(Ok::<_, Infallible>(Response::ok().set_body(STR))))
.tcp()
})
.await;
let response = srv.head("/").send().await.unwrap();
assert!(response.status().is_success());
{
... |
rust_dataset_chunk_493 | rust_dataset.txt | 493 | 512 | ible>(Bytes::from_static(STR.as_ref()))));
ready(Ok::<_, Infallible>(
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
))
})
.tcp()
})
.await;
let response = srv.get("/").send().await.unwrap();
assert!(respons... |
rust_dataset_chunk_494 | rust_dataset.txt | 494 | 512 | ed"
);
// read response
let bytes = srv.load_body(response).await.unwrap();
assert_eq!(bytes, Bytes::from_static(STR.as_ref()));
srv.stop().await;
}
#[tokio::test(flavor = "local")]
async fn h1_response_http_error_handling() {
let mut srv = test_server(|| {
HttpService::build()
... |
rust_dataset_chunk_495 | rust_dataset.txt | 495 | 512 | .tcp()
})
.await;
let response = srv.get("/").send().await.unwrap();
assert!(response.status().is_success());
srv.stop().await;
}
/// Tests compliance with 304 Not Modified spec in RFC 7232 §4.1.
/// https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
#[tokio::test(flavor = "local")]
async... |
rust_dataset_chunk_496 | rust_dataset.txt | 496 | 512 | .get("/cl-none").send().await.unwrap();
assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED);
assert_eq!(
res.headers().get(&CL),
Some(&header::HeaderValue::from_static("24")),
);
assert!(srv.load_body(res).await.unwrap().is_empty());
let res = srv.get("/cl-body").send().await.u... |
rust_dataset_chunk_497 | rust_dataset.txt | 497 | 512 | b"h2"[..]);
srv.stop().await;
}
#[tokio::test(flavor = "local")]
async fn h2_flow_control_window_sizes() {
let mut srv = test_server(|| {
HttpService::build()
.keep_alive(KeepAlive::Disabled)
.finish(|mut req: Request| async move {
while let Some(item) = req.tak... |
rust_dataset_chunk_498 | rust_dataset.txt | 498 | 512 | , App, HttpResponse, HttpServer};
use tokio::sync::Notify;
let started = Arc::new(Notify::new());
let handler_started = started.clone();
let listener = net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = HttpServer::new(move || {
App:... |
rust_dataset_chunk_499 | rust_dataset.txt | 499 | 512 | };
use actix_http::{
body::{BodySize, BoxBody},
h1,
ws::{self, CloseCode, Frame, Item, Message},
Error, HttpService, Request, Response,
};
use actix_http_test::test_server;
use actix_service::{fn_factory, Service};
use bytes::{Bytes, BytesMut};
use derive_more::{Display, Error, From};
use futures_core::... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.