diff --git a/.github/actions/perform_gitlab_smoke_test/action.yaml b/.github/actions/perform_gitlab_smoke_test/action.yaml index c8d349b9..dfe144f8 100644 --- a/.github/actions/perform_gitlab_smoke_test/action.yaml +++ b/.github/actions/perform_gitlab_smoke_test/action.yaml @@ -42,10 +42,10 @@ runs: run: | ./${{ inputs.cli-binary-location }} test \ --org-url-slug trunk-staging-org \ - --test-collection-id z2dzjLHm \ --junit-paths "${{ github.workspace }}/target/**/*junit.xml" \ --token ${{ inputs.staging-api-token }} \ --repo-url https://gitlab.com/trunk-staging-org/analytics-cli-fake-gitlab/ \ + --test-collection-id z2dzjLHm \ cargo nextest run -p smoke-test --profile ci - name: Run tests on production @@ -95,10 +95,10 @@ runs: run: | ./${{ inputs.cli-binary-location }} upload \ --org-url-slug trunk-staging-org \ - --test-collection-id z2dzjLHm \ --junit-paths "${{ github.workspace }}/target/**/*junit.xml" \ --token ${{ inputs.staging-api-token }} \ - --repo-url https://gitlab.com/trunk-staging-org/analytics-cli-fake-gitlab/ + --repo-url https://gitlab.com/trunk-staging-org/analytics-cli-fake-gitlab/ \ + --test-collection-id z2dzjLHm - name: Upload to production if: inputs.environment-type == 'production' || inputs.environment-type == 'both' diff --git a/.github/actions/perform_smoke_test/action.yaml b/.github/actions/perform_smoke_test/action.yaml index 2d871fa9..129a14e5 100644 --- a/.github/actions/perform_smoke_test/action.yaml +++ b/.github/actions/perform_smoke_test/action.yaml @@ -57,9 +57,9 @@ runs: run: | ./${{ inputs.cli-binary-location }} test \ --org-url-slug trunk-staging-org \ - --test-collection-id z2dzjLHm \ --junit-paths "${{ github.workspace }}/target/**/*junit.xml" \ --token ${{ inputs.staging-api-token }} \ + --test-collection-id z2dzjLHm \ cargo nextest run -p smoke-test --profile ci - name: Run Swift tests @@ -123,8 +123,8 @@ runs: --token ${{ inputs.staging-api-token }} \ --test-collection-id Gtnr7BWl # analytics-cli-repo-wide: https://app.trunk-staging.io/trunk-staging-org/flaky-tests/collections/Gtnr7BWl/monitors - - name: Upload to staging with public repo id - id: staging-upload-public-repo-id + - name: Upload to staging from a forked pull request + id: staging-upload-forked-pr if: always() && steps.staging-test-run.outcome == 'success' && (inputs.environment-type == 'staging' || inputs.environment-type == 'both') env: TRUNK_PUBLIC_API_ADDRESS: https://api.trunk-staging.io @@ -132,14 +132,14 @@ runs: run: | ./${{ inputs.cli-binary-location }} upload \ --org-url-slug trunk-staging-org \ - --test-collection-id z2dzjLHm \ --junit-paths "${{ github.workspace }}/target/**/*junit.xml" \ - --public-repo-id NNSvcFXb \ + --allow-forked-pr-uploads \ --use-uncloned-repo \ --repo-url https://github.com/trunk-io/flake-farm-staging-fork-prs.git \ --repo-head-sha ${{ github.sha }} \ --repo-head-branch refs/heads/main \ - --repo-head-author-name "Trunk Smoke Test" + --repo-head-author-name "Trunk Smoke Test" \ + --test-collection-id z2dzjLHm # upload with variant should fail because we treat variant as a separate test - name: Upload to staging with variant @@ -171,9 +171,9 @@ runs: shell: bash run: | if [ "${{ inputs.test-variants }}" == "true" ]; then - echo "staging-success=${{ (steps.staging-upload.outcome == 'success' && steps.staging-upload-repo-wide.outcome == 'success' && steps.staging-upload-public-repo-id.outcome == 'success' && steps.staging-upload-with-variant.outcome == 'success' && (inputs.environment-type == 'staging' || inputs.environment-type == 'both')) || inputs.environment-type == 'production' }}" >> $GITHUB_OUTPUT + echo "staging-success=${{ (steps.staging-upload.outcome == 'success' && steps.staging-upload-repo-wide.outcome == 'success' && steps.staging-upload-forked-pr.outcome == 'success' && steps.staging-upload-with-variant.outcome == 'success' && (inputs.environment-type == 'staging' || inputs.environment-type == 'both')) || inputs.environment-type == 'production' }}" >> $GITHUB_OUTPUT else - echo "staging-success=${{ (steps.staging-upload.outcome == 'success' && steps.staging-upload-repo-wide.outcome == 'success' && steps.staging-upload-public-repo-id.outcome == 'success' && (inputs.environment-type == 'staging' || inputs.environment-type == 'both')) || inputs.environment-type == 'production' }}" >> $GITHUB_OUTPUT + echo "staging-success=${{ (steps.staging-upload.outcome == 'success' && steps.staging-upload-repo-wide.outcome == 'success' && steps.staging-upload-forked-pr.outcome == 'success' && (inputs.environment-type == 'staging' || inputs.environment-type == 'both')) || inputs.environment-type == 'production' }}" >> $GITHUB_OUTPUT fi - name: Run tests on production @@ -230,8 +230,8 @@ runs: --token ${{ inputs.production-api-token }} \ --test-collection-id 4B2wfoEU - - name: Upload to production with public repo id - id: production-upload-public-repo-id + - name: Upload to production from a forked pull request + id: production-upload-forked-pr if: always() && steps.production-test-run.outcome == 'success' && (inputs.environment-type == 'production' || inputs.environment-type == 'both') env: TRUNK_PUBLIC_API_ADDRESS: https://api.trunk.io @@ -240,7 +240,7 @@ runs: ./${{ inputs.cli-binary-location }} upload \ --org-url-slug trunk \ --junit-paths "${{ github.workspace }}/target/**/*junit.xml" \ - --public-repo-id ltT0aeMC \ + --allow-forked-pr-uploads \ --use-uncloned-repo \ --repo-url https://github.com/trunk-io/flake-farm-staging-fork-prs.git \ --repo-head-sha ${{ github.sha }} \ @@ -278,7 +278,7 @@ runs: shell: bash run: | if [ "${{ inputs.test-variants }}" == "true" ]; then - echo "production-success=${{ (steps.production-upload.outcome == 'success' && steps.production-upload-public-repo-id.outcome == 'success' && steps.production-upload-with-variant.outcome == 'success' && (inputs.environment-type == 'production' || inputs.environment-type == 'both')) || inputs.environment-type == 'staging' }}" >> $GITHUB_OUTPUT + echo "production-success=${{ (steps.production-upload.outcome == 'success' && steps.production-upload-forked-pr.outcome == 'success' && steps.production-upload-with-variant.outcome == 'success' && (inputs.environment-type == 'production' || inputs.environment-type == 'both')) || inputs.environment-type == 'staging' }}" >> $GITHUB_OUTPUT else - echo "production-success=${{ (steps.production-upload.outcome == 'success' && steps.production-upload-public-repo-id.outcome == 'success' && (inputs.environment-type == 'production' || inputs.environment-type == 'both')) || inputs.environment-type == 'staging' }}" >> $GITHUB_OUTPUT + echo "production-success=${{ (steps.production-upload.outcome == 'success' && steps.production-upload-forked-pr.outcome == 'success' && (inputs.environment-type == 'production' || inputs.environment-type == 'both')) || inputs.environment-type == 'staging' }}" >> $GITHUB_OUTPUT fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2cc6bf24..3fff7652 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,7 +52,7 @@ For detailed build instructions for each supported package, see their respective ```bash cargo build -./target/debug/trunk-analytics-cli upload --org-url-slug=trunk-io --token=${API_TOKEN} --junit-paths=junit.xml +./target/debug/trunk-analytics-cli upload --org-url-slug=trunk-io --token=${API_TOKEN} --test-collection-id=${TEST_COLLECTION_ID} --junit-paths=junit.xml ``` You can generate sample junit files by running diff --git a/api/src/client/mod.rs b/api/src/client/mod.rs index 1e2e6a4b..238a3220 100644 --- a/api/src/client/mod.rs +++ b/api/src/client/mod.rs @@ -56,7 +56,7 @@ pub struct ApiClient { /// Holds the run's v2 credential: an API token from the start, or a fork pull request's Trunk /// login once it has one. trunk_api_v2_client: Option, - /// `--allow-forked-pr-uploads` with no token and no public repo id. + /// `--allow-forked-pr-uploads` with no token. credential_free: bool, /// A credential-free GitHub Actions fork PR run, which on v2 swaps its `GITHUB_TOKEN` for a login. github_fork_pull_request: Option, @@ -130,27 +130,22 @@ impl ApiClient { // This should always be fast const TRUNK_TELEMETRY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1); const TRUNK_API_TOKEN_HEADER: &'static str = "x-api-token"; - const TRUNK_PUBLIC_REPO_ID_HEADER: &'static str = "x-trunk-public-repo-id"; const TRUNK_ALLOW_FORKED_PR_UPLOADS_HEADER: &'static str = "x-trunk-allow-forked-pr-uploads"; pub fn new( api_token: Option, - public_repo_id: Option, allow_forked_pr_uploads: bool, org_url_slug: impl AsRef, render_sender: Option>, ) -> anyhow::Result { let org_url_slug = String::from(org_url_slug.as_ref()); - // Either a secret API token or a non-secret public repo id authenticates the - // request. Fork PRs can't read repo secrets, so they rely on the public repo id. let api_token = api_token.filter(|token| !token.trim().is_empty()); - let public_repo_id = public_repo_id.filter(|id| !id.trim().is_empty()); // The forked-PR lane presents no credential at all on v1: the collection id already in // the request authorizes it, gated on that collection's opt-in server-side. - if api_token.is_none() && public_repo_id.is_none() && !allow_forked_pr_uploads { + if api_token.is_none() && !allow_forked_pr_uploads { return Err(anyhow::anyhow!( - "Either a Trunk API token, a public repo id, or --allow-forked-pr-uploads is required." + "Either a Trunk API token or --allow-forked-pr-uploads is required." )); } @@ -161,13 +156,6 @@ impl ApiClient { .map_err(|_| anyhow::Error::msg("Trunk API token is not ASCII")) }) .transpose()?; - let public_repo_id_header_value = public_repo_id - .as_deref() - .map(|id| { - HeaderValue::from_str(id) - .map_err(|_| anyhow::Error::msg("Trunk public repo id is not ASCII")) - }) - .transpose()?; let api_host = get_api_host(); tracing::debug!("Using public api address {}", api_host); @@ -193,12 +181,6 @@ impl ApiClient { trunk_api_client_default_headers .append(Self::TRUNK_API_TOKEN_HEADER, api_token_header_value); } - if let Some(public_repo_id_header_value) = public_repo_id_header_value { - trunk_api_client_default_headers.append( - Self::TRUNK_PUBLIC_REPO_ID_HEADER, - public_repo_id_header_value, - ); - } if allow_forked_pr_uploads { trunk_api_client_default_headers.append( Self::TRUNK_ALLOW_FORKED_PR_UPLOADS_HEADER, @@ -215,8 +197,7 @@ impl ApiClient { .clone() .map(|token| V2Credential::ApiKey(token).client()) .transpose()?; - let credential_free = - allow_forked_pr_uploads && api_token.is_none() && public_repo_id.is_none(); + let credential_free = allow_forked_pr_uploads && api_token.is_none(); let mut telemetry_client_default_headers = HeaderMap::new(); telemetry_client_default_headers.append( @@ -751,14 +732,8 @@ mod tests { let state = mock_server_builder.spawn_mock_server().await; - let mut api_client = ApiClient::new( - Some(String::from("mock-token")), - None, - false, - "mock-org", - None, - ) - .unwrap(); + let mut api_client = + ApiClient::new(Some(String::from("mock-token")), false, "mock-org", None).unwrap(); api_client.api_host.clone_from(&state.host); assert!( @@ -806,14 +781,8 @@ mod tests { let state = mock_server_builder.spawn_mock_server().await; - let mut api_client = ApiClient::new( - Some(String::from("mock-token")), - None, - false, - "mock-org", - None, - ) - .unwrap(); + let mut api_client = + ApiClient::new(Some(String::from("mock-token")), false, "mock-org", None).unwrap(); api_client.api_host.clone_from(&state.host); assert!( @@ -856,14 +825,8 @@ mod tests { let state = mock_server_builder.spawn_mock_server().await; - let mut api_client = ApiClient::new( - Some(String::from("mock-token")), - None, - false, - "mock-org", - None, - ) - .unwrap(); + let mut api_client = + ApiClient::new(Some(String::from("mock-token")), false, "mock-org", None).unwrap(); api_client.api_host.clone_from(&state.host); assert!( @@ -889,103 +852,19 @@ mod tests { } #[test] - fn requires_a_token_or_public_repo_id() { - // Neither credential is an error. - let err = ApiClient::new(None, None, false, "mock-org", None) + fn requires_a_token_or_allow_forked_pr_uploads() { + let err = ApiClient::new(None, false, "mock-org", None) .err() .expect("expected an error when no credentials are provided"); - assert!(err.to_string().contains( - "Either a Trunk API token, a public repo id, or --allow-forked-pr-uploads is required" - )); - - // Blank values are treated as absent. assert!( - ApiClient::new( - Some(String::from(" ")), - Some(String::from(" ")), - false, - "mock-org", - None - ) - .is_err() + err.to_string() + .contains("Either a Trunk API token or --allow-forked-pr-uploads is required") ); - // A token alone is sufficient - no public repo id required. - assert!(ApiClient::new(Some(String::from("token")), None, false, "mock-org", None).is_ok()); - - // A public repo id alone is sufficient - no token required. - assert!( - ApiClient::new( - None, - Some(String::from("public-repo-id")), - false, - "mock-org", - None - ) - .is_ok() - ); - } - - #[tokio::test(start_paused = true)] - async fn sends_public_repo_id_header_in_place_of_token() { - let mut mock_server_builder = MockServerBuilder::new(); - - lazy_static! { - static ref CAPTURED_HEADERS: Arc> = - Arc::new(Mutex::new(HeaderMap::new())); - } - - let quarantining_config_handler = move |headers: HeaderMap| async move { - *CAPTURED_HEADERS.lock().unwrap() = headers; - Response::builder() - .status(StatusCode::NOT_FOUND) - .body(String::from( - r#"{ "status_code": 404, "error": "not found" }"#, - )) - .unwrap() - }; - mock_server_builder.set_get_quarantining_config_handler(quarantining_config_handler); - - let state = mock_server_builder.spawn_mock_server().await; - - let mut api_client = ApiClient::new( - None, - Some(String::from("public-repo-id-123")), - false, - "mock-org", - None, - ) - .unwrap(); - api_client.api_host.clone_from(&state.host); - - // The call itself errors (404) - we only care about the headers it sent. - let _ = api_client - .get_quarantining_config(&message::GetQuarantineConfigRequest { - repo: context::repo::RepoUrlParts { - host: String::from("host"), - owner: String::from("owner"), - name: String::from("name"), - }, - org_url_slug: String::from("org_url_slug"), - test_identifiers: vec![], - remote_urls: vec![], - test_collection_short_id: None, - }) - .await; + // A blank token is treated as absent. + assert!(ApiClient::new(Some(String::from(" ")), false, "mock-org", None).is_err()); - let headers = CAPTURED_HEADERS.lock().unwrap(); - assert_eq!( - headers - .get(super::ApiClient::TRUNK_PUBLIC_REPO_ID_HEADER) - .and_then(|value| value.to_str().ok()), - Some("public-repo-id-123") - ); - assert!( - headers - .get(super::ApiClient::TRUNK_API_TOKEN_HEADER) - .is_none(), - "token header should be absent when only a public repo id is provided" - ); + assert!(ApiClient::new(Some(String::from("token")), false, "mock-org", None).is_ok()); } #[tokio::test] @@ -1010,7 +889,7 @@ mod tests { let state = mock_server_builder.spawn_mock_server().await; - let mut api_client = ApiClient::new(None, None, true, "mock-org", None).unwrap(); + let mut api_client = ApiClient::new(None, true, "mock-org", None).unwrap(); api_client.api_host.clone_from(&state.host); let _ = api_client @@ -1039,16 +918,13 @@ mod tests { assert!( headers .get(super::ApiClient::TRUNK_API_TOKEN_HEADER) - .is_none() - && headers - .get(super::ApiClient::TRUNK_PUBLIC_REPO_ID_HEADER) - .is_none(), + .is_none(), "no credential header should be sent on the forked-PR lane" ); } #[test] fn allow_forked_pr_uploads_satisfies_the_credential_requirement() { - assert!(ApiClient::new(None, None, true, "mock-org", None).is_ok()); + assert!(ApiClient::new(None, true, "mock-org", None).is_ok()); } } diff --git a/api/src/urls.rs b/api/src/urls.rs index eaad48b7..265f7e17 100644 --- a/api/src/urls.rs +++ b/api/src/urls.rs @@ -20,27 +20,21 @@ pub fn url_for_test_case( org_url_slug: &String, repo: &RepoUrlParts, test_case: &Test, - test_collection_short_id: Option<&str>, + test_collection_short_id: &str, guid_scope: Option<&TestCaseGuidScope>, ) -> Result { let mut url = Url::parse(convert_to_app_url(public_api_address).as_str())?; - let guid_path = match (test_collection_short_id, guid_scope) { - (Some(short_id), Some(ids)) => test_case_guid(ids, test_case) - .map(|guid| collection_test_guid_path(org_url_slug, short_id, &guid)), - _ => None, - }; - // No `?repo=`: the GUID resolves the whole identity tuple, unlike both short-link forms. + let guid_path = guid_scope + .and_then(|ids| test_case_guid(ids, test_case)) + .map(|guid| collection_test_guid_path(org_url_slug, test_collection_short_id, &guid)); + // No `?repo=`: the GUID resolves the whole identity tuple, unlike the short-link form. if let Some(path) = guid_path { url.set_path(path.as_str()); return Ok(url.to_string()); } - let path = match test_collection_short_id { - Some(short_id) => collection_test_path(org_url_slug, short_id, test_case), - None => test_path(org_url_slug, test_case), - }; - url.set_path(path.as_str()); + url.set_path(collection_test_path(org_url_slug, test_collection_short_id, test_case).as_str()); url.set_query(Some(repo_query(repo).as_str())); Ok(url.to_string()) } @@ -101,10 +95,6 @@ fn convert_to_app_url(public_api_address: &str) -> String { public_api_address.replace("https://api.", "https://app.") } -fn test_path(org_url_slug: &String, test_case: &Test) -> String { - format!("{}/flaky-tests/test/{}", org_url_slug, test_case.id) -} - fn collection_test_guid_path(org_url_slug: &str, short_id: &str, guid: &Uuid) -> String { format!("{org_url_slug}/flaky-tests/collections/{short_id}/tests/{guid}") } @@ -169,7 +159,7 @@ mod tests { fn test_case_url( test_case: &Test, - short_id: Option<&str>, + short_id: &str, guid_scope: Option<&TestCaseGuidScope>, ) -> Result { url_for_test_case( @@ -182,16 +172,6 @@ mod tests { ) } - #[test] - fn test_url_generated() { - assert_eq!( - test_case_url(&test_case(), None, None), - Ok(String::from( - "https://app.trunk-staging.io/bad-app-org/flaky-tests/test/c33a7f64-8f3e-5db9-b37b-2ea870d2441b?repo=bad-app%2Fios-app" - )), - ); - } - const UPLOAD_ID: &str = "c8034184-a9c2-5c53-be91-ef38ffb90df9"; // 1787777896873 const UPLOAD_CREATED_AT: &str = "2026-08-26T20:58:16.873Z"; @@ -237,7 +217,7 @@ mod tests { #[test] fn test_collection_url_generated() { assert_eq!( - test_case_url(&test_case(), Some("tc_123"), None), + test_case_url(&test_case(), "tc_123", None), Ok(String::from( "https://app.trunk-staging.io/bad-app-org/flaky-tests/collections/tc_123/t/c33a7f64-8f3e-5db9-b37b-2ea870d2441b?repo=bad-app%2Fios-app" )), @@ -249,7 +229,7 @@ mod tests { let test_case = test_case_with_id("88e5353c-190c-5dce-9d06-0e66c3e062b1"); assert_eq!( - test_case_url(&test_case, Some("tc_123"), Some(&test_guid_scope())), + test_case_url(&test_case, "tc_123", Some(&test_guid_scope())), Ok(String::from( "https://app.trunk-staging.io/bad-app-org/flaky-tests/collections/tc_123/tests/bfeebcf4-72d1-887d-8bcd-788d0dec7f97" )), @@ -264,16 +244,8 @@ mod tests { }; assert_eq!( - test_case_url(&test_case(), Some("tc_123"), Some(&ids)), - test_case_url(&test_case(), Some("tc_123"), None), - ); - } - - #[test] - fn test_repo_scoped_url_ignores_the_guid_scope() { - assert_eq!( - test_case_url(&test_case(), None, Some(&test_guid_scope())), - test_case_url(&test_case(), None, None), + test_case_url(&test_case(), "tc_123", Some(&ids)), + test_case_url(&test_case(), "tc_123", None), ); } } diff --git a/api/tests/v2_client.rs b/api/tests/v2_client.rs index 5ab0fb29..9cf07313 100644 --- a/api/tests/v2_client.rs +++ b/api/tests/v2_client.rs @@ -36,7 +36,7 @@ async fn serve(routes: Routes) -> SharedMockServerState { } fn client(state: &SharedMockServerState, token: Option<&str>) -> ApiClient { - let mut client = ApiClient::new(token.map(String::from), None, false, "acme", None).unwrap(); + let mut client = ApiClient::new(token.map(String::from), false, "acme", None).unwrap(); client.api_host.clone_from(&state.host); client } @@ -325,11 +325,10 @@ async fn does_not_ask_without_a_token_or_a_collection_and_a_repo() { )]) .await; - let mut public_repo_client = - ApiClient::new(None, Some(String::from("public-id")), false, "acme", None).unwrap(); - public_repo_client.api_host.clone_from(&state.host); + let mut credential_free_client = ApiClient::new(None, true, "acme", None).unwrap(); + credential_free_client.api_host.clone_from(&state.host); assert_eq!( - public_repo_client + credential_free_client .get_upload_api_version(&version_request(Some(SHORT_ID))) .await, UploadApiDecision::default() @@ -730,7 +729,7 @@ fn fork_pull_request(github_token: Option<&str>) -> GithubForkPullRequest { } fn fork_pr_client(state: &SharedMockServerState, github_token: Option<&str>) -> ApiClient { - let mut client = ApiClient::new(None, None, true, "acme", None).unwrap(); + let mut client = ApiClient::new(None, true, "acme", None).unwrap(); client.api_host.clone_from(&state.host); client.set_github_fork_pull_request(fork_pull_request(github_token)); client @@ -963,7 +962,7 @@ async fn a_credential_free_run_that_is_not_a_fork_pr_never_asks() { login_route((StatusCode::OK, LOGIN)), ]) .await; - let mut client = ApiClient::new(None, None, true, "acme", None).unwrap(); + let mut client = ApiClient::new(None, true, "acme", None).unwrap(); client.api_host.clone_from(&state.host); let decision = client @@ -978,8 +977,7 @@ async fn a_credential_free_run_that_is_not_a_fork_pr_never_asks() { #[tokio::test] async fn a_run_with_a_token_never_swaps() { let state = serve(vec![login_route((StatusCode::OK, LOGIN)), uploads_route()]).await; - let mut client = - ApiClient::new(Some(String::from("org-key")), None, true, "acme", None).unwrap(); + let mut client = ApiClient::new(Some(String::from("org-key")), true, "acme", None).unwrap(); client.api_host.clone_from(&state.host); client.set_github_fork_pull_request(fork_pull_request(Some("ghs_job-token"))); diff --git a/bundle/README.md b/bundle/README.md index dc532e1a..8f2b4a49 100644 --- a/bundle/README.md +++ b/bundle/README.md @@ -19,13 +19,13 @@ To inspect the contents of `internal.bin`, you first need to obtain the file. Th When running the upload command with the `--dry-run` flag: ```bash -trunk upload --dry-run --junit-path test-results.xml +trunk upload --dry-run --junit-path test-results.xml --test-collection-id ``` Alternatively, you can use the `TRUNK_DRY_RUN` environment variable: ```bash -TRUNK_DRY_RUN=true trunk upload --junit-path test-results.xml +TRUNK_DRY_RUN=true trunk upload --junit-path test-results.xml --test-collection-id ``` This will create a `bundle_upload` directory in your current working directory. The `internal.bin` file will be located at the top level of this directory: diff --git a/cli/src/context.rs b/cli/src/context.rs index 8425abb4..4de65ed7 100644 --- a/cli/src/context.rs +++ b/cli/src/context.rs @@ -827,7 +827,6 @@ pub async fn gather_exit_code_and_quarantined_tests_context( file_set_builder: &FileSetBuilder, default_exit_code: Option, test_collection_short_id: Option, - hide_test_collection_links: bool, ) -> anyhow::Result { // Run the quarantine step and update the exit code. let failed_tests_extractor = FailedTestsExtractor::new( @@ -879,7 +878,6 @@ pub async fn gather_exit_code_and_quarantined_tests_context( Some(failed_tests_extractor), default_exit_code, &meta.variant.clone().unwrap_or(String::from("")), - hide_test_collection_links, ) .await? }; diff --git a/cli/src/context_quarantine.rs b/cli/src/context_quarantine.rs index acf74de0..62673594 100644 --- a/cli/src/context_quarantine.rs +++ b/cli/src/context_quarantine.rs @@ -316,7 +316,6 @@ pub async fn gather_quarantine_context( failed_tests_extractor: Option, test_run_exit_code: Option, variant: &String, - hide_test_collection_links: bool, ) -> anyhow::Result { let failed_tests_extractor = failed_tests_extractor.unwrap_or_else(|| { FailedTestsExtractor::new( @@ -435,7 +434,6 @@ pub async fn gather_quarantine_context( quarantined_failure, request, api_client, - hide_test_collection_links, guid_scope.as_ref(), ) }); @@ -447,15 +445,9 @@ pub async fn gather_quarantine_context( failures.len(), pluralize("failure", quarantined_failures.len() as isize, false), ); - failures.iter().for_each(|failure| { - log_failure( - failure, - request, - api_client, - hide_test_collection_links, - guid_scope.as_ref(), - ) - }); + failures + .iter() + .for_each(|failure| log_failure(failure, request, api_client, guid_scope.as_ref())); } let quarantined_failure_count = quarantined_failures.len(); quarantine_results.quarantine_results = quarantined_failures; @@ -502,26 +494,26 @@ fn log_failure( failure: &Test, request: &api::message::GetQuarantineConfigRequest, api_client: &ApiClient, - hide_test_collection_links: bool, guid_scope: Option<&TestCaseGuidScope>, ) { - let test_collection_short_id = request - .test_collection_short_id - .as_deref() - .filter(|_| !hide_test_collection_links); // On v1 the upload has not been created yet, so there are no ids to mint a GUID from; // v2's quarantine lookup returns them. - let url = match url_for_test_case( - &api_client.api_host, - &request.org_url_slug, - &request.repo, - failure, - test_collection_short_id, - guid_scope, - ) { - Ok(url) => format!("Learn more > {}", url), - Err(_) => String::from(""), - }; + let url = request + .test_collection_short_id + .as_deref() + .and_then(|test_collection_short_id| { + url_for_test_case( + &api_client.api_host, + &request.org_url_slug, + &request.repo, + failure, + test_collection_short_id, + guid_scope, + ) + .ok() + }) + .map(|url| format!("Learn more > {}", url)) + .unwrap_or_default(); tracing::info!("\t{} -> {} {}", failure.parent_name, failure.name, url,); } diff --git a/cli/src/summary_output/upload.rs b/cli/src/summary_output/upload.rs index 8e3f55df..0aee6386 100644 --- a/cli/src/summary_output/upload.rs +++ b/cli/src/summary_output/upload.rs @@ -275,14 +275,11 @@ impl Outcome { } } -/// Link to this upload's page, when the run is in test-collection link mode. Gated on -/// `test_collection_short_id` rather than `base_props.test_collection.short_id` so an -/// exported-but-blank collection id can't yield a malformed `/collections//uploads/` -/// link. The payload supplies both halves of the key the canonical route is keyed on. +/// Link to this upload's page. Gated on `test_collection_short_id` rather than +/// `base_props.test_collection.short_id` so an exported-but-blank collection id can't yield a +/// malformed `/collections//uploads/` link. The payload supplies both halves of the key the +/// canonical route is keyed on. fn upload_url(result: &UploadRunResult) -> Option { - if result.hide_test_collection_links { - return None; - } let short_id = result.test_collection_short_id.as_deref()?; let test_collection = result.meta.base_props.test_collection.as_ref()?; url_for_upload( @@ -296,18 +293,20 @@ fn upload_url(result: &UploadRunResult) -> Option { } fn failed_test(result: &UploadRunResult, test: &Test, quarantined: bool) -> FailedTest { - let show_collection_links = !result.hide_test_collection_links; - let link = url_for_test_case( - &result.api_address, - &result.quarantine_context.org_url_slug, - &result.quarantine_context.repo, - test, - result - .test_collection_short_id - .as_deref() - .filter(|_| show_collection_links), - result.guid_scope.as_ref().filter(|_| show_collection_links), - ); + let link = result + .test_collection_short_id + .as_deref() + .and_then(|test_collection_short_id| { + url_for_test_case( + &result.api_address, + &result.quarantine_context.org_url_slug, + &result.quarantine_context.repo, + test, + test_collection_short_id, + result.guid_scope.as_ref(), + ) + .ok() + }); FailedTest { name: test.name.clone(), suite: test.parent_name.clone(), @@ -318,7 +317,7 @@ fn failed_test(result: &UploadRunResult, test: &Test, quarantined: bool) -> Fail failure_message: test.failure_message_attribute.clone(), failure_text: test.failure_text.clone(), quarantined, - link: link.ok(), + link, } } diff --git a/cli/src/upload_command.rs b/cli/src/upload_command.rs index 58b3d188..560e01ab 100644 --- a/cli/src/upload_command.rs +++ b/cli/src/upload_command.rs @@ -88,35 +88,31 @@ pub struct UploadArgs { /// a customer. #[arg(long, env = constants::TRUNK_ORG_URL_SLUG_ENV, help = "Organization url slug.")] pub org_url_slug: String, + /// Required on the command line. Kept an `Option` because the test-runner plugins build + /// `UploadArgs` without clap; `run_upload` refuses a run that names no collection. #[arg( long = "test-collection-id", env = constants::TRUNK_TEST_COLLECTION_ID_ENV, - help = "Optional 8 character alphanumeric ID for a test collection.", - required = false, + help = "ID of the test collection to upload to: 8 alphanumeric characters, shown on the collection's page in Trunk.", + required = true, + value_parser = clap::builder::NonEmptyStringValueParser::new(), num_args = 1 )] pub test_collection_short_id: Option, #[arg( long, - required_unless_present_any = ["public_repo_id", "allow_forked_pr_uploads"], + required_unless_present = "allow_forked_pr_uploads", env = constants::TRUNK_API_TOKEN_ENV, help = "Organization token. Defaults to TRUNK_API_TOKEN env var." )] pub token: Option, - #[arg( - long, - required_unless_present_any = ["token", "allow_forked_pr_uploads"], - env = constants::TRUNK_PUBLIC_REPO_ID_ENV, - help = "Non-secret per-repo identifier, usable instead of --token on fork PRs where repo secrets are unavailable." - )] - pub public_repo_id: Option, /// Opting in explicitly is what keeps a job whose token secret failed to interpolate failing /// loudly: without this, "no credential" would silently become an anonymous upload, and the /// fail-open behaviour on auth errors would hide it behind a green CI step. #[arg( long, env = constants::TRUNK_ALLOW_FORKED_PR_UPLOADS_ENV, - help = "Upload with no Trunk credential, as a forked pull request must since it cannot read repository secrets. Works with no credential on Trunk API v1. On Trunk API v2 it works only for a fork pull request on GitHub Actions, using the job's GITHUB_TOKEN: trunk-io/analytics-uploader passes it by default; when running the CLI directly, set `GITHUB_TOKEN: ${{ github.token }}` on the step. Requires --test-collection-id; the collection must have forked-PR uploads enabled in Trunk." + help = "Upload with no Trunk credential, as a forked pull request must since it cannot read repository secrets. Works with no credential on Trunk API v1. On Trunk API v2 it works only for a fork pull request on GitHub Actions, using the job's GITHUB_TOKEN: trunk-io/analytics-uploader passes it by default; when running the CLI directly, set `GITHUB_TOKEN: ${{ github.token }}` on the step. The collection must have forked-PR uploads enabled in Trunk." )] pub allow_forked_pr_uploads: bool, #[arg( @@ -383,16 +379,6 @@ pub struct UploadArgs { default_missing_value = "true" )] pub show_failure_messages: bool, - #[arg( - long, - env = constants::TRUNK_HIDE_TEST_COLLECTION_LINKS_ENV, - help = "Show repo-scoped links in the CLI output instead of test collection links when a test collection ID is passed.", - required = false, - num_args = 0, - default_value = "false", - default_missing_value = "true" - )] - pub hide_test_collection_links: bool, #[arg( long, env = constants::TRUNK_SUMMARY_OUTPUT_FILE_ENV, @@ -482,7 +468,6 @@ pub struct UploadRunResult { pub validation_report: ValidationReport, pub show_failure_messages: bool, pub test_collection_short_id: Option, - pub hide_test_collection_links: bool, pub api_address: String, pub guid_scope: Option, pub notices: Vec, @@ -568,24 +553,21 @@ pub async fn run_upload( notices.push(Notice::deprecation(message)); } - // Caught here rather than server-side: without a collection there is nothing for the forked - // lane to authorize against, and a 401 from a fork run is fail-open — a warning and a green - // step, which is exactly the silent misconfiguration this flag exists to prevent. Any error - // other than an InterruptingError would fail open the same way. - if upload_args.allow_forked_pr_uploads - && upload_args - .test_collection_short_id - .as_ref() - .is_none_or(|id| id.trim().is_empty()) + // clap enforces this for `upload` and `test`; the test-runner plugins build `UploadArgs` + // themselves. An InterruptingError, since any other error fails open: a warning and a green + // step that hides a run whose results go nowhere. + if upload_args + .test_collection_short_id + .as_ref() + .is_none_or(|id| id.trim().is_empty()) { return Err(anyhow::anyhow!(InterruptingError::new( - "--allow-forked-pr-uploads requires --test-collection-id: forked pull request uploads are authorized by the collection's own opt-in." + missing_test_collection_id_message(caller) ))); } let mut api_client = ApiClient::new( upload_args.token.clone(), - upload_args.public_repo_id.clone(), upload_args.allow_forked_pr_uploads, &upload_args.org_url_slug, render_sender, @@ -682,7 +664,6 @@ pub async fn run_upload( .test_collection_short_id .clone() .filter(|id| !id.is_empty()), - upload_args.hide_test_collection_links, ) .await { @@ -857,7 +838,6 @@ pub async fn run_upload( test_collection_short_id: upload_args .test_collection_short_id .filter(|id| !id.is_empty()), - hide_test_collection_links: upload_args.hide_test_collection_links, api_address: api_client.api_host.clone(), guid_scope, notices, @@ -866,6 +846,18 @@ pub async fn run_upload( }) } +pub fn missing_test_collection_id_message(caller: UploadApiCaller) -> String { + let how_to_pass = match caller { + UploadApiCaller::Cli => String::from("Pass --test-collection-id"), + UploadApiCaller::TestRunnerPlugin => { + format!("Set {}", constants::TRUNK_TEST_COLLECTION_ID_ENV) + } + }; + format!( + "This run names no test collection. {how_to_pass} to upload its test results; the ID is on the collection's page in Trunk." + ) +} + /// The run goes on as if the user had named the collection Trunk inferred, until 1.0.0 requires it. pub fn inferred_test_collection_message(short_id: &str, caller: UploadApiCaller) -> String { let how_to_pass = match caller { diff --git a/cli/tests/common/command_builder.rs b/cli/tests/common/command_builder.rs index 67497f79..f463f1da 100644 --- a/cli/tests/common/command_builder.rs +++ b/cli/tests/common/command_builder.rs @@ -1,9 +1,13 @@ use std::{collections::HashMap, path::Path}; use assert_cmd::{Command, cargo}; -use constants::{TRUNK_API_CLIENT_RETRY_COUNT_ENV, TRUNK_PUBLIC_API_ADDRESS_ENV}; +use constants::{ + TRUNK_API_CLIENT_RETRY_COUNT_ENV, TRUNK_PUBLIC_API_ADDRESS_ENV, TRUNK_TEST_COLLECTION_ID_ENV, +}; const DEFAULT_JUNIT_PATHS: &str = "./*"; +/// Set through the environment, so a test passing `--test-collection-id` overrides it. +pub const DEFAULT_TEST_COLLECTION_ID: &str = "dEfault1"; pub struct UploadArgs { repo_root: Option, @@ -26,7 +30,6 @@ pub struct UploadArgs { verbose: Option, validation_report: Option, dry_run: bool, - public_repo_id: Option, forked_pr: bool, } @@ -53,30 +56,19 @@ impl UploadArgs { verbose: None, validation_report: None, dry_run: false, - public_repo_id: None, forked_pr: false, } } pub fn build_args(&self) -> Vec { - // A public repo id is an alternative to the token, so when one is set we send it - // in place of --token (mirroring a fork-PR run that has no repo secrets). - let mut auth_args = vec![String::from("--org-url-slug"), String::from("test-org")]; - match &self.public_repo_id { - Some(public_repo_id) => { - auth_args.push(String::from("--public-repo-id")); - auth_args.push(public_repo_id.clone()); - } - None if self.forked_pr => { - auth_args.push(String::from("--allow-forked-pr-uploads")); - } - None => { - auth_args.push(String::from("--token")); - auth_args.push(String::from("test-token")); - } - } - auth_args + let auth_args = if self.forked_pr { + vec![String::from("--allow-forked-pr-uploads")] + } else { + vec![String::from("--token"), String::from("test-token")] + }; + vec![String::from("--org-url-slug"), String::from("test-org")] .into_iter() + .chain(auth_args) .chain( self.repo_root .clone() @@ -287,14 +279,18 @@ impl CommandType { pub fn build_envs(&self) -> HashMap { match self { - CommandType::Upload { server_host, .. } => HashMap::from([( - String::from(TRUNK_PUBLIC_API_ADDRESS_ENV), - server_host.clone(), - )]), - CommandType::Test { server_host, .. } => HashMap::from([( - String::from(TRUNK_PUBLIC_API_ADDRESS_ENV), - server_host.clone(), - )]), + CommandType::Upload { server_host, .. } | CommandType::Test { server_host, .. } => { + HashMap::from([ + ( + String::from(TRUNK_PUBLIC_API_ADDRESS_ENV), + server_host.clone(), + ), + ( + String::from(TRUNK_TEST_COLLECTION_ID_ENV), + String::from(DEFAULT_TEST_COLLECTION_ID), + ), + ]) + } CommandType::Validate { .. } => { let empty: HashMap = HashMap::new(); empty @@ -573,19 +569,6 @@ impl<'b> CommandBuilder<'b> { self } - pub fn public_repo_id(&mut self, new_value: &str) -> &mut Self { - match &mut self.command_type { - CommandType::Upload { upload_args, .. } => { - upload_args.public_repo_id = Some(new_value.to_string()); - } - CommandType::Test { upload_args, .. } => { - upload_args.public_repo_id = Some(new_value.to_string()); - } - CommandType::Validate { .. } => {} - } - self - } - /// No credential, as a forked pull request's run has: `--allow-forked-pr-uploads` in place of /// `--token`. pub fn forked_pr(&mut self) -> &mut Self { diff --git a/cli/tests/summary/github.rs b/cli/tests/summary/github.rs index d03fd7ed..a93cfe66 100644 --- a/cli/tests/summary/github.rs +++ b/cli/tests/summary/github.rs @@ -146,8 +146,8 @@ fn annotates_each_failure_that_was_not_quarantined() { upload_annotations(&result), [ "::error::2 tests failed and were not quarantined, using exit code: 1", - "::error file=src/math.rs,title=Math%2C Tests%3A unit/subtracts::Failed%0Ahttps://app.trunk.io/test-org/flaky-tests/test/subtracts-id?repo=trunk-io%252Fanalytics-cli", - "::error title=MathTests/divides::expected 1, got 2%0A100%25 wrong%0Ahttps://app.trunk.io/test-org/flaky-tests/test/divides-id?repo=trunk-io%252Fanalytics-cli", + "::error file=src/math.rs,title=Math%2C Tests%3A unit/subtracts::Failed%0Ahttps://app.trunk.io/test-org/flaky-tests/collections/abc123/t/subtracts-id?repo=trunk-io%252Fanalytics-cli", + "::error title=MathTests/divides::expected 1, got 2%0A100%25 wrong%0Ahttps://app.trunk.io/test-org/flaky-tests/collections/abc123/t/divides-id?repo=trunk-io%252Fanalytics-cli", ] ); } diff --git a/cli/tests/summary/upload.rs b/cli/tests/summary/upload.rs index c9b92344..bac0404d 100644 --- a/cli/tests/summary/upload.rs +++ b/cli/tests/summary/upload.rs @@ -97,8 +97,7 @@ pub(super) fn upload_result(num_tests: usize) -> UploadRunResult { validations: JunitReportValidations::new(BTreeMap::new()), validation_report: ValidationReport::Limited, show_failure_messages: false, - test_collection_short_id: None, - hide_test_collection_links: false, + test_collection_short_id: Some(String::from("abc123")), api_address: String::from("https://api.trunk.io"), guid_scope: None, notices: Vec::new(), @@ -328,9 +327,9 @@ fn prints_failures_that_were_all_quarantined() { "", " 📁 src/math.rs", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " MathTests/subtracts", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/subtracts-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/subtracts-id?repo=trunk-io%2Fanalytics-cli", " ", "", "🎉 All test failures were quarantined, overriding exit code to be exit_success (0)", @@ -364,16 +363,16 @@ fn prints_failures_that_were_not_quarantined() { "", " 📁 src/math.rs", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " ", "", "❌ 2 tests failed and were not quarantined", "", " 📁 src/math.rs", " MathTests/subtracts", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/subtracts-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/subtracts-id?repo=trunk-io%2Fanalytics-cli", " MathTests/divides", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/divides-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/divides-id?repo=trunk-io%2Fanalytics-cli", " ", "", "⚠️ Some test failures were not quarantined, using exit code: 1", @@ -402,7 +401,7 @@ fn prints_a_warning_when_the_quarantine_lookup_failed() { "", " 📦 MathTests", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " ", "", "⚠️ Some test failures were not quarantined, using exit code: 1", @@ -472,7 +471,7 @@ fn proceeds_past_an_upload_error() { "", " 📦 MathTests", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " ", "", "⚠️ Some test failures were not quarantined, using exit code: 1", @@ -647,7 +646,7 @@ fn prints_long_failure_messages_when_asked() { "", " 📦 MathTests", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " Failure: ", " assertion `left == right` failed", " left: 1", @@ -734,40 +733,6 @@ fn links_tests_by_short_link_without_collection_ids() { ); } -#[test] -fn prints_the_bundle_upload_id_when_collection_links_are_hidden() { - let mut result = in_collection(upload_result(2)); - result.hide_test_collection_links = true; - result.quarantine_context.exit_code = ExitCode::Failure; - result.quarantine_context.failures = vec![Test { - id: String::from("c33a7f64-8f3e-5db9-b37b-2ea870d2441b"), - ..failure("adds", "MathTests", None) - }]; - result.guid_scope = Some(TestCaseGuidScope { - test_collection_id: String::from("9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d"), - repo_id: String::from("1f2e3d4c-5b6a-4978-8a6b-5c4d3e2f1a0b"), - }); - - assert_eq!( - upload_summary(&result), - [ - "🏷️ Bundle Upload ID: 4b1d2c3e-5f60-4a7b-8c9d-0e1f2a3b4c5d", - "", - "📚 Test Report", - " Total: 2 Pass: 1 Fail: 1 Quarantined: 0 Pass Ratio: 50.0%", - "", - "❌ 1 test failed and was not quarantined", - "", - " 📦 MathTests", - " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/c33a7f64-8f3e-5db9-b37b-2ea870d2441b?repo=trunk-io%2Fanalytics-cli", - " ", - "", - "⚠️ Some test failures were not quarantined, using exit code: 1", - ] - ); -} - #[test] fn omits_the_upload_line_without_a_bundle_upload_id() { let mut result = upload_result(5); @@ -810,25 +775,25 @@ fn groups_failures_by_file_then_suite_then_neither() { "", " 📁 src/a.rs", " formats", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/formats-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/formats-id?repo=trunk-io%2Fanalytics-cli", " ", " 📁 src/date.rs", " DateTests/parses_dates", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/parses_dates-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/parses_dates-id?repo=trunk-io%2Fanalytics-cli", " TimeTests/parses_times", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/parses_times-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/parses_times-id?repo=trunk-io%2Fanalytics-cli", " ", " 📦 MathTests", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " MathTests/subtracts", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/subtracts-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/subtracts-id?repo=trunk-io%2Fanalytics-cli", " ", " 🔍 Other", " loads", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/loads-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/loads-id?repo=trunk-io%2Fanalytics-cli", " boots", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/boots-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/boots-id?repo=trunk-io%2Fanalytics-cli", " ", "", "⚠️ Some test failures were not quarantined, using exit code: 1", @@ -857,11 +822,11 @@ fn shows_three_failures_per_group() { "", " 📁 src/math.rs", " MathTests/adds", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/adds-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/adds-id?repo=trunk-io%2Fanalytics-cli", " MathTests/subtracts", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/subtracts-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/subtracts-id?repo=trunk-io%2Fanalytics-cli", " MathTests/multiplies", - " ⤷ https://app.trunk.io/test-org/flaky-tests/test/multiplies-id?repo=trunk-io%2Fanalytics-cli", + " ⤷ https://app.trunk.io/test-org/flaky-tests/collections/abc123/t/multiplies-id?repo=trunk-io%2Fanalytics-cli", " …and 2 more failures in this group", " ", "", diff --git a/cli/tests/upload.rs b/cli/tests/upload.rs index 5aa21288..8062b132 100644 --- a/cli/tests/upload.rs +++ b/cli/tests/upload.rs @@ -7,6 +7,7 @@ use api::message::{ CreateBundleUploadRequest, CreateBundleUploadResponse, GetQuarantineConfigRequest, GetQuarantineConfigResponse, }; +use assert_cmd::{Command, cargo}; use assert_matches::assert_matches; use axum::body::{Body, Bytes}; use axum::response::IntoResponse; @@ -19,7 +20,7 @@ use clap::Parser; mod common; use codeowners::CodeOwners; -use common::command_builder::CommandBuilder; +use common::command_builder::{CommandBuilder, DEFAULT_TEST_COLLECTION_ID}; #[cfg(unix)] use common::utils::{ LINKED_WORKSPACE_CASES_PER_PACKAGE, generate_mock_linked_workspace, write_junit_xml_to_dir, @@ -60,7 +61,7 @@ use test_utils::{ }, }; use trunk_analytics_cli::exit_code::ExitCode; -use trunk_analytics_cli::upload_command::{DRY_RUN_OUTPUT_DIR, get_bundle_upload_id_message}; +use trunk_analytics_cli::upload_command::DRY_RUN_OUTPUT_DIR; // The mock JUnit generator adds a random number of reruns per test, so the number of // `TestCaseRun`s equals the test cases plus every parsed rerun/flaky attempt. Mirror @@ -408,72 +409,93 @@ async fn upload_bundle_prints_test_collection_upload_link() { .stdout(predicate::str::contains("Bundle Upload ID:").not()); } -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn upload_bundle_prints_bare_upload_id_when_links_hidden() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls(&temp_dir); - - let state = MockServerBuilder::new().spawn_mock_server().await; - - let assert = CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - .env("TRUNK_HIDE_TEST_COLLECTION_LINKS", "true") - .arg("--test-collection-id") - .arg("tc_123") - .assert() - .failure(); - - assert - .stdout(predicate::str::contains( - get_bundle_upload_id_message("test-bundle-upload-id").as_str(), - )) - .stdout(predicate::str::contains("/flaky-tests/collections/tc_123/uploads/").not()); +#[rstest::rstest] +#[case::upload("upload")] +#[case::test("test")] +fn requires_a_test_collection_id(#[case] subcommand: &str) { + let mut command = Command::new(cargo::cargo_bin!()); + command.env_remove("TRUNK_TEST_COLLECTION_ID").args([ + subcommand, + "--junit-paths", + "./*", + "--org-url-slug", + "test-org", + "--token", + "test-token", + ]); + if subcommand == "test" { + command.arg("true"); + } + command.assert().failure().stderr(predicate::str::contains( + "the following required arguments were not provided:\n --test-collection-id ", + )); } -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn upload_bundle_hides_test_collection_links_when_env_set() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls(&temp_dir); - - let state = MockServerBuilder::new().spawn_mock_server().await; - - let assert = CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - .env("TRUNK_HIDE_TEST_COLLECTION_LINKS", "true") - .arg("--test-collection-id") - .arg("tc_123") +#[rstest::rstest] +// An exported-but-blank env var, common in CI, counts as missing. +#[case::blank_env(&[], &[("TRUNK_TEST_COLLECTION_ID", "")], "--test-collection-id ")] +#[case::empty_flag(&["--test-collection-id", ""], &[], "a value is required for '--test-collection-id '")] +fn refuses_a_blank_test_collection_id( + #[case] args: &[&str], + #[case] envs: &[(&str, &str)], + #[case] error: &str, +) { + Command::new(cargo::cargo_bin!()) + .env_remove("TRUNK_TEST_COLLECTION_ID") + .envs(envs.iter().copied()) + .args([ + "upload", + "--junit-paths", + "./*", + "--org-url-slug", + "test-org", + "--token", + "test-token", + ]) + .args(args) .assert() - .failure(); - - assert - .stdout(predicate::str::contains("/test-org/flaky-tests/test/")) - .stdout(predicate::str::contains("/flaky-tests/collections/").not()); + .failure() + .stderr(predicate::str::contains(error)); } -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn upload_bundle_without_test_collection_id_prints_repo_links() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls(&temp_dir); - - let state = MockServerBuilder::new().spawn_mock_server().await; - - let assert = CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - // an exported-but-blank env var (common in CI) must not produce a - // malformed /collections//t/ link - .env("TRUNK_TEST_COLLECTION_ID", "") +#[test] +fn public_repo_id_is_gone() { + Command::new(cargo::cargo_bin!()) + .args([ + "upload", + "--junit-paths", + "./*", + "--org-url-slug", + "test-org", + "--test-collection-id", + "tc_123", + "--public-repo-id", + "public-repo-id-123", + ]) .assert() - .failure(); + .failure() + .stderr(predicate::str::contains( + "unexpected argument '--public-repo-id' found", + )); - assert - .stdout(predicate::str::contains("/test-org/flaky-tests/test/")) - .stdout(predicate::str::contains("/flaky-tests/collections/").not()); + // Its env var no longer stands in for a token. + Command::new(cargo::cargo_bin!()) + .env_remove("TRUNK_API_TOKEN") + .env("TRUNK_PUBLIC_REPO_ID", "public-repo-id-123") + .args([ + "upload", + "--junit-paths", + "./*", + "--org-url-slug", + "test-org", + "--test-collection-id", + "tc_123", + ]) + .assert() + .failure() + .stderr(predicate::str::contains( + "the following required arguments were not provided:\n --token ", + )); } // NOTE: must be multi threaded to start a mock server @@ -535,51 +557,6 @@ async fn upload_bundle_records_quarantine_resolution_mode() { ); } -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn upload_bundle_with_public_repo_id() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls(&temp_dir); - generate_mock_codeowners(&temp_dir); - - let state = MockServerBuilder::new().spawn_mock_server().await; - - let mut command_builder = CommandBuilder::upload(temp_dir.path(), state.host.clone()); - // Authenticate with a public repo id instead of a token (the fork-PR path). - command_builder.public_repo_id("public-repo-id-123"); - - command_builder.command().assert(); - - // The bundle still uploads even though we used a public repo id rather than a token. - let requests = state.requests.lock().unwrap().clone(); - assert!( - requests - .iter() - .any(|request| matches!(request, RequestPayload::CreateBundleUpload(_))), - "expected a createBundleUpload request" - ); - - // Both authenticated endpoints must carry the public repo id header and no token. - let headers = state.request_headers.lock().unwrap(); - for endpoint in ["createBundleUpload", "getQuarantineConfig"] { - let endpoint_headers = headers - .get(endpoint) - .unwrap_or_else(|| panic!("no captured headers for {endpoint}")); - assert_eq!( - endpoint_headers - .get("x-trunk-public-repo-id") - .and_then(|value| value.to_str().ok()), - Some("public-repo-id-123"), - "{endpoint} should send the public repo id header" - ); - assert!( - endpoint_headers.get("x-api-token").is_none(), - "{endpoint} should not send a token when using a public repo id" - ); - } -} - #[tokio::test(flavor = "multi_thread")] async fn upload_bundle_using_bep() { let temp_dir = tempdir().unwrap(); @@ -605,7 +582,13 @@ async fn upload_bundle_using_bep() { let bundle_meta: BundleMeta = serde_json::from_reader(meta_json).unwrap(); assert!(!bundle_meta.base_props.file_sets.is_empty()); - assert_eq!(bundle_meta.base_props.test_collection, None); + assert_eq!( + bundle_meta + .base_props + .test_collection + .map(|collection| collection.short_id), + Some(String::from(DEFAULT_TEST_COLLECTION_ID)) + ); let mut expected_runs = 0usize; bundle_meta .base_props @@ -1488,29 +1471,6 @@ async fn upload_bundle_no_files_allow_missing_junit_files() { } } -#[rstest::rstest] -#[case::without_a_test_collection(&[])] -#[case::with_a_blank_test_collection(&["--test-collection-id", " "])] -#[tokio::test(flavor = "multi_thread")] -async fn upload_fails_when_forked_pr_uploads_have_no_test_collection(#[case] extra_args: &[&str]) { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - - let state = MockServerBuilder::new().spawn_mock_server().await; - - CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - .arg("--allow-forked-pr-uploads") - .args(extra_args) - .assert() - .code(ExitCode::Error.code()) - .stderr(predicate::str::contains( - "--allow-forked-pr-uploads requires --test-collection-id", - )); - - assert!(state.requests.lock().unwrap().is_empty()); -} - #[tokio::test(flavor = "multi_thread")] async fn upload_bundle_invalid_repo_root() { let temp_dir = tempdir().unwrap(); @@ -1614,7 +1574,7 @@ async fn upload_writes_summary_output_file() { failure["link"] .as_str() .unwrap() - .contains("/flaky-tests/test/") + .contains("/flaky-tests/collections/dEfault1/") ); } } @@ -3920,119 +3880,6 @@ async fn upload_on_v2_when_trunk_chooses_it() { ); } -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn upload_on_v2_to_the_collection_trunk_inferred() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls_with_failures(&temp_dir); - - let (mock_server_builder, v2_calls) = v2_mock_server(serde_json::json!({ - "apiVersion": "v2", - "testCollectionShortId": INFERRED_SHORT_ID, - })); - let state = mock_server_builder.spawn_mock_server().await; - - CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - .assert() - // every failure is quarantined, by the inferred collection - .success() - .stderr(predicate::str::contains(format!( - "Uploading to test collection {INFERRED_SHORT_ID}, inferred from the repository. Pass --test-collection-id {INFERRED_SHORT_ID}: analytics-cli 1.0.0 requires it." - ))); - - assert_eq!( - v2_calls.lock().unwrap().clone(), - v2_calls_for(INFERRED_SHORT_ID) - ); - assert_no_v1_calls(&state); - let requests = state.requests.lock().unwrap().clone(); - let tar_extract_directory = requests - .iter() - .find_map(|request| match request { - RequestPayload::S3Upload(directory) => Some(directory), - _ => None, - }) - .expect("the bundle must have been uploaded"); - let file = fs::File::open(tar_extract_directory.join("meta.json")).unwrap(); - let bundle_meta: BundleMeta = serde_json::from_reader(BufReader::new(file)).unwrap(); - assert_eq!( - bundle_meta - .base_props - .test_collection - .map(|collection| collection.short_id), - Some(String::from(INFERRED_SHORT_ID)) - ); -} - -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn skip_the_upload_when_trunk_has_no_collection_for_the_run() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls(&temp_dir); - - let (mock_server_builder, v2_calls) = - v2_mock_server(serde_json::json!({"apiVersion": "v1", "missingTestCollection": true})); - let state = mock_server_builder.spawn_mock_server().await; - - let output = CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - .assert() - // The fixture's failures aren't quarantined, so the run fails either way. - .code(1) - .get_output() - .clone(); - - let console = format!( - "{}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - assert!( - console.contains("Test results were not uploaded"), - "the run must say it skipped the upload: {console}" - ); - assert!(v2_calls.lock().unwrap().is_empty()); - let requests = state.requests.lock().unwrap().clone(); - assert!( - !requests.iter().any(|request| matches!( - request, - RequestPayload::CreateBundleUpload(_) - | RequestPayload::S3Upload(_) - | RequestPayload::TelemetryUploadMetrics(_) - | RequestPayload::GetQuarantineConfig(_) - )), - "a run Trunk has no collection for must not call v1" - ); -} - -// NOTE: must be multi threaded to start a mock server -#[tokio::test(flavor = "multi_thread")] -async fn upload_on_v1_when_trunk_chooses_v2_but_names_no_collection() { - let temp_dir = tempdir().unwrap(); - generate_mock_git_repo(&temp_dir); - generate_mock_valid_junit_xmls(&temp_dir); - - let (mock_server_builder, v2_calls) = v2_mock_server(serde_json::json!({"apiVersion": "v2"})); - let state = mock_server_builder.spawn_mock_server().await; - - CommandBuilder::upload(temp_dir.path(), state.host.clone()) - .command() - .assert() - .stderr(predicate::str::contains("inferred from the repository").not()); - - assert!(v2_calls.lock().unwrap().is_empty()); - let requests = state.requests.lock().unwrap().clone(); - assert!( - requests - .iter() - .any(|request| matches!(request, RequestPayload::CreateBundleUpload(_))), - "the run must have uploaded on v1" - ); -} - const GITHUB_ACTIONS_LOGIN: &str = r#"{"jwt":"trunk-jwt","expiresAt":"2026-11-06T17:15:00Z","organization":{"id":"o","slug":"acme","name":"Acme"},"repository":{"id":"r","name":"acme/web"}}"#; const FORK_HEAD_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; const GITHUB_TOKEN: &str = "ghs_job-token"; diff --git a/constants/src/lib.rs b/constants/src/lib.rs index 12816eb6..4fdb96a9 100644 --- a/constants/src/lib.rs +++ b/constants/src/lib.rs @@ -29,7 +29,6 @@ pub const TRUNK_API_CLIENT_RETRY_DEADLINE_SECS_ENV: &str = "TRUNK_API_CLIENT_RET // Trunk CLI environment variable names for configuration overrides pub const TRUNK_API_TOKEN_ENV: &str = "TRUNK_API_TOKEN"; -pub const TRUNK_PUBLIC_REPO_ID_ENV: &str = "TRUNK_PUBLIC_REPO_ID"; pub const TRUNK_ALLOW_FORKED_PR_UPLOADS_ENV: &str = "TRUNK_ALLOW_FORKED_PR_UPLOADS"; pub const TRUNK_ORG_URL_SLUG_ENV: &str = "TRUNK_ORG_URL_SLUG"; pub const TRUNK_TEST_COLLECTION_ID_ENV: &str = "TRUNK_TEST_COLLECTION_ID"; @@ -54,7 +53,6 @@ pub const TRUNK_DRY_RUN_ENV: &str = "TRUNK_DRY_RUN"; pub const TRUNK_TEST_PROCESS_EXIT_CODE_ENV: &str = "TRUNK_TEST_PROCESS_EXIT_CODE"; pub const TRUNK_VALIDATION_REPORT_ENV: &str = "TRUNK_VALIDATION_REPORT"; pub const TRUNK_SHOW_FAILURE_MESSAGES_ENV: &str = "TRUNK_SHOW_FAILURE_MESSAGES"; -pub const TRUNK_HIDE_TEST_COLLECTION_LINKS_ENV: &str = "TRUNK_HIDE_TEST_COLLECTION_LINKS"; pub const TRUNK_SUMMARY_OUTPUT_FILE_ENV: &str = "TRUNK_SUMMARY_OUTPUT_FILE"; pub const TRUNK_OUTPUT_FORMAT_ENV: &str = "TRUNK_OUTPUT_FORMAT"; pub const TRUNK_DEBUG_ENV: &str = "TRUNK_DEBUG"; @@ -85,7 +83,6 @@ pub const TRUNK_ENVS_TO_CAPTURE: &[&str] = &[ TRUNK_PUBLIC_API_ADDRESS_ENV, TRUNK_API_CLIENT_RETRY_COUNT_ENV, TRUNK_API_CLIENT_RETRY_DEADLINE_SECS_ENV, - TRUNK_PUBLIC_REPO_ID_ENV, TRUNK_ALLOW_FORKED_PR_UPLOADS_ENV, TRUNK_ORG_URL_SLUG_ENV, TRUNK_TEST_COLLECTION_ID_ENV, @@ -109,7 +106,6 @@ pub const TRUNK_ENVS_TO_CAPTURE: &[&str] = &[ TRUNK_TEST_PROCESS_EXIT_CODE_ENV, TRUNK_VALIDATION_REPORT_ENV, TRUNK_SHOW_FAILURE_MESSAGES_ENV, - TRUNK_HIDE_TEST_COLLECTION_LINKS_ENV, TRUNK_SUMMARY_OUTPUT_FILE_ENV, TRUNK_OUTPUT_FORMAT_ENV, TRUNK_DEBUG_ENV, diff --git a/rspec-trunk-flaky-tests/README.md b/rspec-trunk-flaky-tests/README.md index ec18fd3f..c570b2c9 100644 --- a/rspec-trunk-flaky-tests/README.md +++ b/rspec-trunk-flaky-tests/README.md @@ -106,7 +106,7 @@ require 'trunk_spec_helper' ### Environment Variables -For a complete list of environment variables that the gem accepts, see [`lib/trunk_spec_helper.rb`](lib/trunk_spec_helper.rb). The gem uses the same environment variables as the Trunk Analytics CLI for configuration overrides. `TRUNK_ORG_URL_SLUG` and `TRUNK_API_TOKEN` must be set to activate the plugin. +For a complete list of environment variables that the gem accepts, see [`lib/trunk_spec_helper.rb`](lib/trunk_spec_helper.rb). The gem uses the same environment variables as the Trunk Analytics CLI for configuration overrides. `TRUNK_ORG_URL_SLUG` and `TRUNK_API_TOKEN` must be set to activate the plugin, and `TRUNK_TEST_COLLECTION_ID` too: with the first two set and no test collection, the plugin prints a warning and stays off. #### `TRUNK_QUARANTINE_QUERY_FAILURE_EXIT` @@ -147,7 +147,7 @@ This will create an `internal.bin` file in the `./test-results` directory (relat After generating the `internal.bin` file, you can upload it using the Trunk Analytics CLI. The CLI supports taking `internal.bin` files as input when running the upload command: ```bash -trunk upload --test-reports ./test-results/internal.bin +trunk upload --test-reports ./test-results/internal.bin --test-collection-id ``` The CLI will automatically detect that the file is an `internal.bin` file (by its `.bin` extension) and process it accordingly, allowing you to still benefit from quarantining and other features. diff --git a/rspec-trunk-flaky-tests/lib/trunk_spec_helper.rb b/rspec-trunk-flaky-tests/lib/trunk_spec_helper.rb index 5fb9c5f0..8a74b925 100644 --- a/rspec-trunk-flaky-tests/lib/trunk_spec_helper.rb +++ b/rspec-trunk-flaky-tests/lib/trunk_spec_helper.rb @@ -8,6 +8,7 @@ # Required environment variables: # TRUNK_ORG_URL_SLUG - Your organization's URL slug # TRUNK_API_TOKEN - Your API token for authentication +# TRUNK_TEST_COLLECTION_ID - The ID of the test collection to upload to # # Optional environment variables for repository metadata: # TRUNK_REPO_ROOT - Path to repository root @@ -20,7 +21,6 @@ # # Optional environment variables for configuration: # TRUNK_CODEOWNERS_PATH - Path to CODEOWNERS file -# TRUNK_TEST_COLLECTION_ID - Optional 8 character alphanumeric ID for a test collection # TRUNK_VARIANT - Variant name for test results (e.g., 'linux', 'pr-123') # TRUNK_DISABLE_QUARANTINING - Set to 'true' to disable quarantining # TRUNK_ALLOW_EMPTY_TEST_RESULTS - Set to 'true' to allow empty results @@ -97,7 +97,17 @@ def install(config, run) def disabled? knapsack_detector_mode? || ENV['DISABLE_RSPEC_TRUNK_FLAKY_TESTS'] == 'true' || - ENV['TRUNK_ORG_URL_SLUG'].nil? || ENV['TRUNK_API_TOKEN'].nil? + ENV['TRUNK_ORG_URL_SLUG'].nil? || ENV['TRUNK_API_TOKEN'].nil? || missing_test_collection? + end + + # Warns rather than staying silent like the checks before it: a run with a token and a slug + # means to upload, and the native extension's own warnings never reach the console. + def missing_test_collection? + return false unless ENV.fetch('TRUNK_TEST_COLLECTION_ID', '').strip.empty? + + warn('Trunk Flaky Tests is disabled: this run names no test collection. Set ' \ + "TRUNK_TEST_COLLECTION_ID to upload its test results; the ID is on the collection's page in Trunk.") + true end def knapsack_detector_mode? diff --git a/rspec-trunk-flaky-tests/test/namespace_spec.rb b/rspec-trunk-flaky-tests/test/namespace_spec.rb index c331f1e0..cbe3ae2e 100644 --- a/rspec-trunk-flaky-tests/test/namespace_spec.rb +++ b/rspec-trunk-flaky-tests/test/namespace_spec.rb @@ -70,6 +70,7 @@ env = { 'TRUNK_ORG_URL_SLUG' => 'namespace-spec', 'TRUNK_API_TOKEN' => 'namespace-spec', + 'TRUNK_TEST_COLLECTION_ID' => 'namespace-spec', 'DISABLE_RSPEC_TRUNK_FLAKY_TESTS' => nil } stdout, stderr, status = Open3.capture3(env, RbConfig.ruby, '-I', lib_dir, '-e', probe) diff --git a/rspec-trunk-flaky-tests/test/test_collection_spec.rb b/rspec-trunk-flaky-tests/test/test_collection_spec.rb new file mode 100644 index 00000000..6007fd68 --- /dev/null +++ b/rspec-trunk-flaky-tests/test/test_collection_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require 'open3' +require 'rbconfig' +require_relative '../spec/spec_helper' + +# trunk-ignore(rubocop/Metrics/BlockLength) +RSpec.describe 'TRUNK_TEST_COLLECTION_ID' do + let(:probe) do + <<~'RUBY' + require 'rspec_trunk_flaky_tests' + require 'trunk_spec_helper' + puts RSpec::Trunk.current_run ? 'enabled' : 'disabled' + RUBY + end + + let(:lib_dir) { File.dirname($LOAD_PATH.resolve_feature_path('trunk_spec_helper').last) } + + def load_gem(test_collection_id) + env = { + 'TRUNK_ORG_URL_SLUG' => 'test-collection-spec', + 'TRUNK_API_TOKEN' => 'test-collection-spec', + 'TRUNK_TEST_COLLECTION_ID' => test_collection_id, + 'DISABLE_RSPEC_TRUNK_FLAKY_TESTS' => nil + } + Open3.capture3(env, RbConfig.ruby, '-I', lib_dir, '-e', probe) + end + + [nil, '', ' '].each do |test_collection_id| + it "disables Trunk and says why when it is #{test_collection_id.inspect}" do + stdout, stderr, status = load_gem(test_collection_id) + + expect(status).to be_success, stderr + expect(stdout.lines.last.strip).to eq('disabled') + expect(stderr).to include('Trunk Flaky Tests is disabled: this run names no test collection. ' \ + 'Set TRUNK_TEST_COLLECTION_ID') + end + end + + it 'enables Trunk when it is set' do + stdout, stderr, status = load_gem('aB3xY9kQ') + + expect(status).to be_success, stderr + expect(stdout.lines.last.strip).to eq('enabled') + expect(stderr).not_to include('Trunk Flaky Tests is disabled') + end +end diff --git a/test_report/src/report.rs b/test_report/src/report.rs index b070b8d0..17589bda 100644 --- a/test_report/src/report.rs +++ b/test_report/src/report.rs @@ -495,7 +495,13 @@ impl MutTestReport { tracing::warn!("Not checking quarantine status because TRUNK_ORG_URL_SLUG is empty"); return IsQuarantinedResult::default(); } - let api_client = ApiClient::new(Some(token), None, false, org_url_slug.clone(), None); + if requested_test_collection_short_id().is_none() { + tracing::warn!( + "Not checking quarantine status because TRUNK_TEST_COLLECTION_ID is empty" + ); + return IsQuarantinedResult::default(); + } + let api_client = ApiClient::new(Some(token), false, org_url_slug.clone(), None); let use_uncloned_repo = env::var(constants::TRUNK_USE_UNCLONED_REPO_ENV) .ok() .and_then(|v| v.parse().ok()) @@ -881,6 +887,10 @@ impl MutTestReport { tracing::warn!("Not publishing results because TRUNK_ORG_URL_SLUG is empty"); return false; } + if requested_test_collection_short_id().is_none() { + tracing::warn!("Not publishing results because TRUNK_TEST_COLLECTION_ID is empty"); + return false; + } let variant = env::var(constants::TRUNK_VARIANT_ENV).ok(); let summary_output_file = env::var(constants::TRUNK_SUMMARY_OUTPUT_FILE_ENV) @@ -992,7 +1002,6 @@ impl MutTestReport { upload_args.use_uncloned_repo, ) && let Ok(api_client) = ApiClient::new( upload_args.token.clone(), - None, false, upload_args.org_url_slug.clone(), None, diff --git a/test_report/tests/common/env.rs b/test_report/tests/common/env.rs index e4e1eb17..06009dac 100644 --- a/test_report/tests/common/env.rs +++ b/test_report/tests/common/env.rs @@ -13,7 +13,10 @@ use constants::{ use tempfile::TempDir; use test_report::report::quarantine_disk_cache_dir; -/// Cleans up all TRUNK_* and CI-related environment variables to avoid test interference. +pub const DEFAULT_TEST_COLLECTION_ID: &str = "dEfault1"; + +/// Cleans up all TRUNK_* and CI-related environment variables to avoid test interference, and +/// names the test collection every run requires. pub fn cleanup_env_vars() { unsafe { env::remove_var(TRUNK_PUBLIC_API_ADDRESS_ENV); @@ -37,7 +40,7 @@ pub fn cleanup_env_vars() { env::remove_var(TRUNK_QUARANTINED_TESTS_DISK_CACHE_TTL_SECS_ENV); env::remove_var(TRUNK_API_CLIENT_RETRY_COUNT_ENV); env::remove_var(TRUNK_QUARANTINE_DISK_CACHE_DIR_ENV); - env::remove_var(TRUNK_TEST_COLLECTION_ID_ENV); + env::set_var(TRUNK_TEST_COLLECTION_ID_ENV, DEFAULT_TEST_COLLECTION_ID); env::remove_var(TRUNK_SUMMARY_OUTPUT_FILE_ENV); } } diff --git a/test_report/tests/quarantine.rs b/test_report/tests/quarantine.rs index 61bd69b8..236c1113 100644 --- a/test_report/tests/quarantine.rs +++ b/test_report/tests/quarantine.rs @@ -793,136 +793,7 @@ async fn v2_matches_a_test_by_its_computed_test_id() { #[tokio::test(flavor = "multi_thread")] #[serial] -async fn v2_uses_the_collection_trunk_inferred_in_every_process() { - use std::sync::{ - Arc, Mutex, - atomic::{AtomicUsize, Ordering}, - }; - - use axum::{extract::Path, routing::post}; - use context::meta::id::gen_test_case_guid; - use serde_json::json; - use uuid::Uuid; - - const INFERRED_SHORT_ID: &str = "zQ8nP2mW"; - const COLLECTION_UUID: &str = "204b6c93-1c51-4e0f-a13c-e07b9bc60688"; - const REPO_ID: &str = "7a1f0e3d-2b4c-4d5e-8f90-123456789abc"; - - cleanup_env_vars(); - let temp_dir = tempdir().unwrap(); - setup_quarantine_disk_cache_dir(&temp_dir); - let _ = env::set_current_dir(&temp_dir); - - let repo = RepoUrlParts { - host: "github.com".into(), - owner: "test-org".into(), - name: "test-repo".into(), - }; - let quarantined_guid = gen_test_case_guid( - Uuid::parse_str(COLLECTION_UUID).unwrap(), - Uuid::parse_str(REPO_ID).unwrap(), - Uuid::parse_str( - &Test::new( - None::, - "quarantined".to_string(), - "test-parent-name".to_string(), - None, - None, - "test-org".to_string(), - &repo, - None, - "".to_string(), - ) - .id, - ) - .unwrap(), - ) - .to_string(); - - let version_calls = Arc::new(AtomicUsize::new(0)); - let listed_collections: Arc>> = Arc::default(); - let state = { - let mut builder = MockServerBuilder::new(); - builder.set_get_quarantining_config_handler(|| async { - (StatusCode::INTERNAL_SERVER_ERROR, "v1 must not be called") - }); - let calls = version_calls.clone(); - builder.route( - "/v1/metrics/getUploadApiVersion", - post(move || { - calls.fetch_add(1, Ordering::SeqCst); - async { - Json(json!({"apiVersion": "v2", "testCollectionShortId": INFERRED_SHORT_ID})) - } - }), - ); - let listed = listed_collections.clone(); - builder.route( - "/v2/test-collections/:id/all-quarantined-tests", - post(move |Path(id): Path| { - listed.lock().unwrap().push(id); - let quarantined_guid = quarantined_guid.clone(); - async move { - Json(json!({ - "data": [{"testId": quarantined_guid}], - "nextCursor": null, - "hasMore": false, - "testCollectionUuid": COLLECTION_UUID, - "repositoryId": REPO_ID, - "quarantineEnabled": true, - })) - } - }), - ); - builder.spawn_mock_server().await - }; - - unsafe { - env::set_var(TRUNK_PUBLIC_API_ADDRESS_ENV, &state.host); - env::set_var(TRUNK_API_TOKEN_ENV, "test-token"); - env::set_var(TRUNK_ORG_URL_SLUG_ENV, "test-org"); - env::set_var( - TRUNK_REPO_URL_ENV, - "https://github.com/test-org/test-repo.git", - ); - env::set_var(TRUNK_USE_UNCLONED_REPO_ENV, "true"); - env::set_var(TRUNK_REPO_HEAD_SHA_ENV, ""); - env::set_var(TRUNK_REPO_HEAD_BRANCH_ENV, ""); - env::set_var(TRUNK_REPO_HEAD_AUTHOR_NAME_ENV, ""); - env::set_var(TRUNK_QUARANTINED_TESTS_DISK_CACHE_TTL_SECS_ENV, "300"); - } - - // Each report stands for a worker process: the second reads the choice, inferred collection - // included, from disk, and must still look up quarantine on v2. - let results: Vec<_> = (0..2) - .map(|_| { - thread::spawn(|| { - let result = MutTestReport::new("test".into(), "test-command".into(), None) - .is_quarantined( - None, - Some("quarantined".to_string()), - Some("test-parent-name".to_string()), - None, - None, - ); - (result.test_is_quarantined, result.quarantine_lookup_failed) - }) - .join() - .unwrap() - }) - .collect(); - - assert_eq!(results, [(true, false), (true, false)]); - assert_eq!(version_calls.load(Ordering::SeqCst), 1); - assert_eq!( - listed_collections.lock().unwrap().clone(), - [INFERRED_SHORT_ID] - ); -} - -#[tokio::test(flavor = "multi_thread")] -#[serial] -async fn makes_no_quarantine_lookup_when_trunk_has_no_collection() { +async fn makes_no_calls_without_a_test_collection_id() { use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, @@ -936,17 +807,21 @@ async fn makes_no_quarantine_lookup_when_trunk_has_no_collection() { setup_quarantine_disk_cache_dir(&temp_dir); let _ = env::set_current_dir(&temp_dir); - let v1_calls = Arc::new(AtomicUsize::new(0)); + let calls = Arc::new(AtomicUsize::new(0)); let state = { let mut builder = MockServerBuilder::new(); - let calls = v1_calls.clone(); + let quarantine_calls = calls.clone(); builder.set_get_quarantining_config_handler(move || { - calls.fetch_add(1, Ordering::SeqCst); - async { (StatusCode::NOT_FOUND, "A test collection is required") } + quarantine_calls.fetch_add(1, Ordering::SeqCst); + async { (StatusCode::INTERNAL_SERVER_ERROR, "must not be called") } }); + let version_calls = calls.clone(); builder.route( "/v1/metrics/getUploadApiVersion", - post(|| async { Json(json!({"apiVersion": "v1", "missingTestCollection": true})) }), + post(move || { + version_calls.fetch_add(1, Ordering::SeqCst); + async { Json(json!({"apiVersion": "v1"})) } + }), ); builder.spawn_mock_server().await }; @@ -963,23 +838,29 @@ async fn makes_no_quarantine_lookup_when_trunk_has_no_collection() { env::set_var(TRUNK_REPO_HEAD_SHA_ENV, ""); env::set_var(TRUNK_REPO_HEAD_BRANCH_ENV, ""); env::set_var(TRUNK_REPO_HEAD_AUTHOR_NAME_ENV, ""); + // An exported-but-blank variable counts as missing. + env::set_var(constants::TRUNK_TEST_COLLECTION_ID_ENV, " "); } - let result = thread::spawn(|| { - MutTestReport::new("test".into(), "test-command".into(), None).is_quarantined( + let (result, published) = thread::spawn(|| { + let test_report = MutTestReport::new("test".into(), "test-command".into(), None); + let result = test_report.is_quarantined( None, Some("quarantined".to_string()), Some("test-parent-name".to_string()), None, None, - ) + ); + (result, test_report.publish()) }) .join() .unwrap(); assert!(!result.test_is_quarantined); assert!(!result.quarantine_lookup_failed); - assert_eq!(v1_calls.load(Ordering::SeqCst), 0); + assert!(!published); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(state.requests.lock().unwrap().is_empty()); } #[tokio::test(flavor = "multi_thread")]