xtask/tests/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
use crate::Backend;
use cargo_metadata::{Metadata, MetadataCommand};
use std::process::Command;
use std::process::Stdio;

#[derive(clap::Args, Debug)]
pub(crate) struct TestArgs {
    /// Run tests for a specific backend
    #[clap(default_value_t = Backend::All)]
    backend: Backend,
    /// skip the unit/integration tests
    #[clap(long = "no-integration-tests")]
    no_integration_tests: bool,
    /// skip the doc tests
    #[clap(long = "no-doc-tests")]
    no_doc_tests: bool,
    // skip the checks for the example schema setup
    #[clap(long = "no-example-schema-check")]
    no_example_schema_check: bool,
    /// do not abort running if we encounter an error
    /// while running tests for all backends
    #[clap(long = "keep-going")]
    keep_going: bool,
    /// additional flags passed to cargo nextest while running
    /// unit/integration tests.
    ///
    /// This is useful for passing custom test filters/arguments
    ///
    /// See <https://nexte.st/docs/running/> for details
    flags: Vec<String>,
}

impl TestArgs {
    pub(crate) fn run(mut self) {
        let metadata = MetadataCommand::default().exec().unwrap();
        let success = if matches!(self.backend, Backend::All) {
            let mut success = true;
            for backend in Backend::ALL {
                self.backend = *backend;
                let result = self.run_tests(&metadata);
                success = success && result;
                if !result && !self.keep_going {
                    break;
                }
            }
            success
        } else {
            self.run_tests(&metadata)
        };
        if !success {
            std::process::exit(1);
        }
    }

    fn run_tests(&self, metadata: &Metadata) -> bool {
        let backend_name = self.backend.to_string();
        println!("Running tests for {backend_name}");
        let exclude = crate::utils::get_exclude_for_backend(&backend_name, metadata);
        if std::env::var("DATABASE_URL").is_err() {
            match self.backend {
                Backend::Postgres => {
                    if std::env::var("PG_DATABASE_URL").is_err() {
                        println!(
                            "Remember to set `PG_DATABASE_URL` for running the postgres tests"
                        );
                    }
                }
                Backend::Sqlite => {
                    if std::env::var("SQLITE_DATABASE_URL").is_err() {
                        println!(
                            "Remember to set `SQLITE_DATABASE_URL` for running the sqlite tests"
                        );
                    }
                }
                Backend::Mysql => {
                    if std::env::var("MYSQL_DATABASE_URL").is_err()
                        || std::env::var("MYSQL_UNIT_TEST_DATABASE_URL").is_err()
                    {
                        println!("Remember to set `MYSQL_DATABASE_URL` and `MYSQL_UNIT_TEST_DATABASE_URL` for running the mysql tests");
                    }
                }
                Backend::All => unreachable!(),
            }
        }
        let backend = &self.backend;
        let url = match backend {
            Backend::Postgres => std::env::var("PG_DATABASE_URL"),
            Backend::Sqlite => std::env::var("SQLITE_DATABASE_URL"),
            Backend::Mysql => std::env::var("MYSQL_DATABASE_URL"),
            Backend::All => unreachable!(),
        };
        let url = url
            .or_else(|_| std::env::var("DATABASE_URL"))
            .expect("DATABASE_URL is set for tests");

        // run the migrations
        let mut command = Command::new("cargo");
        command
            .args(["run", "-p", "diesel_cli", "--no-default-features", "-F"])
            .arg(backend.to_string())
            .args(["--", "migration", "run", "--migration-dir"])
            .arg(
                metadata
                    .workspace_root
                    .join("migrations")
                    .join(backend.to_string()),
            )
            .arg("--database-url")
            .arg(&url);
        println!("Run database migration via `{command:?}`");
        let status = command
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .unwrap();
        if !status.success() {
            eprintln!("Failed to run migrations");
            return false;
        }

        if !self.no_integration_tests {
            // run the normal tests via nextest
            let mut command = Command::new("cargo");
            command
                .args(["nextest", "run", "--workspace", "--no-default-features"])
                .current_dir(&metadata.workspace_root)
                .args(exclude)
                .arg("-F")
                .arg(format!("diesel/{backend}"))
                .args(["-F", "diesel/extras"])
                .arg("-F")
                .arg(format!("diesel_derives/{backend}"))
                .arg("-F")
                .arg(format!("diesel_cli/{backend}"))
                .arg("-F")
                .arg(format!("migrations_macros/{backend}"))
                .arg("-F")
                .arg(format!("diesel_migrations/{backend}"))
                .arg("-F")
                .arg(format!("diesel_tests/{backend}"))
                .arg("-F")
                .arg(format!("diesel-dynamic-schema/{backend}"))
                .args(&self.flags);

            if matches!(self.backend, Backend::Mysql) {
                // cannot run mysql tests in parallel
                command.args(["-j", "1"]);
            }
            println!("Running tests via `{command:?}`: ");

            let out = command
                .stderr(Stdio::inherit())
                .stdout(Stdio::inherit())
                .status()
                .unwrap();
            if !out.success() {
                eprintln!("Failed to run integration tests");
                return false;
            }
        } else {
            println!("Integration tests skipped because `--no-integration-tests` was passed");
        }
        if !self.no_doc_tests {
            let mut command = Command::new("cargo");

            command
                .current_dir(&metadata.workspace_root)
                .args([
                    "test",
                    "--doc",
                    "--no-default-features",
                    "-p",
                    "diesel",
                    "-p",
                    "diesel_derives",
                    "-p",
                    "diesel_migrations",
                    "-p",
                    "diesel-dynamic-schema",
                    "-p",
                    "dsl_auto_type",
                    "-p",
                    "diesel_table_macro_syntax",
                    "-F",
                    "diesel/extras",
                ])
                .arg("-F")
                .arg(format!("diesel/{backend}"))
                .arg("-F")
                .arg(format!("diesel_derives/{backend}"))
                .arg("-F")
                .arg(format!("diesel-dynamic-schema/{backend}"));
            if matches!(backend, Backend::Mysql) {
                // cannot run mysql tests in parallel
                command.args(["-j", "1"]);
            }
            println!("Running tests via `{command:?}`: ");
            let status = command
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .status()
                .unwrap();
            if !status.success() {
                eprintln!("Failed to run doc tests");
                return false;
            }
        } else {
            println!("Doc tests are skipped because `--no-doc-tests` was passed");
        }

        if !self.no_example_schema_check {
            let examples = metadata
                .workspace_root
                .join("examples")
                .join(backend.to_string());
            let temp_dir = if matches!(backend, Backend::Sqlite) {
                Some(tempfile::tempdir().unwrap())
            } else {
                None
            };
            let mut fail = false;
            for p in metadata
                .workspace_packages()
                .into_iter()
                .filter(|p| p.manifest_path.starts_with(&examples))
            {
                let example_root = p.manifest_path.parent().unwrap();
                if example_root.join("migrations").exists() {
                    let db_url = if matches!(backend, Backend::Sqlite) {
                        temp_dir
                            .as_ref()
                            .unwrap()
                            .path()
                            .join(&p.name)
                            .display()
                            .to_string()
                    } else {
                        // it's a url with the structure postgres://[user:password@host:port/database?options
                        // we parse it manually as we don't want to pull in the url crate with all
                        // its features
                        let (start, end) = url.rsplit_once('/').unwrap();
                        let query = end.split_once('?').map(|(_, q)| q);

                        let mut url = format!("{start}/{}", p.name);
                        if let Some(query) = query {
                            url.push('?');
                            url.push_str(query);
                        }
                        url
                    };

                    let mut command = Command::new("cargo");
                    command
                        .current_dir(example_root)
                        .args(["run", "-p", "diesel_cli", "--no-default-features", "-F"])
                        .arg(backend.to_string())
                        .args(["--", "database", "reset", "--locked-schema"])
                        .env("DATABASE_URL", db_url);
                    println!(
                        "Check schema for example `{}` ({example_root}) with command `{command:?}`",
                        p.name,
                    );
                    let status = command.status().unwrap();
                    if !status.success() {
                        fail = true;
                        eprintln!("Failed to check example schema for `{}`", p.name);
                        if !self.keep_going {
                            return false;
                        }
                    }
                }
            }
            if fail {
                return false;
            }
        } else {
            println!(
                "Example schema check is skipped because `--no-example-schema-check` was passed"
            );
        }

        true
    }
}