|
| 1 | +//@ run-pass |
| 2 | +//@ ignore-cross-compile |
| 3 | +//@ ignore-remote |
| 4 | +//@ edition: 2024 |
| 5 | +//! Uses a rustc driver to check that test entrypoints get a `#[rustc_test_entrypoint_marker]` |
| 6 | +//! and can be found using that attribute in rustc drivers (the main use for this attribute). |
| 7 | +
|
| 8 | +#![feature(rustc_private)] |
| 9 | + |
| 10 | +extern crate rustc_driver; |
| 11 | +extern crate rustc_interface; |
| 12 | +extern crate rustc_middle; |
| 13 | +#[macro_use] |
| 14 | +extern crate rustc_hir; |
| 15 | + |
| 16 | +use interface::Compiler; |
| 17 | +use rustc_driver::Compilation; |
| 18 | +use rustc_interface::interface; |
| 19 | +use rustc_middle::ty::TyCtxt; |
| 20 | +use std::io::Write; |
| 21 | + |
| 22 | +const CRATE_NAME: &str = "input"; |
| 23 | + |
| 24 | +struct TestAttr { |
| 25 | + expected_tests: usize, |
| 26 | +} |
| 27 | + |
| 28 | +impl rustc_driver::Callbacks for TestAttr { |
| 29 | + fn after_analysis<'tcx>(&mut self, _compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation { |
| 30 | + let mut tests = Vec::new(); |
| 31 | + for did in tcx.hir_crate_items(()).definitions() { |
| 32 | + if find_attr!(tcx, did, RustcTestEntrypointMarker) { |
| 33 | + tests.push(did); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // the file contains one test, so we should find one entrypoint marker. |
| 38 | + assert_eq!(tests.len(), self.expected_tests); |
| 39 | + |
| 40 | + Compilation::Stop |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +fn count_tests(src: &str, expected_tests: usize) { |
| 45 | + let path = "test_input.rs"; |
| 46 | + let mut file = std::fs::File::create(path).unwrap(); |
| 47 | + file.write_all(src.as_bytes()).unwrap(); |
| 48 | + |
| 49 | + let args = [ |
| 50 | + "rustc".to_string(), |
| 51 | + "--test".to_string(), |
| 52 | + "--crate-type=lib".to_string(), |
| 53 | + "--crate-name".to_string(), |
| 54 | + CRATE_NAME.to_string(), |
| 55 | + path.to_string(), |
| 56 | + ]; |
| 57 | + rustc_driver::catch_fatal_errors(|| -> interface::Result<()> { |
| 58 | + rustc_driver::run_compiler(&args, &mut TestAttr { expected_tests }); |
| 59 | + Ok(()) |
| 60 | + }) |
| 61 | + .unwrap() |
| 62 | + .unwrap(); |
| 63 | +} |
| 64 | + |
| 65 | +fn main() { |
| 66 | + count_tests( |
| 67 | + r#" |
| 68 | + #[test] |
| 69 | + fn one() {{ }} |
| 70 | +
|
| 71 | + #[test] |
| 72 | + fn two() {{ }} |
| 73 | + "#, |
| 74 | + 2, |
| 75 | + ); |
| 76 | +} |
0 commit comments