openstack_sdk/api/network/v2/address_scope/
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 an address scope.
19//!
20//! Normal response codes: 200
21//!
22//! Error response codes: 400, 401, 403, 404, 412
23//!
24use derive_builder::Builder;
25use http::{HeaderMap, HeaderName, HeaderValue};
26
27use crate::api::rest_endpoint_prelude::*;
28
29use serde::Deserialize;
30use serde::Serialize;
31use std::borrow::Cow;
32
33/// An `address scope` object.
34#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
35#[builder(setter(strip_option))]
36pub struct AddressScope<'a> {
37    /// Human-readable name of the resource. Default is an empty string.
38    #[serde(skip_serializing_if = "Option::is_none")]
39    #[builder(default, setter(into))]
40    pub(crate) name: Option<Cow<'a, str>>,
41
42    /// Indicates whether this resource is shared across all projects. By
43    /// default, only administrative users can change this value.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    #[builder(default, setter(into))]
46    pub(crate) shared: Option<bool>,
47}
48
49#[derive(Builder, Debug, Clone)]
50#[builder(setter(strip_option))]
51pub struct Request<'a> {
52    /// An `address scope` object.
53    #[builder(setter(into))]
54    pub(crate) address_scope: AddressScope<'a>,
55
56    /// id parameter for /v2.0/address-scopes/{id} API
57    #[builder(default, setter(into))]
58    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 Address_Scope.
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!("address-scopes/{id}", id = self.id.as_ref(),).into()
105    }
106
107    fn parameters(&self) -> QueryParams<'_> {
108        QueryParams::default()
109    }
110
111    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
112        let mut params = JsonBodyParams::default();
113
114        params.push("address_scope", serde_json::to_value(&self.address_scope)?);
115
116        params.into_body()
117    }
118
119    fn service_type(&self) -> ServiceType {
120        ServiceType::Network
121    }
122
123    fn response_key(&self) -> Option<Cow<'static, str>> {
124        Some("address_scope".into())
125    }
126
127    /// Returns headers to be set into the request
128    fn request_headers(&self) -> Option<&HeaderMap> {
129        self._headers.as_ref()
130    }
131
132    /// Returns required API version
133    fn api_version(&self) -> Option<ApiVersion> {
134        Some(ApiVersion::new(2, 0))
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    #[cfg(feature = "sync")]
142    use crate::api::Query;
143    use crate::test::client::FakeOpenStackClient;
144    use crate::types::ServiceType;
145    use http::{HeaderName, HeaderValue};
146    use httpmock::MockServer;
147    use serde_json::json;
148
149    #[test]
150    fn test_service_type() {
151        assert_eq!(
152            Request::builder()
153                .address_scope(AddressScopeBuilder::default().build().unwrap())
154                .build()
155                .unwrap()
156                .service_type(),
157            ServiceType::Network
158        );
159    }
160
161    #[test]
162    fn test_response_key() {
163        assert_eq!(
164            Request::builder()
165                .address_scope(AddressScopeBuilder::default().build().unwrap())
166                .build()
167                .unwrap()
168                .response_key()
169                .unwrap(),
170            "address_scope"
171        );
172    }
173
174    #[cfg(feature = "sync")]
175    #[test]
176    fn endpoint() {
177        let server = MockServer::start();
178        let client = FakeOpenStackClient::new(server.base_url());
179        let mock = server.mock(|when, then| {
180            when.method(httpmock::Method::PUT)
181                .path(format!("/address-scopes/{id}", id = "id",));
182
183            then.status(200)
184                .header("content-type", "application/json")
185                .json_body(json!({ "address_scope": {} }));
186        });
187
188        let endpoint = Request::builder()
189            .id("id")
190            .address_scope(AddressScopeBuilder::default().build().unwrap())
191            .build()
192            .unwrap();
193        let _: serde_json::Value = endpoint.query(&client).unwrap();
194        mock.assert();
195    }
196
197    #[cfg(feature = "sync")]
198    #[test]
199    fn endpoint_headers() {
200        let server = MockServer::start();
201        let client = FakeOpenStackClient::new(server.base_url());
202        let mock = server.mock(|when, then| {
203            when.method(httpmock::Method::PUT)
204                .path(format!("/address-scopes/{id}", id = "id",))
205                .header("foo", "bar")
206                .header("not_foo", "not_bar");
207            then.status(200)
208                .header("content-type", "application/json")
209                .json_body(json!({ "address_scope": {} }));
210        });
211
212        let endpoint = Request::builder()
213            .id("id")
214            .address_scope(AddressScopeBuilder::default().build().unwrap())
215            .headers(
216                [(
217                    Some(HeaderName::from_static("foo")),
218                    HeaderValue::from_static("bar"),
219                )]
220                .into_iter(),
221            )
222            .header(
223                HeaderName::from_static("not_foo"),
224                HeaderValue::from_static("not_bar"),
225            )
226            .build()
227            .unwrap();
228        let _: serde_json::Value = endpoint.query(&client).unwrap();
229        mock.assert();
230    }
231}