Skip to main content

openstack_sdk_identity/v3/os_federation/identity_provider/protocol/
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 protocol for an IDP.
19//!
20//! PUT /OS-FEDERATION/identity_providers/{idp_id}/protocols/{protocol_id}
21//!
22use derive_builder::Builder;
23use http::{HeaderMap, HeaderName, HeaderValue};
24
25use openstack_sdk_core::api::rest_endpoint_prelude::*;
26
27use serde::Deserialize;
28use serde::Serialize;
29use std::borrow::Cow;
30
31#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
32#[builder(setter(strip_option))]
33pub struct Protocol<'a> {
34    #[serde()]
35    #[builder(setter(into))]
36    pub(crate) mapping_id: Cow<'a, str>,
37
38    #[serde(skip_serializing_if = "Option::is_none")]
39    #[builder(default, setter(into))]
40    pub(crate) remote_id_attribute: Option<Option<Cow<'a, str>>>,
41}
42
43#[derive(Builder, Debug, Clone)]
44#[builder(setter(strip_option))]
45pub struct Request<'a> {
46    #[builder(setter(into))]
47    pub(crate) protocol: Protocol<'a>,
48
49    /// protocol_id parameter for
50    /// /v3/OS-FEDERATION/identity_providers/{idp_id}/protocols/{protocol_id}
51    /// API
52    #[builder(default, setter(into))]
53    id: Cow<'a, str>,
54
55    /// idp_id parameter for
56    /// /v3/OS-FEDERATION/identity_providers/{idp_id}/protocols API
57    #[builder(default, setter(into))]
58    idp_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 Protocol.
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::PUT
101    }
102
103    fn endpoint(&self) -> Cow<'static, str> {
104        format!(
105            "OS-FEDERATION/identity_providers/{idp_id}/protocols/{id}",
106            idp_id = self.idp_id.as_ref(),
107            id = self.id.as_ref(),
108        )
109        .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        params.push("protocol", serde_json::to_value(&self.protocol)?);
120
121        params.into_body()
122    }
123
124    fn service_type(&self) -> ServiceType {
125        ServiceType::Identity
126    }
127
128    fn response_key(&self) -> Option<Cow<'static, str>> {
129        Some("protocol".into())
130    }
131
132    /// Returns headers to be set into the request
133    fn request_headers(&self) -> Option<&HeaderMap> {
134        self._headers.as_ref()
135    }
136
137    /// Returns required API version
138    fn api_version(&self) -> Option<ApiVersion> {
139        Some(ApiVersion::new(3, 0))
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use http::{HeaderName, HeaderValue};
147    use httpmock::MockServer;
148    #[cfg(feature = "sync")]
149    use openstack_sdk_core::api::Query;
150    use openstack_sdk_core::test::client::FakeOpenStackClient;
151    use openstack_sdk_core::types::ServiceType;
152    use serde_json::json;
153
154    #[test]
155    fn test_service_type() {
156        assert_eq!(
157            Request::builder()
158                .protocol(
159                    ProtocolBuilder::default()
160                        .mapping_id("foo")
161                        .build()
162                        .unwrap()
163                )
164                .build()
165                .unwrap()
166                .service_type(),
167            ServiceType::Identity
168        );
169    }
170
171    #[test]
172    fn test_response_key() {
173        assert_eq!(
174            Request::builder()
175                .protocol(
176                    ProtocolBuilder::default()
177                        .mapping_id("foo")
178                        .build()
179                        .unwrap()
180                )
181                .build()
182                .unwrap()
183                .response_key()
184                .unwrap(),
185            "protocol"
186        );
187    }
188
189    #[cfg(feature = "sync")]
190    #[test]
191    fn endpoint() {
192        let server = MockServer::start();
193        let client = FakeOpenStackClient::new(server.base_url());
194        let mock = server.mock(|when, then| {
195            when.method(httpmock::Method::PUT).path(format!(
196                "/OS-FEDERATION/identity_providers/{idp_id}/protocols/{id}",
197                idp_id = "idp_id",
198                id = "id",
199            ));
200
201            then.status(200)
202                .header("content-type", "application/json")
203                .json_body(json!({ "protocol": {} }));
204        });
205
206        let endpoint = Request::builder()
207            .idp_id("idp_id")
208            .id("id")
209            .protocol(
210                ProtocolBuilder::default()
211                    .mapping_id("foo")
212                    .build()
213                    .unwrap(),
214            )
215            .build()
216            .unwrap();
217        let _: serde_json::Value = endpoint.query(&client).unwrap();
218        mock.assert();
219    }
220
221    #[cfg(feature = "sync")]
222    #[test]
223    fn endpoint_headers() {
224        let server = MockServer::start();
225        let client = FakeOpenStackClient::new(server.base_url());
226        let mock = server.mock(|when, then| {
227            when.method(httpmock::Method::PUT)
228                .path(format!(
229                    "/OS-FEDERATION/identity_providers/{idp_id}/protocols/{id}",
230                    idp_id = "idp_id",
231                    id = "id",
232                ))
233                .header("foo", "bar")
234                .header("not_foo", "not_bar");
235            then.status(200)
236                .header("content-type", "application/json")
237                .json_body(json!({ "protocol": {} }));
238        });
239
240        let endpoint = Request::builder()
241            .idp_id("idp_id")
242            .id("id")
243            .protocol(
244                ProtocolBuilder::default()
245                    .mapping_id("foo")
246                    .build()
247                    .unwrap(),
248            )
249            .headers(
250                [(
251                    Some(HeaderName::from_static("foo")),
252                    HeaderValue::from_static("bar"),
253                )]
254                .into_iter(),
255            )
256            .header(
257                HeaderName::from_static("not_foo"),
258                HeaderValue::from_static("not_bar"),
259            )
260            .build()
261            .unwrap();
262        let _: serde_json::Value = endpoint.query(&client).unwrap();
263        mock.assert();
264    }
265}