From 391a8dabefdad1a96122d7c378cabc1d760f85cd Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Thu, 19 Oct 2023 14:43:43 -0400 Subject: [PATCH 01/10] make all function calls part of api client structs, also introduce with_http_info pattern for less verbose function calls --- .generator/src/generator/openapi.py | 2 +- .generator/src/generator/templates/api.j2 | 483 +++---- .pre-commit-config.yaml | 10 +- generate.sh | 3 +- src/datadogV2/api/api_fastly_integration.rs | 1254 +++++++++++-------- 5 files changed, 984 insertions(+), 768 deletions(-) diff --git a/.generator/src/generator/openapi.py b/.generator/src/generator/openapi.py index 023d450f2..276f51be4 100644 --- a/.generator/src/generator/openapi.py +++ b/.generator/src/generator/openapi.py @@ -306,7 +306,7 @@ def return_type(operation, version): for response in operation.get("responses", {}).values(): for content in response.get("content", {}).values(): if "schema" in content: - return type_to_rust(content["schema"], version=version) + return type_to_rust(content["schema"], version=version, render_option=False) return diff --git a/.generator/src/generator/templates/api.j2 b/.generator/src/generator/templates/api.j2 index 3034ff091..ee70c85ba 100644 --- a/.generator/src/generator/templates/api.j2 +++ b/.generator/src/generator/templates/api.j2 @@ -47,245 +47,282 @@ pub enum {{operation.operationId}}Error { } {% endfor %} -{% for path, method, operation in operations|sort(attribute="2.operationId", case_sensitive=True) %} -{%- set httpMethod = method.upper() %} -{%- set returnType = operation|return_type(version) %} -{% if operation.description is defined %} -{{ operation.description | block_comment }} -{%- endif %} -pub async fn {{operation.operationId | snake_case}}(configuration: &configuration::Configuration{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { - let local_configuration = configuration; +{%- set structName = name|camel_case +"API" %} +pub struct {{ structName }} { + config: configuration::Configuration, +} - // unbox the parameters - {%- for name, parameter in operation|parameters %} - let {{name|variable_name}} = params.{{name|variable_name}}; - {%- endfor %} +impl Default for {{ structName }} { + fn default() -> Self { + Self { + config: configuration::Configuration::new(), + } + } +} - let local_client = &local_configuration.client; +impl {{ structName }} { + pub fn new() -> Self { + Self::default() + } + pub fn with_config(config: configuration::Configuration) -> Self { + Self { config } + } - let local_uri_str = format!( - "{}{{path}}", - local_configuration.base_path - {%- for name, parameter in operation|parameters if parameter.in == "path" %}, {{ name|variable_name }}= - {%- if parameter.schema.type == "string" %} - urlencode({{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %}) - {%- else %} - {{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %} - {%- endif %} - {% endfor %}); - let mut local_req_builder = local_client.request(reqwest::Method::{{ httpMethod }}, local_uri_str.as_str()); -{# - {{#queryParams}} - {{#required}} - {{#isArray}} - local_req_builder = match "{{collectionFormat}}" { - "multi" => local_req_builder.query(&{{{paramName}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), - _ => local_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), - }; - {{/isArray}} - {{^isArray}} - {{^isNullable}} - local_req_builder = local_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.to_string())]); - {{/isNullable}} - {{#isNullable}} - {{#isDeepObject}} - if let Some(ref local_str) = {{{paramName}}} { - let params = crate::apis::parse_deep_object("{{{baseName}}}", local_str); - local_req_builder = local_req_builder.query(¶ms); - }; - {{/isDeepObject}} - {{^isDeepObject}} - if let Some(ref local_str) = {{{paramName}}} { - local_req_builder = local_req_builder.query(&[("{{{baseName}}}", &local_str.to_string())]); - }; - {{/isDeepObject}} - {{/isNullable}} - {{/isArray}} - {{/required}} - {{^required}} - if let Some(ref local_str) = {{{paramName}}} { + {% for path, method, operation in operations|sort(attribute="2.operationId", case_sensitive=True) %} + {%- set httpMethod = method.upper() %} + {%- set returnType = operation|return_type(version) %} + {% if operation.description is defined %} + {{ operation.description | block_comment }} + {%- endif %} + pub async fn {{operation.operationId | snake_case}}(self{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { + match self.{{operation.operationId | snake_case}}_with_http_info({% for name, parameter in operation|parameters %}{% if loop.first %}params{% endif %}{% endfor %}).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } + } + + {% if operation.description is defined %} + {{ operation.description | block_comment }} + {%- endif %} + pub async fn {{operation.operationId | snake_case}}_with_http_info(self{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { + let local_configuration = &self.config; + + // unbox the parameters + {%- for name, parameter in operation|parameters %} + let {{name|variable_name}} = params.{{name|variable_name}}; + {%- endfor %} + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}{{path}}", + local_configuration.base_path + {%- for name, parameter in operation|parameters if parameter.in == "path" %}, {{ name|variable_name }}= + {%- if parameter.schema.type == "string" %} + urlencode({{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %}) + {%- else %} + {{ name|variable_name }}{% if not parameter.required %}.unwrap(){% elif parameter.schema.nullable %}.unwrap(){% endif %}{% if parameter.schema.type == "array" %}.join(",").as_ref(){% endif %} + {%- endif %} + {% endfor %}); + let mut local_req_builder = local_client.request(reqwest::Method::{{ httpMethod }}, local_uri_str.as_str()); + {# + {{#queryParams}} + {{#required}} {{#isArray}} local_req_builder = match "{{collectionFormat}}" { - "multi" => local_req_builder.query(&local_str.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), - _ => local_req_builder.query(&[("{{{baseName}}}", &local_str.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + "multi" => local_req_builder.query(&{{{paramName}}}.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => local_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), }; {{/isArray}} {{^isArray}} + {{^isNullable}} + local_req_builder = local_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}.to_string())]); + {{/isNullable}} + {{#isNullable}} {{#isDeepObject}} - let params = crate::apis::parse_deep_object("{{{baseName}}}", local_str); - local_req_builder = local_req_builder.query(¶ms); + if let Some(ref local_str) = {{{paramName}}} { + let params = crate::apis::parse_deep_object("{{{baseName}}}", local_str); + local_req_builder = local_req_builder.query(¶ms); + }; {{/isDeepObject}} {{^isDeepObject}} - local_req_builder = local_req_builder.query(&[("{{{baseName}}}", &local_str.to_string())]); + if let Some(ref local_str) = {{{paramName}}} { + local_req_builder = local_req_builder.query(&[("{{{baseName}}}", &local_str.to_string())]); + }; {{/isDeepObject}} + {{/isNullable}} {{/isArray}} - } - {{/required}} - {{/queryParams}} -#} - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); - } -{# - {{#hasHeaderParams}} - {{#headerParams}} - {{#required}} - {{^isNullable}} - local_req_builder = local_req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_param_value) => { local_req_builder = local_req_builder.header("{{{baseName}}}", local_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, - None => { local_req_builder = local_req_builder.header("{{{baseName}}}", ""); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_param_value) = {{{paramName}}} { - local_req_builder = local_req_builder.header("{{{baseName}}}", local_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/headerParams}} - {{/hasHeaderParams}} -#} - {%- set authMethods = operation.security if "security" in operation else openapi.security %} - {%- if authMethods %} - {%- for authMethod in authMethods %} - {%- for name in authMethod %} - {%- set schema = openapi.components.securitySchemes[name] %} - {%- if schema.type == "apiKey" and schema.in != "cookie" %} - if let Some(ref local_apikey) = local_configuration.{{name|variable_name}} { - local_req_builder = local_req_builder.header("{{schema.name}}", local_apikey); - }; - {%- endif %} - {%- endfor %} - {%- endfor %} - {%- endif %} -{# - {{#isMultipart}} - {{#hasFormParams}} - let mut local_form = reqwest::multipart::Form::new(); - {{#formParams}} - {{#isFile}} - {{^supportAsync}} - {{#required}} - {{^isNullable}} - local_form = local_form.file("{{{baseName}}}", {{{paramName}}})?; - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_param_value) => { local_form = local_form.file("{{{baseName}}}", local_param_value)?; }, - None => { unimplemented!("Required nullable form file param not supported"); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_param_value) = {{{paramName}}} { - local_form = local_form.file("{{{baseName}}}", local_param_value)?; - } - {{/required}} - // TODO: support file upload for '{{{baseName}}}' parameter - - {{/isFile}} - {{^isFile}} - {{#required}} - {{^isNullable}} - local_form = local_form.text("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_param_value) => { local_form = local_form.text("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, - None => { local_form = local_form.text("{{{baseName}}}", ""); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_param_value) = {{{paramName}}} { - local_form = local_form.text("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/isFile}} - {{/formParams}} - local_req_builder = local_req_builder.multipart(local_form); - {{/hasFormParams}} - {{/isMultipart}} - {{^isMultipart}} - {{#hasFormParams}} - let mut local_form_params = std::collections::HashMap::new(); - {{#formParams}} - {{#isFile}} - {{#required}} - {{^isNullable}} - local_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_param_value) => { local_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, - None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_param_value) = {{{paramName}}} { + {{/required}} + {{^required}} + if let Some(ref local_str) = {{{paramName}}} { + {{#isArray}} + local_req_builder = match "{{collectionFormat}}" { + "multi" => local_req_builder.query(&local_str.into_iter().map(|p| ("{{{baseName}}}".to_owned(), p.to_string())).collect::>()), + _ => local_req_builder.query(&[("{{{baseName}}}", &local_str.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]), + }; + {{/isArray}} + {{^isArray}} + {{#isDeepObject}} + let params = crate::apis::parse_deep_object("{{{baseName}}}", local_str); + local_req_builder = local_req_builder.query(¶ms); + {{/isDeepObject}} + {{^isDeepObject}} + local_req_builder = local_req_builder.query(&[("{{{baseName}}}", &local_str.to_string())]); + {{/isDeepObject}} + {{/isArray}} + } + {{/required}} + {{/queryParams}} + #} + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + {# + {{#hasHeaderParams}} + {{#headerParams}} + {{#required}} + {{^isNullable}} + local_req_builder = local_req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isArray}}.join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_param_value) => { local_req_builder = local_req_builder.header("{{{baseName}}}", local_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); }, + None => { local_req_builder = local_req_builder.header("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_param_value) = {{{paramName}}} { + local_req_builder = local_req_builder.header("{{{baseName}}}", local_param_value{{#isArray}}.join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/headerParams}} + {{/hasHeaderParams}} + #} + {%- set authMethods = operation.security if "security" in operation else openapi.security %} + {%- if authMethods %} + {%- for authMethod in authMethods %} + {%- for name in authMethod %} + {%- set schema = openapi.components.securitySchemes[name] %} + {%- if schema.type == "apiKey" and schema.in != "cookie" %} + if let Some(ref local_apikey) = local_configuration.{{name|variable_name}} { + local_req_builder = local_req_builder.header("{{schema.name}}", local_apikey); + }; + {%- endif %} + {%- endfor %} + {%- endfor %} + {%- endif %} + {# + {{#isMultipart}} + {{#hasFormParams}} + let mut local_form = reqwest::multipart::Form::new(); + {{#formParams}} + {{#isFile}} + {{^supportAsync}} + {{#required}} + {{^isNullable}} + local_form = local_form.file("{{{baseName}}}", {{{paramName}}})?; + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_param_value) => { local_form = local_form.file("{{{baseName}}}", local_param_value)?; }, + None => { unimplemented!("Required nullable form file param not supported"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_param_value) = {{{paramName}}} { + local_form = local_form.file("{{{baseName}}}", local_param_value)?; + } + {{/required}} + // TODO: support file upload for '{{{baseName}}}' parameter + + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + local_form = local_form.text("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_param_value) => { local_form = local_form.text("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { local_form = local_form.text("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_param_value) = {{{paramName}}} { + local_form = local_form.text("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + local_req_builder = local_req_builder.multipart(local_form); + {{/hasFormParams}} + {{/isMultipart}} + {{^isMultipart}} + {{#hasFormParams}} + let mut local_form_params = std::collections::HashMap::new(); + {{#formParams}} + {{#isFile}} + {{#required}} + {{^isNullable}} local_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); - } - {{/required}} - {{/isFile}} - {{^isFile}} - {{#required}} - {{^isNullable}} - local_form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - {{/isNullable}} - {{#isNullable}} - match {{{paramName}}} { - Some(local_param_value) => { local_form_params.insert("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, - None => { local_form_params.insert("{{{baseName}}}", ""); }, - } - {{/isNullable}} - {{/required}} - {{^required}} - if let Some(local_param_value) = {{{paramName}}} { - local_form_params.insert("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); - } - {{/required}} - {{/isFile}} - {{/formParams}} - local_req_builder = local_req_builder.form(&local_form_params); - {{/hasFormParams}} - {{/isMultipart}} -#} - {%- if operation.requestBody is defined and not formParameter %} - {%- set isBodyOptional = False if "required" in operation.requestBody and operation.requestBody.required else True %} - // body params - {%- if isBodyOptional %} - if {{operation.get("x-codegen-request-body-name", "body")|variable_name}}.is_some() { - local_req_builder = local_req_builder.json(&{{operation.get("x-codegen-request-body-name", "body")|variable_name}}.unwrap()); - } - {%- else %} - local_req_builder = local_req_builder.json(&{{operation.get("x-codegen-request-body-name", "body")|variable_name}}); - {%- endif %} - {%- endif %} + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_param_value) => { local_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, + None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_param_value) = {{{paramName}}} { + local_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + } + {{/required}} + {{/isFile}} + {{^isFile}} + {{#required}} + {{^isNullable}} + local_form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + {{/isNullable}} + {{#isNullable}} + match {{{paramName}}} { + Some(local_param_value) => { local_form_params.insert("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); }, + None => { local_form_params.insert("{{{baseName}}}", ""); }, + } + {{/isNullable}} + {{/required}} + {{^required}} + if let Some(local_param_value) = {{{paramName}}} { + local_form_params.insert("{{{baseName}}}", local_param_value{{#isArray}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isArray}}.to_string()); + } + {{/required}} + {{/isFile}} + {{/formParams}} + local_req_builder = local_req_builder.form(&local_form_params); + {{/hasFormParams}} + {{/isMultipart}} + #} + {%- if operation.requestBody is defined and not formParameter %} + {%- set isBodyOptional = False if "required" in operation.requestBody and operation.requestBody.required else True %} + // body params + {%- if isBodyOptional %} + if {{operation.get("x-codegen-request-body-name", "body")|variable_name}}.is_some() { + local_req_builder = local_req_builder.json(&{{operation.get("x-codegen-request-body-name", "body")|variable_name}}.unwrap()); + } + {%- else %} + local_req_builder = local_req_builder.json(&{{operation.get("x-codegen-request-body-name", "body")|variable_name}}); + {%- endif %} + {%- endif %} - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - {%- if returnType %} - entity: serde_json::from_str(&local_content).ok(), - {%- else %} - entity: None, - {%- endif %} - }) - } else { - let local_entity: Option<{{operation.operationId}}Error> = serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { status: local_status, content: local_content, entity: local_entity }; - Err(Error::ResponseError(local_error)) + if !local_status.is_client_error() && !local_status.is_server_error() { + {%- if returnType %} + let local_entity: Option<{{returnType}}> = serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + {%- else %} + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: None, + }) + {%- endif %} + } else { + let local_entity: Option<{{operation.operationId}}Error> = serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { status: local_status, content: local_content, entity: local_entity }; + Err(Error::ResponseError(local_error)) + } } + {%- endfor %} } -{%- endfor %} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a94087521..72ab15308 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,11 +10,15 @@ repos: - id: lint name: Lint language: rust - entry: cargo fmt + entry: cargo check + pass_filenames: false stages: [manual] - # files: '^api/.*\.go' - # types: ["file", "go"] + - id: format + name: Format + language: rust + entry: cargo fmt pass_filenames: false + stages: [manual] - id: generator name: generator language: python diff --git a/generate.sh b/generate.sh index fc3796f89..f5ba38b30 100755 --- a/generate.sh +++ b/generate.sh @@ -25,4 +25,5 @@ pre_commit_wrapper () { rm -rf src/* examples/* pre_commit_wrapper generator -pre_commit_wrapper lint \ No newline at end of file +pre_commit_wrapper lint +pre_commit_wrapper format \ No newline at end of file diff --git a/src/datadogV2/api/api_fastly_integration.rs b/src/datadogV2/api/api_fastly_integration.rs index 6a987067c..3f80b9d5e 100644 --- a/src/datadogV2/api/api_fastly_integration.rs +++ b/src/datadogV2/api/api_fastly_integration.rs @@ -186,595 +186,769 @@ pub enum UpdateFastlyServiceError { UnknownValue(serde_json::Value), } -/// Create a Fastly account. -pub async fn create_fastly_account( - configuration: &configuration::Configuration, - params: CreateFastlyAccountParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let body = params.body; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts", - local_configuration.base_path - ); - let mut local_req_builder = local_client.request(reqwest::Method::POST, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); - } +pub struct FastlyIntegrationAPI { + config: configuration::Configuration, +} - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - // body params - local_req_builder = local_req_builder.json(&body); - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, - }; - Err(Error::ResponseError(local_error)) +impl Default for FastlyIntegrationAPI { + fn default() -> Self { + Self { + config: configuration::Configuration::new(), + } } } -/// Create a Fastly service for an account. -pub async fn create_fastly_service( - configuration: &configuration::Configuration, - params: CreateFastlyServiceParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - let body = params.body; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}/services", - local_configuration.base_path, - account_id = urlencode(account_id) - ); - let mut local_req_builder = local_client.request(reqwest::Method::POST, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); +impl FastlyIntegrationAPI { + pub fn new() -> Self { + Self::default() + } + pub fn with_config(config: configuration::Configuration) -> Self { + Self { config } + } + + /// Create a Fastly account. + pub async fn create_fastly_account( + self, + params: CreateFastlyAccountParams, + ) -> Result< + Option, + Error, + > { + match self.create_fastly_account_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - // body params - local_req_builder = local_req_builder.json(&body); - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Create a Fastly account. + pub async fn create_fastly_account_with_http_info( + self, + params: CreateFastlyAccountParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let body = params.body; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts", + local_configuration.base_path + ); + let mut local_req_builder = + local_client.request(reqwest::Method::POST, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + + // body params + local_req_builder = local_req_builder.json(&body); + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// Delete a Fastly account. -pub async fn delete_fastly_account( - configuration: &configuration::Configuration, - params: DeleteFastlyAccountParams, -) -> Result, Error> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}", - local_configuration.base_path, - account_id = urlencode(account_id) - ); - let mut local_req_builder = - local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// Create a Fastly service for an account. + pub async fn create_fastly_service( + self, + params: CreateFastlyServiceParams, + ) -> Result< + Option, + Error, + > { + match self.create_fastly_service_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: None, - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Create a Fastly service for an account. + pub async fn create_fastly_service_with_http_info( + self, + params: CreateFastlyServiceParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + let body = params.body; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}/services", + local_configuration.base_path, + account_id = urlencode(account_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::POST, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + + // body params + local_req_builder = local_req_builder.json(&body); + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// Delete a Fastly service for an account. -pub async fn delete_fastly_service( - configuration: &configuration::Configuration, - params: DeleteFastlyServiceParams, -) -> Result, Error> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - let service_id = params.service_id; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}/services/{service_id}", - local_configuration.base_path, - account_id = urlencode(account_id), - service_id = urlencode(service_id) - ); - let mut local_req_builder = - local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// Delete a Fastly account. + pub async fn delete_fastly_account( + self, + params: DeleteFastlyAccountParams, + ) -> Result, Error> { + match self.delete_fastly_account_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: None, - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Delete a Fastly account. + pub async fn delete_fastly_account_with_http_info( + self, + params: DeleteFastlyAccountParams, + ) -> Result, Error> { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}", + local_configuration.base_path, + account_id = urlencode(account_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: None, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// Get a Fastly account. -pub async fn get_fastly_account( - configuration: &configuration::Configuration, - params: GetFastlyAccountParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}", - local_configuration.base_path, - account_id = urlencode(account_id) - ); - let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// Delete a Fastly service for an account. + pub async fn delete_fastly_service( + self, + params: DeleteFastlyServiceParams, + ) -> Result, Error> { + match self.delete_fastly_service_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Delete a Fastly service for an account. + pub async fn delete_fastly_service_with_http_info( + self, + params: DeleteFastlyServiceParams, + ) -> Result, Error> { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + let service_id = params.service_id; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}/services/{service_id}", + local_configuration.base_path, + account_id = urlencode(account_id), + service_id = urlencode(service_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); + }; + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: None, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// Get a Fastly service for an account. -pub async fn get_fastly_service( - configuration: &configuration::Configuration, - params: GetFastlyServiceParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - let service_id = params.service_id; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}/services/{service_id}", - local_configuration.base_path, - account_id = urlencode(account_id), - service_id = urlencode(service_id) - ); - let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// Get a Fastly account. + pub async fn get_fastly_account( + self, + params: GetFastlyAccountParams, + ) -> Result, Error> + { + match self.get_fastly_account_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Get a Fastly account. + pub async fn get_fastly_account_with_http_info( + self, + params: GetFastlyAccountParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}", + local_configuration.base_path, + account_id = urlencode(account_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) - } -} -/// List Fastly accounts. -pub async fn list_fastly_accounts( - configuration: &configuration::Configuration, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } + } - // unbox the parameters + /// Get a Fastly service for an account. + pub async fn get_fastly_service( + self, + params: GetFastlyServiceParams, + ) -> Result, Error> + { + match self.get_fastly_service_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } + } - let local_client = &local_configuration.client; + /// Get a Fastly service for an account. + pub async fn get_fastly_service_with_http_info( + self, + params: GetFastlyServiceParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + let service_id = params.service_id; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}/services/{service_id}", + local_configuration.base_path, + account_id = urlencode(account_id), + service_id = urlencode(service_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); + }; - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts", - local_configuration.base_path - ); - let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } + } - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// List Fastly accounts. + pub async fn list_fastly_accounts( + self, + ) -> Result< + Option, + Error, + > { + match self.list_fastly_accounts_with_http_info().await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// List Fastly accounts. + pub async fn list_fastly_accounts_with_http_info( + self, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts", + local_configuration.base_path + ); + let mut local_req_builder = + local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); + }; + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// List Fastly services for an account. -pub async fn list_fastly_services( - configuration: &configuration::Configuration, - params: ListFastlyServicesParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}/services", - local_configuration.base_path, - account_id = urlencode(account_id) - ); - let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// List Fastly services for an account. + pub async fn list_fastly_services( + self, + params: ListFastlyServicesParams, + ) -> Result< + Option, + Error, + > { + match self.list_fastly_services_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// List Fastly services for an account. + pub async fn list_fastly_services_with_http_info( + self, + params: ListFastlyServicesParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}/services", + local_configuration.base_path, + account_id = urlencode(account_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// Update a Fastly account. -pub async fn update_fastly_account( - configuration: &configuration::Configuration, - params: UpdateFastlyAccountParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - let body = params.body; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}", - local_configuration.base_path, - account_id = urlencode(account_id) - ); - let mut local_req_builder = - local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// Update a Fastly account. + pub async fn update_fastly_account( + self, + params: UpdateFastlyAccountParams, + ) -> Result< + Option, + Error, + > { + match self.update_fastly_account_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - // body params - local_req_builder = local_req_builder.json(&body); - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Update a Fastly account. + pub async fn update_fastly_account_with_http_info( + self, + params: UpdateFastlyAccountParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + let body = params.body; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}", + local_configuration.base_path, + account_id = urlencode(account_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); + }; + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + + // body params + local_req_builder = local_req_builder.json(&body); + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } -} -/// Update a Fastly service for an account. -pub async fn update_fastly_service( - configuration: &configuration::Configuration, - params: UpdateFastlyServiceParams, -) -> Result< - ResponseContent>, - Error, -> { - let local_configuration = configuration; - - // unbox the parameters - let account_id = params.account_id; - let service_id = params.service_id; - let body = params.body; - - let local_client = &local_configuration.client; - - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts/{account_id}/services/{service_id}", - local_configuration.base_path, - account_id = urlencode(account_id), - service_id = urlencode(service_id) - ); - let mut local_req_builder = - local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); - - if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + /// Update a Fastly service for an account. + pub async fn update_fastly_service( + self, + params: UpdateFastlyServiceParams, + ) -> Result< + Option, + Error, + > { + match self.update_fastly_service_with_http_info(params).await { + Ok(response_content) => Ok(response_content.entity), + Err(err) => Err(err), + } } - if let Some(ref local_apikey) = local_configuration.api_key_auth { - local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); - }; - if let Some(ref local_apikey) = local_configuration.app_key_auth { - local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); - }; - - // body params - local_req_builder = local_req_builder.json(&body); - - let local_req = local_req_builder.build()?; - let local_resp = local_client.execute(local_req).await?; - - let local_status = local_resp.status(); - let local_content = local_resp.text().await?; - - if !local_status.is_client_error() && !local_status.is_server_error() { - Ok(ResponseContent { - status: local_status, - content: local_content.clone(), - entity: serde_json::from_str(&local_content).ok(), - }) - } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); - let local_error = ResponseContent { - status: local_status, - content: local_content, - entity: local_entity, + /// Update a Fastly service for an account. + pub async fn update_fastly_service_with_http_info( + self, + params: UpdateFastlyServiceParams, + ) -> Result< + ResponseContent, + Error, + > { + let local_configuration = &self.config; + + // unbox the parameters + let account_id = params.account_id; + let service_id = params.service_id; + let body = params.body; + + let local_client = &local_configuration.client; + + let local_uri_str = format!( + "{}/api/v2/integrations/fastly/accounts/{account_id}/services/{service_id}", + local_configuration.base_path, + account_id = urlencode(account_id), + service_id = urlencode(service_id) + ); + let mut local_req_builder = + local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); + + if let Some(ref local_user_agent) = local_configuration.user_agent { + local_req_builder = + local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + } + + if let Some(ref local_apikey) = local_configuration.api_key_auth { + local_req_builder = local_req_builder.header("DD-API-KEY", local_apikey); }; - Err(Error::ResponseError(local_error)) + if let Some(ref local_apikey) = local_configuration.app_key_auth { + local_req_builder = local_req_builder.header("DD-APPLICATION-KEY", local_apikey); + }; + + // body params + local_req_builder = local_req_builder.json(&body); + + let local_req = local_req_builder.build()?; + let local_resp = local_client.execute(local_req).await?; + + let local_status = local_resp.status(); + let local_content = local_resp.text().await?; + + if !local_status.is_client_error() && !local_status.is_server_error() { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + Ok(ResponseContent { + status: local_status, + content: local_content.clone(), + entity: local_entity, + }) + } else { + let local_entity: Option = + serde_json::from_str(&local_content).ok(); + let local_error = ResponseContent { + status: local_status, + content: local_content, + entity: local_entity, + }; + Err(Error::ResponseError(local_error)) + } } } From 6abebd71f9a71b7b386fcdae70dc94b6a6ca8b77 Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Mon, 23 Oct 2023 10:41:47 -0400 Subject: [PATCH 02/10] cleanup unneeded clones --- .generator/src/generator/templates/api.j2 | 4 ++-- .pre-commit-config.yaml | 4 +++- generate.sh | 4 ++-- src/datadogV2/api/api_fastly_integration.rs | 20 ++++++++++---------- 4 files changed, 17 insertions(+), 15 deletions(-) diff --git a/.generator/src/generator/templates/api.j2 b/.generator/src/generator/templates/api.j2 index ee70c85ba..f7d8ca250 100644 --- a/.generator/src/generator/templates/api.j2 +++ b/.generator/src/generator/templates/api.j2 @@ -308,13 +308,13 @@ impl {{ structName }} { let local_entity: Option<{{returnType}}> = serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) {%- else %} Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: None, }) {%- endif %} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 72ab15308..f37ba9ca4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,7 +10,9 @@ repos: - id: lint name: Lint language: rust - entry: cargo check + entry: cargo fix + args: + - "--allow-staged" pass_filenames: false stages: [manual] - id: format diff --git a/generate.sh b/generate.sh index f5ba38b30..df529f973 100755 --- a/generate.sh +++ b/generate.sh @@ -25,5 +25,5 @@ pre_commit_wrapper () { rm -rf src/* examples/* pre_commit_wrapper generator -pre_commit_wrapper lint -pre_commit_wrapper format \ No newline at end of file +pre_commit_wrapper format +pre_commit_wrapper lint \ No newline at end of file diff --git a/src/datadogV2/api/api_fastly_integration.rs b/src/datadogV2/api/api_fastly_integration.rs index 3f80b9d5e..321715431 100644 --- a/src/datadogV2/api/api_fastly_integration.rs +++ b/src/datadogV2/api/api_fastly_integration.rs @@ -268,7 +268,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -347,7 +347,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -414,7 +414,7 @@ impl FastlyIntegrationAPI { if !local_status.is_client_error() && !local_status.is_server_error() { Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: None, }) } else { @@ -483,7 +483,7 @@ impl FastlyIntegrationAPI { if !local_status.is_client_error() && !local_status.is_server_error() { Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: None, }) } else { @@ -556,7 +556,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -631,7 +631,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -702,7 +702,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -777,7 +777,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -856,7 +856,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { @@ -937,7 +937,7 @@ impl FastlyIntegrationAPI { serde_json::from_str(&local_content).ok(); Ok(ResponseContent { status: local_status, - content: local_content.clone(), + content: local_content, entity: local_entity, }) } else { From 54761b9c7fee1481b8334c0d82b32e380d3479b9 Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Mon, 23 Oct 2023 14:41:57 -0400 Subject: [PATCH 03/10] fix testing framework to use and initialize api instances. also adds linting --- .generator/src/generator/templates/api.j2 | 5 +- .../generator/templates/function_mappings.j2 | 48 +++++- .pre-commit-config.yaml | 6 +- src/datadogV2/api/api_fastly_integration.rs | 41 ++--- tests/scenarios/fixtures.rs | 34 ++-- tests/scenarios/function_mappings.rs | 148 +++++++++++++----- 6 files changed, 197 insertions(+), 85 deletions(-) diff --git a/.generator/src/generator/templates/api.j2 b/.generator/src/generator/templates/api.j2 index f7d8ca250..ef485cb60 100644 --- a/.generator/src/generator/templates/api.j2 +++ b/.generator/src/generator/templates/api.j2 @@ -48,6 +48,7 @@ pub enum {{operation.operationId}}Error { {% endfor %} {%- set structName = name|camel_case +"API" %} +#[derive(Debug, Clone)] pub struct {{ structName }} { config: configuration::Configuration, } @@ -74,7 +75,7 @@ impl {{ structName }} { {% if operation.description is defined %} {{ operation.description | block_comment }} {%- endif %} - pub async fn {{operation.operationId | snake_case}}(self{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { + pub async fn {{operation.operationId | snake_case}}(&self{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { match self.{{operation.operationId | snake_case}}_with_http_info({% for name, parameter in operation|parameters %}{% if loop.first %}params{% endif %}{% endfor %}).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -84,7 +85,7 @@ impl {{ structName }} { {% if operation.description is defined %} {{ operation.description | block_comment }} {%- endif %} - pub async fn {{operation.operationId | snake_case}}_with_http_info(self{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { + pub async fn {{operation.operationId | snake_case}}_with_http_info(&self{% for name, parameter in operation|parameters %}{% if loop.first %}, params: {{operation.operationId}}Params{% endif %}{% endfor %}) -> Result, Error<{{operation.operationId}}Error>> { let local_configuration = &self.config; // unbox the parameters diff --git a/.generator/src/generator/templates/function_mappings.j2 b/.generator/src/generator/templates/function_mappings.j2 index 8dfba2405..90b07b2b4 100644 --- a/.generator/src/generator/templates/function_mappings.j2 +++ b/.generator/src/generator/templates/function_mappings.j2 @@ -3,18 +3,48 @@ use futures::executor::block_on; use serde_json::Value; use std::collections::HashMap; -use datadog_api_client::datadog::*;{# +use datadog_api_client::datadog::*; +{# {% for name, operations in apis["v1"].items() %} {%- set classname = "api_"+name%} use datadog_api_client::datadogV1::{{classname | snake_case}}::*; {%- endfor %} -#}{%- for version, apis in all_apis.items() %} +#} +{%- for version, apis in all_apis.items() %} {%- for name, operations in apis.items() %} {%- set classname = "api_"+name %} use datadog_api_client::datadog{{ version.upper() }}::api::{{classname | snake_case}}::*; {%- endfor %} {%- endfor %} +#[derive(Debug, Default)] +pub struct ApiInstances { +{%- for version, apis in all_apis.items() %} +{%- for name, operations in apis.items() %} +{%- set fieldName = "api_"+name %} +{%- set structName = name|camel_case +"API" %} + pub {{fieldName | snake_case}}: Option<{{structName}}>, +{%- endfor %} +{%- endfor %} +} + +pub fn initialize_api_instance(world: &mut DatadogWorld, api: String) { + match api.as_str() { + {%- for version, apis in all_apis.items() %} + {%- for name, operations in apis.items() %} + {%- set fieldName = "api_"+name %} + {%- set structName = name|camel_case +"API" %} + "{{name|camel_case}}" => { + if world.api_instances.api_fastly_integration.is_none() { + world.api_instances.{{fieldName | snake_case}} = Some({{structName}}::with_config(world.config.clone())); + } + }, + {%- endfor %} + {%- endfor %} + _ => panic!("{api} API instance not found"), + } +} + pub fn collect_function_calls(world: &mut DatadogWorld) { {%- for _, apis in all_apis.items() %} {%- for _, operations in apis.items() %} @@ -26,26 +56,28 @@ pub fn collect_function_calls(world: &mut DatadogWorld) { } {%- for _, apis in all_apis.items() %} -{%- for _, operations in apis.items() %} +{%- for name, operations in apis.items() %} +{%- set apiName = "api_"+name | snake_case %} {% for _, _, operation in operations %} {%- set operationParams = operation|parameters|list %} fn test_{{ operation['operationId'] | snake_case }}(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world.api_instances.{{ apiName }}.as_ref().expect("api instance not found"); {%- if operationParams|length > 0 -%} let params = {{ operation['operationId'] }}Params { {%- for param in operationParams %} {{ param[0] }}: serde_json::from_value(_parameters.get("{{ param[0] }}").unwrap().clone()).unwrap(), {%- endfor %} }; - let response = match block_on({{ operation['operationId'] | snake_case}}(&world.config, params)) { + let response = match block_on(api.{{ operation['operationId'] | snake_case}}_with_http_info(params)) { {%- else %} - let response = match block_on({{ operation['operationId'] | snake_case}}(&world.config)) { + let response = match block_on(api.{{ operation['operationId'] | snake_case}}_with_http_info()) { {%- endif %} Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f37ba9ca4..40ba28c53 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,10 +9,8 @@ repos: pass_filenames: false - id: lint name: Lint - language: rust - entry: cargo fix - args: - - "--allow-staged" + entry: cargo clippy + language: system pass_filenames: false stages: [manual] - id: format diff --git a/src/datadogV2/api/api_fastly_integration.rs b/src/datadogV2/api/api_fastly_integration.rs index 321715431..12d19cfbe 100644 --- a/src/datadogV2/api/api_fastly_integration.rs +++ b/src/datadogV2/api/api_fastly_integration.rs @@ -186,6 +186,7 @@ pub enum UpdateFastlyServiceError { UnknownValue(serde_json::Value), } +#[derive(Debug, Clone)] pub struct FastlyIntegrationAPI { config: configuration::Configuration, } @@ -208,7 +209,7 @@ impl FastlyIntegrationAPI { /// Create a Fastly account. pub async fn create_fastly_account( - self, + &self, params: CreateFastlyAccountParams, ) -> Result< Option, @@ -222,7 +223,7 @@ impl FastlyIntegrationAPI { /// Create a Fastly account. pub async fn create_fastly_account_with_http_info( - self, + &self, params: CreateFastlyAccountParams, ) -> Result< ResponseContent, @@ -285,7 +286,7 @@ impl FastlyIntegrationAPI { /// Create a Fastly service for an account. pub async fn create_fastly_service( - self, + &self, params: CreateFastlyServiceParams, ) -> Result< Option, @@ -299,7 +300,7 @@ impl FastlyIntegrationAPI { /// Create a Fastly service for an account. pub async fn create_fastly_service_with_http_info( - self, + &self, params: CreateFastlyServiceParams, ) -> Result< ResponseContent, @@ -364,7 +365,7 @@ impl FastlyIntegrationAPI { /// Delete a Fastly account. pub async fn delete_fastly_account( - self, + &self, params: DeleteFastlyAccountParams, ) -> Result, Error> { match self.delete_fastly_account_with_http_info(params).await { @@ -375,7 +376,7 @@ impl FastlyIntegrationAPI { /// Delete a Fastly account. pub async fn delete_fastly_account_with_http_info( - self, + &self, params: DeleteFastlyAccountParams, ) -> Result, Error> { let local_configuration = &self.config; @@ -431,7 +432,7 @@ impl FastlyIntegrationAPI { /// Delete a Fastly service for an account. pub async fn delete_fastly_service( - self, + &self, params: DeleteFastlyServiceParams, ) -> Result, Error> { match self.delete_fastly_service_with_http_info(params).await { @@ -442,7 +443,7 @@ impl FastlyIntegrationAPI { /// Delete a Fastly service for an account. pub async fn delete_fastly_service_with_http_info( - self, + &self, params: DeleteFastlyServiceParams, ) -> Result, Error> { let local_configuration = &self.config; @@ -500,7 +501,7 @@ impl FastlyIntegrationAPI { /// Get a Fastly account. pub async fn get_fastly_account( - self, + &self, params: GetFastlyAccountParams, ) -> Result, Error> { @@ -512,7 +513,7 @@ impl FastlyIntegrationAPI { /// Get a Fastly account. pub async fn get_fastly_account_with_http_info( - self, + &self, params: GetFastlyAccountParams, ) -> Result< ResponseContent, @@ -573,7 +574,7 @@ impl FastlyIntegrationAPI { /// Get a Fastly service for an account. pub async fn get_fastly_service( - self, + &self, params: GetFastlyServiceParams, ) -> Result, Error> { @@ -585,7 +586,7 @@ impl FastlyIntegrationAPI { /// Get a Fastly service for an account. pub async fn get_fastly_service_with_http_info( - self, + &self, params: GetFastlyServiceParams, ) -> Result< ResponseContent, @@ -648,7 +649,7 @@ impl FastlyIntegrationAPI { /// List Fastly accounts. pub async fn list_fastly_accounts( - self, + &self, ) -> Result< Option, Error, @@ -661,7 +662,7 @@ impl FastlyIntegrationAPI { /// List Fastly accounts. pub async fn list_fastly_accounts_with_http_info( - self, + &self, ) -> Result< ResponseContent, Error, @@ -719,7 +720,7 @@ impl FastlyIntegrationAPI { /// List Fastly services for an account. pub async fn list_fastly_services( - self, + &self, params: ListFastlyServicesParams, ) -> Result< Option, @@ -733,7 +734,7 @@ impl FastlyIntegrationAPI { /// List Fastly services for an account. pub async fn list_fastly_services_with_http_info( - self, + &self, params: ListFastlyServicesParams, ) -> Result< ResponseContent, @@ -794,7 +795,7 @@ impl FastlyIntegrationAPI { /// Update a Fastly account. pub async fn update_fastly_account( - self, + &self, params: UpdateFastlyAccountParams, ) -> Result< Option, @@ -808,7 +809,7 @@ impl FastlyIntegrationAPI { /// Update a Fastly account. pub async fn update_fastly_account_with_http_info( - self, + &self, params: UpdateFastlyAccountParams, ) -> Result< ResponseContent, @@ -873,7 +874,7 @@ impl FastlyIntegrationAPI { /// Update a Fastly service for an account. pub async fn update_fastly_service( - self, + &self, params: UpdateFastlyServiceParams, ) -> Result< Option, @@ -887,7 +888,7 @@ impl FastlyIntegrationAPI { /// Update a Fastly service for an account. pub async fn update_fastly_service_with_http_info( - self, + &self, params: UpdateFastlyServiceParams, ) -> Result< ResponseContent, diff --git a/tests/scenarios/fixtures.rs b/tests/scenarios/fixtures.rs index 4e5f40f12..d9a3dce95 100644 --- a/tests/scenarios/fixtures.rs +++ b/tests/scenarios/fixtures.rs @@ -1,4 +1,6 @@ -use crate::scenarios::function_mappings::*; +use crate::scenarios::function_mappings::{ + collect_function_calls, initialize_api_instance, ApiInstances, +}; use cucumber::{ event::ScenarioFinished, gherkin::{Feature, Rule, Scenario}, @@ -40,6 +42,7 @@ pub struct DatadogWorld { pub operation_id: String, pub parameters: HashMap, pub response: Response, + pub api_instances: ApiInstances, given_map: Value, undo_map: Value, undo_operations: Vec, @@ -137,8 +140,8 @@ fn valid_appkey_auth(world: &mut DatadogWorld) { } #[given(expr = "an instance of {string} API")] -fn instance_of_api(_world: &mut DatadogWorld, _api: String) { - // rust client doesn't have concept of an api instance at the moment. +fn instance_of_api(world: &mut DatadogWorld, api: String) { + initialize_api_instance(world, api); } #[given(expr = "there is a valid {string} in the system")] @@ -171,12 +174,23 @@ fn given_resource_in_system(world: &mut DatadogWorld, given_key: String) { }; } } + + if let Some(tag) = given.get("tag") { + let mut api_name = tag + .as_str() + .expect("failed to parse given tag as str") + .to_string(); + api_name.retain(|c| !c.is_whitespace()); + initialize_api_instance(world, api_name); + } + let operation_id = given .get("operationId") - .unwrap() + .expect("operationId missing from given") .as_str() - .unwrap() + .expect("failed to parse given operation id as str") .to_string(); + world.function_mappings.get(&operation_id).unwrap()(world, &given_parameters); match build_undo(world, &operation_id) { Ok(Some(undo)) => { @@ -192,10 +206,8 @@ fn given_resource_in_system(world: &mut DatadogWorld, given_key: String) { map.insert(given_key, fixture); } } - } else { - if let Value::Object(ref mut map) = world.fixtures { - map.insert(given_key, world.response.object.clone()); - } + } else if let Value::Object(ref mut map) = world.fixtures { + map.insert(given_key, world.response.object.clone()); } } @@ -226,7 +238,7 @@ fn body_from_file(world: &mut DatadogWorld, path: String) { #[given(expr = "request contains {string} parameter from {string}")] fn request_parameter_from_path(world: &mut DatadogWorld, param: String, path: String) { let lookup = lookup(&path, &world.fixtures).unwrap(); - world.parameters.insert(param, Value::from(lookup)); + world.parameters.insert(param, lookup); } #[given(expr = "request contains {string} parameter with value {}")] @@ -272,7 +284,7 @@ fn response_has_length(world: &mut DatadogWorld, path: String, expected_len: usi fn lookup(path: &String, object: &Value) -> Option { let index_re = Regex::new(r"\[(\d+)\]+").unwrap(); - let mut json_pointer = format!("/{}", path).replace(".", "/"); + let mut json_pointer = format!("/{}", path).replace('.', "/"); for (_, [idx]) in index_re .captures_iter(&json_pointer.clone()) .map(|c| c.extract()) diff --git a/tests/scenarios/function_mappings.rs b/tests/scenarios/function_mappings.rs index f8d1472e4..b316f0e75 100644 --- a/tests/scenarios/function_mappings.rs +++ b/tests/scenarios/function_mappings.rs @@ -4,8 +4,26 @@ use serde_json::Value; use std::collections::HashMap; use datadog_api_client::datadog::*; + use datadog_api_client::datadogV2::api::api_fastly_integration::*; +#[derive(Debug, Default)] +pub struct ApiInstances { + pub api_fastly_integration: Option, +} + +pub fn initialize_api_instance(world: &mut DatadogWorld, api: String) { + match api.as_str() { + "FastlyIntegration" => { + if world.api_instances.api_fastly_integration.is_none() { + world.api_instances.api_fastly_integration = + Some(FastlyIntegrationAPI::with_config(world.config.clone())); + } + } + _ => panic!("{api} API instance not found"), + } +} + pub fn collect_function_calls(world: &mut DatadogWorld) { world .function_mappings @@ -46,13 +64,18 @@ pub fn collect_function_calls(world: &mut DatadogWorld) { } fn test_list_fastly_accounts(world: &mut DatadogWorld, _parameters: &HashMap) { - let response = match block_on(list_fastly_accounts(&world.config)) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); + let response = match block_on(api.list_fastly_accounts_with_http_info()) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -62,16 +85,21 @@ fn test_list_fastly_accounts(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = CreateFastlyAccountParams { body: serde_json::from_value(_parameters.get("body").unwrap().clone()).unwrap(), }; - let response = match block_on(create_fastly_account(&world.config, params)) { + let response = match block_on(api.create_fastly_account_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -81,16 +109,21 @@ fn test_create_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = DeleteFastlyAccountParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), }; - let response = match block_on(delete_fastly_account(&world.config, params)) { + let response = match block_on(api.delete_fastly_account_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -100,16 +133,21 @@ fn test_delete_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = GetFastlyAccountParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), }; - let response = match block_on(get_fastly_account(&world.config, params)) { + let response = match block_on(api.get_fastly_account_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -119,17 +157,22 @@ fn test_get_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = UpdateFastlyAccountParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), body: serde_json::from_value(_parameters.get("body").unwrap().clone()).unwrap(), }; - let response = match block_on(update_fastly_account(&world.config, params)) { + let response = match block_on(api.update_fastly_account_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -139,16 +182,21 @@ fn test_update_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = ListFastlyServicesParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), }; - let response = match block_on(list_fastly_services(&world.config, params)) { + let response = match block_on(api.list_fastly_services_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -158,17 +206,22 @@ fn test_list_fastly_services(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = CreateFastlyServiceParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), body: serde_json::from_value(_parameters.get("body").unwrap().clone()).unwrap(), }; - let response = match block_on(create_fastly_service(&world.config, params)) { + let response = match block_on(api.create_fastly_service_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -178,17 +231,22 @@ fn test_create_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = DeleteFastlyServiceParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), service_id: serde_json::from_value(_parameters.get("service_id").unwrap().clone()).unwrap(), }; - let response = match block_on(delete_fastly_service(&world.config, params)) { + let response = match block_on(api.delete_fastly_service_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -198,17 +256,22 @@ fn test_delete_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = GetFastlyServiceParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), service_id: serde_json::from_value(_parameters.get("service_id").unwrap().clone()).unwrap(), }; - let response = match block_on(get_fastly_service(&world.config, params)) { + let response = match block_on(api.get_fastly_service_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } @@ -218,18 +281,23 @@ fn test_get_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap) { + let api = world + .api_instances + .api_fastly_integration + .as_ref() + .expect("api instance not found"); let params = UpdateFastlyServiceParams { account_id: serde_json::from_value(_parameters.get("account_id").unwrap().clone()).unwrap(), service_id: serde_json::from_value(_parameters.get("service_id").unwrap().clone()).unwrap(), body: serde_json::from_value(_parameters.get("body").unwrap().clone()).unwrap(), }; - let response = match block_on(update_fastly_service(&world.config, params)) { + let response = match block_on(api.update_fastly_service_with_http_info(params)) { Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e.to_string()), - Error::Serde(e) => panic!("serde error: {}", e.to_string()), - Error::Io(e) => panic!("io error: {}", e.to_string()), + Error::Reqwest(e) => panic!("reqwest error: {}", e), + Error::Serde(e) => panic!("serde error: {}", e), + Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), }; } From 4aebe1ae7632433430e2bb6a2e5e8e3f569361cc Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Mon, 23 Oct 2023 15:28:44 -0400 Subject: [PATCH 04/10] tweak rustfmt --- rustfmt.toml | 3 + src/datadog/mod.rs | 16 +- src/datadogV2/api/api_fastly_integration.rs | 176 +++++------------- .../model_fastly_account_create_request.rs | 8 +- .../model_fastly_account_update_request.rs | 8 +- .../model/model_fastly_service_request.rs | 4 +- tests/main.rs | 15 +- tests/scenarios/fixtures.rs | 89 ++------- tests/scenarios/function_mappings.rs | 44 ++--- 9 files changed, 101 insertions(+), 262 deletions(-) create mode 100644 rustfmt.toml diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..5bf9a7ba5 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +max_width = 120 +edition = "2021" +use_small_heuristics = "Default" \ No newline at end of file diff --git a/src/datadog/mod.rs b/src/datadog/mod.rs index 89c150e43..6a6d2c1f9 100644 --- a/src/datadog/mod.rs +++ b/src/datadog/mod.rs @@ -67,21 +67,15 @@ pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String for (key, value) in object { match value { - serde_json::Value::Object(_) => params.append(&mut parse_deep_object( - &format!("{}[{}]", prefix, key), - value, - )), + serde_json::Value::Object(_) => { + params.append(&mut parse_deep_object(&format!("{}[{}]", prefix, key), value)) + } serde_json::Value::Array(array) => { for (i, value) in array.iter().enumerate() { - params.append(&mut parse_deep_object( - &format!("{}[{}][{}]", prefix, key, i), - value, - )); + params.append(&mut parse_deep_object(&format!("{}[{}][{}]", prefix, key, i), value)); } } - serde_json::Value::String(s) => { - params.push((format!("{}[{}]", prefix, key), s.clone())) - } + serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), } } diff --git a/src/datadogV2/api/api_fastly_integration.rs b/src/datadogV2/api/api_fastly_integration.rs index 12d19cfbe..43a60b25e 100644 --- a/src/datadogV2/api/api_fastly_integration.rs +++ b/src/datadogV2/api/api_fastly_integration.rs @@ -211,10 +211,7 @@ impl FastlyIntegrationAPI { pub async fn create_fastly_account( &self, params: CreateFastlyAccountParams, - ) -> Result< - Option, - Error, - > { + ) -> Result, Error> { match self.create_fastly_account_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -225,10 +222,7 @@ impl FastlyIntegrationAPI { pub async fn create_fastly_account_with_http_info( &self, params: CreateFastlyAccountParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -236,16 +230,11 @@ impl FastlyIntegrationAPI { let local_client = &local_configuration.client; - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts", - local_configuration.base_path - ); - let mut local_req_builder = - local_client.request(reqwest::Method::POST, local_uri_str.as_str()); + let local_uri_str = format!("{}/api/v2/integrations/fastly/accounts", local_configuration.base_path); + let mut local_req_builder = local_client.request(reqwest::Method::POST, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -273,8 +262,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -288,10 +276,7 @@ impl FastlyIntegrationAPI { pub async fn create_fastly_service( &self, params: CreateFastlyServiceParams, - ) -> Result< - Option, - Error, - > { + ) -> Result, Error> { match self.create_fastly_service_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -302,10 +287,7 @@ impl FastlyIntegrationAPI { pub async fn create_fastly_service_with_http_info( &self, params: CreateFastlyServiceParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -319,12 +301,10 @@ impl FastlyIntegrationAPI { local_configuration.base_path, account_id = urlencode(account_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::POST, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::POST, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -352,8 +332,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -391,12 +370,10 @@ impl FastlyIntegrationAPI { local_configuration.base_path, account_id = urlencode(account_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -419,8 +396,7 @@ impl FastlyIntegrationAPI { entity: None, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -460,12 +436,10 @@ impl FastlyIntegrationAPI { account_id = urlencode(account_id), service_id = urlencode(service_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::DELETE, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -488,8 +462,7 @@ impl FastlyIntegrationAPI { entity: None, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -503,8 +476,7 @@ impl FastlyIntegrationAPI { pub async fn get_fastly_account( &self, params: GetFastlyAccountParams, - ) -> Result, Error> - { + ) -> Result, Error> { match self.get_fastly_account_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -515,10 +487,7 @@ impl FastlyIntegrationAPI { pub async fn get_fastly_account_with_http_info( &self, params: GetFastlyAccountParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -531,12 +500,10 @@ impl FastlyIntegrationAPI { local_configuration.base_path, account_id = urlencode(account_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -561,8 +528,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -576,8 +542,7 @@ impl FastlyIntegrationAPI { pub async fn get_fastly_service( &self, params: GetFastlyServiceParams, - ) -> Result, Error> - { + ) -> Result, Error> { match self.get_fastly_service_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -588,10 +553,7 @@ impl FastlyIntegrationAPI { pub async fn get_fastly_service_with_http_info( &self, params: GetFastlyServiceParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -606,12 +568,10 @@ impl FastlyIntegrationAPI { account_id = urlencode(account_id), service_id = urlencode(service_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -636,8 +596,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -650,10 +609,7 @@ impl FastlyIntegrationAPI { /// List Fastly accounts. pub async fn list_fastly_accounts( &self, - ) -> Result< - Option, - Error, - > { + ) -> Result, Error> { match self.list_fastly_accounts_with_http_info().await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -663,26 +619,18 @@ impl FastlyIntegrationAPI { /// List Fastly accounts. pub async fn list_fastly_accounts_with_http_info( &self, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters let local_client = &local_configuration.client; - let local_uri_str = format!( - "{}/api/v2/integrations/fastly/accounts", - local_configuration.base_path - ); - let mut local_req_builder = - local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + let local_uri_str = format!("{}/api/v2/integrations/fastly/accounts", local_configuration.base_path); + let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -707,8 +655,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -722,10 +669,7 @@ impl FastlyIntegrationAPI { pub async fn list_fastly_services( &self, params: ListFastlyServicesParams, - ) -> Result< - Option, - Error, - > { + ) -> Result, Error> { match self.list_fastly_services_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -736,10 +680,7 @@ impl FastlyIntegrationAPI { pub async fn list_fastly_services_with_http_info( &self, params: ListFastlyServicesParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -752,12 +693,10 @@ impl FastlyIntegrationAPI { local_configuration.base_path, account_id = urlencode(account_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::GET, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::GET, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -782,8 +721,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -797,10 +735,7 @@ impl FastlyIntegrationAPI { pub async fn update_fastly_account( &self, params: UpdateFastlyAccountParams, - ) -> Result< - Option, - Error, - > { + ) -> Result, Error> { match self.update_fastly_account_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -811,10 +746,7 @@ impl FastlyIntegrationAPI { pub async fn update_fastly_account_with_http_info( &self, params: UpdateFastlyAccountParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -828,12 +760,10 @@ impl FastlyIntegrationAPI { local_configuration.base_path, account_id = urlencode(account_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -861,8 +791,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, @@ -876,10 +805,7 @@ impl FastlyIntegrationAPI { pub async fn update_fastly_service( &self, params: UpdateFastlyServiceParams, - ) -> Result< - Option, - Error, - > { + ) -> Result, Error> { match self.update_fastly_service_with_http_info(params).await { Ok(response_content) => Ok(response_content.entity), Err(err) => Err(err), @@ -890,10 +816,7 @@ impl FastlyIntegrationAPI { pub async fn update_fastly_service_with_http_info( &self, params: UpdateFastlyServiceParams, - ) -> Result< - ResponseContent, - Error, - > { + ) -> Result, Error> { let local_configuration = &self.config; // unbox the parameters @@ -909,12 +832,10 @@ impl FastlyIntegrationAPI { account_id = urlencode(account_id), service_id = urlencode(service_id) ); - let mut local_req_builder = - local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); + let mut local_req_builder = local_client.request(reqwest::Method::PATCH, local_uri_str.as_str()); if let Some(ref local_user_agent) = local_configuration.user_agent { - local_req_builder = - local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); + local_req_builder = local_req_builder.header(reqwest::header::USER_AGENT, local_user_agent.clone()); } if let Some(ref local_apikey) = local_configuration.api_key_auth { @@ -942,8 +863,7 @@ impl FastlyIntegrationAPI { entity: local_entity, }) } else { - let local_entity: Option = - serde_json::from_str(&local_content).ok(); + let local_entity: Option = serde_json::from_str(&local_content).ok(); let local_error = ResponseContent { status: local_status, content: local_content, diff --git a/src/datadogV2/model/model_fastly_account_create_request.rs b/src/datadogV2/model/model_fastly_account_create_request.rs index d1908b005..2862f33da 100644 --- a/src/datadogV2/model/model_fastly_account_create_request.rs +++ b/src/datadogV2/model/model_fastly_account_create_request.rs @@ -11,11 +11,7 @@ pub struct FastlyAccountCreateRequest { impl FastlyAccountCreateRequest { /// Payload schema when adding a Fastly account. - pub fn new( - data: crate::datadogV2::model::FastlyAccountCreateRequestData, - ) -> FastlyAccountCreateRequest { - FastlyAccountCreateRequest { - data: Box::new(data), - } + pub fn new(data: crate::datadogV2::model::FastlyAccountCreateRequestData) -> FastlyAccountCreateRequest { + FastlyAccountCreateRequest { data: Box::new(data) } } } diff --git a/src/datadogV2/model/model_fastly_account_update_request.rs b/src/datadogV2/model/model_fastly_account_update_request.rs index 1d4c1d7ff..6ef6ea1f5 100644 --- a/src/datadogV2/model/model_fastly_account_update_request.rs +++ b/src/datadogV2/model/model_fastly_account_update_request.rs @@ -11,11 +11,7 @@ pub struct FastlyAccountUpdateRequest { impl FastlyAccountUpdateRequest { /// Payload schema when updating a Fastly account. - pub fn new( - data: crate::datadogV2::model::FastlyAccountUpdateRequestData, - ) -> FastlyAccountUpdateRequest { - FastlyAccountUpdateRequest { - data: Box::new(data), - } + pub fn new(data: crate::datadogV2::model::FastlyAccountUpdateRequestData) -> FastlyAccountUpdateRequest { + FastlyAccountUpdateRequest { data: Box::new(data) } } } diff --git a/src/datadogV2/model/model_fastly_service_request.rs b/src/datadogV2/model/model_fastly_service_request.rs index 6945a7480..b3b1e74ac 100644 --- a/src/datadogV2/model/model_fastly_service_request.rs +++ b/src/datadogV2/model/model_fastly_service_request.rs @@ -12,8 +12,6 @@ pub struct FastlyServiceRequest { impl FastlyServiceRequest { /// Payload schema for Fastly service requests. pub fn new(data: crate::datadogV2::model::FastlyServiceData) -> FastlyServiceRequest { - FastlyServiceRequest { - data: Box::new(data), - } + FastlyServiceRequest { data: Box::new(data) } } } diff --git a/tests/main.rs b/tests/main.rs index 178cb8bfd..eeda5028a 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -12,20 +12,13 @@ async fn main() { for api_version in 1..3 { println!("[Testing v{}]", api_version); DatadogWorld::cucumber() - .before(|_feature, _rule, _scenario, world| { - Box::pin(before_scenario(_feature, _rule, _scenario, world)) - }) + .before(|_feature, _rule, _scenario, world| Box::pin(before_scenario(_feature, _rule, _scenario, world))) .after(|_feature, _rule, _scenario, _ev, _world| { Box::pin(after_scenario(_feature, _rule, _scenario, _ev, _world)) }) - .filter_run( - format!("tests/scenarios/features/v{}/", api_version), - |_, _, sc| { - sc.tags - .iter() - .all(|tag| tag != "skip" && tag != "skip-rust") - }, - ) + .filter_run(format!("tests/scenarios/features/v{}/", api_version), |_, _, sc| { + sc.tags.iter().all(|tag| tag != "skip" && tag != "skip-rust") + }) .await; } } diff --git a/tests/scenarios/fixtures.rs b/tests/scenarios/fixtures.rs index d9a3dce95..16ceff5da 100644 --- a/tests/scenarios/fixtures.rs +++ b/tests/scenarios/fixtures.rs @@ -1,6 +1,4 @@ -use crate::scenarios::function_mappings::{ - collect_function_calls, initialize_api_instance, ApiInstances, -}; +use crate::scenarios::function_mappings::{collect_function_calls, initialize_api_instance, ApiInstances}; use cucumber::{ event::ScenarioFinished, gherkin::{Feature, Rule, Scenario}, @@ -48,12 +46,7 @@ pub struct DatadogWorld { undo_operations: Vec, } -pub async fn before_scenario( - feature: &Feature, - _rule: Option<&Rule>, - scenario: &Scenario, - world: &mut DatadogWorld, -) { +pub async fn before_scenario(feature: &Feature, _rule: Option<&Rule>, scenario: &Scenario, world: &mut DatadogWorld) { let api_version_re = Regex::new(r"tests/scenarios/features/v(\d+)/").unwrap(); // TODO: refactor this lol world.api_version = api_version_re @@ -66,17 +59,9 @@ pub async fn before_scenario( .unwrap(); collect_function_calls(world); - let given_file = File::open(format!( - "tests/scenarios/features/v{}/given.json", - world.api_version - )) - .unwrap(); + let given_file = File::open(format!("tests/scenarios/features/v{}/given.json", world.api_version)).unwrap(); world.given_map = serde_json::from_reader(BufReader::new(given_file)).unwrap(); - let undo_file = File::open(format!( - "tests/scenarios/features/v{}/undo.json", - world.api_version - )) - .unwrap(); + let undo_file = File::open(format!("tests/scenarios/features/v{}/undo.json", world.api_version)).unwrap(); world.undo_map = serde_json::from_reader(BufReader::new(undo_file)).unwrap(); let mut config = Configuration::new(); @@ -94,9 +79,7 @@ pub async fn before_scenario( .unwrap() .as_secs(); - let escaped_name = non_alnum_re - .replace_all(scenario.name.as_str(), "_") - .to_string(); + let escaped_name = non_alnum_re.replace_all(scenario.name.as_str(), "_").to_string(); let name = match escaped_name.len() > 100 { true => escaped_name[..100].to_string(), false => escaped_name, @@ -159,27 +142,20 @@ fn given_resource_in_system(world: &mut DatadogWorld, given_key: String) { for param in params.as_array().unwrap() { let param_name = param.get("name").unwrap().as_str().unwrap().to_string(); if let Some(source) = param.get("source") { - if let Some(value) = lookup(&source.as_str().unwrap().to_string(), &world.fixtures) - { + if let Some(value) = lookup(&source.as_str().unwrap().to_string(), &world.fixtures) { given_parameters.insert(param_name.clone(), value); } }; if let Some(template_value) = param.get("value") { let mut rendered = template(template_value.to_string(), &world.fixtures); rendered = serde_json::from_str(rendered.as_str()).unwrap(); - given_parameters.insert( - param_name.clone(), - serde_json::from_str(rendered.as_str()).unwrap(), - ); + given_parameters.insert(param_name.clone(), serde_json::from_str(rendered.as_str()).unwrap()); }; } } if let Some(tag) = given.get("tag") { - let mut api_name = tag - .as_str() - .expect("failed to parse given tag as str") - .to_string(); + let mut api_name = tag.as_str().expect("failed to parse given tag as str").to_string(); api_name.retain(|c| !c.is_whitespace()); initialize_api_instance(world, api_name); } @@ -225,11 +201,7 @@ fn body_with_value(world: &mut DatadogWorld, body: String) { #[given(regex = r"^body from file (.*)$")] fn body_from_file(world: &mut DatadogWorld, path: String) { - let body = read_to_string(format!( - "tests/scenarios/features/v{}/{}", - world.api_version, path, - )) - .unwrap(); + let body = read_to_string(format!("tests/scenarios/features/v{}/{}", world.api_version, path,)).unwrap(); let rendered = template(body, &world.fixtures); let body_struct = serde_json::from_str(rendered.as_str()).unwrap(); world.parameters.insert("body".to_string(), body_struct); @@ -274,64 +246,37 @@ fn response_equal_to(world: &mut DatadogWorld, path: String, value: String) { #[then(expr = "the response {string} has length {int}")] fn response_has_length(world: &mut DatadogWorld, path: String, expected_len: usize) { - let len = lookup(&path, &world.response.object) - .unwrap() - .as_array() - .unwrap() - .len(); + let len = lookup(&path, &world.response.object).unwrap().as_array().unwrap().len(); assert_eq!(len, expected_len); } fn lookup(path: &String, object: &Value) -> Option { let index_re = Regex::new(r"\[(\d+)\]+").unwrap(); let mut json_pointer = format!("/{}", path).replace('.', "/"); - for (_, [idx]) in index_re - .captures_iter(&json_pointer.clone()) - .map(|c| c.extract()) - { - json_pointer = index_re - .replace(&json_pointer, format!("/{idx}")) - .to_string(); + for (_, [idx]) in index_re.captures_iter(&json_pointer.clone()).map(|c| c.extract()) { + json_pointer = index_re.replace(&json_pointer, format!("/{idx}")).to_string(); } return object.pointer(&json_pointer).cloned(); } fn template(string: String, fixtures: &Value) -> String { - Handlebars::new() - .render_template(string.as_str(), &fixtures) - .unwrap() + Handlebars::new().render_template(string.as_str(), &fixtures).unwrap() } -fn build_undo( - world: &mut DatadogWorld, - operation_id: &String, -) -> Result, Value> { - let undo = world - .undo_map - .get(operation_id) - .unwrap() - .get("undo") - .unwrap(); +fn build_undo(world: &mut DatadogWorld, operation_id: &String) -> Result, Value> { + let undo = world.undo_map.get(operation_id).unwrap().get("undo").unwrap(); match undo.get("type").unwrap().as_str() { Some("unsafe") => { let mut undo_operation = UndoOperation { - operation_id: undo - .get("operationId") - .unwrap() - .as_str() - .unwrap() - .to_string(), + operation_id: undo.get("operationId").unwrap().as_str().unwrap().to_string(), parameters: HashMap::new(), }; let params = undo.get("parameters").unwrap().as_array().unwrap(); for param in params { let param_name = param.get("name").unwrap().as_str().unwrap().to_string(); if let Some(source) = param.get("source") { - if let Some(value) = lookup( - &source.as_str().unwrap().to_string(), - &world.response.object, - ) { + if let Some(value) = lookup(&source.as_str().unwrap().to_string(), &world.response.object) { undo_operation.parameters.insert(param_name.clone(), value); } }; diff --git a/tests/scenarios/function_mappings.rs b/tests/scenarios/function_mappings.rs index b316f0e75..6e1640c19 100644 --- a/tests/scenarios/function_mappings.rs +++ b/tests/scenarios/function_mappings.rs @@ -20,7 +20,7 @@ pub fn initialize_api_instance(world: &mut DatadogWorld, api: String) { Some(FastlyIntegrationAPI::with_config(world.config.clone())); } } - _ => panic!("{api} API instance not found"), + _ => panic!("'{api}' API instance tag not found"), } } @@ -28,39 +28,33 @@ pub fn collect_function_calls(world: &mut DatadogWorld) { world .function_mappings .insert("ListFastlyAccounts".to_string(), test_list_fastly_accounts); - world.function_mappings.insert( - "CreateFastlyAccount".to_string(), - test_create_fastly_account, - ); - world.function_mappings.insert( - "DeleteFastlyAccount".to_string(), - test_delete_fastly_account, - ); + world + .function_mappings + .insert("CreateFastlyAccount".to_string(), test_create_fastly_account); + world + .function_mappings + .insert("DeleteFastlyAccount".to_string(), test_delete_fastly_account); world .function_mappings .insert("GetFastlyAccount".to_string(), test_get_fastly_account); - world.function_mappings.insert( - "UpdateFastlyAccount".to_string(), - test_update_fastly_account, - ); + world + .function_mappings + .insert("UpdateFastlyAccount".to_string(), test_update_fastly_account); world .function_mappings .insert("ListFastlyServices".to_string(), test_list_fastly_services); - world.function_mappings.insert( - "CreateFastlyService".to_string(), - test_create_fastly_service, - ); - world.function_mappings.insert( - "DeleteFastlyService".to_string(), - test_delete_fastly_service, - ); + world + .function_mappings + .insert("CreateFastlyService".to_string(), test_create_fastly_service); + world + .function_mappings + .insert("DeleteFastlyService".to_string(), test_delete_fastly_service); world .function_mappings .insert("GetFastlyService".to_string(), test_get_fastly_service); - world.function_mappings.insert( - "UpdateFastlyService".to_string(), - test_update_fastly_service, - ); + world + .function_mappings + .insert("UpdateFastlyService".to_string(), test_update_fastly_service); } fn test_list_fastly_accounts(world: &mut DatadogWorld, _parameters: &HashMap) { From 0b509cdbb096a5c1e3f4610af4f66ddd1758d78f Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Tue, 24 Oct 2023 17:22:38 -0400 Subject: [PATCH 05/10] record/replay/passthrough functionality --- .generator/src/generator/templates/api_mod.j2 | 96 --------------- .../src/generator/templates/common_mod.j2 | 9 ++ .../src/generator/templates/configuration.j2 | 5 +- .../generator/templates/function_mappings.j2 | 4 +- Cargo.toml | 3 + src/datadog/configuration.rs | 5 +- src/datadog/mod.rs | 9 ++ ...ly-account-returns-CREATED-response.frozen | 1 + ...stly-account-returns-CREATED-response.json | 67 +++++++++++ ...-Fastly-account-returns-OK-response.frozen | 1 + ...et-Fastly-account-returns-OK-response.json | 95 +++++++++++++++ ...Fastly-accounts-returns-OK-response.frozen | 1 + ...t-Fastly-accounts-returns-OK-response.json | 95 +++++++++++++++ ...-Fastly-account-returns-OK-response.frozen | 1 + ...te-Fastly-account-returns-OK-response.json | 101 ++++++++++++++++ tests/scenarios/fixtures.rs | 111 +++++++++++++++--- tests/scenarios/function_mappings.rs | 42 ++----- 17 files changed, 493 insertions(+), 153 deletions(-) delete mode 100644 .generator/src/generator/templates/api_mod.j2 create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.frozen create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.frozen create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.frozen create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.frozen create mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json diff --git a/.generator/src/generator/templates/api_mod.j2 b/.generator/src/generator/templates/api_mod.j2 deleted file mode 100644 index 980159af0..000000000 --- a/.generator/src/generator/templates/api_mod.j2 +++ /dev/null @@ -1,96 +0,0 @@ -use std::error; -use std::fmt; - -#[derive(Debug, Clone)] -pub struct ResponseContent { - pub status: reqwest::StatusCode, - pub content: String, - pub entity: Option, -} - -#[derive(Debug)] -pub enum Error { - Reqwest(reqwest::Error), - Serde(serde_json::Error), - Io(std::io::Error), - ResponseError(ResponseContent), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let (module, e) = match self { - Error::Reqwest(e) => ("reqwest", e.to_string()), - Error::Serde(e) => ("serde", e.to_string()), - Error::Io(e) => ("IO", e.to_string()), - Error::ResponseError(e) => ("response", format!("status code {}", e.status)), - }; - write!(f, "error in {}: {}", module, e) - } -} - -impl error::Error for Error { - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - Some(match self { - Error::Reqwest(e) => e, - Error::Serde(e) => e, - Error::Io(e) => e, - Error::ResponseError(_) => return None, - }) - } -} - -impl From for Error { - fn from(e: reqwest::Error) -> Self { - Error::Reqwest(e) - } -} - -impl From for Error { - fn from(e: serde_json::Error) -> Self { - Error::Serde(e) - } -} - -impl From for Error { - fn from(e: std::io::Error) -> Self { - Error::Io(e) - } -} - -pub fn urlencode>(s: T) -> String { - ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() -} - -pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { - if let serde_json::Value::Object(object) = value { - let mut params = vec![]; - - for (key, value) in object { - match value { - serde_json::Value::Object(_) => params.append(&mut parse_deep_object( - &format!("{}[{}]", prefix, key), - value, - )), - serde_json::Value::Array(array) => { - for (i, value) in array.iter().enumerate() { - params.append(&mut parse_deep_object( - &format!("{}[{}][{}]", prefix, key, i), - value, - )); - } - }, - serde_json::Value::String(s) => params.push((format!("{}[{}]", prefix, key), s.clone())), - _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), - } - } - return params; - } - unimplemented!("Only objects are supported with style=deepObject") -} - -{%- for name, operations in all_operations|sort %} -{%- set classname = name + " api" %} -pub mod {{ classname | snake_case}}; -{%- endfor %} - -pub mod configuration; diff --git a/.generator/src/generator/templates/common_mod.j2 b/.generator/src/generator/templates/common_mod.j2 index 980159af0..19b9a3b2e 100644 --- a/.generator/src/generator/templates/common_mod.j2 +++ b/.generator/src/generator/templates/common_mod.j2 @@ -11,6 +11,7 @@ pub struct ResponseContent { #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), + ReqwestMiddleware(reqwest_middleware::Error), Serde(serde_json::Error), Io(std::io::Error), ResponseError(ResponseContent), @@ -20,6 +21,7 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), + Error::ReqwestMiddleware(e) => ("reqwest_middleware", e.to_string()), Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), Error::ResponseError(e) => ("response", format!("status code {}", e.status)), @@ -32,6 +34,7 @@ impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(match self { Error::Reqwest(e) => e, + Error::ReqwestMiddleware(e) => e, Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, @@ -45,6 +48,12 @@ impl From for Error { } } +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + impl From for Error { fn from(e: serde_json::Error) -> Self { Error::Serde(e) diff --git a/.generator/src/generator/templates/configuration.j2 b/.generator/src/generator/templates/configuration.j2 index c758d13ea..62f201e26 100644 --- a/.generator/src/generator/templates/configuration.j2 +++ b/.generator/src/generator/templates/configuration.j2 @@ -6,7 +6,7 @@ use std::env; pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest_middleware::ClientWithMiddleware, {%- set authMethods = openapi.security %} {%- if authMethods %} {%- for authMethod in authMethods %} @@ -29,6 +29,7 @@ impl Configuration { impl Default for Configuration { fn default() -> Self { + let http_client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new()); Configuration { base_path: "https://api.datadoghq.com".to_owned(), user_agent: Some(format!( @@ -38,7 +39,7 @@ impl Default for Configuration { env::consts::OS, env::consts::ARCH, )), - client: reqwest::Client::new(), + client: http_client.build(), {%- set authMethods = openapi.security %} {%- if authMethods %} {%- for authMethod in authMethods %} diff --git a/.generator/src/generator/templates/function_mappings.j2 b/.generator/src/generator/templates/function_mappings.j2 index 90b07b2b4..9c9912a41 100644 --- a/.generator/src/generator/templates/function_mappings.j2 +++ b/.generator/src/generator/templates/function_mappings.j2 @@ -75,10 +75,8 @@ fn test_{{ operation['operationId'] | snake_case }}(world: &mut DatadogWorld, _p Ok(response) => response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; diff --git a/Cargo.toml b/Cargo.toml index c5663bc99..f8033f0e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ url = "^2.2" uuid = { version = "^1.0", features = ["serde"] } rustc_version = "0.4.0" log = "0.4.20" +reqwest-middleware = "0.1.6" [dependencies.reqwest] version = "^0.11" features = ["json", "multipart"] @@ -28,6 +29,8 @@ handlebars = "4.4.0" regex = "1.9.5" sha256 = "1.4.0" futures = "0.3.28" +rvcr = { git = "https://github.com/nkzou/rvcr.git", rev = "a3fc79e" } +chrono = "0.4.31" [[test]] name = "main" diff --git a/src/datadog/configuration.rs b/src/datadog/configuration.rs index bc9adadc4..a4037869b 100644 --- a/src/datadog/configuration.rs +++ b/src/datadog/configuration.rs @@ -8,7 +8,7 @@ use std::env; pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest_middleware::ClientWithMiddleware, pub api_key_auth: Option, pub app_key_auth: Option, } @@ -21,6 +21,7 @@ impl Configuration { impl Default for Configuration { fn default() -> Self { + let http_client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new()); Configuration { base_path: "https://api.datadoghq.com".to_owned(), user_agent: Some(format!( @@ -30,7 +31,7 @@ impl Default for Configuration { env::consts::OS, env::consts::ARCH, )), - client: reqwest::Client::new(), + client: http_client.build(), api_key_auth: env::var("DD_API_KEY").ok(), app_key_auth: env::var("DD_APP_KEY").ok(), } diff --git a/src/datadog/mod.rs b/src/datadog/mod.rs index 6a6d2c1f9..805146b8b 100644 --- a/src/datadog/mod.rs +++ b/src/datadog/mod.rs @@ -11,6 +11,7 @@ pub struct ResponseContent { #[derive(Debug)] pub enum Error { Reqwest(reqwest::Error), + ReqwestMiddleware(reqwest_middleware::Error), Serde(serde_json::Error), Io(std::io::Error), ResponseError(ResponseContent), @@ -20,6 +21,7 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (module, e) = match self { Error::Reqwest(e) => ("reqwest", e.to_string()), + Error::ReqwestMiddleware(e) => ("reqwest_middleware", e.to_string()), Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), Error::ResponseError(e) => ("response", format!("status code {}", e.status)), @@ -32,6 +34,7 @@ impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(match self { Error::Reqwest(e) => e, + Error::ReqwestMiddleware(e) => e, Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, @@ -45,6 +48,12 @@ impl From for Error { } } +impl From for Error { + fn from(e: reqwest_middleware::Error) -> Self { + Error::ReqwestMiddleware(e) + } +} + impl From for Error { fn from(e: serde_json::Error) -> Self { Error::Serde(e) diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.frozen b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.frozen new file mode 100644 index 000000000..f0b6e19ec --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.frozen @@ -0,0 +1 @@ +2023-01-19T15:15:56.412Z \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json new file mode 100644 index 000000000..0affacb28 --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json @@ -0,0 +1,67 @@ +{ + "http_interactions": [ + { + "recorded_at": "Thu, 19 Jan 2023 15:15:56 GMT", + "request": { + "body": { + "encoding": null, + "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestAddFastlyaccountreturnsCREATEDresponse1674141356\",\"name\":\"Test-Add_Fastly_account_returns_CREATED_response-1674141356\",\"services\":[]},\"type\":\"fastly-accounts\"}}" + }, + "headers": { + "Accept": [ + "application/json" + ], + "Content-Type": [ + "application/json" + ] + }, + "method": "post", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":{\"attributes\":{\"services\":[],\"name\":\"Test-Add_Fastly_account_returns_CREATED_response-1674141356\"},\"type\":\"fastly-accounts\",\"id\":\"0427b05b6f56f454ca1477aa8df5e75d\"}}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 201, + "message": "Created" + } + } + }, + { + "recorded_at": "Thu, 19 Jan 2023 15:15:56 GMT", + "request": { + "body": "", + "headers": { + "Accept": [ + "*/*" + ] + }, + "method": "delete", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/0427b05b6f56f454ca1477aa8df5e75d" + }, + "response": { + "body": { + "encoding": null, + "string": "" + }, + "headers": { + "Content-Type": [ + "text/html; charset=utf-8" + ] + }, + "status": { + "code": 204, + "message": "No Content" + } + } + } + ], + "recorded_with": "VCR 6.0.0" +} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.frozen b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.frozen new file mode 100644 index 000000000..2ee7e978b --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.frozen @@ -0,0 +1 @@ +2023-03-13T10:11:14.475Z \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json new file mode 100644 index 000000000..d3c4aaef2 --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json @@ -0,0 +1,95 @@ +{ + "http_interactions": [ + { + "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT", + "request": { + "body": { + "encoding": null, + "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestGetFastlyaccountreturnsOKresponse1678702274\",\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\",\"services\":[]},\"type\":\"fastly-accounts\"}}" + }, + "headers": { + "Accept": [ + "application/json" + ], + "Content-Type": [ + "application/json" + ] + }, + "method": "post", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"6d8f2860f9f3e953fb46d554b9a19627\",\"attributes\":{\"services\":[],\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\"}}}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 201, + "message": "Created" + } + } + }, + { + "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT", + "request": { + "body": "", + "headers": { + "Accept": [ + "application/json" + ] + }, + "method": "get", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/6d8f2860f9f3e953fb46d554b9a19627" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"6d8f2860f9f3e953fb46d554b9a19627\",\"attributes\":{\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\",\"services\":[]}}}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 200, + "message": "OK" + } + } + }, + { + "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT", + "request": { + "body": "", + "headers": { + "Accept": [ + "*/*" + ] + }, + "method": "delete", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/6d8f2860f9f3e953fb46d554b9a19627" + }, + "response": { + "body": { + "encoding": null, + "string": "" + }, + "headers": { + "Content-Type": [ + "text/html; charset=utf-8" + ] + }, + "status": { + "code": 204, + "message": "No Content" + } + } + } + ], + "recorded_with": "VCR 6.0.0" +} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.frozen b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.frozen new file mode 100644 index 000000000..1e15453e8 --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.frozen @@ -0,0 +1 @@ +2023-03-13T10:10:50.453Z \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json new file mode 100644 index 000000000..622732efb --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json @@ -0,0 +1,95 @@ +{ + "http_interactions": [ + { + "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT", + "request": { + "body": { + "encoding": null, + "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestListFastlyaccountsreturnsOKresponse1678702250\",\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"type\":\"fastly-accounts\"}}" + }, + "headers": { + "Accept": [ + "application/json" + ], + "Content-Type": [ + "application/json" + ] + }, + "method": "post", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":{\"type\":\"fastly-accounts\",\"attributes\":{\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"id\":\"07ec97dd43cd794c847ecf15cb25eb1c\"}}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 201, + "message": "Created" + } + } + }, + { + "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT", + "request": { + "body": "", + "headers": { + "Accept": [ + "application/json" + ] + }, + "method": "get", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":[{\"type\":\"fastly-accounts\",\"attributes\":{\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"id\":\"07ec97dd43cd794c847ecf15cb25eb1c\"}]}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 200, + "message": "OK" + } + } + }, + { + "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT", + "request": { + "body": "", + "headers": { + "Accept": [ + "*/*" + ] + }, + "method": "delete", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/07ec97dd43cd794c847ecf15cb25eb1c" + }, + "response": { + "body": { + "encoding": null, + "string": "" + }, + "headers": { + "Content-Type": [ + "text/html; charset=utf-8" + ] + }, + "status": { + "code": 204, + "message": "No Content" + } + } + } + ], + "recorded_with": "VCR 6.0.0" +} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.frozen b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.frozen new file mode 100644 index 000000000..64bd5f8bd --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.frozen @@ -0,0 +1 @@ +2023-03-13T10:10:17.626Z \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json new file mode 100644 index 000000000..74a2bd6f1 --- /dev/null +++ b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json @@ -0,0 +1,101 @@ +{ + "http_interactions": [ + { + "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT", + "request": { + "body": { + "encoding": null, + "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestUpdateFastlyaccountreturnsOKresponse1678702217\",\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\",\"services\":[]},\"type\":\"fastly-accounts\"}}" + }, + "headers": { + "Accept": [ + "application/json" + ], + "Content-Type": [ + "application/json" + ] + }, + "method": "post", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"e37e834ae856fa24a2924973fdc7c276\",\"attributes\":{\"services\":[],\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\"}}}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 201, + "message": "Created" + } + } + }, + { + "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT", + "request": { + "body": { + "encoding": null, + "string": "{\"data\":{\"attributes\":{\"api_key\":\"update-secret\"},\"type\":\"fastly-accounts\"}}" + }, + "headers": { + "Accept": [ + "application/json" + ], + "Content-Type": [ + "application/json" + ] + }, + "method": "patch", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/e37e834ae856fa24a2924973fdc7c276" + }, + "response": { + "body": { + "encoding": null, + "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"e37e834ae856fa24a2924973fdc7c276\",\"attributes\":{\"services\":[],\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\"}}}\n" + }, + "headers": { + "Content-Type": [ + "application/json" + ] + }, + "status": { + "code": 200, + "message": "OK" + } + } + }, + { + "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT", + "request": { + "body": "", + "headers": { + "Accept": [ + "*/*" + ] + }, + "method": "delete", + "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/e37e834ae856fa24a2924973fdc7c276" + }, + "response": { + "body": { + "encoding": null, + "string": "" + }, + "headers": { + "Content-Type": [ + "text/html; charset=utf-8" + ] + }, + "status": { + "code": 204, + "message": "No Content" + } + } + } + ], + "recorded_with": "VCR 6.0.0" +} diff --git a/tests/scenarios/fixtures.rs b/tests/scenarios/fixtures.rs index 16ceff5da..61e0aa9d2 100644 --- a/tests/scenarios/fixtures.rs +++ b/tests/scenarios/fixtures.rs @@ -1,4 +1,5 @@ use crate::scenarios::function_mappings::{collect_function_calls, initialize_api_instance, ApiInstances}; +use chrono::DateTime; use cucumber::{ event::ScenarioFinished, gherkin::{Feature, Rule, Scenario}, @@ -6,13 +7,18 @@ use cucumber::{ }; use datadog_api_client::datadog::configuration::Configuration; use handlebars::Handlebars; +use log::debug; use regex::Regex; +use reqwest_middleware::ClientBuilder; +use rvcr::{VCRMiddleware, VCRMode}; use serde_json::{json, Value}; use sha256::digest; use std::{ collections::HashMap, - fs::{read_to_string, File}, + env, + fs::{create_dir_all, read_to_string, File}, io::BufReader, + path::PathBuf, time::SystemTime, }; @@ -64,37 +70,107 @@ pub async fn before_scenario(feature: &Feature, _rule: Option<&Rule>, scenario: let undo_file = File::open(format!("tests/scenarios/features/v{}/undo.json", world.api_version)).unwrap(); world.undo_map = serde_json::from_reader(BufReader::new(undo_file)).unwrap(); - let mut config = Configuration::new(); - config.api_key_auth = Some("00000000000000000000000000000000".to_string()); - config.app_key_auth = Some("0000000000000000000000000000000000000000".to_string()); - world.config = config; - let non_alnum_re = Regex::new(r"[^A-Za-z0-9]+").unwrap(); - let prefix = match true { - true => "Test-Rust", - false => "Test", + let escaped_filename = non_alnum_re.replace_all(scenario.name.as_str(), "-").to_string(); + let filename = match escaped_filename.len() > 100 { + true => escaped_filename[..100].to_string(), + false => escaped_filename, }; - let now = SystemTime::now() + let mut prefix = "Test".to_string(); + let mut cassette_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + cassette_dir.push(format!( + "tests/scenarios/cassettes/v{}/Feature_{}", + world.api_version, + feature.name.replace(' ', "_") + )); + create_dir_all(&cassette_dir).expect("failed to create cassette directory"); + let mut cassette = cassette_dir.clone(); + cassette.push(format!("{}.json", filename)); + let mut freeze = cassette_dir.clone(); + freeze.push(format!("{}.frozen", filename)); + let mut config = Configuration::new(); + let mut frozen_time = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs(); + let vcr_client_builder = ClientBuilder::new(reqwest::Client::new()); + config.client = match env::var("RECORD").unwrap_or("false".to_string()).as_str() { + "none" => { + prefix.push_str("-Rust"); + vcr_client_builder.build() + } + "true" => { + // let _ = remove_file(cassette.clone()); + // let _ = remove_file(freeze.clone()); + // let mut freeze_file = File::create(freeze).expect("failed to write freeze file"); + // freeze_file + // .write_all( + // DateTime::to_rfc3339( + // &DateTime::from_timestamp(frozen_time as i64, 0) + // .expect("failed to convert timestamp to datetime"), + // ) + // .as_bytes(), + // ) + // .expect("failed to write freeze file"); + // let middleware: VCRMiddleware = VCRMiddleware::try_from(cassette) + // .expect("Failed to initialize rVCR middleware") + // .with_mode(VCRMode::Record) + // .with_modify_request(|req| { + // req.headers.remove_entry("dd-api-key"); + // req.headers.remove_entry("dd-application-key"); + // }) + // .with_modify_response(|res| { + // res.headers.remove_entry("content-security-policy"); + // }); + // vcr_client_builder.with(middleware).build() + panic!("sdk's shouldn't be recording, that's the spec repo's job."); + } + _ => { + frozen_time = + DateTime::parse_from_rfc3339(read_to_string(freeze).expect("Failed to read freeze file").as_str()) + .expect("Failed to parse freeze file time") + .signed_duration_since(DateTime::UNIX_EPOCH) + .num_seconds() as u64; + debug!("{}", frozen_time); + let middleware: VCRMiddleware = VCRMiddleware::try_from(cassette) + .expect("Failed to initialize rVCR middleware") + .with_mode(VCRMode::Replay) + .with_modify_request(|req| { + req.headers.remove_entry("dd-api-key"); + req.headers.remove_entry("dd-application-key"); + }) + .with_modify_response(|res| { + res.headers.remove_entry("content-security-policy"); + }) + .with_request_matcher(|vcr_req, req| { + vcr_req.uri.to_string() == req.uri.to_string() + && vcr_req.body.string == req.body.string + && vcr_req.method == req.method + }); + vcr_client_builder.with(middleware).build() + } + }; + config.api_key_auth = Some("00000000000000000000000000000000".to_string()); + config.app_key_auth = Some("0000000000000000000000000000000000000000".to_string()); + world.config = config; + let escaped_name = non_alnum_re.replace_all(scenario.name.as_str(), "_").to_string(); let name = match escaped_name.len() > 100 { true => escaped_name[..100].to_string(), false => escaped_name, }; - let unique = format!("{}-{}-{}", prefix, name, now); + let unique = format!("{}-{}-{}", prefix, name, frozen_time); let unique_alnum = non_alnum_re.replace_all(unique.as_str(), "").to_string(); world.fixtures = json!({ "unique": unique, - "unique_lower": unique.to_ascii_lowercase(), + "unique_lowe: Stringr": unique.to_ascii_lowercase(), "unique_upper": unique.to_ascii_uppercase(), "unique_alnum": unique_alnum, "unique_lower_alnum": unique_alnum.to_ascii_lowercase(), "unique_upper_alnum": unique_alnum.to_ascii_uppercase(), "unique_hash": digest(unique)[..16], - "now": now, + "now": frozen_time, }); } @@ -114,12 +190,12 @@ pub async fn after_scenario( #[given(expr = "a valid \"apiKeyAuth\" key in the system")] fn valid_apikey_auth(world: &mut DatadogWorld) { - world.config.api_key_auth = std::env::var("DD_TEST_CLIENT_API_KEY").ok(); + world.config.api_key_auth = env::var("DD_TEST_CLIENT_API_KEY").ok(); } #[given(expr = "a valid \"appKeyAuth\" key in the system")] fn valid_appkey_auth(world: &mut DatadogWorld) { - world.config.app_key_auth = std::env::var("DD_TEST_CLIENT_APP_KEY").ok(); + world.config.app_key_auth = env::var("DD_TEST_CLIENT_APP_KEY").ok(); } #[given(expr = "an instance of {string} API")] @@ -169,9 +245,7 @@ fn given_resource_in_system(world: &mut DatadogWorld, given_key: String) { world.function_mappings.get(&operation_id).unwrap()(world, &given_parameters); match build_undo(world, &operation_id) { - Ok(Some(undo)) => { - world.undo_operations.push(undo); - } + Ok(Some(undo)) => world.undo_operations.push(undo), Ok(None) => {} Err(err) => panic!("{err}"), } @@ -256,7 +330,6 @@ fn lookup(path: &String, object: &Value) -> Option { for (_, [idx]) in index_re.captures_iter(&json_pointer.clone()).map(|c| c.extract()) { json_pointer = index_re.replace(&json_pointer, format!("/{idx}")).to_string(); } - return object.pointer(&json_pointer).cloned(); } diff --git a/tests/scenarios/function_mappings.rs b/tests/scenarios/function_mappings.rs index 6e1640c19..7b15f202d 100644 --- a/tests/scenarios/function_mappings.rs +++ b/tests/scenarios/function_mappings.rs @@ -20,7 +20,7 @@ pub fn initialize_api_instance(world: &mut DatadogWorld, api: String) { Some(FastlyIntegrationAPI::with_config(world.config.clone())); } } - _ => panic!("'{api}' API instance tag not found"), + _ => panic!("{api} API instance not found"), } } @@ -67,10 +67,8 @@ fn test_list_fastly_accounts(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -91,10 +89,8 @@ fn test_create_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -115,10 +111,8 @@ fn test_delete_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -139,10 +133,8 @@ fn test_get_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -164,10 +156,8 @@ fn test_update_fastly_account(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -188,10 +178,8 @@ fn test_list_fastly_services(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -213,10 +201,8 @@ fn test_create_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -238,10 +224,8 @@ fn test_delete_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -263,10 +247,8 @@ fn test_get_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; @@ -289,10 +271,8 @@ fn test_update_fastly_service(world: &mut DatadogWorld, _parameters: &HashMap response, Err(error) => { return match error { - Error::Reqwest(e) => panic!("reqwest error: {}", e), - Error::Serde(e) => panic!("serde error: {}", e), - Error::Io(e) => panic!("io error: {}", e), Error::ResponseError(e) => world.response.code = e.status.as_u16(), + _ => panic!("error parsing response: {}", error), }; } }; From c0b8f5ca28b4eeef82af68cf55b8535e2ded6428 Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Wed, 25 Oct 2023 14:45:40 -0400 Subject: [PATCH 06/10] replace some unwraps with descriptive errors --- tests/scenarios/fixtures.rs | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/tests/scenarios/fixtures.rs b/tests/scenarios/fixtures.rs index 61e0aa9d2..a0ecc03cb 100644 --- a/tests/scenarios/fixtures.rs +++ b/tests/scenarios/fixtures.rs @@ -53,7 +53,7 @@ pub struct DatadogWorld { } pub async fn before_scenario(feature: &Feature, _rule: Option<&Rule>, scenario: &Scenario, world: &mut DatadogWorld) { - let api_version_re = Regex::new(r"tests/scenarios/features/v(\d+)/").unwrap(); + let api_version_re = Regex::new(r"tests/scenarios/features/v(\d+)/").expect("api version regex failed"); // TODO: refactor this lol world.api_version = api_version_re .captures(feature.path.as_ref().unwrap().to_str().unwrap()) @@ -65,12 +65,14 @@ pub async fn before_scenario(feature: &Feature, _rule: Option<&Rule>, scenario: .unwrap(); collect_function_calls(world); - let given_file = File::open(format!("tests/scenarios/features/v{}/given.json", world.api_version)).unwrap(); - world.given_map = serde_json::from_reader(BufReader::new(given_file)).unwrap(); - let undo_file = File::open(format!("tests/scenarios/features/v{}/undo.json", world.api_version)).unwrap(); - world.undo_map = serde_json::from_reader(BufReader::new(undo_file)).unwrap(); + let given_file = File::open(format!("tests/scenarios/features/v{}/given.json", world.api_version)) + .expect("failed to open given.json file"); + world.given_map = serde_json::from_reader(BufReader::new(given_file)).expect("failed to deserialize given.json"); + let undo_file = File::open(format!("tests/scenarios/features/v{}/undo.json", world.api_version)) + .expect("failed to open undo.json file"); + world.undo_map = serde_json::from_reader(BufReader::new(undo_file)).expect("failed to deserialize undo.json"); - let non_alnum_re = Regex::new(r"[^A-Za-z0-9]+").unwrap(); + let non_alnum_re = Regex::new(r"[^A-Za-z0-9]+").expect("non alnum regex failed"); let escaped_filename = non_alnum_re.replace_all(scenario.name.as_str(), "-").to_string(); let filename = match escaped_filename.len() > 100 { true => escaped_filename[..100].to_string(), @@ -183,7 +185,10 @@ pub async fn after_scenario( ) { if let Some(world) = world { for undo in world.undo_operations.clone().iter().rev() { - world.function_mappings.get(&undo.operation_id).unwrap()(world, &undo.parameters); + world + .function_mappings + .get(&undo.operation_id) + .expect("undo operation not found")(world, &undo.parameters); } } } @@ -243,7 +248,10 @@ fn given_resource_in_system(world: &mut DatadogWorld, given_key: String) { .expect("failed to parse given operation id as str") .to_string(); - world.function_mappings.get(&operation_id).unwrap()(world, &given_parameters); + world + .function_mappings + .get(&operation_id) + .expect("given operation not found")(world, &given_parameters); match build_undo(world, &operation_id) { Ok(Some(undo)) => world.undo_operations.push(undo), Ok(None) => {} @@ -295,7 +303,10 @@ fn request_parameter_with_value(world: &mut DatadogWorld, param: String, value: #[when(regex = r"^the request is sent$")] fn request_sent(world: &mut DatadogWorld) { - world.function_mappings.get(&world.operation_id).unwrap()(world, &world.parameters.clone()); + world + .function_mappings + .get(&world.operation_id) + .expect("request operation not found")(world, &world.parameters.clone()); match build_undo(world, &world.operation_id.clone()) { Ok(Some(undo)) => { world.undo_operations.push(undo); @@ -312,7 +323,7 @@ fn response_status_is(world: &mut DatadogWorld, status_code: u16, _status_messag #[then(expr = "the response {string} is equal to {}")] fn response_equal_to(world: &mut DatadogWorld, path: String, value: String) { - let lookup = lookup(&path, &world.response.object).unwrap(); + let lookup = lookup(&path, &world.response.object).expect("value not found in response"); let rendered_value = template(value, &world.fixtures); let expected: Value = serde_json::from_str(rendered_value.as_str()).unwrap(); assert_eq!(lookup, expected); @@ -325,7 +336,7 @@ fn response_has_length(world: &mut DatadogWorld, path: String, expected_len: usi } fn lookup(path: &String, object: &Value) -> Option { - let index_re = Regex::new(r"\[(\d+)\]+").unwrap(); + let index_re = Regex::new(r"\[(\d+)\]+").expect("index regex failed"); let mut json_pointer = format!("/{}", path).replace('.', "/"); for (_, [idx]) in index_re.captures_iter(&json_pointer.clone()).map(|c| c.extract()) { json_pointer = index_re.replace(&json_pointer, format!("/{idx}")).to_string(); @@ -334,7 +345,9 @@ fn lookup(path: &String, object: &Value) -> Option { } fn template(string: String, fixtures: &Value) -> String { - Handlebars::new().render_template(string.as_str(), &fixtures).unwrap() + Handlebars::new() + .render_template(string.as_str(), &fixtures) + .expect("failed to apply template") } fn build_undo(world: &mut DatadogWorld, operation_id: &String) -> Result, Value> { From 5660e12280e80d88a0859bd0bbb48442dca6b053 Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Wed, 25 Oct 2023 15:20:23 -0400 Subject: [PATCH 07/10] add transformed cassettes --- ...stly-account-returns-CREATED-response.json | 67 ------------ ...et-Fastly-account-returns-OK-response.json | 95 ---------------- ...t-Fastly-accounts-returns-OK-response.json | 95 ---------------- ...te-Fastly-account-returns-OK-response.json | 101 ------------------ ...ly-account-returns-CREATED-response.frozen | 0 ...stly-account-returns-CREATED-response.json | 1 + ...-Fastly-account-returns-OK-response.frozen | 0 ...et-Fastly-account-returns-OK-response.json | 1 + ...Fastly-accounts-returns-OK-response.frozen | 0 ...t-Fastly-accounts-returns-OK-response.json | 1 + ...-Fastly-account-returns-OK-response.frozen | 0 ...te-Fastly-account-returns-OK-response.json | 1 + tests/scenarios/fixtures.rs | 4 +- 13 files changed, 6 insertions(+), 360 deletions(-) delete mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json delete mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json delete mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json delete mode 100644 tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json rename tests/scenarios/cassettes/v2/{Feature_Fastly_Integration => fastly_integration}/Add-Fastly-account-returns-CREATED-response.frozen (100%) create mode 100644 tests/scenarios/cassettes/v2/fastly_integration/Add-Fastly-account-returns-CREATED-response.json rename tests/scenarios/cassettes/v2/{Feature_Fastly_Integration => fastly_integration}/Get-Fastly-account-returns-OK-response.frozen (100%) create mode 100644 tests/scenarios/cassettes/v2/fastly_integration/Get-Fastly-account-returns-OK-response.json rename tests/scenarios/cassettes/v2/{Feature_Fastly_Integration => fastly_integration}/List-Fastly-accounts-returns-OK-response.frozen (100%) create mode 100644 tests/scenarios/cassettes/v2/fastly_integration/List-Fastly-accounts-returns-OK-response.json rename tests/scenarios/cassettes/v2/{Feature_Fastly_Integration => fastly_integration}/Update-Fastly-account-returns-OK-response.frozen (100%) create mode 100644 tests/scenarios/cassettes/v2/fastly_integration/Update-Fastly-account-returns-OK-response.json diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json deleted file mode 100644 index 0affacb28..000000000 --- a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "http_interactions": [ - { - "recorded_at": "Thu, 19 Jan 2023 15:15:56 GMT", - "request": { - "body": { - "encoding": null, - "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestAddFastlyaccountreturnsCREATEDresponse1674141356\",\"name\":\"Test-Add_Fastly_account_returns_CREATED_response-1674141356\",\"services\":[]},\"type\":\"fastly-accounts\"}}" - }, - "headers": { - "Accept": [ - "application/json" - ], - "Content-Type": [ - "application/json" - ] - }, - "method": "post", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":{\"attributes\":{\"services\":[],\"name\":\"Test-Add_Fastly_account_returns_CREATED_response-1674141356\"},\"type\":\"fastly-accounts\",\"id\":\"0427b05b6f56f454ca1477aa8df5e75d\"}}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 201, - "message": "Created" - } - } - }, - { - "recorded_at": "Thu, 19 Jan 2023 15:15:56 GMT", - "request": { - "body": "", - "headers": { - "Accept": [ - "*/*" - ] - }, - "method": "delete", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/0427b05b6f56f454ca1477aa8df5e75d" - }, - "response": { - "body": { - "encoding": null, - "string": "" - }, - "headers": { - "Content-Type": [ - "text/html; charset=utf-8" - ] - }, - "status": { - "code": 204, - "message": "No Content" - } - } - } - ], - "recorded_with": "VCR 6.0.0" -} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json deleted file mode 100644 index d3c4aaef2..000000000 --- a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "http_interactions": [ - { - "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT", - "request": { - "body": { - "encoding": null, - "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestGetFastlyaccountreturnsOKresponse1678702274\",\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\",\"services\":[]},\"type\":\"fastly-accounts\"}}" - }, - "headers": { - "Accept": [ - "application/json" - ], - "Content-Type": [ - "application/json" - ] - }, - "method": "post", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"6d8f2860f9f3e953fb46d554b9a19627\",\"attributes\":{\"services\":[],\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\"}}}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 201, - "message": "Created" - } - } - }, - { - "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT", - "request": { - "body": "", - "headers": { - "Accept": [ - "application/json" - ] - }, - "method": "get", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/6d8f2860f9f3e953fb46d554b9a19627" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"6d8f2860f9f3e953fb46d554b9a19627\",\"attributes\":{\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\",\"services\":[]}}}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 200, - "message": "OK" - } - } - }, - { - "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT", - "request": { - "body": "", - "headers": { - "Accept": [ - "*/*" - ] - }, - "method": "delete", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/6d8f2860f9f3e953fb46d554b9a19627" - }, - "response": { - "body": { - "encoding": null, - "string": "" - }, - "headers": { - "Content-Type": [ - "text/html; charset=utf-8" - ] - }, - "status": { - "code": 204, - "message": "No Content" - } - } - } - ], - "recorded_with": "VCR 6.0.0" -} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json deleted file mode 100644 index 622732efb..000000000 --- a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.json +++ /dev/null @@ -1,95 +0,0 @@ -{ - "http_interactions": [ - { - "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT", - "request": { - "body": { - "encoding": null, - "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestListFastlyaccountsreturnsOKresponse1678702250\",\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"type\":\"fastly-accounts\"}}" - }, - "headers": { - "Accept": [ - "application/json" - ], - "Content-Type": [ - "application/json" - ] - }, - "method": "post", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":{\"type\":\"fastly-accounts\",\"attributes\":{\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"id\":\"07ec97dd43cd794c847ecf15cb25eb1c\"}}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 201, - "message": "Created" - } - } - }, - { - "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT", - "request": { - "body": "", - "headers": { - "Accept": [ - "application/json" - ] - }, - "method": "get", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":[{\"type\":\"fastly-accounts\",\"attributes\":{\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"id\":\"07ec97dd43cd794c847ecf15cb25eb1c\"}]}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 200, - "message": "OK" - } - } - }, - { - "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT", - "request": { - "body": "", - "headers": { - "Accept": [ - "*/*" - ] - }, - "method": "delete", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/07ec97dd43cd794c847ecf15cb25eb1c" - }, - "response": { - "body": { - "encoding": null, - "string": "" - }, - "headers": { - "Content-Type": [ - "text/html; charset=utf-8" - ] - }, - "status": { - "code": 204, - "message": "No Content" - } - } - } - ], - "recorded_with": "VCR 6.0.0" -} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json b/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json deleted file mode 100644 index 74a2bd6f1..000000000 --- a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "http_interactions": [ - { - "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT", - "request": { - "body": { - "encoding": null, - "string": "{\"data\":{\"attributes\":{\"api_key\":\"TestUpdateFastlyaccountreturnsOKresponse1678702217\",\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\",\"services\":[]},\"type\":\"fastly-accounts\"}}" - }, - "headers": { - "Accept": [ - "application/json" - ], - "Content-Type": [ - "application/json" - ] - }, - "method": "post", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"e37e834ae856fa24a2924973fdc7c276\",\"attributes\":{\"services\":[],\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\"}}}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 201, - "message": "Created" - } - } - }, - { - "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT", - "request": { - "body": { - "encoding": null, - "string": "{\"data\":{\"attributes\":{\"api_key\":\"update-secret\"},\"type\":\"fastly-accounts\"}}" - }, - "headers": { - "Accept": [ - "application/json" - ], - "Content-Type": [ - "application/json" - ] - }, - "method": "patch", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/e37e834ae856fa24a2924973fdc7c276" - }, - "response": { - "body": { - "encoding": null, - "string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"e37e834ae856fa24a2924973fdc7c276\",\"attributes\":{\"services\":[],\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\"}}}\n" - }, - "headers": { - "Content-Type": [ - "application/json" - ] - }, - "status": { - "code": 200, - "message": "OK" - } - } - }, - { - "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT", - "request": { - "body": "", - "headers": { - "Accept": [ - "*/*" - ] - }, - "method": "delete", - "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/e37e834ae856fa24a2924973fdc7c276" - }, - "response": { - "body": { - "encoding": null, - "string": "" - }, - "headers": { - "Content-Type": [ - "text/html; charset=utf-8" - ] - }, - "status": { - "code": 204, - "message": "No Content" - } - } - } - ], - "recorded_with": "VCR 6.0.0" -} diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.frozen b/tests/scenarios/cassettes/v2/fastly_integration/Add-Fastly-account-returns-CREATED-response.frozen similarity index 100% rename from tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Add-Fastly-account-returns-CREATED-response.frozen rename to tests/scenarios/cassettes/v2/fastly_integration/Add-Fastly-account-returns-CREATED-response.frozen diff --git a/tests/scenarios/cassettes/v2/fastly_integration/Add-Fastly-account-returns-CREATED-response.json b/tests/scenarios/cassettes/v2/fastly_integration/Add-Fastly-account-returns-CREATED-response.json new file mode 100644 index 000000000..fa365e20b --- /dev/null +++ b/tests/scenarios/cassettes/v2/fastly_integration/Add-Fastly-account-returns-CREATED-response.json @@ -0,0 +1 @@ +{"http_interactions": [{"request": {"body": {"string": "{\"data\":{\"attributes\":{\"api_key\":\"TestAddFastlyaccountreturnsCREATEDresponse1674141356\",\"name\":\"Test-Add_Fastly_account_returns_CREATED_response-1674141356\",\"services\":[]},\"type\":\"fastly-accounts\"}}", "encoding": null}, "headers": {"Accept": ["application/json"], "Content-Type": ["application/json"]}, "method": "post", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts"}, "response": {"body": {"string": "{\"data\":{\"attributes\":{\"services\":[],\"name\":\"Test-Add_Fastly_account_returns_CREATED_response-1674141356\"},\"type\":\"fastly-accounts\",\"id\":\"0427b05b6f56f454ca1477aa8df5e75d\"}}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 201, "message": "Created"}}, "recorded_at": "Thu, 19 Jan 2023 15:15:56 GMT"}, {"request": {"body": "", "headers": {"Accept": ["*/*"]}, "method": "delete", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/0427b05b6f56f454ca1477aa8df5e75d"}, "response": {"body": {"string": "", "encoding": null}, "headers": {"Content-Type": ["text/html; charset=utf-8"]}, "status": {"code": 204, "message": "No Content"}}, "recorded_at": "Thu, 19 Jan 2023 15:15:56 GMT"}], "recorded_with": "VCR 6.0.0"} \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.frozen b/tests/scenarios/cassettes/v2/fastly_integration/Get-Fastly-account-returns-OK-response.frozen similarity index 100% rename from tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Get-Fastly-account-returns-OK-response.frozen rename to tests/scenarios/cassettes/v2/fastly_integration/Get-Fastly-account-returns-OK-response.frozen diff --git a/tests/scenarios/cassettes/v2/fastly_integration/Get-Fastly-account-returns-OK-response.json b/tests/scenarios/cassettes/v2/fastly_integration/Get-Fastly-account-returns-OK-response.json new file mode 100644 index 000000000..1af728d7a --- /dev/null +++ b/tests/scenarios/cassettes/v2/fastly_integration/Get-Fastly-account-returns-OK-response.json @@ -0,0 +1 @@ +{"http_interactions": [{"request": {"body": {"string": "{\"data\":{\"attributes\":{\"api_key\":\"TestGetFastlyaccountreturnsOKresponse1678702274\",\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\",\"services\":[]},\"type\":\"fastly-accounts\"}}", "encoding": null}, "headers": {"Accept": ["application/json"], "Content-Type": ["application/json"]}, "method": "post", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts"}, "response": {"body": {"string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"6d8f2860f9f3e953fb46d554b9a19627\",\"attributes\":{\"services\":[],\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\"}}}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 201, "message": "Created"}}, "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT"}, {"request": {"body": "", "headers": {"Accept": ["application/json"]}, "method": "get", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/6d8f2860f9f3e953fb46d554b9a19627"}, "response": {"body": {"string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"6d8f2860f9f3e953fb46d554b9a19627\",\"attributes\":{\"name\":\"Test-Get_Fastly_account_returns_OK_response-1678702274\",\"services\":[]}}}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT"}, {"request": {"body": "", "headers": {"Accept": ["*/*"]}, "method": "delete", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/6d8f2860f9f3e953fb46d554b9a19627"}, "response": {"body": {"string": "", "encoding": null}, "headers": {"Content-Type": ["text/html; charset=utf-8"]}, "status": {"code": 204, "message": "No Content"}}, "recorded_at": "Mon, 13 Mar 2023 10:11:14 GMT"}], "recorded_with": "VCR 6.0.0"} \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.frozen b/tests/scenarios/cassettes/v2/fastly_integration/List-Fastly-accounts-returns-OK-response.frozen similarity index 100% rename from tests/scenarios/cassettes/v2/Feature_Fastly_Integration/List-Fastly-accounts-returns-OK-response.frozen rename to tests/scenarios/cassettes/v2/fastly_integration/List-Fastly-accounts-returns-OK-response.frozen diff --git a/tests/scenarios/cassettes/v2/fastly_integration/List-Fastly-accounts-returns-OK-response.json b/tests/scenarios/cassettes/v2/fastly_integration/List-Fastly-accounts-returns-OK-response.json new file mode 100644 index 000000000..e322e188a --- /dev/null +++ b/tests/scenarios/cassettes/v2/fastly_integration/List-Fastly-accounts-returns-OK-response.json @@ -0,0 +1 @@ +{"http_interactions": [{"request": {"body": {"string": "{\"data\":{\"attributes\":{\"api_key\":\"TestListFastlyaccountsreturnsOKresponse1678702250\",\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"type\":\"fastly-accounts\"}}", "encoding": null}, "headers": {"Accept": ["application/json"], "Content-Type": ["application/json"]}, "method": "post", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts"}, "response": {"body": {"string": "{\"data\":{\"type\":\"fastly-accounts\",\"attributes\":{\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"id\":\"07ec97dd43cd794c847ecf15cb25eb1c\"}}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 201, "message": "Created"}}, "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT"}, {"request": {"body": "", "headers": {"Accept": ["application/json"]}, "method": "get", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts"}, "response": {"body": {"string": "{\"data\":[{\"type\":\"fastly-accounts\",\"attributes\":{\"name\":\"Test-List_Fastly_accounts_returns_OK_response-1678702250\",\"services\":[]},\"id\":\"07ec97dd43cd794c847ecf15cb25eb1c\"}]}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT"}, {"request": {"body": "", "headers": {"Accept": ["*/*"]}, "method": "delete", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/07ec97dd43cd794c847ecf15cb25eb1c"}, "response": {"body": {"string": "", "encoding": null}, "headers": {"Content-Type": ["text/html; charset=utf-8"]}, "status": {"code": 204, "message": "No Content"}}, "recorded_at": "Mon, 13 Mar 2023 10:10:50 GMT"}], "recorded_with": "VCR 6.0.0"} \ No newline at end of file diff --git a/tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.frozen b/tests/scenarios/cassettes/v2/fastly_integration/Update-Fastly-account-returns-OK-response.frozen similarity index 100% rename from tests/scenarios/cassettes/v2/Feature_Fastly_Integration/Update-Fastly-account-returns-OK-response.frozen rename to tests/scenarios/cassettes/v2/fastly_integration/Update-Fastly-account-returns-OK-response.frozen diff --git a/tests/scenarios/cassettes/v2/fastly_integration/Update-Fastly-account-returns-OK-response.json b/tests/scenarios/cassettes/v2/fastly_integration/Update-Fastly-account-returns-OK-response.json new file mode 100644 index 000000000..f7b1c27d3 --- /dev/null +++ b/tests/scenarios/cassettes/v2/fastly_integration/Update-Fastly-account-returns-OK-response.json @@ -0,0 +1 @@ +{"http_interactions": [{"request": {"body": {"string": "{\"data\":{\"attributes\":{\"api_key\":\"TestUpdateFastlyaccountreturnsOKresponse1678702217\",\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\",\"services\":[]},\"type\":\"fastly-accounts\"}}", "encoding": null}, "headers": {"Accept": ["application/json"], "Content-Type": ["application/json"]}, "method": "post", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts"}, "response": {"body": {"string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"e37e834ae856fa24a2924973fdc7c276\",\"attributes\":{\"services\":[],\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\"}}}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 201, "message": "Created"}}, "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT"}, {"request": {"body": {"string": "{\"data\":{\"attributes\":{\"api_key\":\"update-secret\"},\"type\":\"fastly-accounts\"}}", "encoding": null}, "headers": {"Accept": ["application/json"], "Content-Type": ["application/json"]}, "method": "patch", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/e37e834ae856fa24a2924973fdc7c276"}, "response": {"body": {"string": "{\"data\":{\"type\":\"fastly-accounts\",\"id\":\"e37e834ae856fa24a2924973fdc7c276\",\"attributes\":{\"services\":[],\"name\":\"Test-Update_Fastly_account_returns_OK_response-1678702217\"}}}\n", "encoding": null}, "headers": {"Content-Type": ["application/json"]}, "status": {"code": 200, "message": "OK"}}, "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT"}, {"request": {"body": "", "headers": {"Accept": ["*/*"]}, "method": "delete", "uri": "https://api.datadoghq.com/api/v2/integrations/fastly/accounts/e37e834ae856fa24a2924973fdc7c276"}, "response": {"body": {"string": "", "encoding": null}, "headers": {"Content-Type": ["text/html; charset=utf-8"]}, "status": {"code": 204, "message": "No Content"}}, "recorded_at": "Mon, 13 Mar 2023 10:10:17 GMT"}], "recorded_with": "VCR 6.0.0"} \ No newline at end of file diff --git a/tests/scenarios/fixtures.rs b/tests/scenarios/fixtures.rs index a0ecc03cb..fd7869500 100644 --- a/tests/scenarios/fixtures.rs +++ b/tests/scenarios/fixtures.rs @@ -81,9 +81,9 @@ pub async fn before_scenario(feature: &Feature, _rule: Option<&Rule>, scenario: let mut prefix = "Test".to_string(); let mut cassette_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); cassette_dir.push(format!( - "tests/scenarios/cassettes/v{}/Feature_{}", + "tests/scenarios/cassettes/v{}/{}", world.api_version, - feature.name.replace(' ', "_") + feature.name.replace(' ', "_").to_lowercase() )); create_dir_all(&cassette_dir).expect("failed to create cassette directory"); let mut cassette = cassette_dir.clone(); From 4b768de7d8617704f0bbe8d45bc69fd4f9d97854 Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Thu, 2 Nov 2023 15:19:15 -0400 Subject: [PATCH 08/10] fix typo and update git hash of rvcr fork --- Cargo.toml | 2 +- tests/scenarios/fixtures.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index f8033f0e2..84c3561c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ handlebars = "4.4.0" regex = "1.9.5" sha256 = "1.4.0" futures = "0.3.28" -rvcr = { git = "https://github.com/nkzou/rvcr.git", rev = "a3fc79e" } +rvcr = { git = "https://github.com/nkzou/rvcr.git", rev = "b8f84bc0dfacd539fdc6f7446637c6276dcbb57c" } chrono = "0.4.31" [[test]] diff --git a/tests/scenarios/fixtures.rs b/tests/scenarios/fixtures.rs index fd7869500..d4eaa3cee 100644 --- a/tests/scenarios/fixtures.rs +++ b/tests/scenarios/fixtures.rs @@ -166,7 +166,7 @@ pub async fn before_scenario(feature: &Feature, _rule: Option<&Rule>, scenario: let unique_alnum = non_alnum_re.replace_all(unique.as_str(), "").to_string(); world.fixtures = json!({ "unique": unique, - "unique_lowe: Stringr": unique.to_ascii_lowercase(), + "unique_lower": unique.to_ascii_lowercase(), "unique_upper": unique.to_ascii_uppercase(), "unique_alnum": unique_alnum, "unique_lower_alnum": unique_alnum.to_ascii_lowercase(), @@ -283,7 +283,7 @@ fn body_with_value(world: &mut DatadogWorld, body: String) { #[given(regex = r"^body from file (.*)$")] fn body_from_file(world: &mut DatadogWorld, path: String) { - let body = read_to_string(format!("tests/scenarios/features/v{}/{}", world.api_version, path,)).unwrap(); + let body = read_to_string(format!("tests/scenarios/features/v{}/{}", world.api_version, path)).unwrap(); let rendered = template(body, &world.fixtures); let body_struct = serde_json::from_str(rendered.as_str()).unwrap(); world.parameters.insert("body".to_string(), body_struct); From de1cf921cb5380f6d7fd33fc7743f8951567e4bb Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Thu, 2 Nov 2023 15:31:45 -0400 Subject: [PATCH 09/10] sort cargo toml file --- Cargo.toml | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 84c3561c0..e3b95da9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,35 +3,34 @@ name = "datadog-api-client" version = "1.0.0" authors = ["support@datadoghq.com"] description = "Collection of all Datadog Public endpoints." -# Override this license by providing a License Object in the OpenAPI. license = "Apache-2.0" edition = "2021" [dependencies] +log = "0.4.20" +reqwest-middleware = "0.1.6" +rustc_version = "0.4.0" serde = "^1.0" serde_derive = "^1.0" -serde_with = "^2.0" serde_json = "^1.0" +serde_with = "^2.0" url = "^2.2" uuid = { version = "^1.0", features = ["serde"] } -rustc_version = "0.4.0" -log = "0.4.20" -reqwest-middleware = "0.1.6" [dependencies.reqwest] -version = "^0.11" features = ["json", "multipart"] +version = "^0.11" [dev-dependencies] +chrono = "0.4.31" cucumber = "0.19.1" env_logger = "0.10.0" -tokio = { version = "1.10", features = ["macros", "rt-multi-thread", "time"] } +futures = "0.3.28" handlebars = "4.4.0" regex = "1.9.5" -sha256 = "1.4.0" -futures = "0.3.28" rvcr = { git = "https://github.com/nkzou/rvcr.git", rev = "b8f84bc0dfacd539fdc6f7446637c6276dcbb57c" } -chrono = "0.4.31" +sha256 = "1.4.0" +tokio = { version = "1.10", features = ["macros", "rt-multi-thread", "time"] } [[test]] -name = "main" harness = false # allows Cucumber to print output instead of libtest +name = "main" From 7bf07ed12c3010cda74f14bcda8a090fa5c1cab4 Mon Sep 17 00:00:00 2001 From: Kevin Zou Date: Thu, 2 Nov 2023 15:47:29 -0400 Subject: [PATCH 10/10] refmt reqwest dependency --- Cargo.toml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e3b95da9c..6fcaaf3ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ edition = "2021" [dependencies] log = "0.4.20" +reqwest = { version = "^0.11", features = ["json", "multipart"] } reqwest-middleware = "0.1.6" rustc_version = "0.4.0" serde = "^1.0" @@ -15,10 +16,6 @@ serde_derive = "^1.0" serde_json = "^1.0" serde_with = "^2.0" url = "^2.2" -uuid = { version = "^1.0", features = ["serde"] } -[dependencies.reqwest] -features = ["json", "multipart"] -version = "^0.11" [dev-dependencies] chrono = "0.4.31"