openstack_sdk/api/compute/v2/server/
change_password.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 serde::Deserialize;
24use serde::Serialize;
25use std::borrow::Cow;
26
27/// The action to change an administrative password of the server.
28#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
29#[builder(setter(strip_option))]
30pub struct ChangePassword<'a> {
31    /// The administrative password for the server.
32    #[serde(rename = "adminPass")]
33    #[builder(setter(into))]
34    pub(crate) admin_pass: Cow<'a, str>,
35}
36
37#[derive(Builder, Debug, Clone)]
38#[builder(setter(strip_option))]
39pub struct Request<'a> {
40    /// The action to change an administrative password of the server.
41    #[builder(setter(into))]
42    pub(crate) change_password: ChangePassword<'a>,
43
44    /// id parameter for /v2.1/servers/{id}/action API
45    #[builder(default, setter(into))]
46    id: Cow<'a, str>,
47
48    #[builder(setter(name = "_headers"), default, private)]
49    _headers: Option<HeaderMap>,
50}
51impl<'a> Request<'a> {
52    /// Create a builder for the endpoint.
53    pub fn builder() -> RequestBuilder<'a> {
54        RequestBuilder::default()
55    }
56}
57
58impl<'a> RequestBuilder<'a> {
59    /// Add a single header to the Server.
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::POST
89    }
90
91    fn endpoint(&self) -> Cow<'static, str> {
92        format!("servers/{id}/action", 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(
103            "changePassword",
104            serde_json::to_value(&self.change_password)?,
105        );
106
107        params.into_body()
108    }
109
110    fn service_type(&self) -> ServiceType {
111        ServiceType::Compute
112    }
113
114    fn response_key(&self) -> Option<Cow<'static, str>> {
115        None
116    }
117
118    /// Returns headers to be set into the request
119    fn request_headers(&self) -> Option<&HeaderMap> {
120        self._headers.as_ref()
121    }
122
123    /// Returns required API version
124    fn api_version(&self) -> Option<ApiVersion> {
125        Some(ApiVersion::new(2, 1))
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    #[cfg(feature = "sync")]
133    use crate::api::Query;
134    use crate::test::client::FakeOpenStackClient;
135    use crate::types::ServiceType;
136    use http::{HeaderName, HeaderValue};
137    use httpmock::MockServer;
138    use serde_json::json;
139
140    #[test]
141    fn test_service_type() {
142        assert_eq!(
143            Request::builder()
144                .change_password(
145                    ChangePasswordBuilder::default()
146                        .admin_pass("foo")
147                        .build()
148                        .unwrap()
149                )
150                .build()
151                .unwrap()
152                .service_type(),
153            ServiceType::Compute
154        );
155    }
156
157    #[test]
158    fn test_response_key() {
159        assert!(Request::builder()
160            .change_password(
161                ChangePasswordBuilder::default()
162                    .admin_pass("foo")
163                    .build()
164                    .unwrap()
165            )
166            .build()
167            .unwrap()
168            .response_key()
169            .is_none())
170    }
171
172    #[cfg(feature = "sync")]
173    #[test]
174    fn endpoint() {
175        let server = MockServer::start();
176        let client = FakeOpenStackClient::new(server.base_url());
177        let mock = server.mock(|when, then| {
178            when.method(httpmock::Method::POST)
179                .path(format!("/servers/{id}/action", id = "id",));
180
181            then.status(200)
182                .header("content-type", "application/json")
183                .json_body(json!({ "dummy": {} }));
184        });
185
186        let endpoint = Request::builder()
187            .id("id")
188            .change_password(
189                ChangePasswordBuilder::default()
190                    .admin_pass("foo")
191                    .build()
192                    .unwrap(),
193            )
194            .build()
195            .unwrap();
196        let _: serde_json::Value = endpoint.query(&client).unwrap();
197        mock.assert();
198    }
199
200    #[cfg(feature = "sync")]
201    #[test]
202    fn endpoint_headers() {
203        let server = MockServer::start();
204        let client = FakeOpenStackClient::new(server.base_url());
205        let mock = server.mock(|when, then| {
206            when.method(httpmock::Method::POST)
207                .path(format!("/servers/{id}/action", id = "id",))
208                .header("foo", "bar")
209                .header("not_foo", "not_bar");
210            then.status(200)
211                .header("content-type", "application/json")
212                .json_body(json!({ "dummy": {} }));
213        });
214
215        let endpoint = Request::builder()
216            .id("id")
217            .change_password(
218                ChangePasswordBuilder::default()
219                    .admin_pass("foo")
220                    .build()
221                    .unwrap(),
222            )
223            .headers(
224                [(
225                    Some(HeaderName::from_static("foo")),
226                    HeaderValue::from_static("bar"),
227                )]
228                .into_iter(),
229            )
230            .header(
231                HeaderName::from_static("not_foo"),
232                HeaderValue::from_static("not_bar"),
233            )
234            .build()
235            .unwrap();
236        let _: serde_json::Value = endpoint.query(&client).unwrap();
237        mock.assert();
238    }
239}