passivized_docker_engine_client 0.0.9

Docker Engine Client - manage and run containers, images, and volumes.
Documentation
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use std::collections::HashMap;
use std::string::FromUtf8Error;
use hyper::http::header::CONTENT_TYPE;

use hyper::{Request, StatusCode};
use hyper::body::Bytes;
use log::debug;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Deserializer;

use crate::errors::{DecLibraryError, DecUseError};
use crate::imp::content_type;
use crate::imp::hyper_proxy::HyperHttpClient;
use crate::imp::other::{base64_encode, converge};
use crate::model::{RegistryAuth, RegistryConfig};
use crate::responses::ErrorResponse;

/// A proxy class that provides a basic REST-based DSL for interacting
/// with a Docker Engine HTTP API endpoint. Most payloads are JSON.
#[derive(Clone, Debug)]
pub(crate) struct DockerEngineHttpClient {
    client: HyperHttpClient
}

impl DockerEngineHttpClient {

    pub fn new(client: HyperHttpClient) -> Self {
        Self {
            client
        }
    }

    fn build_delete(uri: &str) -> Result<Request<hyper::Body>, DecLibraryError> {
        Request::delete(uri)
            .body(hyper::Body::empty())
            .map_err(DecLibraryError::HttpRequestBuilderError)
    }

    fn build_get(uri: &str) -> Result<Request<hyper::Body>, DecLibraryError> {
        Request::get(uri.to_string())
            .body(hyper::Body::empty())
            .map_err(DecLibraryError::HttpRequestBuilderError)
    }

    #[cfg(not(windows))]
    fn build_put(uri: &str, content_type: &str, content: Vec<u8>) -> Result<Request<hyper::Body>, DecLibraryError> {
        Request::put(uri)
            .header(CONTENT_TYPE, content_type)
            .body(content.into())
            .map_err(DecLibraryError::HttpRequestBuilderError)
    }

    fn build_post_json<B: Serialize>(uri: &str, body: &B) -> Result<Request<hyper::Body>, DecLibraryError> {
        let json = serde_json::to_string(body)
            .map_err(DecLibraryError::RequestSerializationError)?;

        Request::post(uri.to_string())
            .header(CONTENT_TYPE, content_type::JSON)
            .body(hyper::Body::from(json))
            .map_err(DecLibraryError::HttpRequestBuilderError)
    }

    fn build_post_with_auth(uri: &str, registry_auth: &Option<RegistryAuth>) -> Result<Request<hyper::Body>, DecLibraryError> {
        let mut builder = Request::post(uri.to_string());

        if let Some(value) = Self::x_registry_auth(registry_auth)? {
            builder = builder.header("X-Registry-Auth", value);
        }

        builder
            .body(hyper::Body::empty())
            .map_err(DecLibraryError::HttpRequestBuilderError)
    }

    fn build_post_with_auth_config(
        uri: &str,
        registry_config: &HashMap<String, RegistryConfig>,
        content_type: &str,
        body: Vec<u8>) -> Result<Request<hyper::Body>, DecLibraryError>
    {
        let mut builder = Request::post(uri.to_string())
            .header(CONTENT_TYPE, content_type);

        if let Some(value) = Self::x_registry_config(registry_config)? {
            builder = builder.header("X-Registry-Config", value);
        }

        builder
            .body(hyper::Body::from(body))
            .map_err(DecLibraryError::HttpRequestBuilderError)
    }

    fn build_request<U, F>(&self, uri: U, request_from_uri: F) -> Result<DockerEngineHttpRequest, DecLibraryError>
    where
        U: ToString,
        F: FnOnce(&str) -> Result<Request<hyper::Body>, DecLibraryError>
    {
        let u = uri.to_string();

        Ok(DockerEngineHttpRequest {
            client: self.client.clone(),
            request: request_from_uri(&u)?,
            uri: u
        })
    }

    pub fn delete<U: ToString>(&self, uri: U) -> Result<DockerEngineHttpRequest, DecLibraryError> {
        self.build_request(uri, Self::build_delete)
    }

    pub fn get<U: ToString>(&self, uri: U) -> Result<DockerEngineHttpRequest, DecLibraryError> {
        self.build_request(uri, Self::build_get)
    }

    pub fn post<U: ToString>(&self, uri: U) -> Result<DockerEngineHttpRequest, DecLibraryError> {
        self.build_request(uri, |u| Self::build_post_with_auth(u, &None))
    }

    pub fn post_json<U: ToString, B: Serialize>(&self, uri: U, body: &B) -> Result<DockerEngineHttpRequest, DecLibraryError> {
        self.build_request(uri, |u| Self::build_post_json(u, body))
    }

    pub fn post_with_auth<U: ToString>(&self, uri: U, registry_auth: &Option<RegistryAuth>) -> Result<DockerEngineHttpRequest, DecLibraryError> {
        self.build_request(uri, |u| Self::build_post_with_auth(u, registry_auth))
    }

    pub fn post_with_auth_config<U: ToString>(
        &self,
        uri: U,
        registry_auth: &Option<RegistryAuth>,
        content_type: &str,
        body: Vec<u8>
    ) -> Result<DockerEngineHttpRequest, DecLibraryError>
    {
        let auth_config = registry_auth
            .as_ref()
            .map(|ra| ra.as_config())
            .unwrap_or_default();

        self.build_request(uri, |u| Self::build_post_with_auth_config(u, &auth_config, content_type, body))
    }

    #[cfg(not(windows))]
    pub fn put<U: ToString>(&self, uri: U, content_type: &str, content: Vec<u8>) -> Result<DockerEngineHttpRequest, DecLibraryError> {
        self.build_request(uri, |u| Self::build_put(u, content_type, content))
    }

    fn x_registry_auth(registry_auth: &Option<RegistryAuth>) -> Result<Option<String>, DecLibraryError> {
        match registry_auth {
            None => Ok(None),
            Some(auth) => {
                let json = serde_json::to_string(&auth)
                    .map_err(DecLibraryError::RegistryAuthJsonEncodingError)?;

                Ok(Some(base64_encode(json)))
            }
        }
    }

    fn x_registry_config(registry_config: &HashMap<String, RegistryConfig>) -> Result<Option<String>, DecLibraryError> {
        if registry_config.is_empty() {
            Ok(None)
        }
        else {
            let json = serde_json::to_string(registry_config)
                .map_err(DecLibraryError::RegistryAuthJsonEncodingError)?;

            Ok(Some(base64_encode(json)))
        }
    }
}

#[derive(Debug)]
pub(crate) struct DockerEngineHttpRequest {
    client: HyperHttpClient,
    request: Request<hyper::Body>,
    uri: String
}

impl DockerEngineHttpRequest {

    pub async fn execute(self) -> Result<DockerEngineHttpResponse, DecUseError> {
        let response = self.client
            .apply(self.request)
            .await
            .map_err(DecUseError::HttpClientError)?;

        Ok(
            DockerEngineHttpResponse {
                request_uri: self.uri,
                status: response.status(),
                content_type: match response.headers().get("Content-Type") {
                    None => None,
                    Some(hv) => match hv.to_str() {
                        Ok(text) => Some(text.to_string()),
                        Err(_) => None
                    }
                },
                body: hyper::body::to_bytes(response.into_body())
                    .await
                    .map_err(DecUseError::HttpClientError)?
            }
        )
    }

}

#[derive(Clone, Debug)]
pub(crate) struct DockerEngineHttpResponse {
    pub(crate) request_uri: String,
    pub(crate) status: StatusCode,
    pub(crate) content_type: Option<String>,
    pub(crate) body: Bytes,
}

impl DockerEngineHttpResponse {

    pub(crate) fn assert_item_status(self: DockerEngineHttpResponse, expected: StatusCode) -> Result<DockerEngineHttpResponse, DecUseError> {
        self.assert_item_status_in(&[expected])
    }

    pub(crate) fn assert_item_status_in(self: DockerEngineHttpResponse, expected: &[StatusCode]) -> Result<DockerEngineHttpResponse, DecUseError> {
        if expected.contains(&self.status) {
            Ok(self)
        }
        else {
            Err(self.parse_other_item_response())
        }
    }

    pub(crate) fn assert_list_status(self: DockerEngineHttpResponse, expected: StatusCode) -> Result<DockerEngineHttpResponse, DecUseError> {
        if self.status == expected {
            Ok(self)
        }
        else {
            Err(self.parse_other_list_response())
        }
    }

    pub(crate) fn assert_unit_status(self: DockerEngineHttpResponse, expected: StatusCode) -> Result<(), DecUseError> {
        self.assert_unit_status_in(&[expected])
    }

    pub(crate) fn assert_unit_status_in(self: DockerEngineHttpResponse, expected: &[StatusCode]) -> Result<(), DecUseError> {
        self.assert_item_status_in(expected)?;

        Ok(())
    }

    fn assume_utf8(&self) -> Result<String, DockerEngineResponseNotUtf8> {
        // With the exception of exec output, and file copies, all responses are application/json,
        // which has a default encoding of UTF-8 according to RFC4627.
        // https://www.ietf.org/rfc/rfc4627.txt
        String::from_utf8(self.body.to_vec())
            .map_err(|e|
                DockerEngineResponseNotUtf8 {
                    status: self.status,
                    content_type: self.content_type.clone(),
                    error: e
                }
            )
    }

    pub(crate) fn assert_content_type(self, expected: &str) -> Result<Self, DecUseError> {
        if self.content_type == Some(expected.to_string()) {
            Ok(self)
        }
        else {
            Err(DecUseError::UnexpectedResponseContentType {
                expected: expected.to_string(),
                actual: self.content_type
            })
        }
    }

    pub fn assume_content_type(self, expected: &str) -> Result<Self, DecUseError> {
        if self.content_type.is_none() {
            Ok(self)
        }
        else {
            self.assert_content_type(expected)
        }
    }

    fn assert_json_text(self) -> Result<String, DecUseError> {
        self
            .assert_content_type(content_type::JSON)?
            .assume_utf8()
            .map_err(DecUseError::from_not_utf8)
    }

    pub(crate) fn parse_stream<A: DeserializeOwned>(self) -> Result<Vec<A>, DecUseError> {
        let status = self.status;
        let request_uri = self.request_uri.clone();
        let body = self.assert_json_text()?;
        let parser = Deserializer::from_str(&body).into_iter::<A>();

        let mut result: Vec<A> = Vec::new();

        for parse_result in parser {
            let parsed = parse_result
                .map_err(|e| Self::parsing_error(request_uri.clone(), status, body.clone(), e))?;

            result.push(parsed)
        }

        Ok(result)
    }

    pub(crate) fn parse<A: DeserializeOwned>(self) -> Result<A, DecUseError> {
        let status = self.status;
        let request_uri = self.request_uri.clone();
        let body = self.assert_json_text()?;
        let parse_result = serde_json::from_str(&body);

        parse_result
            .map_err(|e| Self::parsing_error(request_uri, status, body, e))
    }

    fn parsing_error(request_uri: String, status: StatusCode, body: String, e: serde_json::Error) -> DecUseError {
        debug!(
            "Failed to parse {} received from {}: {}\n{}",
            content_type::JSON,
            request_uri,
            e,
            body
        );

        DecUseError::UnparseableJsonResponse {
            status,
            text: body,
            parse_error: e
        }
    }

    /// Parse a response where either:
    /// a) the URL asserts that something exists, such as a container or image, at its path, or
    /// b) the URL is for creating a new item (possibly a sub item of a parent item)
    ///
    /// If a 404 Not Found is returned, its most likely because the item (e.g. container or image)
    /// is not present. For a creation URL, its possible the API does not exist at that path either,
    /// but for now we do not distinguish that. It is not known if the Docker Engine will return
    /// a 404 Not Found error if we have the right URL, but a dependency of what we are creating
    /// (such as an existing network required by a new container) does not exist.
    fn parse_other_item_response(self) -> DecUseError {
        let parse = move || -> Result<DecUseError, DecUseError> {
            Ok(match self.status {
                StatusCode::NOT_FOUND => {
                    let parsed: ErrorResponse = self.parse()?;

                    DecUseError::NotFound {
                        message: parsed.message
                    }
                },

                StatusCode::NOT_IMPLEMENTED =>
                    DecUseError::ApiNotImplemented { uri: self.request_uri },

                _ => self.unexpected_status()
            })
        };

        converge(parse())
    }

    /// Parse a response where the URL only asserts that a list-based API exists its path.
    ///
    /// If a 404 Not Found is returned, its most likely because a Docker Engine does not exist
    /// at the base URL the client was provided.
    pub(crate) fn parse_other_list_response(self) -> DecUseError {
        let parse = move || -> Result<DecUseError, DecUseError> {
            Ok(match self.status {
                StatusCode::NOT_FOUND =>
                    DecUseError::ApiNotFound { uri: self.request_uri },

                StatusCode::NOT_IMPLEMENTED =>
                    DecUseError::ApiNotImplemented { uri: self.request_uri },

                _ => self.unexpected_status()
            })
        };

        converge(parse())
    }

    /// Syntax sugar for calling a custom parser after asserting a status code.
    ///
    /// Prevents creating an intermediate variable at the call site of the same
    /// type as the original.
    pub(crate) fn parse_with<A, P>(self, parser: P) -> Result<A, DecUseError>
    where
        P: FnOnce(Self) -> Result<A, DecUseError> {

        parser(self)
    }

    fn unexpected_status(self) -> DecUseError {
        let status = self.status;
        let parse_result: Result<ErrorResponse, DecUseError> = self.parse();

        match parse_result {
            Err(e) => e,
            Ok(parsed) =>
                DecUseError::Rejected {
                    status,
                    message: parsed.message
                }
        }
    }

}

#[derive(Clone, Debug)]
pub struct DockerEngineResponseNotUtf8 {
    pub status: StatusCode,
    pub content_type: Option<String>,
    pub error: FromUtf8Error
}

#[cfg(test)]
mod test_der {
    use http::StatusCode;
    use hyper::body::Bytes;

    use super::DockerEngineHttpResponse;

    fn arbitrary() -> DockerEngineHttpResponse {
        DockerEngineHttpResponse {
            request_uri: "foo".into(),
            status: StatusCode::from_u16(123).unwrap(),
            content_type: Some("arbitrary".into()),
            body: Bytes::from(vec![123])
        }
    }

    mod assert_item_status {
        use http::StatusCode;
        use hyper::body::Bytes;
        use crate::errors::DecUseError;
        use crate::imp::content_type::JSON;
        use crate::imp::http_proxy::DockerEngineHttpResponse;

        #[test]
        fn fails_when_item_not_found() {
            let response = DockerEngineHttpResponse {
                content_type: Some(JSON.into()),
                status: StatusCode::NOT_FOUND,
                body: Bytes::from(&b"{ \"message\": \"missing\" }"[..]),
                ..super::arbitrary()
            };

            let actual = response.assert_item_status(StatusCode::OK)
                .unwrap_err();

            if let DecUseError::NotFound { message } = actual {
                assert_eq!("missing", message);
            }
            else {
                panic!("Unexpected error: {}", actual);
            }
        }

        #[test]
        fn fails_and_parses_docker_json_error_when_different() {
            let response = DockerEngineHttpResponse {
                content_type: Some(JSON.into()),
                status: StatusCode::CREATED,
                body: Bytes::from(&b"{ \"message\": \"boom\" }"[..]),
                ..super::arbitrary()
            };

            let actual = response.assert_item_status(StatusCode::ACCEPTED)
                .unwrap_err();

            if let DecUseError::Rejected { status, message } = actual {
                assert_eq!(StatusCode::CREATED, status);
                assert_eq!("boom", message);
            }
            else {
                panic!("Unexpected error: {}", actual);
            }
        }

        #[test]
        fn passes_when_equal() {
            let response = DockerEngineHttpResponse {
                status: StatusCode::NOT_MODIFIED,
                ..super::arbitrary()
            };

            response.assert_item_status(StatusCode::NOT_MODIFIED)
                .unwrap();
        }
    }

    mod assert_item_status_in {
        use http::StatusCode;
        use hyper::body::Bytes;
        use crate::errors::DecUseError;
        use crate::imp::content_type::JSON;
        use crate::imp::http_proxy::DockerEngineHttpResponse;

        #[test]
        fn fails_and_parses_docker_json_error_when_no_match() {
            let response = DockerEngineHttpResponse {
                content_type: Some(JSON.into()),
                status: StatusCode::CREATED,
                body: Bytes::from(&b"{ \"message\": \"boom\" }"[..]),
                ..super::arbitrary()
            };

            let actual = response.assert_item_status_in(&[StatusCode::OK, StatusCode::ACCEPTED])
                .unwrap_err();

            if let DecUseError::Rejected { status, message } = actual {
                assert_eq!(StatusCode::CREATED, status);
                assert_eq!("boom", message);
            }
            else {
                panic!("Unexpected error: {}", actual);
            }
        }

        #[test]
        fn passes_when_matched() {
            let response = DockerEngineHttpResponse {
                status: StatusCode::NOT_MODIFIED,
                ..super::arbitrary()
            };

            response.assert_item_status_in(&[StatusCode::CREATED, StatusCode::NOT_MODIFIED])
                .unwrap();
        }
    }

    mod assert_list_status {
        use http::StatusCode;
        use crate::errors::DecUseError;
        use crate::imp::http_proxy::DockerEngineHttpResponse;

        #[test]
        fn fails_when_api_not_found() {
            let response = DockerEngineHttpResponse {
                request_uri: "some-uri".into(),
                content_type: None,
                status: StatusCode::NOT_FOUND,
                body: Default::default(),
                ..super::arbitrary()
            };

            let actual = response.assert_list_status(StatusCode::OK)
                .unwrap_err();

            if let DecUseError::ApiNotFound { uri } = actual {
                assert_eq!("some-uri", uri);
            }
            else {
                panic!("Unexpected error: {}", actual);
            }
        }

    }

    mod assume_utf8 {
        use hyper::body::Bytes;

        use super::super::DockerEngineHttpResponse;

        #[test]
        fn valid_utf8() {
            let response = DockerEngineHttpResponse {
                body: Bytes::from(vec![65]),
                ..super::arbitrary()
            };

            let actual = response.assume_utf8()
                .unwrap();

            assert_eq!("A", actual);
        }

        #[test]
        fn invalid_utf8() {
            let response = DockerEngineHttpResponse {
                body: Bytes::from(vec![0xc3, 0x28]),
                ..super::arbitrary()
            };

            let actual = response.assume_utf8()
                .unwrap_err();

            assert_eq!(123, actual.status.as_u16());
            assert_eq!(Some("arbitrary".to_string()), actual.content_type);
            assert_eq!("invalid utf-8 sequence of 1 bytes from index 0".to_string(), format!("{}", actual.error));
        }
    }

    mod assert_content_type {
        use crate::errors::DecUseError;
        use super::super::DockerEngineHttpResponse;

        #[test]
        fn err_when_none() {
            let response = DockerEngineHttpResponse {
                content_type: None,
                ..super::arbitrary()
            };

            let result = response.assert_content_type("foo")
                .unwrap_err();

            if let DecUseError::UnexpectedResponseContentType { expected, actual } = result {
                assert_eq!("foo", expected);
                assert_eq!(None, actual);
            }
            else {
                panic!("Unexpected result: {}", result)
            }
        }

        #[test]
        fn ok_when_match() {
            let response = DockerEngineHttpResponse {
                content_type: Some("bar".to_string()),
                ..super::arbitrary()
            };

            response.assert_content_type("bar")
                .unwrap();
        }

        #[test]
        fn err_when_different() {
            let response = DockerEngineHttpResponse {
                content_type: Some("qux".to_string()),
                ..super::arbitrary()
            };

            let result= response.assert_content_type("baz")
                .unwrap_err();

            if let DecUseError::UnexpectedResponseContentType { expected, actual } = result {
                assert_eq!("baz", expected);
                assert_eq!(Some("qux".to_string()), actual);
            }
            else {
                panic!("Unexpected result: {}", result)
            }
        }
    }

    mod assume_content_type {
        use crate::errors::DecUseError;
        use super::super::DockerEngineHttpResponse;

        #[test]
        fn ok_when_none() {
            let response = DockerEngineHttpResponse {
                content_type: None,
                ..super::arbitrary()
            };

            response.assume_content_type("foo")
                .unwrap();
        }

        #[test]
        fn ok_when_match() {
            let response = DockerEngineHttpResponse {
                content_type: Some("bar".to_string()),
                ..super::arbitrary()
            };

            response.assume_content_type("bar")
                .unwrap();
        }

        #[test]
        fn err_when_different() {
            let response = DockerEngineHttpResponse {
                content_type: Some("qux".to_string()),
                ..super::arbitrary()
            };

            let result= response.assume_content_type("baz")
                .unwrap_err();

            if let DecUseError::UnexpectedResponseContentType { expected, actual } = result {
                assert_eq!("baz", expected);
                assert_eq!(Some("qux".to_string()), actual);
            }
            else {
                panic!("Unexpected result: {}", result)
            }
        }
    }

    mod parse_other_item_response {
        use http::StatusCode;
        use crate::errors::DecUseError;
        use crate::imp::http_proxy::DockerEngineHttpResponse;

        #[test]
        fn maps_status_to_error_when_api_not_implemented() {
            let response = DockerEngineHttpResponse {
                request_uri: "bar".into(),
                status: StatusCode::NOT_IMPLEMENTED,
                content_type: Some("foo".into()),
                body: Default::default()
            };

            let actual = response.parse_other_item_response();

            if let DecUseError::ApiNotImplemented { uri} = actual {
                assert_eq!("bar", uri);
            }
            else {
                panic!("Unexpected result: {}", actual);
            }
        }
    }

    mod parse_other_list_response {
        use http::StatusCode;
        use crate::errors::DecUseError;
        use super::super::DockerEngineHttpResponse;

        #[test]
        fn maps_status_to_error_when_api_not_found() {
            let response = DockerEngineHttpResponse {
                request_uri: "bar".into(),
                status: StatusCode::NOT_FOUND,
                content_type: Some("foo".into()),
                body: Default::default()
            };

            let actual = response.parse_other_list_response();

            if let DecUseError::ApiNotFound { uri} = actual {
                assert_eq!("bar", uri);
            }
            else {
                panic!("Unexpected result: {}", actual);
            }
        }

        #[test]
        fn maps_status_to_error_when_api_not_implemented() {
            let response = DockerEngineHttpResponse {
                request_uri: "bar".into(),
                status: StatusCode::NOT_IMPLEMENTED,
                content_type: Some("foo".into()),
                body: Default::default()
            };

            let actual = response.parse_other_list_response();

            if let DecUseError::ApiNotImplemented { uri} = actual {
                assert_eq!("bar", uri);
            }
            else {
                panic!("Unexpected result: {}", actual);
            }
        }
    }

}