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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use super::{ConfigIdentifier, TestThreads};
use crate::errors::InvalidCustomTestGroupName;
use serde::Deserialize;
use smol_str::SmolStr;
use std::{fmt, str::FromStr};

/// Represents the test group a test is in.
#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum TestGroup {
    /// This test is in the named custom group.
    Custom(CustomTestGroup),

    /// This test is not in a group.
    Global,
}

impl TestGroup {
    pub(crate) fn make_all_groups(
        custom_groups: impl IntoIterator<Item = CustomTestGroup>,
    ) -> impl Iterator<Item = Self> {
        custom_groups
            .into_iter()
            .map(TestGroup::Custom)
            .chain(std::iter::once(TestGroup::Global))
    }
}

impl<'de> Deserialize<'de> for TestGroup {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Try and deserialize the group as a string. (Note: we don't deserialize a
        // `CustomTestGroup` directly because that errors out on None.
        let group = SmolStr::deserialize(deserializer)?;
        if group == "@global" {
            Ok(TestGroup::Global)
        } else {
            Ok(TestGroup::Custom(
                CustomTestGroup::new(group).map_err(serde::de::Error::custom)?,
            ))
        }
    }
}

impl FromStr for TestGroup {
    type Err = InvalidCustomTestGroupName;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "@global" {
            Ok(TestGroup::Global)
        } else {
            Ok(TestGroup::Custom(CustomTestGroup::new(s.into())?))
        }
    }
}

impl fmt::Display for TestGroup {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TestGroup::Global => write!(f, "@global"),
            TestGroup::Custom(group) => write!(f, "{}", group.as_str()),
        }
    }
}

/// Represents a custom test group.
#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct CustomTestGroup(ConfigIdentifier);

impl CustomTestGroup {
    /// Creates a new custom test group, returning an error if it is invalid.
    pub fn new(name: SmolStr) -> Result<Self, InvalidCustomTestGroupName> {
        let identifier = ConfigIdentifier::new(name).map_err(InvalidCustomTestGroupName)?;
        Ok(Self(identifier))
    }

    /// Creates a new custom test group from an identifier.
    pub fn from_identifier(identifier: ConfigIdentifier) -> Self {
        Self(identifier)
    }

    /// Returns the test group as a [`ConfigIdentifier`].
    pub fn as_identifier(&self) -> &ConfigIdentifier {
        &self.0
    }

    /// Returns the test group as a string.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl<'de> Deserialize<'de> for CustomTestGroup {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Try and deserialize as a string.
        let identifier = SmolStr::deserialize(deserializer)?;
        Self::new(identifier).map_err(serde::de::Error::custom)
    }
}

impl fmt::Display for CustomTestGroup {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Configuration for a test group.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct TestGroupConfig {
    /// The maximum number of threads allowed for this test group.
    pub max_threads: TestThreads,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        config::{test_helpers::*, NextestConfig, ToolConfigFile},
        errors::{ConfigParseErrorKind, UnknownTestGroupError},
    };
    use camino::Utf8Path;
    use camino_tempfile::tempdir;
    use indoc::indoc;
    use maplit::btreeset;
    use std::collections::BTreeSet;
    use test_case::test_case;

    #[derive(Debug)]
    enum GroupExpectedError {
        DeserializeError(&'static str),
        InvalidTestGroups(BTreeSet<CustomTestGroup>),
    }

    #[test_case(
        indoc!{r#"
            [test-groups."@tool:my-tool:foo"]
            max-threads = 1
        "#},
        Ok(btreeset! {custom_test_group("user-group"), custom_test_group("@tool:my-tool:foo")})
        ; "group name valid")]
    #[test_case(
        indoc!{r#"
            [test-groups.foo]
            max-threads = 1
        "#},
        Err(GroupExpectedError::InvalidTestGroups(btreeset! {custom_test_group("foo")}))
        ; "group name doesn't start with @tool:")]
    #[test_case(
        indoc!{r#"
            [test-groups."@tool:moo:test"]
            max-threads = 1
        "#},
        Err(GroupExpectedError::InvalidTestGroups(btreeset! {custom_test_group("@tool:moo:test")}))
        ; "group name doesn't start with tool name")]
    #[test_case(
        indoc!{r#"
            [test-groups."@tool:my-tool"]
            max-threads = 1
        "#},
        Err(GroupExpectedError::DeserializeError("test-groups.@tool:my-tool: invalid custom test group name: tool identifier not of the form \"@tool:tool-name:identifier\": `@tool:my-tool`"))
        ; "group name missing suffix colon")]
    #[test_case(
        indoc!{r#"
            [test-groups.'@global']
            max-threads = 1
        "#},
        Err(GroupExpectedError::DeserializeError("test-groups.@global: invalid custom test group name: invalid identifier `@global`"))
        ; "group name is @global")]
    #[test_case(
        indoc!{r#"
            [test-groups.'@foo']
            max-threads = 1
        "#},
        Err(GroupExpectedError::DeserializeError("test-groups.@foo: invalid custom test group name: invalid identifier `@foo`"))
        ; "group name starts with @")]
    fn tool_config_define_groups(
        input: &str,
        expected: Result<BTreeSet<CustomTestGroup>, GroupExpectedError>,
    ) {
        let config_contents = indoc! {r#"
            [profile.default]
            test-group = "user-group"

            [test-groups.user-group]
            max-threads = 1
        "#};
        let workspace_dir = tempdir().unwrap();

        let graph = temp_workspace(workspace_dir.path(), config_contents);
        let workspace_root = graph.workspace().root();
        let tool_path = workspace_root.join(".config/tool.toml");
        std::fs::write(&tool_path, input).unwrap();

        let config_res = NextestConfig::from_sources(
            workspace_root,
            &graph,
            None,
            &[ToolConfigFile {
                tool: "my-tool".to_owned(),
                config_file: tool_path.clone(),
            }][..],
            &Default::default(),
        );
        match expected {
            Ok(expected_groups) => {
                let config = config_res.expect("config is valid");
                let profile = config.profile("default").expect("default profile is known");
                let profile = profile.apply_build_platforms(&build_platforms());
                assert_eq!(
                    profile
                        .test_group_config()
                        .keys()
                        .cloned()
                        .collect::<BTreeSet<_>>(),
                    expected_groups
                );
            }
            Err(expected_error) => {
                let error = config_res.expect_err("config is invalid");
                assert_eq!(error.config_file(), &tool_path);
                assert_eq!(error.tool(), Some("my-tool"));
                match &expected_error {
                    GroupExpectedError::InvalidTestGroups(expected_groups) => {
                        assert!(
                            matches!(
                                error.kind(),
                                ConfigParseErrorKind::InvalidTestGroupsDefinedByTool(groups)
                                    if groups == expected_groups
                            ),
                            "expected config.kind ({}) to be {:?}",
                            error.kind(),
                            expected_error,
                        );
                    }
                    GroupExpectedError::DeserializeError(error_str) => {
                        assert!(
                            matches!(
                                error.kind(),
                                ConfigParseErrorKind::DeserializeError(error)
                                    if error.to_string() == *error_str
                            ),
                            "expected config.kind ({}) to be {:?}",
                            error.kind(),
                            expected_error,
                        );
                    }
                }
            }
        }
    }

    #[test_case(
        indoc!{r#"
            [test-groups."my-group"]
            max-threads = 1
        "#},
        Ok(btreeset! {custom_test_group("my-group")})
        ; "group name valid")]
    #[test_case(
        indoc!{r#"
            [test-groups."@tool:"]
            max-threads = 1
        "#},
        Err(GroupExpectedError::DeserializeError("test-groups.@tool:: invalid custom test group name: tool identifier not of the form \"@tool:tool-name:identifier\": `@tool:`"))
        ; "group name starts with @tool:")]
    #[test_case(
        indoc!{r#"
            [test-groups.'@global']
            max-threads = 1
        "#},
        Err(GroupExpectedError::DeserializeError("test-groups.@global: invalid custom test group name: invalid identifier `@global`"))
        ; "group name is @global")]
    #[test_case(
        indoc!{r#"
            [test-groups.'@foo']
            max-threads = 1
        "#},
        Err(GroupExpectedError::DeserializeError("test-groups.@foo: invalid custom test group name: invalid identifier `@foo`"))
        ; "group name starts with @")]
    fn user_config_define_groups(
        config_contents: &str,
        expected: Result<BTreeSet<CustomTestGroup>, GroupExpectedError>,
    ) {
        let workspace_dir = tempdir().unwrap();
        let workspace_path: &Utf8Path = workspace_dir.path();

        let graph = temp_workspace(workspace_path, config_contents);
        let workspace_root = graph.workspace().root();

        let config_res =
            NextestConfig::from_sources(workspace_root, &graph, None, &[][..], &Default::default());
        match expected {
            Ok(expected_groups) => {
                let config = config_res.expect("config is valid");
                let profile = config.profile("default").expect("default profile is known");
                let profile = profile.apply_build_platforms(&build_platforms());
                assert_eq!(
                    profile
                        .test_group_config()
                        .keys()
                        .cloned()
                        .collect::<BTreeSet<_>>(),
                    expected_groups
                );
            }
            Err(expected_error) => {
                let error = config_res.expect_err("config is invalid");
                assert_eq!(error.tool(), None);
                match &expected_error {
                    GroupExpectedError::InvalidTestGroups(expected_groups) => {
                        assert!(
                            matches!(
                                error.kind(),
                                ConfigParseErrorKind::InvalidTestGroupsDefined(groups)
                                    if groups == expected_groups
                            ),
                            "expected config.kind ({}) to be {:?}",
                            error.kind(),
                            expected_error,
                        );
                    }
                    GroupExpectedError::DeserializeError(error_str) => {
                        assert!(
                            matches!(
                                error.kind(),
                                ConfigParseErrorKind::DeserializeError(error)
                                    if error.to_string() == *error_str
                            ),
                            "expected config.kind ({}) to be {:?}",
                            error.kind(),
                            expected_error,
                        );
                    }
                }
            }
        }
    }

    #[test_case(
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "foo"
        "#},
        "",
        "",
        Some("tool1"),
        vec![UnknownTestGroupError {
            profile_name: "default".to_owned(),
            name: test_group("foo"),
        }],
        btreeset! { TestGroup::Global }
        ; "unknown group in tool config")]
    #[test_case(
        "",
        "",
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "foo"
        "#},
        None,
        vec![UnknownTestGroupError {
            profile_name: "default".to_owned(),
            name: test_group("foo"),
        }],
        btreeset! { TestGroup::Global }
        ; "unknown group in user config")]
    #[test_case(
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "@tool:tool1:foo"

            [test-groups."@tool:tool1:foo"]
            max-threads = 1
        "#},
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "@tool:tool1:foo"
        "#},
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "foo"
        "#},
        Some("tool2"),
        vec![UnknownTestGroupError {
            profile_name: "default".to_owned(),
            name: test_group("@tool:tool1:foo"),
        }],
        btreeset! { TestGroup::Global }
        ; "depends on downstream tool config")]
    #[test_case(
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "foo"
        "#},
        "",
        indoc!{r#"
            [[profile.default.overrides]]
            filter = 'all()'
            test-group = "foo"

            [test-groups.foo]
            max-threads = 1
        "#},
        Some("tool1"),
        vec![UnknownTestGroupError {
            profile_name: "default".to_owned(),
            name: test_group("foo"),
        }],
        btreeset! { TestGroup::Global }
        ; "depends on user config")]
    fn unknown_groups(
        tool1_config: &str,
        tool2_config: &str,
        user_config: &str,
        tool: Option<&str>,
        expected_errors: Vec<UnknownTestGroupError>,
        expected_known_groups: BTreeSet<TestGroup>,
    ) {
        let workspace_dir = tempdir().unwrap();
        let workspace_path: &Utf8Path = workspace_dir.path();

        let graph = temp_workspace(workspace_path, user_config);
        let workspace_root = graph.workspace().root();
        let tool1_path = workspace_root.join(".config/tool1.toml");
        std::fs::write(&tool1_path, tool1_config).unwrap();
        let tool2_path = workspace_root.join(".config/tool2.toml");
        std::fs::write(&tool2_path, tool2_config).unwrap();

        let config = NextestConfig::from_sources(
            workspace_root,
            &graph,
            None,
            &[
                ToolConfigFile {
                    tool: "tool1".to_owned(),
                    config_file: tool1_path,
                },
                ToolConfigFile {
                    tool: "tool2".to_owned(),
                    config_file: tool2_path,
                },
            ][..],
            &Default::default(),
        )
        .expect_err("config is invalid");
        assert_eq!(config.tool(), tool);
        match config.kind() {
            ConfigParseErrorKind::UnknownTestGroups {
                errors,
                known_groups,
            } => {
                assert_eq!(errors, &expected_errors, "expected errors match");
                assert_eq!(known_groups, &expected_known_groups, "known groups match");
            }
            other => {
                panic!("expected ConfigParseErrorKind::UnknownTestGroups, got {other}");
            }
        }
    }
}