changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / rust/lib/dl/tests/read-proxy-env.rs

changeset 78: 966f92770ddf
parent: 97c99e44a22f
author: ellis <ellis@rwest.io>
date: Sun, 03 Dec 2023 23:25:08 -0500
permissions: -rw-r--r--
description: lisp groveling and rust fmt
1 #![cfg(feature = "reqwest-backend")]
2 
3 use std::{
4  env::{remove_var, set_var},
5  error::Error,
6  net::TcpListener,
7  sync::{
8  atomic::{AtomicUsize, Ordering},
9  Mutex,
10  },
11  thread,
12  time::Duration,
13 };
14 
15 use env_proxy::for_url;
16 use reqwest::{blocking::Client, Proxy};
17 use url::Url;
18 
19 static SERIALISE_TESTS: Mutex<()> = Mutex::new(());
20 
21 fn scrub_env() {
22  remove_var("http_proxy");
23  remove_var("https_proxy");
24  remove_var("HTTPS_PROXY");
25  remove_var("ftp_proxy");
26  remove_var("FTP_PROXY");
27  remove_var("all_proxy");
28  remove_var("ALL_PROXY");
29  remove_var("no_proxy");
30  remove_var("NO_PROXY");
31 }
32 
33 // Tests for correctly retrieving the proxy (host, port) tuple from $https_proxy
34 #[test]
35 fn read_basic_proxy_params() {
36  let _guard = SERIALISE_TESTS
37  .lock()
38  .expect("Unable to lock the test guard");
39  scrub_env();
40  set_var("https_proxy", "http://proxy.example.com:8080");
41  let u = Url::parse("https://www.example.org").ok().unwrap();
42  assert_eq!(
43  for_url(&u).host_port(),
44  Some(("proxy.example.com".to_string(), 8080))
45  );
46 }
47 
48 // Tests to verify if socks feature is available and being used
49 #[test]
50 fn socks_proxy_request() {
51  static CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
52  let _guard = SERIALISE_TESTS
53  .lock()
54  .expect("Unable to lock the test guard");
55 
56  scrub_env();
57  set_var("all_proxy", "socks5://127.0.0.1:1080");
58 
59  thread::spawn(move || {
60  let listener = TcpListener::bind("127.0.0.1:1080").unwrap();
61  let incoming = listener.incoming();
62  for _ in incoming {
63  CALL_COUNT.fetch_add(1, Ordering::SeqCst);
64  }
65  });
66 
67  let env_proxy = |url: &Url| for_url(url).to_url();
68  let url = Url::parse("http://192.168.0.1/").unwrap();
69 
70  let client = Client::builder()
71  .proxy(Proxy::custom(env_proxy))
72  .timeout(Duration::from_secs(1))
73  .build()
74  .unwrap();
75  let res = client.get(url.as_str()).send();
76 
77  if let Err(e) = res {
78  let s = e.source().unwrap();
79  assert!(
80  s.to_string().contains("socks connect error"),
81  "Expected socks connect error, got: {s}",
82  );
83  assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1);
84  } else {
85  panic!("Socks proxy was ignored")
86  }
87 }