openstack_sdk/api/network/v2/qos/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 QoS policy.
19//!
20//! Creates a QoS policy by using the configuration that you define in the
21//! request object. A response object is returned. The object contains a unique
22//! ID.
23//!
24//! By the default policy configuration, if the caller is not an administrative
25//! user, this call returns the HTTP `Forbidden (403)` response code.
26//!
27//! Users with an administrative role can create policies on behalf of other
28//! projects by specifying a project ID that is different than their own.
29//!
30//! Normal response codes: 201
31//!
32//! Error response codes: 401, 403, 404, 409
33//!
34use derive_builder::Builder;
35use http::{HeaderMap, HeaderName, HeaderValue};
36
37use crate::api::rest_endpoint_prelude::*;
38
39use serde::Deserialize;
40use serde::Serialize;
41use std::borrow::Cow;
42
43/// A QoS `policy` object.
44#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
45#[builder(setter(strip_option))]
46pub struct Policy<'a> {
47    /// A human-readable description for the resource. Default is an empty
48    /// string.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    #[builder(default, setter(into))]
51    pub(crate) description: Option<Cow<'a, str>>,
52
53    /// If `true`, the QoS `policy` is the default policy.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    #[builder(default, setter(into))]
56    pub(crate) is_default: Option<bool>,
57
58    /// Human-readable name of the resource.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    #[builder(default, setter(into))]
61    pub(crate) name: Option<Cow<'a, str>>,
62
63    /// Set to `true` to share this policy with other projects. Default is
64    /// `false`.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    #[builder(default, setter(into))]
67    pub(crate) shared: Option<bool>,
68
69    /// The ID of the project that owns the resource. Only administrative and
70    /// users with advsvc role can specify a project ID other than their own.
71    /// You cannot change this value through authorization policies.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    #[builder(default, setter(into))]
74    pub(crate) tenant_id: Option<Cow<'a, str>>,
75}
76
77#[derive(Builder, Debug, Clone)]
78#[builder(setter(strip_option))]
79pub struct Request<'a> {
80    /// A QoS `policy` object.
81    #[builder(setter(into))]
82    pub(crate) policy: Policy<'a>,
83
84    #[builder(setter(name = "_headers"), default, private)]
85    _headers: Option<HeaderMap>,
86}
87impl<'a> Request<'a> {
88    /// Create a builder for the endpoint.
89    pub fn builder() -> RequestBuilder<'a> {
90        RequestBuilder::default()
91    }
92}
93
94impl<'a> RequestBuilder<'a> {
95    /// Add a single header to the Policy.
96    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
97    where
98        K: Into<HeaderName>,
99        V: Into<HeaderValue>,
100    {
101        self._headers
102            .get_or_insert(None)
103            .get_or_insert_with(HeaderMap::new)
104            .insert(header_name.into(), header_value.into());
105        self
106    }
107
108    /// Add multiple headers.
109    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
110    where
111        I: Iterator<Item = T>,
112        T: Into<(Option<HeaderName>, HeaderValue)>,
113    {
114        self._headers
115            .get_or_insert(None)
116            .get_or_insert_with(HeaderMap::new)
117            .extend(iter.map(Into::into));
118        self
119    }
120}
121
122impl RestEndpoint for Request<'_> {
123    fn method(&self) -> http::Method {
124        http::Method::POST
125    }
126
127    fn endpoint(&self) -> Cow<'static, str> {
128        "qos/policies".to_string().into()
129    }
130
131    fn parameters(&self) -> QueryParams<'_> {
132        QueryParams::default()
133    }
134
135    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
136        let mut params = JsonBodyParams::default();
137
138        params.push("policy", serde_json::to_value(&self.policy)?);
139
140        params.into_body()
141    }
142
143    fn service_type(&self) -> ServiceType {
144        ServiceType::Network
145    }
146
147    fn response_key(&self) -> Option<Cow<'static, str>> {
148        Some("policy".into())
149    }
150
151    /// Returns headers to be set into the request
152    fn request_headers(&self) -> Option<&HeaderMap> {
153        self._headers.as_ref()
154    }
155
156    /// Returns required API version
157    fn api_version(&self) -> Option<ApiVersion> {
158        Some(ApiVersion::new(2, 0))
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    #[cfg(feature = "sync")]
166    use crate::api::Query;
167    use crate::test::client::FakeOpenStackClient;
168    use crate::types::ServiceType;
169    use http::{HeaderName, HeaderValue};
170    use httpmock::MockServer;
171    use serde_json::json;
172
173    #[test]
174    fn test_service_type() {
175        assert_eq!(
176            Request::builder()
177                .policy(PolicyBuilder::default().build().unwrap())
178                .build()
179                .unwrap()
180                .service_type(),
181            ServiceType::Network
182        );
183    }
184
185    #[test]
186    fn test_response_key() {
187        assert_eq!(
188            Request::builder()
189                .policy(PolicyBuilder::default().build().unwrap())
190                .build()
191                .unwrap()
192                .response_key()
193                .unwrap(),
194            "policy"
195        );
196    }
197
198    #[cfg(feature = "sync")]
199    #[test]
200    fn endpoint() {
201        let server = MockServer::start();
202        let client = FakeOpenStackClient::new(server.base_url());
203        let mock = server.mock(|when, then| {
204            when.method(httpmock::Method::POST)
205                .path("/qos/policies".to_string());
206
207            then.status(200)
208                .header("content-type", "application/json")
209                .json_body(json!({ "policy": {} }));
210        });
211
212        let endpoint = Request::builder()
213            .policy(PolicyBuilder::default().build().unwrap())
214            .build()
215            .unwrap();
216        let _: serde_json::Value = endpoint.query(&client).unwrap();
217        mock.assert();
218    }
219
220    #[cfg(feature = "sync")]
221    #[test]
222    fn endpoint_headers() {
223        let server = MockServer::start();
224        let client = FakeOpenStackClient::new(server.base_url());
225        let mock = server.mock(|when, then| {
226            when.method(httpmock::Method::POST)
227                .path("/qos/policies".to_string())
228                .header("foo", "bar")
229                .header("not_foo", "not_bar");
230            then.status(200)
231                .header("content-type", "application/json")
232                .json_body(json!({ "policy": {} }));
233        });
234
235        let endpoint = Request::builder()
236            .policy(PolicyBuilder::default().build().unwrap())
237            .headers(
238                [(
239                    Some(HeaderName::from_static("foo")),
240                    HeaderValue::from_static("bar"),
241                )]
242                .into_iter(),
243            )
244            .header(
245                HeaderName::from_static("not_foo"),
246                HeaderValue::from_static("not_bar"),
247            )
248            .build()
249            .unwrap();
250        let _: serde_json::Value = endpoint.query(&client).unwrap();
251        mock.assert();
252    }
253}