Skip to main content

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