Skip to content

Commit

Permalink
mutually exclusive test
Browse files Browse the repository at this point in the history
  • Loading branch information
TylerJang27 committed Dec 6, 2024
1 parent 00cd6bc commit 32bc6ef
Show file tree
Hide file tree
Showing 11 changed files with 263 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions cli-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ edition = "2021"
api = { path = "../api" }
assert_cmd = "2.0.16"
assert_matches = "1.5.0"
# Fork from 0.2.2 that adds serde serialize/deserialize via pbjson
bazel-bep = { git = "https://github.com/TylerJang27/bazel-bep.git", rev = "e51c546960067b9fe98ae35ae00bc53302973a9e" }
bundle = { path = "../bundle" }
chrono = "0.4.33"
codeowners = { path = "../codeowners" }
Expand Down
49 changes: 47 additions & 2 deletions cli-tests/src/upload.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::{fs, io::BufReader};

use crate::utils::{
generate_mock_codeowners, generate_mock_git_repo, generate_mock_valid_junit_xmls, CARGO_RUN,
generate_mock_bazel_bep, generate_mock_codeowners, generate_mock_git_repo,
generate_mock_valid_junit_xmls, CARGO_RUN,
};
use api::{
BundleUploadStatus, CreateRepoRequest, GetQuarantineBulkTestStatusRequest,
Expand All @@ -11,7 +12,7 @@ use assert_cmd::Command;
use assert_matches::assert_matches;
use bundle::{BundleMeta, FileSetType};
use codeowners::CodeOwners;
use context::repo::RepoUrlParts as Repo;
use context::{junit::parser::JunitParser, repo::RepoUrlParts as Repo};
use predicates::prelude::*;
use tempfile::tempdir;
use test_utils::mock_server::{MockServerBuilder, RequestPayload};
Expand Down Expand Up @@ -187,6 +188,50 @@ async fn upload_bundle() {
println!("{assert}");
}

#[tokio::test(flavor = "multi_thread")]
async fn upload_bundle_using_bep() {
let temp_dir = tempdir().unwrap();
generate_mock_git_repo(&temp_dir);
generate_mock_bazel_bep(&temp_dir);

let state = MockServerBuilder::new().spawn_mock_server().await;

let args = &[
"upload",
"--bazel-bep-path",
"./bep.json",
"--org-url-slug",
"test-org",
"--token",
"test-token",
];

let assert = Command::new(CARGO_RUN.path())
.current_dir(&temp_dir)
.env("TRUNK_PUBLIC_API_ADDRESS", &state.host)
.env("CI", "1")
.env("GITHUB_JOB", "test-job")
.args(args)
.assert()
.failure();

let requests = state.requests.lock().unwrap().clone();
assert_eq!(requests.len(), 5);

let tar_extract_directory = assert_matches!(&requests[3], RequestPayload::S3Upload(d) => d);

let file = fs::File::open(tar_extract_directory.join("junit/0")).unwrap();
let reader = BufReader::new(file);

// Uploaded file is a junit, even when using BEP
let mut junit_parser = JunitParser::new();
assert!(junit_parser.parse(reader).is_ok());
assert!(junit_parser.errors().is_empty());

// HINT: View CLI output with `cargo test -- --nocapture`
println!("{assert}");
}

#[tokio::test(flavor = "multi_thread")]
async fn upload_bundle_empty_junit_paths() {
let temp_dir = tempdir().unwrap();
Expand Down
35 changes: 33 additions & 2 deletions cli-tests/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use bazel_bep::types::build_event_stream::{
build_event::Payload, file::File::Uri, BuildEvent, File, TestResult,
};
use chrono::{TimeDelta, Utc};
use escargot::{CargoBuild, CargoRun};
use junit_mock::JunitMock;
Expand Down Expand Up @@ -26,15 +29,43 @@ pub fn generate_mock_git_repo<T: AsRef<Path>>(directory: T) {
setup_repo_with_commit(directory).unwrap();
}

pub fn generate_mock_valid_junit_xmls<T: AsRef<Path>>(directory: T) {
pub fn generate_mock_valid_junit_xmls<T: AsRef<Path>>(directory: T) -> Vec<PathBuf> {
let mut jm_options = junit_mock::Options::default();
jm_options.global.timestamp = Utc::now()
.fixed_offset()
.checked_sub_signed(TimeDelta::minutes(1));
let mut jm = JunitMock::new(junit_mock::Options::default());
let reports = jm.generate_reports();
jm.write_reports_to_file(directory.as_ref(), reports)
.unwrap();
.unwrap()
}

pub fn generate_mock_bazel_bep<T: AsRef<Path>>(directory: T) {
let mock_junits = generate_mock_valid_junit_xmls(&directory);

let build_events: Vec<BuildEvent> = mock_junits
.iter()
.map(|junit| {
let mut build_event = BuildEvent::default();
let mut payload = TestResult::default();
payload.test_action_output = vec![File {
name: junit.file_name().unwrap().to_str().unwrap().to_string(),
file: Some(Uri(junit.to_string_lossy().to_string())),
..Default::default()
}];
build_event.payload = Some(Payload::TestResult(payload));
build_event
})
.collect();

// bep JSON is a list of new-line separated JSON objects
let outputs_contents = build_events
.iter()
.map(|be| serde_json::to_string(be).unwrap())
.collect::<Vec<String>>()
.join("\n");
let mut file = fs::File::create(&directory.as_ref().join("bep.json")).unwrap();
file.write_all(outputs_contents.as_bytes()).unwrap();
}

pub fn generate_mock_invalid_junit_xmls<T: AsRef<Path>>(directory: T) {
Expand Down
14 changes: 14 additions & 0 deletions cli-tests/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,20 @@ fn validate_success() {
println!("{assert}");
}

#[test]
fn validate_junit_and_bep() {
let temp_dir = tempdir().unwrap();

let assert = Command::new(CARGO_RUN.path())
.current_dir(&temp_dir)
.args(&["validate", "--junit-paths", "./*", "--bazel-bep-path", "bep.json"])
.assert()
.failure()
.stderr(predicate::str::contains("the argument '--junit-paths <JUNIT_PATHS>' cannot be used with '--bazel-bep-path <BAZEL_BEP_PATH>'"));

println!("{assert}");
}

#[test]
fn validate_no_junits() {
let temp_dir = tempdir().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ async fn run_test(test_args: TestArgs) -> anyhow::Result<i32> {
)?;

if junit_paths.is_empty() && bazel_bep_path.is_none() {
return Err(anyhow::anyhow!("No junit or bazel BEP paths provided."));
return Err(anyhow::anyhow!("No junit paths provided."));
}

let api_client = ApiClient::new(String::from(token))?;
Expand Down
1 change: 0 additions & 1 deletion cli/src/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,6 @@ pub async fn run_upload(

log::info!("Total files pack and upload: {}", file_counter.get_count());
if file_counter.get_count() == 0 {
// DONOTLAND FIX LOG MESSAGE HERE
log::warn!(
"No JUnit files found to pack and upload using globs: {:?}",
junit_paths
Expand Down
56 changes: 56 additions & 0 deletions context/src/bazel_bep/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,59 @@ impl BazelBepParser {
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;

const SIMPLE_EXAMPLE: &str = "test_fixtures/bep_example";
const EMPTY_EXAMPLE: &str = "test_fixtures/bep_empty";
const PARTIAL_EXAMPLE: &str = "test_fixtures/bep_partially_valid";

fn get_test_file(file: &str) -> String {
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join(file)
.to_str()
.unwrap()
.to_string()
}

#[test]
fn test_parse_simple_bep() {
let input_file = get_test_file(SIMPLE_EXAMPLE);
let mut parser = BazelBepParser::new(input_file);
parser.parse().unwrap();

let empty_vec: Vec<String> = Vec::new();
assert_eq!(parser.xml_files(), vec!["/tmp/hello_test/test.xml"]);
assert_eq!(*parser.errors(), empty_vec);
}

#[test]
fn test_parse_empty_bep() {
let input_file = get_test_file(EMPTY_EXAMPLE);
let mut parser = BazelBepParser::new(input_file);
parser.parse().unwrap();

let empty_vec: Vec<String> = Vec::new();
assert_eq!(parser.xml_files(), empty_vec);
assert_eq!(*parser.errors(), empty_vec);
}

#[test]
fn test_parse_partial_bep() {
let input_file = get_test_file(PARTIAL_EXAMPLE);
let mut parser = BazelBepParser::new(input_file);
parser.parse().unwrap();

assert_eq!(
parser.xml_files(),
vec!["/tmp/hello_test/test.xml", "/tmp/client_test/test.xml"]
);
assert_eq!(
*parser.errors(),
vec!["Error parsing build event: EOF while parsing a value at line 108 column 0"]
);
}
}
1 change: 1 addition & 0 deletions context/test_fixtures/bep_empty
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions context/test_fixtures/bep_example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"id":{"testResult":{"label":"//trunk/hello_world/cc:hello_test","run":1,"shard":1,"attempt":1,"configuration":{"id":"505b27c8ff9839fd314110b87c91532df190ce138243ef37a6fd2ad06b7054e9"}}},"testResult":{"testActionOutput":[{"name":"test.log","uri":"file:///tmp/hello_test/test.log"},{"name":"test.xml","uri":"file:///tmp/hello_test/test.xml"}],"testAttemptDurationMillis":"153","status":"PASSED","testAttemptStartMillisEpoch":"1733171237474","executionInfo":{},"testAttemptStart":"2024-12-02T20:27:17.474Z","testAttemptDuration":"0.153s"}}
Loading

0 comments on commit 32bc6ef

Please sign in to comment.