Skip to main content

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