1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
use std::collections::HashMap;
use std::convert::From;
use std::env;
use std::fmt;
use std::iter::FromIterator;
use std::process;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use futures::future::result;
use http;
use http::StatusCode;
use hyper::client::{Client, HttpConnector};
use hyper::rt::Future;
use hyper::{Body, Request};
use hyper_tls::HttpsConnector;
use os_type;
use tokio::util::FutureExt;

use errors::*;

use hostname;
use notice;
use notice::{Notice, Notifier};

use serde_json;

const HONEYBADGER_ENDPOINT: &'static str = "https://api.honeybadger.io/v1/notices";
const HONEYBADGER_DEFAULT_TIMEOUT: u64 = 5;
const HONEYBADGER_DEFAULT_THREADS: usize = 4;

const NOTIFIER_NAME: &'static str = "honeybadger";
const NOTIFIER_URL: &'static str = "https://github.com/fussybeaver/honeybader-rs";

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

/// Config instance containing user-defined configuration for this crate.
#[derive(Debug)]
pub struct Config {
    api_key: String,
    root: String,
    env: String,
    hostname: String,
    endpoint: String,
    timeout: Duration,
    threads: usize,
}

/// Configuration builder struct, used for building a `Config` instance
pub struct ConfigBuilder {
    api_key: String,
    root: Option<String>,
    env: Option<String>,
    hostname: Option<String>,
    endpoint: Option<String>,
    timeout: Option<Duration>,
    threads: Option<usize>,
}

/// Instance containing the client connection and user configuration for this crate.
pub struct Honeybadger {
    client: Arc<Client<HttpsConnector<HttpConnector>>>,
    config: Config,
    user_agent: String,
}

impl ConfigBuilder {
    /// Construct a `ConfigBuilder` to parametrize the Honeybadger client.
    ///
    /// `ConfigBuilder` is populated using environment variables, which will inject
    /// Honeybadger event fields:
    ///   - `HONEYBADGER_ROOT` - project root for each event.
    ///   - `ENV` - environment name for each event.
    ///   - `HOSTNAME` - host name for each event.
    ///   - `HONEYBADGER_ENDPOINT` - override the default endpoint for the HTTPS client.
    ///   - `HONEYBADGER_TIMEOUT` - write timeout for the Honeybadger HTTPS client.
    ///
    /// # Arguments
    ///
    /// * `api_token` - API key for the honeybadger project
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token);
    /// ```
    pub fn new(api_token: &str) -> Self {
        Self {
            api_key: api_token.to_owned(),
            root: env::var("HONEYBADGER_ROOT").ok(),
            env: env::var("ENV").ok(),
            hostname: env::var("HOSTNAME").ok(),
            endpoint: env::var("HONEYBADGER_ENDPOINT").ok(),
            timeout: env::var("HONEYBADGER_TIMEOUT")
                .ok()
                .and_then(|s| s.parse().ok())
                .map(|t| Duration::new(t, 0)),
            threads: None,
        }
    }

    /// Override the project root property for events posted to the Honeybadger API. Consumes the
    /// `ConfigBuilder` and returns a new value.
    ///
    /// # Arguments
    ///
    /// * `project_root` - The directory where your code lives.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).with_root("/tmp/my_project_root");
    /// ```
    pub fn with_root(mut self, project_root: &str) -> Self {
        self.root = Some(project_root.to_owned());
        self
    }

    /// Add an environment name property for events posted to the Honeybadger API, which will then
    /// be categorized accordingly in the UI. Consumes the `ConfigBuilder` and returns a new
    /// value.
    ///
    /// # Arguments
    ///
    /// * `environment` - The directory where your code lives.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).with_env("production");
    /// ```
    pub fn with_env(mut self, environment: &str) -> Self {
        self.env = Some(environment.to_owned());
        self
    }

    /// Override the hostname property for events posted to the Honeybadger API. Consumes the
    /// `ConfigBuilder` and returns a new value.
    ///
    /// # Arguments
    ///
    /// * `hostname` - The server's hostname
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).with_hostname("localhost");
    /// ```
    pub fn with_hostname(mut self, hostname: &str) -> Self {
        self.hostname = Some(hostname.to_owned());
        self
    }

    /// Override the Honeybadger endpoint used to post HTTP payloads. Consumes the `ConfigBuilder`
    /// and returns a new value.
    ///
    /// # Arguments
    ///
    /// * `endpoint` - A custom honeybadger endpoint to query
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).with_endpoint("http://proxy.example.com:5050/");
    /// ```
    pub fn with_endpoint(mut self, endpoint: &str) -> Self {
        self.endpoint = Some(endpoint.to_owned());
        self
    }

    /// Override the HTTP write timeout for the client used to post events to Honeybadger.
    /// Consumes the `ConfigBuilder` and returns a new value.
    ///
    /// # Arguments
    ///
    /// * `timeout` - A `Duration` reference specifying the HTTP timeout for the write request
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// # use std::time::Duration;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).with_timeout(&Duration::new(20, 0));
    /// ```
    pub fn with_timeout(mut self, timeout: &Duration) -> Self {
        self.timeout = Some(timeout.to_owned());
        self
    }

    /// Override the number of threads the async HTTP connection should use to queue Honeybadger
    /// payloads.  Consumes the `ConfigBuilder` and returns a new reference.
    ///
    /// # Arguments
    ///
    /// * `threads` - The number of threads to configure the hyper connector
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).with_threads(8);
    /// ```
    pub fn with_threads(mut self, threads: usize) -> Self {
        self.threads = Some(threads);
        self
    }

    /// Prepare a `Config` instance for constructing a Honeybadger instance.
    ///
    /// Defaults are set if the `ConfigBuilder` used to construct the `Config` is empty.
    ///
    ///   - _default root_: the current directory
    ///   - _default hostname_: the host name as reported by the operating system
    ///   - _default endpoint_: `https://api.honeybadger.io/v1/notices`
    ///   - _default timeout_: a 5 second client write timeout
    ///   - _default threads_: 4 threads are used in the asynchronous runtime pool
    ///
    /// # Example
    ///
    /// ```rust
    /// # use honeybadger::ConfigBuilder;
    /// # let api_token = "ffffff";
    /// ConfigBuilder::new(api_token).build();
    /// ```
    pub fn build(self) -> Config {
        Config {
            api_key: self.api_key,
            root: self
                .root
                .or(env::current_dir()
                    .ok()
                    .and_then(|x| x.to_str().map(|x| x.to_owned())))
                .unwrap_or_else(|| "".to_owned()),
            env: self.env.unwrap_or_else(|| "".to_owned()),
            hostname: self
                .hostname
                .or(hostname::get_hostname())
                .unwrap_or_else(|| "".to_owned()),
            endpoint: self
                .endpoint
                .unwrap_or_else(|| HONEYBADGER_ENDPOINT.to_owned()),
            timeout: self
                .timeout
                .unwrap_or_else(|| Duration::new(HONEYBADGER_DEFAULT_TIMEOUT, 0)),
            threads: self.threads.unwrap_or(HONEYBADGER_DEFAULT_THREADS),
        }
    }
}

impl Honeybadger {
    /// Constructs a Honeybadger instance, which may be used to send API notify requests.
    ///
    /// # Arguments
    ///
    /// * `config` - `Config` instance, which is built using the `ConfigBuilder`
    ///
    /// # Example
    ///
    /// ```
    /// # use honeybadger::{ConfigBuilder, Honeybadger};
    /// # let api_token = "ffffff";
    /// let config = ConfigBuilder::new(api_token).build();
    ///
    /// assert_eq!(true, Honeybadger::new(config).is_ok());
    /// ```
    pub fn new(config: Config) -> Result<Self> {
        let https = HttpsConnector::new(config.threads)?;

        let builder = Client::builder();

        let os = os_type::current_platform();
        let user_agent: String = fmt::format(format_args!(
            "HB-rust {}; {:?}/{}",
            VERSION, os.os_type, os.version
        ));

        debug!(
            "Constructed honeybadger instance with configuration: {:?}",
            config
        );

        Ok(Honeybadger {
            config: config,
            client: Arc::new(builder.build(https)),
            user_agent: user_agent,
        })
    }

    fn serialize<'req>(
        config: &Config,
        error: notice::Error,
        context: Option<HashMap<&'req str, &'req str>>,
    ) -> serde_json::Result<Vec<u8>> {
        let notifier = Notifier {
            name: NOTIFIER_NAME,
            url: NOTIFIER_URL,
            version: VERSION,
        };

        let request = notice::Request {
            context: context,
            cgi_data: HashMap::<String, String>::from_iter(env::vars()),
        };

        let server = notice::Server {
            project_root: &config.root,
            environment_name: &config.env,
            hostname: &config.hostname,
            time: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|v| v.as_secs())
                .unwrap_or(0),
            pid: process::id(),
        };

        let notice = Notice {
            api_key: &config.api_key,
            notifier: notifier,
            error: error,
            request: request,
            server: server,
        };

        serde_json::to_vec(&notice)
    }

    fn create_payload_with_config<'req>(
        config: &Config,
        user_agent: &str,
        error: notice::Error,
        context: Option<HashMap<&'req str, &'req str>>,
    ) -> Result<Request<Body>> {
        let mut request = Request::builder();

        let api_key: &str = config.api_key.as_ref();
        let user_agent: &str = user_agent.as_ref();

        request
            .uri(config.endpoint.clone())
            .method(http::Method::POST)
            .header(http::header::ACCEPT, "application/json")
            .header("X-API-Key", api_key)
            .header(http::header::USER_AGENT, user_agent);

        let data = Honeybadger::serialize(config, error, context)?;

        let r = request.body(Body::from(data))?;
        Ok(r)
    }

    fn convert_error(kind: ErrorKind) -> Error {
        let e: Result<()> = Err(kind.into());
        e.err().unwrap()
    }

    /// Trigger the notify request using an async HTTPS request.
    ///
    /// Requires an initialized [Tokio][1] `Runtime`, and returns a [Future][2] that must be
    /// resolved using the Tokio framework orchestration methods.
    ///
    /// # Arguments
    ///
    /// * `error` - a struct that implements the [`From`][4] trait for a
    /// [`notice::Error`][5].
    /// * `context` - Optional [`HashMap`][7] to pass to the [Honeybadger context][6] API
    ///
    /// # Examples
    ///
    /// ## With `chained_error::Error`
    ///
    /// ```rust
    /// #[macro_use] extern crate error_chain;
    /// # extern crate honeybadger;
    /// # extern crate tokio;
    /// error_chain! {
    ///   errors {
    ///     MyCustomError
    ///   }
    /// }
    /// #
    /// # fn main() {
    /// # use honeybadger::{ConfigBuilder, Honeybadger};
    /// # use tokio::runtime::current_thread;
    /// # let api_token = "ffffff";
    /// # let config = ConfigBuilder::new(api_token).build();
    /// # let mut honeybadger = Honeybadger::new(config).unwrap();
    ///
    /// let error : Result<()> = Err(ErrorKind::MyCustomError.into());
    ///
    /// let mut rt = current_thread::Runtime::new().unwrap();
    /// let future = honeybadger.notify(
    ///   honeybadger::notice::Error::new(&error.unwrap_err()),
    ///   None);
    ///
    /// rt.block_on(future);
    /// #
    /// # }
    /// ```
    ///
    /// ## With `failure::Error`
    ///
    /// ```rust
    /// #[macro_use] extern crate failure;
    /// # extern crate honeybadger;
    /// # extern crate tokio;
    /// #[derive(Fail, Debug)]
    /// #[fail(display = "Failure error")]
    /// struct MyCustomError;
    /// # fn main() {
    /// # use honeybadger::{ConfigBuilder, Honeybadger};
    /// # use tokio::runtime::current_thread;
    /// # let api_token = "ffffff";
    /// # let config = ConfigBuilder::new(api_token).build();
    /// # let mut honeybadger = Honeybadger::new(config).unwrap();
    ///
    /// let error: Result<(), failure::Error> = Err(MyCustomError {}.into());
    ///
    /// let mut rt = current_thread::Runtime::new().unwrap();
    /// let future = honeybadger.notify(
    ///   error.unwrap_err(),
    ///   None);
    ///
    /// rt.block_on(future);
    /// #
    /// # }
    /// ```
    ///
    /// ## With `Box<std::error::Error>`.
    ///
    /// Note that [`std::error::Error`](8) does not implement [Sync](9), and it's not possible to
    /// use the error type across future combinators, so it's recommended to convert into a
    /// `Box<std::error::Error>` in the same closure as the Honeybadger API call.
    ///
    /// ```rust
    /// # extern crate honeybadger;
    /// # extern crate tokio;
    /// # fn main() {
    /// # use honeybadger::{ConfigBuilder, Honeybadger};
    /// # use tokio::runtime::current_thread;
    /// # let api_token = "ffffff";
    /// # let config = ConfigBuilder::new(api_token).build();
    /// # let mut honeybadger = Honeybadger::new(config).unwrap();
    ///
    /// let error: Result<(), Box<std::error::Error>> = Err(
    ///   std::io::Error::new(
    ///     std::io::ErrorKind::Other, "std Error"
    ///   ).into()
    /// );
    ///
    /// let mut rt = current_thread::Runtime::new().unwrap();
    /// let future = honeybadger.notify(
    ///   error.unwrap_err(),
    ///   None);
    ///
    /// rt.block_on(future);
    /// #
    /// # }
    /// ```
    ///
    /// [1]: https://github.com/tokio-rs/tokio
    /// [2]: https://docs.rs/futures/0.2.1/futures/future/index.html
    /// [3]: https://docs.rs/hyper/0.12.5/hyper/struct.Request.html
    /// [4]: https://doc.rust-lang.org/std/convert/trait.From.html
    /// [5]: notice/struct.Error.html
    /// [6]: https://docs.honeybadger.io/ruby/getting-started/adding-context-to-errors.html#context-in-honeybadger-notify
    /// [7]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
    /// [8]: https://doc.rust-lang.org/std/error/trait.Error.html
    /// [9]: https://doc.rust-lang.org/std/marker/trait.Sync.html
    pub fn notify<'req, E: Into<::notice::Error>>(
        self,
        error: E,
        context: Option<HashMap<&'req str, &'req str>>,
    ) -> impl Future<Item = (), Error = Error> + '_
    where
        ::notice::Error: From<E>,
    {
        let client = Arc::clone(&self.client);
        let t = self.config.timeout.as_secs();
        result(Honeybadger::create_payload_with_config(
            &self.config,
            &self.user_agent,
            error.into(),
            context,
        ))
        .and_then(move |request| Honeybadger::notify_with_client(client, t, request))
    }

    fn notify_with_client<'req, C>(
        client: Arc<Client<C>>,
        timeout: u64,
        request: Request<Body>,
    ) -> impl Future<Item = (), Error = Error>
    where
        C: ::hyper::client::connect::Connect + Sync + 'static,
        C::Error: 'static,
        C::Transport: 'static,
    {
        let now = ::std::time::Instant::now();

        client
            .request(request)
            .map_err(move |e| {
                error!("Honeybadger client error: {}", e);
                Honeybadger::convert_error(ErrorKind::Hyper(e))
            })
            .deadline(now + Duration::from_secs(timeout))
            .map_err(move |e| {
                error!("Honeybadger request timed-out!: {}", e);
                Honeybadger::convert_error(ErrorKind::TimeoutError(timeout))
            })
            .and_then(|response| {
                let (parts, _) = response.into_parts();
                debug!("Honeybadger API returned status: {}", parts.status);
                match parts.status {
                    s if s.is_success() => Ok(()),
                    s if s.is_redirection() => Err(ErrorKind::RedirectionError.into()),
                    StatusCode::UNAUTHORIZED => Err(ErrorKind::UnauthorizedError.into()),
                    StatusCode::UNPROCESSABLE_ENTITY => Err(ErrorKind::NotProcessedError.into()),
                    StatusCode::TOO_MANY_REQUESTS => Err(ErrorKind::RateExceededError.into()),
                    StatusCode::INTERNAL_SERVER_ERROR => Err(ErrorKind::ServerError.into()),
                    _ => Err(ErrorKind::UnknownStatusCodeError(parts.status.as_u16()).into()),
                }
            })
    }
}

#[cfg(test)]
mod tests {

    use honeybadger::*;
    use hyper::client::Client;
    use hyper::Body;
    use hyper_mock::SequentialConnector;
    use std::time::Duration;
    use tokio::runtime::current_thread;

    fn test_client_with_response(res: String, config: &Config) -> Result<()> {
        let mut c = SequentialConnector::default();
        c.content.push(res);

        let client = Arc::new(Client::builder().build::<SequentialConnector, Body>(c));

        let mut rt = current_thread::Runtime::new().unwrap();

        let error: Result<()> = Err(ErrorKind::RedirectionError.into());
        let error = notice::Error::new(&error.unwrap_err());
        let req =
            Honeybadger::create_payload_with_config(config, "test-client", error, None).unwrap();
        let t = config.timeout.as_secs();
        let res = Honeybadger::notify_with_client(client, t, req);

        rt.block_on(res)
    }

    #[test]
    fn test_notify_ok() {
        let config = ConfigBuilder::new("dummy-api-key").build();
        let res = test_client_with_response(
            "HTTP/1.1 201 Created\r\n\
             Server: mock1\r\n\
             \r\n\
             "
            .to_string(),
            &config,
        );

        assert_eq!((), res.unwrap());
    }

    #[test]
    fn test_notify_timeout() {
        let config = ConfigBuilder::new("dummy-api-key").build();
        let res = test_client_with_response("HTTP/1.1 201 Created\r\n".to_string(), &config);

        match res {
            Err(Error(ErrorKind::TimeoutError(5), _)) => assert!(true),
            _ => assert_eq!("", "expected timeout error, but was not"),
        }
    }

    #[test]
    fn test_notify_rate_exceeded() {
        let config = ConfigBuilder::new("dummy-api-key").build();
        let res = test_client_with_response(
            "HTTP/1.1 429 Too Many Requests\r\n\
             Server: mock1\r\n\
             \r\n\
             "
            .to_string(),
            &config,
        );

        match res {
            Err(Error(ErrorKind::RateExceededError, _)) => assert!(true),
            _ => assert_eq!("", "expected rate exceeded error, but was not"),
        }
    }

    #[test]
    fn test_with_root() {
        let config = ConfigBuilder::new("dummy-api-key").build();

        assert_ne!("/tmp/build", config.root);

        let config = ConfigBuilder::new("dummy-api-key")
            .with_root("/tmp/build")
            .build();

        assert_eq!("/tmp/build", config.root);
    }

    #[test]
    fn test_with_env() {
        let config = ConfigBuilder::new("dummy-api-key").build();

        assert_eq!("", config.env);

        let config = ConfigBuilder::new("dummy-api-key").with_env("test").build();

        assert_eq!("test", config.env);
    }

    #[test]
    fn test_with_hostname() {
        let config = ConfigBuilder::new("dummy-api-key").build();

        assert_ne!("hickyblue", config.hostname);

        let config = ConfigBuilder::new("dummy-api-key")
            .with_hostname("hickyblue")
            .build();

        assert_eq!("hickyblue", config.hostname);
    }

    #[test]
    fn test_with_endpoint() {
        let config = ConfigBuilder::new("dummy-api-key").build();

        assert_eq!(HONEYBADGER_ENDPOINT, config.endpoint);

        let config = ConfigBuilder::new("dummy-api-key")
            .with_endpoint("http://example.com/")
            .build();

        assert_eq!("http://example.com/", config.endpoint);
    }

    #[test]
    fn test_with_timeout() {
        let config = ConfigBuilder::new("dummy-api-key").build();

        assert_eq!(
            Duration::new(HONEYBADGER_DEFAULT_TIMEOUT, 0),
            config.timeout
        );

        let config = ConfigBuilder::new("dummy-api-key")
            .with_timeout(&Duration::new(20, 0))
            .build();

        assert_eq!(Duration::new(20, 0), config.timeout);
    }

    #[test]
    fn test_with_threads() {
        let config = ConfigBuilder::new("dummy-api-key").build();

        assert_eq!(HONEYBADGER_DEFAULT_THREADS, config.threads);

        let config = ConfigBuilder::new("dummy-api-key")
            .with_threads(128)
            .build();

        assert_eq!(128, config.threads);
    }
}