Skip to main content

openstack_sdk_identity/v3/policy/
set.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//! Updates a policy.
19//!
20//! Relationship:
21//! `https://docs.openstack.org/api/openstack-identity/3/rel/policy`
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::borrow::Cow;
30use std::collections::BTreeMap;
31
32#[derive(Builder, Debug, Clone)]
33#[builder(setter(strip_option))]
34pub struct Request<'a> {
35    /// policy_id parameter for /v3/policies/{policy_id} API
36    #[builder(default, setter(into))]
37    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 Policy.
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::PATCH
95    }
96
97    fn endpoint(&self) -> Cow<'static, str> {
98        format!("policies/{id}", id = self.id.as_ref(),).into()
99    }
100
101    fn parameters(&self) -> QueryParams<'_> {
102        QueryParams::default()
103    }
104
105    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
106        let mut params = JsonBodyParams::default();
107
108        for (key, val) in &self._properties {
109            params.push(key.clone(), val.clone());
110        }
111
112        params.into_body()
113    }
114
115    fn service_type(&self) -> ServiceType {
116        ServiceType::Identity
117    }
118
119    fn response_key(&self) -> Option<Cow<'static, str>> {
120        None
121    }
122
123    /// Returns headers to be set into the request
124    fn request_headers(&self) -> Option<&HeaderMap> {
125        self._headers.as_ref()
126    }
127
128    /// Returns required API version
129    fn api_version(&self) -> Option<ApiVersion> {
130        Some(ApiVersion::new(3, 0))
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137    use http::{HeaderName, HeaderValue};
138    use httpmock::MockServer;
139    #[cfg(feature = "sync")]
140    use openstack_sdk_core::api::Query;
141    use openstack_sdk_core::test::client::FakeOpenStackClient;
142    use openstack_sdk_core::types::ServiceType;
143    use serde_json::json;
144
145    #[test]
146    fn test_service_type() {
147        assert_eq!(
148            Request::builder().build().unwrap().service_type(),
149            ServiceType::Identity
150        );
151    }
152
153    #[test]
154    fn test_response_key() {
155        assert!(Request::builder().build().unwrap().response_key().is_none())
156    }
157
158    #[cfg(feature = "sync")]
159    #[test]
160    fn endpoint() {
161        let server = MockServer::start();
162        let client = FakeOpenStackClient::new(server.base_url());
163        let mock = server.mock(|when, then| {
164            when.method(httpmock::Method::PATCH)
165                .path(format!("/policies/{id}", id = "id",));
166
167            then.status(200)
168                .header("content-type", "application/json")
169                .json_body(json!({ "dummy": {} }));
170        });
171
172        let endpoint = Request::builder().id("id").build().unwrap();
173        let _: serde_json::Value = endpoint.query(&client).unwrap();
174        mock.assert();
175    }
176
177    #[cfg(feature = "sync")]
178    #[test]
179    fn endpoint_headers() {
180        let server = MockServer::start();
181        let client = FakeOpenStackClient::new(server.base_url());
182        let mock = server.mock(|when, then| {
183            when.method(httpmock::Method::PATCH)
184                .path(format!("/policies/{id}", id = "id",))
185                .header("foo", "bar")
186                .header("not_foo", "not_bar");
187            then.status(200)
188                .header("content-type", "application/json")
189                .json_body(json!({ "dummy": {} }));
190        });
191
192        let endpoint = Request::builder()
193            .id("id")
194            .headers(
195                [(
196                    Some(HeaderName::from_static("foo")),
197                    HeaderValue::from_static("bar"),
198                )]
199                .into_iter(),
200            )
201            .header(
202                HeaderName::from_static("not_foo"),
203                HeaderValue::from_static("not_bar"),
204            )
205            .build()
206            .unwrap();
207        let _: serde_json::Value = endpoint.query(&client).unwrap();
208        mock.assert();
209    }
210}