]> git.lizzy.rs Git - rust.git/blob - test-cargo-miri/run-test.py
make test-cargo-miri only about cargo
[rust.git] / 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     return re.sub("finished in \d+\.\d\ds", "finished in $TIME", str)
29
30 def check_output(actual, path, name):
31     expected = open(path).read()
32     if expected == actual:
33         return True
34     print(f"{path} did not match reference!")
35     print(f"--- BEGIN diff {name} ---")
36     for text in difflib.unified_diff(expected.split("\n"), actual.split("\n")):
37         print(text)
38     print(f"--- END diff {name} ---")
39     return False
40
41 def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env={}):
42     print("Testing {}...".format(name))
43     ## Call `cargo miri`, capture all output
44     p_env = os.environ.copy()
45     p_env.update(env)
46     p = subprocess.Popen(
47         cmd,
48         stdin=subprocess.PIPE,
49         stdout=subprocess.PIPE,
50         stderr=subprocess.PIPE,
51         env=p_env,
52     )
53     (stdout, stderr) = p.communicate(input=stdin)
54     stdout = stdout.decode("UTF-8")
55     stderr = stderr.decode("UTF-8")
56     stdout = normalize_stdout(stdout)
57
58     stdout_matches = check_output(stdout, stdout_ref, "stdout")
59     stderr_matches = check_output(stderr, stderr_ref, "stderr")
60     
61     if p.returncode == 0 and stdout_matches and stderr_matches:
62         # All good!
63         return
64     fail("exit code was {}".format(p.returncode))
65
66 def test_no_rebuild(name, cmd, env={}):
67     print("Testing {}...".format(name))
68     p_env = os.environ.copy()
69     p_env.update(env)
70     p = subprocess.Popen(
71         cmd,
72         stdout=subprocess.PIPE,
73         stderr=subprocess.PIPE,
74         env=p_env,
75     )
76     (stdout, stderr) = p.communicate()
77     stdout = stdout.decode("UTF-8")
78     stderr = stderr.decode("UTF-8")
79     if p.returncode != 0:
80         fail("rebuild failed");
81     # Also check for 'Running' as a sanity check.
82     if stderr.count(" Compiling ") > 0 or stderr.count(" Running ") == 0:
83         print("--- BEGIN stderr ---")
84         print(stderr, end="")
85         print("--- END stderr ---")
86         fail("Something was being rebuilt when it should not be (or we got no output)");
87
88 def test_cargo_miri_run():
89     test("`cargo miri run` (no isolation)",
90         cargo_miri("run"),
91         "run.default.stdout.ref", "run.default.stderr.ref",
92         stdin=b'12\n21\n',
93         env={
94             'MIRIFLAGS': "-Zmiri-disable-isolation",
95             'MIRITESTVAR': "wrongval", # make sure the build.rs value takes precedence
96         },
97     )
98     # Special test: run it again *without* `-q` to make sure nothing is being rebuilt (Miri issue #1722)
99     test_no_rebuild("`cargo miri run` (no rebuild)",
100         cargo_miri("run", quiet=False) + ["--", ""],
101         env={'MIRITESTVAR': "wrongval"}, # changing the env var causes a rebuild (re-runs build.rs),
102                                          # so keep it set
103     )
104     test("`cargo miri run` (with arguments and target)",
105         cargo_miri("run") + ["--bin", "cargo-miri-test", "--", "hello world", '"hello world"', r'he\\llo\"world'],
106         "run.args.stdout.ref", "run.args.stderr.ref",
107     )
108     test("`cargo miri r` (subcrate, no isolation)",
109         cargo_miri("r") + ["-p", "subcrate"],
110         "run.subcrate.stdout.ref", "run.subcrate.stderr.ref",
111         env={'MIRIFLAGS': "-Zmiri-disable-isolation"},
112     )
113     test("`cargo miri run` (custom target dir)",
114         # Attempt to confuse the argument parser.
115         cargo_miri("run") + ["--target-dir=custom-run", "--", "--target-dir=target/custom-run"],
116         "run.args.stdout.ref", "run.custom-target-dir.stderr.ref",
117     )
118
119 def test_cargo_miri_test():
120     # rustdoc is not run on foreign targets
121     is_foreign = 'MIRI_TEST_TARGET' in os.environ
122     default_ref = "test.cross-target.stdout.ref" if is_foreign else "test.default.stdout.ref"
123     filter_ref = "test.filter.cross-target.stdout.ref" if is_foreign else "test.filter.stdout.ref"
124
125     # macOS needs permissive provenance inside getrandom_1.
126     test("`cargo miri test`",
127         cargo_miri("test"),
128         default_ref, "test.stderr-empty.ref",
129         env={'MIRIFLAGS': "-Zmiri-permissive-provenance -Zmiri-seed=feed"},
130     )
131     test("`cargo miri test` (no isolation, no doctests)",
132         cargo_miri("test") + ["--bins", "--tests"], # no `--lib`, we disabled that in `Cargo.toml`
133         "test.cross-target.stdout.ref", "test.stderr-empty.ref",
134         env={'MIRIFLAGS': "-Zmiri-permissive-provenance -Zmiri-disable-isolation"},
135     )
136     test("`cargo miri test` (with filter)",
137         cargo_miri("test") + ["--", "--format=pretty", "pl"],
138         filter_ref, "test.stderr-empty.ref",
139     )
140     test("`cargo miri test` (test target)",
141         cargo_miri("test") + ["--test", "test", "--", "--format=pretty"],
142         "test.test-target.stdout.ref", "test.stderr-empty.ref",
143         env={'MIRIFLAGS': "-Zmiri-permissive-provenance"},
144     )
145     test("`cargo miri test` (bin target)",
146         cargo_miri("test") + ["--bin", "cargo-miri-test", "--", "--format=pretty"],
147         "test.bin-target.stdout.ref", "test.stderr-empty.ref",
148     )
149     test("`cargo miri t` (subcrate, no isolation)",
150         cargo_miri("t") + ["-p", "subcrate"],
151         "test.subcrate.stdout.ref", "test.stderr-proc-macro.ref",
152         env={'MIRIFLAGS': "-Zmiri-disable-isolation"},
153     )
154     test("`cargo miri test` (subcrate, doctests)",
155         cargo_miri("test") + ["-p", "subcrate", "--doc"],
156         "test.stdout-empty.ref", "test.stderr-proc-macro-doctest.ref",
157     )
158     test("`cargo miri test` (custom target dir)",
159         cargo_miri("test") + ["--target-dir=custom-test"],
160         default_ref, "test.stderr-empty.ref",
161         env={'MIRIFLAGS': "-Zmiri-permissive-provenance"},
162     )
163     del os.environ["CARGO_TARGET_DIR"] # this overrides `build.target-dir` passed by `--config`, so unset it
164     test("`cargo miri test` (config-cli)",
165         cargo_miri("test") + ["--config=build.target-dir=\"config-cli\"", "-Zunstable-options"],
166         default_ref, "test.stderr-empty.ref",
167         env={'MIRIFLAGS': "-Zmiri-permissive-provenance"},
168     )
169
170 os.chdir(os.path.dirname(os.path.realpath(__file__)))
171 os.environ["CARGO_TARGET_DIR"] = "target" # this affects the location of the target directory that we need to check
172 os.environ["RUST_TEST_NOCAPTURE"] = "0" # this affects test output, so make sure it is not set
173 os.environ["RUST_TEST_THREADS"] = "1" # avoid non-deterministic output due to concurrent test runs
174
175 target_str = " for target {}".format(os.environ['MIRI_TEST_TARGET']) if 'MIRI_TEST_TARGET' in os.environ else ""
176 print(CGREEN + CBOLD + "## Running `cargo miri` tests{}".format(target_str) + CEND)
177
178 if not 'MIRI_SYSROOT' in os.environ:
179     # Make sure we got a working sysroot.
180     # (If the sysroot gets built later when output is compared, that leads to test failures.)
181     subprocess.run(cargo_miri("setup"), check=True)
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)