openstack_sdk/api/compute/v2/aggregate/
add_host.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
18use derive_builder::Builder;
19use http::{HeaderMap, HeaderName, HeaderValue};
20
21use crate::api::rest_endpoint_prelude::*;
22
23use serde::Deserialize;
24use serde::Serialize;
25use std::borrow::Cow;
26
27#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
28#[builder(setter(strip_option))]
29pub struct AddHost<'a> {
30    #[serde()]
31    #[builder(setter(into))]
32    pub(crate) host: Cow<'a, str>,
33}
34
35#[derive(Builder, Debug, Clone)]
36#[builder(setter(strip_option))]
37pub struct Request<'a> {
38    #[builder(setter(into))]
39    pub(crate) add_host: AddHost<'a>,
40
41    /// id parameter for /v2.1/os-aggregates/{id}/action API
42    #[builder(default, setter(into))]
43    id: Cow<'a, str>,
44
45    #[builder(setter(name = "_headers"), default, private)]
46    _headers: Option<HeaderMap>,
47}
48impl<'a> Request<'a> {
49    /// Create a builder for the endpoint.
50    pub fn builder() -> RequestBuilder<'a> {
51        RequestBuilder::default()
52    }
53}
54
55impl RequestBuilder<'_> {
56    /// Add a single header to the Aggregate.
57    pub fn header(&mut self, header_name: &'static str, header_value: &'static str) -> &mut Self
58where {
59        self._headers
60            .get_or_insert(None)
61            .get_or_insert_with(HeaderMap::new)
62            .insert(header_name, HeaderValue::from_static(header_value));
63        self
64    }
65
66    /// Add multiple headers.
67    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
68    where
69        I: Iterator<Item = T>,
70        T: Into<(Option<HeaderName>, HeaderValue)>,
71    {
72        self._headers
73            .get_or_insert(None)
74            .get_or_insert_with(HeaderMap::new)
75            .extend(iter.map(Into::into));
76        self
77    }
78}
79
80impl RestEndpoint for Request<'_> {
81    fn method(&self) -> http::Method {
82        http::Method::POST
83    }
84
85    fn endpoint(&self) -> Cow<'static, str> {
86        format!("os-aggregates/{id}/action", id = self.id.as_ref(),).into()
87    }
88
89    fn parameters(&self) -> QueryParams {
90        QueryParams::default()
91    }
92
93    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
94        let mut params = JsonBodyParams::default();
95
96        params.push("add_host", serde_json::to_value(&self.add_host)?);
97
98        params.into_body()
99    }
100
101    fn service_type(&self) -> ServiceType {
102        ServiceType::Compute
103    }
104
105    fn response_key(&self) -> Option<Cow<'static, str>> {
106        Some("aggregate".into())
107    }
108
109    /// Returns headers to be set into the request
110    fn request_headers(&self) -> Option<&HeaderMap> {
111        self._headers.as_ref()
112    }
113
114    /// Returns required API version
115    fn api_version(&self) -> Option<ApiVersion> {
116        Some(ApiVersion::new(2, 1))
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    #[cfg(feature = "sync")]
124    use crate::api::Query;
125    use crate::test::client::FakeOpenStackClient;
126    use crate::types::ServiceType;
127    use http::{HeaderName, HeaderValue};
128    use httpmock::MockServer;
129    use serde_json::json;
130
131    #[test]
132    fn test_service_type() {
133        assert_eq!(
134            Request::builder()
135                .add_host(AddHostBuilder::default().host("foo").build().unwrap())
136                .build()
137                .unwrap()
138                .service_type(),
139            ServiceType::Compute
140        );
141    }
142
143    #[test]
144    fn test_response_key() {
145        assert_eq!(
146            Request::builder()
147                .add_host(AddHostBuilder::default().host("foo").build().unwrap())
148                .build()
149                .unwrap()
150                .response_key()
151                .unwrap(),
152            "aggregate"
153        );
154    }
155
156    #[cfg(feature = "sync")]
157    #[test]
158    fn endpoint() {
159        let server = MockServer::start();
160        let client = FakeOpenStackClient::new(server.base_url());
161        let mock = server.mock(|when, then| {
162            when.method(httpmock::Method::POST)
163                .path(format!("/os-aggregates/{id}/action", id = "id",));
164
165            then.status(200)
166                .header("content-type", "application/json")
167                .json_body(json!({ "aggregate": {} }));
168        });
169
170        let endpoint = Request::builder()
171            .id("id")
172            .add_host(AddHostBuilder::default().host("foo").build().unwrap())
173            .build()
174            .unwrap();
175        let _: serde_json::Value = endpoint.query(&client).unwrap();
176        mock.assert();
177    }
178
179    #[cfg(feature = "sync")]
180    #[test]
181    fn endpoint_headers() {
182        let server = MockServer::start();
183        let client = FakeOpenStackClient::new(server.base_url());
184        let mock = server.mock(|when, then| {
185            when.method(httpmock::Method::POST)
186                .path(format!("/os-aggregates/{id}/action", id = "id",))
187                .header("foo", "bar")
188                .header("not_foo", "not_bar");
189            then.status(200)
190                .header("content-type", "application/json")
191                .json_body(json!({ "aggregate": {} }));
192        });
193
194        let endpoint = Request::builder()
195            .id("id")
196            .add_host(AddHostBuilder::default().host("foo").build().unwrap())
197            .headers(
198                [(
199                    Some(HeaderName::from_static("foo")),
200                    HeaderValue::from_static("bar"),
201                )]
202                .into_iter(),
203            )
204            .header("not_foo", "not_bar")
205            .build()
206            .unwrap();
207        let _: serde_json::Value = endpoint.query(&client).unwrap();
208        mock.assert();
209    }
210}