Skip to content

Commit

Permalink
feat: Pass the test context values through to the ProviderStateGenera…
Browse files Browse the repository at this point in the history
…tor #69
  • Loading branch information
rholshausen committed Aug 7, 2024
1 parent 7e85d34 commit 6064316
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 12 deletions.
14 changes: 7 additions & 7 deletions src/dynamic_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::slice::Iter;
use anyhow::anyhow;
use bytes::{BufMut, Bytes};
use itertools::Itertools;
use maplit::hashmap;
use pact_models::generators::{
GenerateValue,
Generator,
Expand All @@ -19,6 +18,7 @@ use pact_models::path_exp::{DocPath, PathToken};
use pact_models::v4::sync_message::SynchronousMessage;
use prost::encoding::{encode_key, encode_varint, WireType};
use prost_types::{DescriptorProto, FileDescriptorSet};
use serde_json::Value;
use tonic::codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};
use tonic::Status;
use tracing::{debug, error, instrument, trace};
Expand Down Expand Up @@ -233,12 +233,12 @@ impl DynamicMessage {
pub fn apply_generators(
&mut self,
generators: Option<&HashMap<DocPath, Generator>>,
mode: &GeneratorTestMode
mode: &GeneratorTestMode,
context: &HashMap<&str, Value>
) -> anyhow::Result<()> {
if let Some(generators) = generators {
let variant_matcher = NoopVariantMatcher {};
let vm_boxed = variant_matcher.boxed();
let context = hashmap!{};

for (path, generator) in generators {
let value = self.fetch_value(&path);
Expand Down Expand Up @@ -455,7 +455,7 @@ mod tests {
path.clone() => RandomInt(1, 10)
};

expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider)).to(be_ok());
expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider, &hashmap!{})).to(be_ok());
}

#[test]
Expand All @@ -475,7 +475,7 @@ mod tests {
DocPath::new_unwrap("$.two") => RandomInt(1, 10)
};

expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider)).to(be_ok());
expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider, &hashmap!{})).to(be_ok());
}

#[test]
Expand All @@ -495,7 +495,7 @@ mod tests {
DocPath::new_unwrap("$.one") => RandomInt(1, 10)
};

expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider)).to(be_ok());
expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider, &hashmap!{})).to(be_ok());
expect!(message.fields[0].data.as_i64().unwrap()).to_not(be_equal_to(100));
}

Expand Down Expand Up @@ -550,7 +550,7 @@ mod tests {
path.clone() => RandomInt(1, 10)
};

expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider)).to(be_ok());
expect!(message.apply_generators(Some(&generators), &GeneratorTestMode::Provider, &hashmap!{})).to(be_ok());
expect!(message.fetch_value(&path).unwrap().data.as_i64().unwrap()).to_not(be_equal_to(100));
}
}
16 changes: 13 additions & 3 deletions src/message_decoder/generators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use pact_models::time_utils::{parse_pattern, to_chrono_pattern};
use rand::prelude::*;
use regex::{Captures, Regex};
use serde_json::Value;
use serde_json::Value::Object;
use tracing::{debug, instrument, warn};
use uuid::Uuid;

Expand Down Expand Up @@ -186,8 +187,16 @@ impl GenerateValue<ProtobufFieldData> for Generator {
_ => Err(anyhow!("Can not generate a boolean value for a field type {:?}", value))
}
},
Generator::ProviderStateGenerator(ref exp, ref dt) =>
match generate_value_from_context(exp, context, dt) {
Generator::ProviderStateGenerator(ref exp, ref dt) => {
let provider_state_config = if let Some(Object(psc)) = context.get("providerState") {
psc
.iter()
.map(|(k, v)| (k.as_str(), v.clone()))
.collect()
} else {
context.clone()
};
match generate_value_from_context(exp, &provider_state_config, dt) {
Ok(val) => match value {
ProtobufFieldData::String(_) => Ok(ProtobufFieldData::String(val.to_string())),
ProtobufFieldData::Boolean(_) => Ok(ProtobufFieldData::Boolean(bool::try_from(val)?)),
Expand All @@ -200,7 +209,8 @@ impl GenerateValue<ProtobufFieldData> for Generator {
_ => Err(anyhow!("Can not generate a value from the provider state for a field type {:?}", value))
},
Err(err) => Err(err)
},
}
}
Generator::MockServerURL(example, regex) => {
debug!("context = {:?}", context);
if let Some(mock_server_details) = context.get("mockServer") {
Expand Down
6 changes: 4 additions & 2 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ impl PactPlugin for ProtobufPactPlugin {
let mut raw_request_body = interaction.request.contents.value().unwrap_or_default();
let input_message_name = method_desc.input_type.clone().unwrap_or_default();
let input_message = match find_message_type_by_name(last_name(input_message_name.as_str()), &file_desc) {
Ok(message) => message.0,
Ok((message, _)) => message,
Err(err) => {
return Ok(Self::verification_preparation_error_response(err.to_string()))
}
Expand All @@ -748,9 +748,11 @@ impl PactPlugin for ProtobufPactPlugin {
let decoded_body = match decode_message(&mut raw_request_body, &input_message, &file_desc) {
Ok(message) => {
let mut message = DynamicMessage::new(&message, &file_desc);
let config = proto_struct_to_map(&request.config.clone().unwrap_or_default());
if let Err(err) = message.apply_generators(
interaction.request.generators.categories.get(&GeneratorCategory::BODY),
&GeneratorTestMode::Provider
&GeneratorTestMode::Provider,
&config.iter().map(|(k, v)| (k.as_str(), v.clone())).collect()
) {
return Ok(Self::verification_preparation_error_response(err.to_string()));
}
Expand Down

0 comments on commit 6064316

Please sign in to comment.