blob: 7e455a2af6f3ccb87eeb666dd3ca61f9d3e54ab7 [file] [log] [blame]
Brian Silverman4e662aa2022-05-11 23:10:19 -07001// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use std::{convert::TryInto, fs::File, io::Write, path::Path};
10
11use indexmap::map::IndexMap as HashMap;
12
13use assert_cmd::Command;
14use autocxx_integration_tests::{build_from_folder, RsFindMode};
15use itertools::Itertools;
Brian Silvermanf3ec38b2022-07-06 20:43:36 -070016use tempfile::{tempdir, TempDir};
Brian Silverman4e662aa2022-05-11 23:10:19 -070017
18static MAIN_RS: &str = concat!(
19 include_str!("../../../demo/src/main.rs"),
20 "#[link(name = \"autocxx-demo\")]\nextern \"C\" {}"
21);
22static INPUT_H: &str = include_str!("../../../demo/src/input.h");
23static BLANK: &str = "// Blank autocxx placeholder";
24
25static MAIN2_RS: &str = concat!(
26 include_str!("data/main2.rs"),
27 "#[link(name = \"autocxx-demo\")]\nextern \"C\" {}"
28);
29static DIRECTIVE1_RS: &str = include_str!("data/directive1.rs");
30static DIRECTIVE2_RS: &str = include_str!("data/directive2.rs");
31static INPUT2_H: &str = include_str!("data/input2.h");
32static INPUT3_H: &str = include_str!("data/input3.h");
33
Brian Silvermanf3ec38b2022-07-06 20:43:36 -070034const KEEP_TEMPDIRS: bool = true;
Brian Silverman4e662aa2022-05-11 23:10:19 -070035
36#[test]
37fn test_help() -> Result<(), Box<dyn std::error::Error>> {
38 let mut cmd = Command::cargo_bin("autocxx-gen")?;
39 cmd.arg("-h").assert().success();
40 Ok(())
41}
42
43enum RsGenMode {
44 Single,
45 Archive,
46}
47
48fn base_test<F>(
49 tmp_dir: &TempDir,
50 rs_gen_mode: RsGenMode,
51 arg_modifier: F,
52) -> Result<(), Box<dyn std::error::Error>>
53where
54 F: FnOnce(&mut Command),
55{
56 let mut standard_files = HashMap::new();
57 standard_files.insert("input.h", INPUT_H.as_bytes());
58 standard_files.insert("main.rs", MAIN_RS.as_bytes());
59 let result = base_test_ex(
60 tmp_dir,
61 rs_gen_mode,
62 arg_modifier,
63 standard_files,
64 vec!["main.rs"],
65 );
66 assert_contentful(tmp_dir, "gen0.cc");
67 result
68}
69
70fn base_test_ex<F>(
71 tmp_dir: &TempDir,
72 rs_gen_mode: RsGenMode,
73 arg_modifier: F,
74 files_to_write: HashMap<&str, &[u8]>,
75 files_to_process: Vec<&str>,
76) -> Result<(), Box<dyn std::error::Error>>
77where
78 F: FnOnce(&mut Command),
79{
80 let demo_code_dir = tmp_dir.path().join("demo");
81 std::fs::create_dir(&demo_code_dir).unwrap();
82 for (filename, content) in files_to_write {
83 write_to_file(&demo_code_dir, filename, content);
84 }
85 let mut cmd = Command::cargo_bin("autocxx-gen")?;
86 arg_modifier(&mut cmd);
87 cmd.arg("--inc")
88 .arg(demo_code_dir.to_str().unwrap())
89 .arg("--outdir")
90 .arg(tmp_dir.path().to_str().unwrap())
91 .arg("--gen-cpp");
92 cmd.arg(match rs_gen_mode {
93 RsGenMode::Single => "--gen-rs-include",
94 RsGenMode::Archive => "--gen-rs-archive",
95 });
96 for file in files_to_process {
97 cmd.arg(demo_code_dir.join(file));
98 }
99 let output = cmd.output();
100 if let Ok(output) = output {
101 eprintln!("Cmd stdout: {:?}", std::str::from_utf8(&output.stdout));
102 eprintln!("Cmd stderr: {:?}", std::str::from_utf8(&output.stderr));
103 }
104 cmd.assert().success();
105 Ok(())
106}
107
108#[test]
109fn test_gen() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700110 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700111 base_test(&tmp_dir, RsGenMode::Single, |_| {})?;
112 File::create(tmp_dir.path().join("cxx.h"))
113 .and_then(|mut cxx_h| cxx_h.write_all(autocxx_engine::HEADER.as_bytes()))?;
114 std::env::set_var("OUT_DIR", tmp_dir.path().to_str().unwrap());
115 let r = build_from_folder(
116 tmp_dir.path(),
117 &tmp_dir.path().join("demo/main.rs"),
118 vec![tmp_dir.path().join("autocxx-ffi-default-gen.rs")],
119 &["gen0.cc"],
120 RsFindMode::AutocxxRs,
121 );
122 if KEEP_TEMPDIRS {
123 println!("Tempdir: {:?}", tmp_dir.into_path().to_str());
124 }
125 r.unwrap();
126 Ok(())
127}
128
129#[test]
130fn test_gen_archive() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700131 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700132 base_test(&tmp_dir, RsGenMode::Archive, |_| {})?;
133 File::create(tmp_dir.path().join("cxx.h"))
134 .and_then(|mut cxx_h| cxx_h.write_all(autocxx_engine::HEADER.as_bytes()))?;
135 let r = build_from_folder(
136 tmp_dir.path(),
137 &tmp_dir.path().join("demo/main.rs"),
138 vec![tmp_dir.path().join("gen.rs.json")],
139 &["gen0.cc"],
140 RsFindMode::AutocxxRsArchive,
141 );
142 if KEEP_TEMPDIRS {
143 println!("Tempdir: {:?}", tmp_dir.into_path().to_str());
144 }
145 r.unwrap();
146 Ok(())
147}
148
149#[test]
150fn test_gen_multiple_in_archive() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700151 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700152
153 let mut files = HashMap::new();
154 files.insert("input2.h", INPUT2_H.as_bytes());
155 files.insert("input3.h", INPUT3_H.as_bytes());
156 files.insert("main.rs", MAIN2_RS.as_bytes());
157 files.insert("directive1.rs", DIRECTIVE1_RS.as_bytes());
158 files.insert("directive2.rs", DIRECTIVE2_RS.as_bytes());
159 base_test_ex(
160 &tmp_dir,
161 RsGenMode::Archive,
162 |cmd| {
163 cmd.arg("--generate-exact").arg("8");
164 },
165 files,
166 vec!["directive1.rs", "directive2.rs"],
167 )?;
168 File::create(tmp_dir.path().join("cxx.h"))
169 .and_then(|mut cxx_h| cxx_h.write_all(autocxx_engine::HEADER.as_bytes()))?;
170 // We've asked to create 8 C++ files, mostly blank. Build 'em all.
171 let cpp_files = (0..7).map(|id| format!("gen{}.cc", id)).collect_vec();
172 let cpp_files = cpp_files.iter().map(|s| s.as_str()).collect_vec();
173 let r = build_from_folder(
174 tmp_dir.path(),
175 &tmp_dir.path().join("demo/main.rs"),
176 vec![tmp_dir.path().join("gen.rs.json")],
177 &cpp_files,
178 RsFindMode::AutocxxRsArchive,
179 );
180 if KEEP_TEMPDIRS {
181 println!("Tempdir: {:?}", tmp_dir.into_path().to_str());
182 }
183 r.unwrap();
184 Ok(())
185}
186
187#[test]
188fn test_include_prefixes() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700189 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700190 base_test(&tmp_dir, RsGenMode::Single, |cmd| {
191 cmd.arg("--cxx-h-path")
192 .arg("foo/")
193 .arg("--cxxgen-h-path")
194 .arg("bar/")
195 .arg("--generate-exact")
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700196 .arg("3")
197 .arg("--fix-rs-include-name");
Brian Silverman4e662aa2022-05-11 23:10:19 -0700198 })?;
199 assert_contains(&tmp_dir, "autocxxgen0.h", "foo/cxx.h");
200 // Currently we don't test cxxgen-h-path because we build the demo code
201 // which doesn't refer to generated cxx header code.
202 Ok(())
203}
204
205#[test]
206fn test_gen_fixed_num() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700207 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700208 let depfile = tmp_dir.path().join("test.d");
209 base_test(&tmp_dir, RsGenMode::Single, |cmd| {
210 cmd.arg("--generate-exact")
211 .arg("2")
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700212 .arg("--fix-rs-include-name")
Brian Silverman4e662aa2022-05-11 23:10:19 -0700213 .arg("--depfile")
214 .arg(depfile);
215 })?;
216 assert_contentful(&tmp_dir, "gen0.cc");
217 assert_contentful(&tmp_dir, "gen0.h");
218 assert_not_contentful(&tmp_dir, "gen1.cc");
219 assert_contentful(&tmp_dir, "autocxxgen0.h");
220 assert_not_contentful(&tmp_dir, "gen1.h");
221 assert_not_contentful(&tmp_dir, "autocxxgen1.h");
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700222 assert_contentful(&tmp_dir, "gen0.include.rs");
Brian Silverman4e662aa2022-05-11 23:10:19 -0700223 assert_contentful(&tmp_dir, "test.d");
224 File::create(tmp_dir.path().join("cxx.h"))
225 .and_then(|mut cxx_h| cxx_h.write_all(autocxx_engine::HEADER.as_bytes()))?;
226 let r = build_from_folder(
227 tmp_dir.path(),
228 &tmp_dir.path().join("demo/main.rs"),
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700229 vec![tmp_dir.path().join("gen0.include.rs")],
Brian Silverman4e662aa2022-05-11 23:10:19 -0700230 &["gen0.cc"],
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700231 RsFindMode::AutocxxRsFile,
Brian Silverman4e662aa2022-05-11 23:10:19 -0700232 );
233 if KEEP_TEMPDIRS {
234 println!("Tempdir: {:?}", tmp_dir.into_path().to_str());
235 }
236 r.unwrap();
237 Ok(())
238}
239
240#[test]
241fn test_gen_preprocess() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700242 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700243 let prepro_path = tmp_dir.path().join("preprocessed.h");
244 base_test(&tmp_dir, RsGenMode::Single, |cmd| {
245 cmd.env("AUTOCXX_PREPROCESS", prepro_path.to_str().unwrap());
246 })?;
247 assert_contentful(&tmp_dir, "preprocessed.h");
248 // Check that a random thing from one of the headers in
249 // `ALL_KNOWN_SYSTEM_HEADERS` is included.
250 assert!(std::fs::read_to_string(prepro_path)?.contains("integer_sequence"));
251 Ok(())
252}
253
254#[test]
255fn test_gen_repro() -> Result<(), Box<dyn std::error::Error>> {
Brian Silvermanf3ec38b2022-07-06 20:43:36 -0700256 let tmp_dir = tempdir()?;
Brian Silverman4e662aa2022-05-11 23:10:19 -0700257 let repro_path = tmp_dir.path().join("repro.json");
258 base_test(&tmp_dir, RsGenMode::Single, |cmd| {
259 cmd.env("AUTOCXX_REPRO_CASE", repro_path.to_str().unwrap());
260 })?;
261 assert_contentful(&tmp_dir, "repro.json");
262 // Check that a random thing from one of the headers in
263 // `ALL_KNOWN_SYSTEM_HEADERS` is included.
264 assert!(std::fs::read_to_string(repro_path)?.contains("integer_sequence"));
265 Ok(())
266}
267
268fn write_to_file(dir: &Path, filename: &str, content: &[u8]) {
269 let path = dir.join(filename);
270 let mut f = File::create(&path).expect("Unable to create file");
271 f.write_all(content).expect("Unable to write file");
272}
273
274fn assert_contentful(outdir: &TempDir, fname: &str) {
275 let p = outdir.path().join(fname);
276 if !p.exists() {
277 panic!("File {} didn't exist", p.to_string_lossy());
278 }
279 assert!(
280 p.metadata().unwrap().len() > BLANK.len().try_into().unwrap(),
281 "File {} is empty",
282 fname
283 );
284}
285
286fn assert_not_contentful(outdir: &TempDir, fname: &str) {
287 let p = outdir.path().join(fname);
288 if !p.exists() {
289 panic!("File {} didn't exist", p.to_string_lossy());
290 }
291 assert!(
292 p.metadata().unwrap().len() <= BLANK.len().try_into().unwrap(),
293 "File {} is not empty; it contains {}",
294 fname,
295 std::fs::read_to_string(&p).unwrap_or_default()
296 );
297}
298
299fn assert_contains(outdir: &TempDir, fname: &str, pattern: &str) {
300 let p = outdir.path().join(fname);
301 let content = std::fs::read_to_string(&p).expect(fname);
302 eprintln!("content = {}", content);
303 assert!(content.contains(pattern));
304}