Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cassette record/replay/passthrough modes in bdd runner #4

Merged
merged 11 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .generator/src/generator/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
484 changes: 261 additions & 223 deletions .generator/src/generator/templates/api.j2

Large diffs are not rendered by default.

96 changes: 0 additions & 96 deletions .generator/src/generator/templates/api_mod.j2

This file was deleted.

9 changes: 9 additions & 0 deletions .generator/src/generator/templates/common_mod.j2
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub struct ResponseContent<T> {
#[derive(Debug)]
pub enum Error<T> {
Reqwest(reqwest::Error),
ReqwestMiddleware(reqwest_middleware::Error),
Serde(serde_json::Error),
Io(std::io::Error),
ResponseError(ResponseContent<T>),
Expand All @@ -20,6 +21,7 @@ impl <T> fmt::Display for Error<T> {
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)),
Expand All @@ -32,6 +34,7 @@ impl <T: fmt::Debug> error::Error for Error<T> {
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,
Expand All @@ -45,6 +48,12 @@ impl <T> From<reqwest::Error> for Error<T> {
}
}

impl<T> From<reqwest_middleware::Error> for Error<T> {
fn from(e: reqwest_middleware::Error) -> Self {
Error::ReqwestMiddleware(e)
}
}

impl <T> From<serde_json::Error> for Error<T> {
fn from(e: serde_json::Error) -> Self {
Error::Serde(e)
Expand Down
5 changes: 3 additions & 2 deletions .generator/src/generator/templates/configuration.j2
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::env;
pub struct Configuration {
pub base_path: String,
pub user_agent: Option<String>,
pub client: reqwest::Client,
pub client: reqwest_middleware::ClientWithMiddleware,
{%- set authMethods = openapi.security %}
{%- if authMethods %}
{%- for authMethod in authMethods %}
Expand All @@ -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!(
Expand All @@ -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 %}
Expand Down
46 changes: 38 additions & 8 deletions .generator/src/generator/templates/function_mappings.j2
Original file line number Diff line number Diff line change
Expand Up @@ -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() %}
Expand All @@ -26,27 +56,27 @@ 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<String, Value>) {
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::ResponseError(e) => world.response.code = e.status.as_u16(),
_ => panic!("error parsing response: {}", error),
};
}
};
Expand Down
10 changes: 7 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ repos:
pass_filenames: false
- id: lint
name: Lint
entry: cargo clippy
language: system
pass_filenames: false
stages: [manual]
- id: format
name: Format
language: rust
entry: cargo fmt
stages: [manual]
# files: '^api/.*\.go'
# types: ["file", "go"]
pass_filenames: false
stages: [manual]
- id: generator
name: generator
language: python
Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -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"
Expand Down
1 change: 1 addition & 0 deletions generate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ pre_commit_wrapper () {

rm -rf src/* examples/*
pre_commit_wrapper generator
pre_commit_wrapper format
pre_commit_wrapper lint
3 changes: 3 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
max_width = 120
edition = "2021"
use_small_heuristics = "Default"
5 changes: 3 additions & 2 deletions src/datadog/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::env;
pub struct Configuration {
pub base_path: String,
pub user_agent: Option<String>,
pub client: reqwest::Client,
pub client: reqwest_middleware::ClientWithMiddleware,
pub api_key_auth: Option<String>,
pub app_key_auth: Option<String>,
}
Expand All @@ -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!(
Expand All @@ -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(),
}
Expand Down
25 changes: 14 additions & 11 deletions src/datadog/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub struct ResponseContent<T> {
#[derive(Debug)]
pub enum Error<T> {
Reqwest(reqwest::Error),
ReqwestMiddleware(reqwest_middleware::Error),
Serde(serde_json::Error),
Io(std::io::Error),
ResponseError(ResponseContent<T>),
Expand All @@ -20,6 +21,7 @@ impl<T> fmt::Display for Error<T> {
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)),
Expand All @@ -32,6 +34,7 @@ impl<T: fmt::Debug> error::Error for Error<T> {
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,
Expand All @@ -45,6 +48,12 @@ impl<T> From<reqwest::Error> for Error<T> {
}
}

impl<T> From<reqwest_middleware::Error> for Error<T> {
fn from(e: reqwest_middleware::Error) -> Self {
Error::ReqwestMiddleware(e)
}
}

impl<T> From<serde_json::Error> for Error<T> {
fn from(e: serde_json::Error) -> Self {
Error::Serde(e)
Expand All @@ -67,21 +76,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())),
}
}
Expand Down
Loading