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