Skip to content

Commit

Permalink
add basic unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
Redent0r committed Feb 21, 2025
1 parent f4192ca commit e711e5f
Show file tree
Hide file tree
Showing 5 changed files with 2,494 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/agent/samples/policy/yaml/pod/pod-exec.yaml

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/agent/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ use tokio::{
mod rpc;
mod tracer;

#[cfg(feature = "agent-policy")]
// #[cfg(feature = "agent-policy")]
mod policy;

cfg_if! {
Expand Down
39 changes: 38 additions & 1 deletion src/agent/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,41 @@ struct MetadataResponse {
ops: Option<json_patch::Patch>,
}

#[cfg(test)]
mod tests {
use super::*; // Import the function and structs to be tested

#[tokio::test]
async fn test_allow_request() {
let mut policy = AgentPolicy::new();

let data =
std::fs::read_to_string("../tools/genpolicy/create.json").expect("Unable to read file");

let request: protocols::agent::CreateContainerRequest =
serde_json::from_str(&data).expect("JSON was not well-formatted");

let request = serde_json::to_string(&request).unwrap();
let ep = "CreateContainerRequest";

policy
.engine
.add_policy_from_file("../tools/genpolicy/exec2.rego")
.unwrap();

// Call the function
let result = policy.allow_request(ep, &request).await;
// let result = is_allowed_create_container_test(&request, &mut policy).await;
// Assert the expected result
match result {
Ok((allowed, _)) => assert!(allowed, "Expected the request to be allowed"),
Err(e) => panic!("Unexpected error: {:?}", e),
}

// assert!(false, "fail");
}
}

impl AgentPolicy {
/// Create AgentPolicy object.
pub fn new() -> Self {
Expand Down Expand Up @@ -201,10 +236,12 @@ impl AgentPolicy {
let results = self.engine.eval_query(query, false)?;

let prints = match self.engine.take_prints() {
Ok(p) => p.join(" "),
Ok(p) => p.join("\n"),
Err(e) => format!("Failed to get policy log: {e}"),
};

println!("Policy prints: {}", prints);

if results.result.len() != 1 {
// Results are empty when AllowRequestsFailingPolicy is used to allow a Request that hasn't been defined in the policy
if self.allow_failures {
Expand Down
Loading

0 comments on commit e711e5f

Please sign in to comment.