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