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