Skip to main content

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