Skip to main content

openstack_sdk_identity/v3/os_federation/service_provider/
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 a service provider.
19//!
20//! PUT /OS-FEDERATION/service_providers/{service_provider_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 ServiceProvider<'a> {
34    /// The URL to authenticate against
35    #[serde()]
36    #[builder(setter(into))]
37    pub(crate) auth_url: Cow<'a, str>,
38
39    /// The description of the service provider
40    #[serde(skip_serializing_if = "Option::is_none")]
41    #[builder(default, setter(into))]
42    pub(crate) description: Option<Option<Cow<'a, str>>>,
43
44    /// Whether the service provider is enabled or not
45    #[serde(skip_serializing_if = "Option::is_none")]
46    #[builder(default, setter(into))]
47    pub(crate) enabled: Option<bool>,
48
49    /// The prefix of the RelayState SAML attribute
50    #[serde(skip_serializing_if = "Option::is_none")]
51    #[builder(default, setter(into))]
52    pub(crate) relay_state_prefix: Option<Option<Cow<'a, str>>>,
53
54    /// The service provider's URL
55    #[serde()]
56    #[builder(setter(into))]
57    pub(crate) sp_url: Cow<'a, str>,
58}
59
60#[derive(Builder, Debug, Clone)]
61#[builder(setter(strip_option))]
62pub struct Request<'a> {
63    #[builder(setter(into))]
64    pub(crate) service_provider: ServiceProvider<'a>,
65
66    /// service_provider_id parameter for
67    /// /v3/OS-FEDERATION/service_providers/{service_provider_id} API
68    #[builder(default, setter(into))]
69    id: Cow<'a, str>,
70
71    #[builder(setter(name = "_headers"), default, private)]
72    _headers: Option<HeaderMap>,
73}
74impl<'a> Request<'a> {
75    /// Create a builder for the endpoint.
76    pub fn builder() -> RequestBuilder<'a> {
77        RequestBuilder::default()
78    }
79}
80
81impl<'a> RequestBuilder<'a> {
82    /// Add a single header to the Service_Provider.
83    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
84    where
85        K: Into<HeaderName>,
86        V: Into<HeaderValue>,
87    {
88        self._headers
89            .get_or_insert(None)
90            .get_or_insert_with(HeaderMap::new)
91            .insert(header_name.into(), header_value.into());
92        self
93    }
94
95    /// Add multiple headers.
96    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
97    where
98        I: Iterator<Item = T>,
99        T: Into<(Option<HeaderName>, HeaderValue)>,
100    {
101        self._headers
102            .get_or_insert(None)
103            .get_or_insert_with(HeaderMap::new)
104            .extend(iter.map(Into::into));
105        self
106    }
107}
108
109impl RestEndpoint for Request<'_> {
110    fn method(&self) -> http::Method {
111        http::Method::PUT
112    }
113
114    fn endpoint(&self) -> Cow<'static, str> {
115        format!(
116            "OS-FEDERATION/service_providers/{id}",
117            id = self.id.as_ref(),
118        )
119        .into()
120    }
121
122    fn parameters(&self) -> QueryParams<'_> {
123        QueryParams::default()
124    }
125
126    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
127        let mut params = JsonBodyParams::default();
128
129        params.push(
130            "service_provider",
131            serde_json::to_value(&self.service_provider)?,
132        );
133
134        params.into_body()
135    }
136
137    fn service_type(&self) -> ServiceType {
138        ServiceType::Identity
139    }
140
141    fn response_key(&self) -> Option<Cow<'static, str>> {
142        Some("service_provider".into())
143    }
144
145    /// Returns headers to be set into the request
146    fn request_headers(&self) -> Option<&HeaderMap> {
147        self._headers.as_ref()
148    }
149
150    /// Returns required API version
151    fn api_version(&self) -> Option<ApiVersion> {
152        Some(ApiVersion::new(3, 0))
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159    use http::{HeaderName, HeaderValue};
160    use httpmock::MockServer;
161    #[cfg(feature = "sync")]
162    use openstack_sdk_core::api::Query;
163    use openstack_sdk_core::test::client::FakeOpenStackClient;
164    use openstack_sdk_core::types::ServiceType;
165    use serde_json::json;
166
167    #[test]
168    fn test_service_type() {
169        assert_eq!(
170            Request::builder()
171                .service_provider(
172                    ServiceProviderBuilder::default()
173                        .auth_url("foo")
174                        .sp_url("foo")
175                        .build()
176                        .unwrap()
177                )
178                .build()
179                .unwrap()
180                .service_type(),
181            ServiceType::Identity
182        );
183    }
184
185    #[test]
186    fn test_response_key() {
187        assert_eq!(
188            Request::builder()
189                .service_provider(
190                    ServiceProviderBuilder::default()
191                        .auth_url("foo")
192                        .sp_url("foo")
193                        .build()
194                        .unwrap()
195                )
196                .build()
197                .unwrap()
198                .response_key()
199                .unwrap(),
200            "service_provider"
201        );
202    }
203
204    #[cfg(feature = "sync")]
205    #[test]
206    fn endpoint() {
207        let server = MockServer::start();
208        let client = FakeOpenStackClient::new(server.base_url());
209        let mock = server.mock(|when, then| {
210            when.method(httpmock::Method::PUT)
211                .path(format!("/OS-FEDERATION/service_providers/{id}", id = "id",));
212
213            then.status(200)
214                .header("content-type", "application/json")
215                .json_body(json!({ "service_provider": {} }));
216        });
217
218        let endpoint = Request::builder()
219            .id("id")
220            .service_provider(
221                ServiceProviderBuilder::default()
222                    .auth_url("foo")
223                    .sp_url("foo")
224                    .build()
225                    .unwrap(),
226            )
227            .build()
228            .unwrap();
229        let _: serde_json::Value = endpoint.query(&client).unwrap();
230        mock.assert();
231    }
232
233    #[cfg(feature = "sync")]
234    #[test]
235    fn endpoint_headers() {
236        let server = MockServer::start();
237        let client = FakeOpenStackClient::new(server.base_url());
238        let mock = server.mock(|when, then| {
239            when.method(httpmock::Method::PUT)
240                .path(format!("/OS-FEDERATION/service_providers/{id}", id = "id",))
241                .header("foo", "bar")
242                .header("not_foo", "not_bar");
243            then.status(200)
244                .header("content-type", "application/json")
245                .json_body(json!({ "service_provider": {} }));
246        });
247
248        let endpoint = Request::builder()
249            .id("id")
250            .service_provider(
251                ServiceProviderBuilder::default()
252                    .auth_url("foo")
253                    .sp_url("foo")
254                    .build()
255                    .unwrap(),
256            )
257            .headers(
258                [(
259                    Some(HeaderName::from_static("foo")),
260                    HeaderValue::from_static("bar"),
261                )]
262                .into_iter(),
263            )
264            .header(
265                HeaderName::from_static("not_foo"),
266                HeaderValue::from_static("not_bar"),
267            )
268            .build()
269            .unwrap();
270        let _: serde_json::Value = endpoint.query(&client).unwrap();
271        mock.assert();
272    }
273}