]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/test-cargo-miri/run-test.py
Auto merge of #101969 - reez12g:issue-101306, r=reez12g
[rust.git] / src / tools / miri / test-cargo-miri / run-test.py
1 #!/usr/bin/env python3
2 '''
3 Test whether cargo-miri works properly.
4 Assumes the `MIRI_SYSROOT` env var to be set appropriately,
5 and the working directory to contain the cargo-miri-test project.
6 '''
7
8 import sys, subprocess, os, re, difflib
9
10 CGREEN  = '\33[32m'
11 CBOLD   = '\33[1m'
12 CEND    = '\33[0m'
13
14 def fail(msg):
15     print("\nTEST FAIL: {}".format(msg))
16     sys.exit(1)
17
18 def cargo_miri(cmd, quiet = True):
19     args = ["cargo", "miri", cmd]
20     if quiet:
21         args += ["-q"]
22     if 'MIRI_TEST_TARGET' in os.environ:
23         args += ["--target", os.environ['MIRI_TEST_TARGET']]
24     return args
25
26 def normalize_stdout(str):
27     str = str.replace("src\\", "src/") # normalize paths across platforms
28     str = re.sub("finished in \d+\.\d\ds", "finished in $TIME", str) # the time keeps changing, obviously
29     return str
30
31 def normalize_stderr(str):
32     str = re.sub("Preparing a sysroot for Miri \(target: [a-z0-9_-]+\)\.\.\. done\n", "", str) # remove leading cargo-miri setup output
33     return str
34
35 def check_output(actual, path, name):
36     expected = open(path).read()
37     if expected == actual:
38         return True
39     print(f"{path} did not match reference!")
40     print(f"--- BEGIN diff {name} ---")
41     for text in difflib.unified_diff(expected.split("\n"), actual.split("\n")):
42         print(text)
43     print(f"--- END diff {name} ---")
44     return False
45
46 def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env={}):
47     print("Testing {}...".format(name))
48     ## Call `cargo miri`, capture all output
49     p_env = os.environ.copy()
50     p_env.update(env)
51     p = subprocess.Popen(
52         cmd,
53         stdin=subprocess.PIPE,
54         stdout=subprocess.PIPE,
55         stderr=subprocess.PIPE,
56         env=p_env,
57     )
58     (stdout, stderr) = p.communicate(input=stdin)
59     stdout = normalize_stdout(stdout.decode("UTF-8"))
60     stderr = normalize_stderr(stderr.decode("UTF-8"))
61
62     stdout_matches = check_output(stdout, stdout_ref, "stdout")
63     stderr_matches = check_output(stderr, stderr_ref, "stderr")
64     
65     if p.returncode == 0 and stdout_matches and stderr_matches:
66         # All good!
67         return
68     fail("exit code was {}".format(p.returncode))
69
70 def test_no_rebuild(name, cmd, env={}):
71     print("Testing {}...".format(name))
72     p_env = os.environ.copy()
73     p_env.update(env)
74     p = subprocess.Popen(
75         cmd,
76         stdout=subprocess.PIPE,
77         stderr=subprocess.PIPE,
78         env=p_env,
79     )
80     (stdout, stderr) = p.communicate()
81     stdout = stdout.decode("UTF-8")
82     stderr = stderr.decode("UTF-8")
83     if p.returncode != 0:
84         fail("rebuild failed");
85     # Also check for 'Running' as a sanity check.
86     if stderr.count(" Compiling ") > 0 or stderr.count(" Running ") == 0:
87         print("--- BEGIN stderr ---")
88         print(stderr, end="")
89         print("--- END stderr ---")
90         fail("Something was being rebuilt when it should not be (or we got no output)");
91
92 def test_cargo_miri_run():
93     test("`cargo miri run` (no isolation)",
94         cargo_miri("run"),
95         "run.default.stdout.ref", "run.default.stderr.ref",
96         stdin=b'12\n21\n',
97         env={
98             'MIRIFLAGS': "-Zmiri-disable-isolation",
99             'MIRITESTVAR': "wrongval", # make sure the build.rs value takes precedence
100         },
101     )
102     # Special test: run it again *without* `-q` to make sure nothing is being rebuilt (Miri issue #1722)
103     test_no_rebuild("`cargo miri run` (no rebuild)",
104         cargo_miri("run", quiet=False) + ["--", ""],
105         env={'MIRITESTVAR': "wrongval"}, # changing the env var causes a rebuild (re-runs build.rs),
106                                          # so keep it set
107     )
108     test("`cargo miri run` (with arguments and target)",
109         cargo_miri("run") + ["--bin", "cargo-miri-test", "--", "hello world", '"hello world"', r'he\\llo\"world'],
110         "run.args.stdout.ref", "run.args.stderr.ref",
111     )
112     test("`cargo miri r` (subcrate, no isolation)",
113         cargo_miri("r") + ["-p", "subcrate"],
114         "run.subcrate.stdout.ref", "run.subcrate.stderr.ref",
115         env={'MIRIFLAGS': "-Zmiri-disable-isolation"},
116     )
117     test("`cargo miri run` (custom target dir)",
118         # Attempt to confuse the argument parser.
119         cargo_miri("run") + ["--target-dir=custom-run", "--", "--target-dir=target/custom-run"],
120         "run.args.stdout.ref", "run.custom-target-dir.stderr.ref",
121     )
122
123 def test_cargo_miri_test():
124     # rustdoc is not run on foreign targets
125     is_foreign = 'MIRI_TEST_TARGET' in os.environ
126     default_ref = "test.cross-target.stdout.ref" if is_foreign else "test.default.stdout.ref"
127     filter_ref = "test.filter.cross-target.stdout.ref" if is_foreign else "test.filter.stdout.ref"
128
129     # macOS needs permissive provenance inside getrandom_1.
130     test("`cargo miri test`",
131         cargo_miri("test"),
132         default_ref, "test.stderr-empty.ref",
133         env={'MIRIFLAGS': "-Zmiri-permissive-provenance -Zmiri-seed=feed"},
134     )
135     test("`cargo miri test` (no isolation, no doctests)",
136         cargo_miri("test") + ["--bins", "--tests"], # no `--lib`, we disabled that in `Cargo.toml`
137         "test.cross-target.stdout.ref", "test.stderr-empty.ref",
138         env={'MIRIFLAGS': "-Zmiri-permissive-provenance -Zmiri-disable-isolation"},
139     )
140     test("`cargo miri test` (with filter)",
141         cargo_miri("test") + ["--", "--format=pretty", "pl"],
142         filter_ref, "test.stderr-empty.ref",
143     )
144     test("`cargo miri test` (test target)",
145         cargo_miri("test") + ["--test", "test", "--", "--format=pretty"],
146         "test.test-target.stdout.ref", "test.stderr-empty.ref",
147         env={'MIRIFLAGS': "-Zmiri-permissive-provenance"},
148     )
149     test("`cargo miri test` (bin target)",
150         cargo_miri("test") + ["--bin", "cargo-miri-test", "--", "--format=pretty"],
151         "test.bin-target.stdout.ref", "test.stderr-empty.ref",
152     )
153     test("`cargo miri t` (subcrate, no isolation)",
154         cargo_miri("t") + ["-p", "subcrate"],
155         "test.subcrate.stdout.ref", "test.stderr-proc-macro.ref",
156         env={'MIRIFLAGS': "-Zmiri-disable-isolation"},
157     )
158     test("`cargo miri test` (subcrate, doctests)",
159         cargo_miri("test") + ["-p", "subcrate", "--doc"],
160         "test.stdout-empty.ref", "test.stderr-proc-macro-doctest.ref",
161     )
162     test("`cargo miri test` (custom target dir)",
163         cargo_miri("test") + ["--target-dir=custom-test"],
164         default_ref, "test.stderr-empty.ref",
165         env={'MIRIFLAGS': "-Zmiri-permissive-provenance"},
166     )
167     del os.environ["CARGO_TARGET_DIR"] # this overrides `build.target-dir` passed by `--config`, so unset it
168     test("`cargo miri test` (config-cli)",
169         cargo_miri("test") + ["--config=build.target-dir=\"config-cli\"", "-Zunstable-options"],
170         default_ref, "test.stderr-empty.ref",
171         env={'MIRIFLAGS': "-Zmiri-permissive-provenance"},
172     )
173
174 os.chdir(os.path.dirname(os.path.realpath(__file__)))
175 os.environ["CARGO_TARGET_DIR"] = "target" # this affects the location of the target directory that we need to check
176 os.environ["RUST_TEST_NOCAPTURE"] = "0" # this affects test output, so make sure it is not set
177 os.environ["RUST_TEST_THREADS"] = "1" # avoid non-deterministic output due to concurrent test runs
178
179 target_str = " for target {}".format(os.environ['MIRI_TEST_TARGET']) if 'MIRI_TEST_TARGET' in os.environ else ""
180 print(CGREEN + CBOLD + "## Running `cargo miri` tests{}".format(target_str) + CEND)
181
182 test_cargo_miri_run()
183 test_cargo_miri_test()
184 # Ensure we did not create anything outside the expected target dir.
185 for target_dir in ["target", "custom-run", "custom-test", "config-cli"]:
186     if os.listdir(target_dir) != ["miri"]:
187         fail(f"`{target_dir}` contains unexpected files")
188     # Ensure something exists inside that target dir.
189     os.access(os.path.join(target_dir, "miri", "debug", "deps"), os.F_OK)
190
191 print("\nTEST SUCCESSFUL!")
192 sys.exit(0)