openstack_sdk/api/compute/v2/server/share/
create_297.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//! Attach a share to an instance.
19//!
20//! Normal response codes: 201
21//!
22//! Error response codes: badRequest(400), forbidden(403), itemNotFound(404),
23//! conflict(409)
24//!
25use derive_builder::Builder;
26use http::{HeaderMap, HeaderName, HeaderValue};
27
28use crate::api::rest_endpoint_prelude::*;
29
30use serde::Deserialize;
31use serde::Serialize;
32use std::borrow::Cow;
33
34#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
35#[builder(setter(strip_option))]
36pub struct Share<'a> {
37    /// The UUID of the attached share.
38    #[serde()]
39    #[builder(setter(into))]
40    pub(crate) share_id: Cow<'a, str>,
41
42    /// The device tag to be used by users to mount the share within the
43    /// instance, if not provided then the share UUID will be used
44    /// automatically.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    #[builder(default, setter(into))]
47    pub(crate) tag: Option<Cow<'a, str>>,
48}
49
50#[derive(Builder, Debug, Clone)]
51#[builder(setter(strip_option))]
52pub struct Request<'a> {
53    #[builder(setter(into))]
54    pub(crate) share: Share<'a>,
55
56    /// server_id parameter for /v2.1/servers/{server_id}/shares/{id} API
57    #[builder(default, setter(into))]
58    server_id: Cow<'a, str>,
59
60    #[builder(setter(name = "_headers"), default, private)]
61    _headers: Option<HeaderMap>,
62}
63impl<'a> Request<'a> {
64    /// Create a builder for the endpoint.
65    pub fn builder() -> RequestBuilder<'a> {
66        RequestBuilder::default()
67    }
68}
69
70impl<'a> RequestBuilder<'a> {
71    /// Add a single header to the Share.
72    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
73    where
74        K: Into<HeaderName>,
75        V: Into<HeaderValue>,
76    {
77        self._headers
78            .get_or_insert(None)
79            .get_or_insert_with(HeaderMap::new)
80            .insert(header_name.into(), header_value.into());
81        self
82    }
83
84    /// Add multiple headers.
85    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
86    where
87        I: Iterator<Item = T>,
88        T: Into<(Option<HeaderName>, HeaderValue)>,
89    {
90        self._headers
91            .get_or_insert(None)
92            .get_or_insert_with(HeaderMap::new)
93            .extend(iter.map(Into::into));
94        self
95    }
96}
97
98impl RestEndpoint for Request<'_> {
99    fn method(&self) -> http::Method {
100        http::Method::POST
101    }
102
103    fn endpoint(&self) -> Cow<'static, str> {
104        format!(
105            "servers/{server_id}/shares",
106            server_id = self.server_id.as_ref(),
107        )
108        .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("share", serde_json::to_value(&self.share)?);
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("share".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, 97))
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                .share(ShareBuilder::default().share_id("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                .share(ShareBuilder::default().share_id("foo").build().unwrap())
170                .build()
171                .unwrap()
172                .response_key()
173                .unwrap(),
174            "share"
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::POST).path(format!(
185                "/servers/{server_id}/shares",
186                server_id = "server_id",
187            ));
188
189            then.status(200)
190                .header("content-type", "application/json")
191                .json_body(json!({ "share": {} }));
192        });
193
194        let endpoint = Request::builder()
195            .server_id("server_id")
196            .share(ShareBuilder::default().share_id("foo").build().unwrap())
197            .build()
198            .unwrap();
199        let _: serde_json::Value = endpoint.query(&client).unwrap();
200        mock.assert();
201    }
202
203    #[cfg(feature = "sync")]
204    #[test]
205    fn endpoint_headers() {
206        let server = MockServer::start();
207        let client = FakeOpenStackClient::new(server.base_url());
208        let mock = server.mock(|when, then| {
209            when.method(httpmock::Method::POST)
210                .path(format!(
211                    "/servers/{server_id}/shares",
212                    server_id = "server_id",
213                ))
214                .header("foo", "bar")
215                .header("not_foo", "not_bar");
216            then.status(200)
217                .header("content-type", "application/json")
218                .json_body(json!({ "share": {} }));
219        });
220
221        let endpoint = Request::builder()
222            .server_id("server_id")
223            .share(ShareBuilder::default().share_id("foo").build().unwrap())
224            .headers(
225                [(
226                    Some(HeaderName::from_static("foo")),
227                    HeaderValue::from_static("bar"),
228                )]
229                .into_iter(),
230            )
231            .header(
232                HeaderName::from_static("not_foo"),
233                HeaderValue::from_static("not_bar"),
234            )
235            .build()
236            .unwrap();
237        let _: serde_json::Value = endpoint.query(&client).unwrap();
238        mock.assert();
239    }
240}