openstack_sdk/api/compute/v2/hypervisor/
list.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Lists hypervisors.
19//!
20//! Policy defaults enable only users with the administrative role to perform
21//! this operation. Cloud providers can change these permissions through the
22//! `policy.json` file.
23//!
24//! Normal response codes: 200
25//!
26//! Error response codes: badRequest(400), unauthorized(401), forbidden(403)
27//!
28use derive_builder::Builder;
29use http::{HeaderMap, HeaderName, HeaderValue};
30
31use crate::api::rest_endpoint_prelude::*;
32
33use std::borrow::Cow;
34
35use crate::api::Pageable;
36#[derive(Builder, Debug, Clone)]
37#[builder(setter(strip_option))]
38pub struct Request<'a> {
39    #[builder(default, setter(into))]
40    hypervisor_hostname_pattern: Option<Cow<'a, str>>,
41
42    #[builder(default)]
43    limit: Option<u32>,
44
45    #[builder(default, setter(into))]
46    marker: Option<Cow<'a, str>>,
47
48    #[builder(default)]
49    with_servers: Option<bool>,
50
51    #[builder(setter(name = "_headers"), default, private)]
52    _headers: Option<HeaderMap>,
53}
54impl<'a> Request<'a> {
55    /// Create a builder for the endpoint.
56    pub fn builder() -> RequestBuilder<'a> {
57        RequestBuilder::default()
58    }
59}
60
61impl<'a> RequestBuilder<'a> {
62    /// Add a single header to the Hypervisor.
63    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
64    where
65        K: Into<HeaderName>,
66        V: Into<HeaderValue>,
67    {
68        self._headers
69            .get_or_insert(None)
70            .get_or_insert_with(HeaderMap::new)
71            .insert(header_name.into(), header_value.into());
72        self
73    }
74
75    /// Add multiple headers.
76    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
77    where
78        I: Iterator<Item = T>,
79        T: Into<(Option<HeaderName>, HeaderValue)>,
80    {
81        self._headers
82            .get_or_insert(None)
83            .get_or_insert_with(HeaderMap::new)
84            .extend(iter.map(Into::into));
85        self
86    }
87}
88
89impl RestEndpoint for Request<'_> {
90    fn method(&self) -> http::Method {
91        http::Method::GET
92    }
93
94    fn endpoint(&self) -> Cow<'static, str> {
95        "os-hypervisors".to_string().into()
96    }
97
98    fn parameters(&self) -> QueryParams<'_> {
99        let mut params = QueryParams::default();
100        params.push_opt(
101            "hypervisor_hostname_pattern",
102            self.hypervisor_hostname_pattern.as_ref(),
103        );
104        params.push_opt("limit", self.limit);
105        params.push_opt("marker", self.marker.as_ref());
106        params.push_opt("with_servers", self.with_servers);
107
108        params
109    }
110
111    fn service_type(&self) -> ServiceType {
112        ServiceType::Compute
113    }
114
115    fn response_key(&self) -> Option<Cow<'static, str>> {
116        Some("hypervisors".into())
117    }
118
119    /// Returns headers to be set into the request
120    fn request_headers(&self) -> Option<&HeaderMap> {
121        self._headers.as_ref()
122    }
123
124    /// Returns required API version
125    fn api_version(&self) -> Option<ApiVersion> {
126        Some(ApiVersion::new(2, 1))
127    }
128}
129impl Pageable for Request<'_> {}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    #[cfg(feature = "sync")]
135    use crate::api::Query;
136    use crate::test::client::FakeOpenStackClient;
137    use crate::types::ServiceType;
138    use http::{HeaderName, HeaderValue};
139    use httpmock::MockServer;
140    use serde_json::json;
141
142    #[test]
143    fn test_service_type() {
144        assert_eq!(
145            Request::builder().build().unwrap().service_type(),
146            ServiceType::Compute
147        );
148    }
149
150    #[test]
151    fn test_response_key() {
152        assert_eq!(
153            Request::builder().build().unwrap().response_key().unwrap(),
154            "hypervisors"
155        );
156    }
157
158    #[cfg(feature = "sync")]
159    #[test]
160    fn endpoint() {
161        let server = MockServer::start();
162        let client = FakeOpenStackClient::new(server.base_url());
163        let mock = server.mock(|when, then| {
164            when.method(httpmock::Method::GET)
165                .path("/os-hypervisors".to_string());
166
167            then.status(200)
168                .header("content-type", "application/json")
169                .json_body(json!({ "hypervisors": {} }));
170        });
171
172        let endpoint = Request::builder().build().unwrap();
173        let _: serde_json::Value = endpoint.query(&client).unwrap();
174        mock.assert();
175    }
176
177    #[cfg(feature = "sync")]
178    #[test]
179    fn endpoint_headers() {
180        let server = MockServer::start();
181        let client = FakeOpenStackClient::new(server.base_url());
182        let mock = server.mock(|when, then| {
183            when.method(httpmock::Method::GET)
184                .path("/os-hypervisors".to_string())
185                .header("foo", "bar")
186                .header("not_foo", "not_bar");
187            then.status(200)
188                .header("content-type", "application/json")
189                .json_body(json!({ "hypervisors": {} }));
190        });
191
192        let endpoint = Request::builder()
193            .headers(
194                [(
195                    Some(HeaderName::from_static("foo")),
196                    HeaderValue::from_static("bar"),
197                )]
198                .into_iter(),
199            )
200            .header(
201                HeaderName::from_static("not_foo"),
202                HeaderValue::from_static("not_bar"),
203            )
204            .build()
205            .unwrap();
206        let _: serde_json::Value = endpoint.query(&client).unwrap();
207        mock.assert();
208    }
209}