| 106 | |
| 107 | impl MockServer { |
| 108 | fn new(status: u16, response: Value) -> Self { |
| 109 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); |
| 110 | let url = format!("http://{}", listener.local_addr().unwrap()); |
| 111 | listener.set_nonblocking(true).unwrap(); |
| 112 | let requests = Arc::new(Mutex::new(Vec::new())); |
| 113 | let stop = Arc::new(AtomicBool::new(false)); |
| 114 | let worker = { |
| 115 | let requests = Arc::clone(&requests); |
| 116 | let stop = Arc::clone(&stop); |
| 117 | thread::spawn(move || { |
| 118 | while !stop.load(Ordering::Relaxed) { |
| 119 | let mut stream = match listener.accept() { |
| 120 | Ok((stream, _)) => stream, |
| 121 | Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { |
| 122 | thread::sleep(Duration::from_millis(5)); |
| 123 | continue; |
| 124 | } |
| 125 | Err(error) => panic!("accept mock request: {error}"), |
| 126 | }; |
| 127 | stream.set_nonblocking(false).unwrap(); |
| 128 | stream |
| 129 | .set_read_timeout(Some(Duration::from_secs(5))) |
| 130 | .unwrap(); |
| 131 | stream |
| 132 | .set_write_timeout(Some(Duration::from_secs(5))) |
| 133 | .unwrap(); |
| 134 | let mut reader = BufReader::new(stream.try_clone().unwrap()); |
| 135 | let mut request = String::new(); |
| 136 | reader.read_line(&mut request).unwrap(); |
| 137 | let mut length = 0; |
| 138 | loop { |
| 139 | let mut header = String::new(); |
| 140 | reader.read_line(&mut header).unwrap(); |
| 141 | if header.trim().is_empty() { |
| 142 | break; |
| 143 | } |
| 144 | if let Some((name, value)) = header.split_once(':') { |
| 145 | if name.eq_ignore_ascii_case("content-length") { |
| 146 | length = value.trim().parse().unwrap(); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | let mut body = vec![0; length]; |
| 151 | reader.read_exact(&mut body).unwrap(); |
| 152 | let body = if body.is_empty() { |
| 153 | Value::Null |
| 154 | } else { |
| 155 | serde_json::from_slice(&body).unwrap() |
| 156 | }; |
| 157 | requests |
| 158 | .lock() |
| 159 | .expect("requests lock poisoned") |
| 160 | .push((request, body)); |
| 161 | let body = response.to_string(); |
| 162 | write!(stream, "HTTP/1.1 {status} Mock\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap(); |
| 163 | } |
| 164 | }) |
| 165 | }; |