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