maelstrom-pytest 0.14.0

Python Test Runner for Maelstrom.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
pub mod cli;
mod config;
pub mod pattern;
mod pytest;

pub use config::{Config, PytestConfig};
pub use maelstrom_test_runner::log::LoggerBuilder;

use anyhow::{anyhow, bail, Result};
use cli::ExtraCommandLineOptions;
use maelstrom_base::{
    enum_set, CaptureFileSystemChanges, JobDevice, JobMount, JobNetwork, JobOutcome,
    JobTerminationStatus, Utf8PathBuf,
};
use maelstrom_client::{
    glob_layer_spec, job_spec,
    spec::{ContainerParent, ImageRef, LayerSpec, PathsLayerSpec, PrefixOptions, StubsLayerSpec},
    Client, ProjectDir,
};
use maelstrom_container::{DockerReference, ImageName};
use maelstrom_test_runner::{
    metadata::Metadata,
    ui::{UiMessage, UiSender},
    util::UseColor,
    BuildDir, Directories, ListingMode, TestArtifact, TestArtifactKey, TestCaseMetadata,
    TestCollector, TestFilter, TestPackage, TestPackageId, Wait, WaitStatus,
};
use maelstrom_util::{fs::Fs, root::RootBuf};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{
    collections::{
        HashSet,
        {hash_map::Entry, HashMap},
    },
    fmt,
    os::unix::fs::PermissionsExt as _,
    path::{Path, PathBuf},
    str::FromStr,
    sync::Mutex,
};

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PytestArtifactKey {
    path: PathBuf,
}

impl TestArtifactKey for PytestArtifactKey {}

impl fmt::Display for PytestArtifactKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.path.display().fmt(f)
    }
}

impl FromStr for PytestArtifactKey {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self> {
        Ok(Self { path: s.into() })
    }
}

impl TestFilter for pattern::Pattern {
    type Package = PytestPackage;
    type ArtifactKey = PytestArtifactKey;
    type CaseMetadata = PytestCaseMetadata;

    fn compile(include: &[String], exclude: &[String]) -> Result<Self> {
        pattern::compile_filter(include, exclude)
    }

    fn filter(
        &self,
        package: &PytestPackage,
        artifact: Option<&PytestArtifactKey>,
        case: Option<(&str, &PytestCaseMetadata)>,
    ) -> Option<bool> {
        let c = pattern::Context {
            package: package.name().into(),
            file: artifact.map(|a| a.path.display().to_string()),
            case: case.map(|(name, metadata)| pattern::Case {
                name: name.into(),
                node_id: metadata.node_id.clone(),
                markers: metadata.markers.clone(),
            }),
        };
        pattern::interpret_pattern(self, &c)
    }
}

pub struct PytestTestCollector<'client> {
    client: &'client Client,
    config: PytestConfig,
    directories: Directories,
    test_layers: Mutex<HashMap<ImageRef, LayerSpec>>,
}

impl PytestTestCollector<'_> {
    fn get_pip_packages(
        &self,
        image_spec: ImageRef,
        ref_: &DockerReference,
        ui: &UiSender,
    ) -> Result<Utf8PathBuf> {
        let fs = Fs::new();

        // Build some paths
        let cache_dir: &Path = self.directories.cache.as_ref();
        let project_dir: &Path = self.directories.project.as_ref();
        let packages_path: PathBuf = cache_dir.join(format!("pip_packages/{ref_}"));
        if !fs.exists(&packages_path) {
            fs.create_dir_all(&packages_path)?;
        }
        let source_req_path = project_dir.join("test-requirements.txt");
        let saved_req_path = packages_path.join("requirements.txt");
        let upper = packages_path.join("root");

        // Are the existing packages up-to-date
        let source_req = fs.read_to_string(&source_req_path)?;
        let saved_req = fs.read_to_string_if_exists(&saved_req_path)?;
        if Some(source_req) == saved_req {
            return Ok(upper.try_into()?);
        }

        ui.send(UiMessage::UpdateEnqueueStatus(
            "installing pip packages".into(),
        ));

        // Delete the work dir in case we have leaked it
        let work = packages_path.join("work");
        if fs.exists(&work) {
            let inner_work = work.join("work");
            if fs.exists(&inner_work) {
                let mut work_perm = fs.metadata(&inner_work)?.permissions();
                work_perm.set_mode(0o777);
                fs.set_permissions(work.join("work"), work_perm)?;
            }
            fs.remove_dir_all(&work)?;
        }

        // Ensure the work and upper exist now
        fs.create_dir_all(&work)?;
        if !fs.exists(&upper) {
            fs.create_dir_all(&upper)?;
        }

        // We need to install our own resolv.conf to get internet access
        // These two addresses are for cloudflare's DNS server
        let resolv_conf = packages_path.join("resolv.conf");
        fs.write(&resolv_conf, b"nameserver 1.1.1.1\nnameserver 1.0.0.1")?;

        // Run a local job to install the packages
        let layers = vec![
            LayerSpec::Paths(PathsLayerSpec {
                paths: vec![source_req_path.clone().try_into()?],
                prefix_options: Default::default(),
            }),
            LayerSpec::Stubs(StubsLayerSpec {
                stubs: vec!["/dev/null".into()],
            }),
            LayerSpec::Paths(PathsLayerSpec {
                paths: vec![resolv_conf.clone().try_into()?],
                prefix_options: PrefixOptions {
                    strip_prefix: Some(resolv_conf.parent().unwrap().to_owned().try_into()?),
                    prepend_prefix: Some("/etc/".into()),
                    canonicalize: false,
                    follow_symlinks: false,
                },
            }),
        ];
        let (_, outcome) = self.client.run_job(job_spec! {
            "/bin/sh",
            layers: layers,
            arguments: [
                "-c".to_owned(),
                format!(
                    "
                        set -ex
                        pip install --requirement {}
                        python -m compileall /usr/lib/python* /usr/local/lib/python*
                        ",
                    source_req_path
                        .to_str()
                        .ok_or_else(|| anyhow!("non-UTF8 path"))?
                ),
            ],
            parent: ContainerParent::Image(image_spec),
            network: JobNetwork::Local,
            mounts: [
                JobMount::Devices {
                    devices: enum_set![JobDevice::Null],
                },
            ],
            capture_file_system_changes: CaptureFileSystemChanges {
                upper: upper.clone().try_into()?,
                work: work.clone().try_into()?,
            },
        })?;
        let outcome = outcome.map_err(|err| anyhow!("error installing pip packages: {err:?}"))?;
        match outcome {
            JobOutcome::Completed(completed) => {
                if completed.status != JobTerminationStatus::Exited(0) {
                    bail!(
                        "pip install failed:\nstderr: {}\nstdout{}",
                        completed.effects.stderr,
                        completed.effects.stdout
                    )
                }
            }
            JobOutcome::TimedOut(_) => bail!("pip install timed out"),
        }

        // Delete any special character files
        for path in fs.walk(&upper) {
            let path = path?;
            let meta = fs.symlink_metadata(&path)?;
            if !(meta.is_file() || meta.is_dir() || meta.is_symlink()) {
                fs.remove_file(path)?;
            }
        }

        // Remove work
        let mut work_perm = fs.metadata(work.join("work"))?.permissions();
        work_perm.set_mode(0o777);
        fs.set_permissions(work.join("work"), work_perm)?;
        fs.remove_dir_all(work)?;

        // Save requirements
        fs.copy(source_req_path, saved_req_path)?;

        Ok(upper.try_into()?)
    }

    fn build_test_layer(&self, image: ImageRef, ui: &UiSender) -> Result<Option<LayerSpec>> {
        let image_name: ImageName = image.name.parse()?;
        let ImageName::Docker(ref_) = image_name else {
            return Ok(None);
        };
        if ref_.name() != "python" {
            return Ok(None);
        }

        let packages_path = self.get_pip_packages(image, &ref_, ui)?;
        let packages_path = packages_path
            .strip_prefix(&self.directories.project)
            .unwrap();
        Ok(Some(glob_layer_spec! {
            format!("{packages_path}/**"),
            strip_prefix: packages_path,
        }))
    }
}

#[derive(Debug)]
pub struct PytestTestArtifact {
    path: PathBuf,
    tests: Vec<(String, PytestCaseMetadata)>,
    ignored_tests: Vec<String>,
    package: PytestPackageId,
    pytest_options: PytestConfig,
    test_layers: HashMap<ImageRef, LayerSpec>,
}

#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
pub struct PytestPackageId(String);

impl TestPackageId for PytestPackageId {}

#[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq, Serialize, Deserialize)]
pub struct PytestCaseMetadata {
    node_id: String,
    markers: Vec<String>,
}

impl TestCaseMetadata for PytestCaseMetadata {}

impl TestArtifact for PytestTestArtifact {
    type ArtifactKey = PytestArtifactKey;
    type PackageId = PytestPackageId;
    type CaseMetadata = PytestCaseMetadata;

    fn package(&self) -> PytestPackageId {
        self.package.clone()
    }

    fn to_key(&self) -> PytestArtifactKey {
        PytestArtifactKey {
            path: self.path.clone(),
        }
    }

    fn path(&self) -> &Path {
        &self.path
    }

    fn list_tests(&self) -> Result<Vec<(String, PytestCaseMetadata)>> {
        Ok(self.tests.clone())
    }

    fn list_ignored_tests(&self) -> Result<Vec<String>> {
        Ok(self.ignored_tests.clone())
    }

    fn build_command(
        &self,
        _case_name: &str,
        case_metadata: &PytestCaseMetadata,
    ) -> (Utf8PathBuf, Vec<String>) {
        let mut args = vec!["-m".into(), "pytest".into(), "--verbose".into()];
        args.extend(self.pytest_options.extra_pytest_args.clone());
        args.extend(self.pytest_options.extra_pytest_test_args.clone());
        args.push(case_metadata.node_id.clone());
        ("/usr/local/bin/python".into(), args)
    }

    fn format_case(
        &self,
        _package_name: &str,
        _case_name: &str,
        case_metadata: &PytestCaseMetadata,
    ) -> String {
        case_metadata.node_id.clone()
    }

    fn get_test_layers(&self, metadata: &Metadata) -> Vec<LayerSpec> {
        match &metadata.container.parent {
            Some(ContainerParent::Image(image_spec)) => self
                .test_layers
                .get(image_spec)
                .into_iter()
                .cloned()
                .collect(),
            _ => vec![],
        }
    }
}

#[derive(Clone, Debug)]
pub struct PytestPackage {
    name: String,
    id: PytestPackageId,
    artifacts: Vec<PytestArtifactKey>,
}

impl TestPackage for PytestPackage {
    type PackageId = PytestPackageId;
    type ArtifactKey = PytestArtifactKey;

    fn name(&self) -> &str {
        &self.name
    }

    fn artifacts(&self) -> Vec<PytestArtifactKey> {
        self.artifacts.clone()
    }

    fn id(&self) -> PytestPackageId {
        self.id.clone()
    }
}

impl TestCollector for PytestTestCollector<'_> {
    const ENQUEUE_MESSAGE: &'static str = "collecting tests...";

    type BuildHandle = pytest::WaitHandle;
    type Artifact = PytestTestArtifact;
    type ArtifactStream = pytest::TestArtifactStream;
    type TestFilter = pattern::Pattern;
    type PackageId = PytestPackageId;
    type Package = PytestPackage;
    type ArtifactKey = PytestArtifactKey;
    type CaseMetadata = PytestCaseMetadata;

    fn start(
        &self,
        use_color: UseColor,
        _packages: Vec<&PytestPackage>,
        _ui: &UiSender,
    ) -> Result<(pytest::WaitHandle, pytest::TestArtifactStream)> {
        let test_layers = self.test_layers.lock().unwrap().clone();
        let (handle, stream) = pytest::pytest_collect_tests(
            use_color,
            &self.config,
            &self.directories.project,
            &self.directories.build,
            test_layers,
        )?;
        Ok((handle, stream))
    }

    fn build_test_layers(&self, images: HashSet<ImageRef>, ui: &UiSender) -> Result<()> {
        let mut test_layers = self.test_layers.lock().unwrap();
        for image in images {
            if let Entry::Vacant(e) = test_layers.entry(image.clone()) {
                if let Some(layer) = self.build_test_layer(image, ui)? {
                    e.insert(layer);
                }
            }
        }
        Ok(())
    }

    fn get_packages(&self, _ui: &UiSender) -> Result<Vec<PytestPackage>> {
        Ok(vec![PytestPackage {
            name: "default".into(),
            id: PytestPackageId("default".into()),
            artifacts: find_artifacts(self.directories.project.as_ref())?,
        }])
    }

    fn remove_fixture_output(_case_str: &str, mut lines: Vec<String>) -> Vec<String> {
        let start_re = Regex::new("=+ FAILURES =+").unwrap();
        let end_re = Regex::new("=+ short test summary info =+").unwrap();

        if let Some(pos) = lines.iter().position(|s| start_re.is_match(s.as_str())) {
            lines = lines[(pos + 2)..].to_vec();
        }
        if let Some(pos) = lines.iter().rposition(|s| end_re.is_match(s.as_str())) {
            lines = lines[..pos].to_vec();
        }
        lines
    }
}

#[test]
fn remove_fixture_output_basic_case() {
    let example = indoc::indoc!(
        "
        ============================= test session starts ==============================
        platform linux -- Python 3.12.3, pytest-8.1.1, pluggy-1.4.0 -- /usr/local/bin/python
        cachedir: .pytest_cache
        rootdir: /
        configfile: pyproject.toml
        plugins: cov-4.1.0, xdist-3.3.1
        created: 1/1 worker
        1 worker [1 item]

        scheduling tests via LoadScheduling

        mypyc/test/test_commandline.py::TestCommandLine::testCompileMypyc
        [gw0] [100%] FAILED mypyc/test/test_commandline.py::TestCommandLine::testCompileMypyc

        =================================== FAILURES ===================================
        _______________________________ testCompileMypyc _______________________________
        [gw0] linux -- Python 3.12.3 /usr/local/bin/python
        data: /mypyc/test-data/commandline.test:5:
        Failed: Invalid output (/mypyc/test-data/commandline.test, line 5)
        ----------------------------- Captured stderr call -----------------------------
        this is the stderr of the test
        this is also test output
        =========================== short test summary info ============================
        FAILED mypyc/test/test_commandline.py::TestCommandLine::testCompileMypyc
        ============================== 1 failed in 2.22s ===============================
        "
    );
    let cleansed = PytestTestCollector::remove_fixture_output(
        "tests::i_be_failing",
        example.split('\n').map(ToOwned::to_owned).collect(),
    );
    assert_eq!(
        cleansed.join("\n"),
        indoc::indoc!(
            "
            [gw0] linux -- Python 3.12.3 /usr/local/bin/python
            data: /mypyc/test-data/commandline.test:5:
            Failed: Invalid output (/mypyc/test-data/commandline.test, line 5)
            ----------------------------- Captured stderr call -----------------------------
            this is the stderr of the test
            this is also test output\
            "
        )
    );
}

#[test]
fn default_test_metadata_parses() {
    use maelstrom_test_runner::TestRunner as _;
    maelstrom_test_runner::metadata::Store::<pattern::Pattern>::load(
        TestRunner::DEFAULT_TEST_METADATA_FILE_CONTENTS,
        &Default::default(),
    )
    .unwrap();
}

impl Wait for pytest::WaitHandle {
    fn wait(&self) -> Result<WaitStatus> {
        pytest::WaitHandle::wait(self)
    }

    fn kill(&self) -> Result<()> {
        pytest::WaitHandle::kill(self)
    }
}

fn find_artifacts(path: &Path) -> Result<Vec<PytestArtifactKey>> {
    let cwd = path.canonicalize()?;
    Ok(Fs
        .walk(&cwd)
        .filter_map(|path| {
            path.ok().map(|path| PytestArtifactKey {
                path: path.strip_prefix(&cwd).unwrap().into(),
            })
        })
        .collect())
}

pub struct TestRunner;

impl maelstrom_test_runner::TestRunner for TestRunner {
    type Config = Config;
    type ExtraCommandLineOptions = ExtraCommandLineOptions;
    type Metadata = ();
    type TestCollector<'client> = PytestTestCollector<'client>;
    type TestCollectorConfig = PytestConfig;

    const BASE_DIRECTORIES_PREFIX: &'static str = "maelstrom/maelstrom-pytest";
    const ENVIRONMENT_VARIABLE_PREFIX: &'static str = "MAELSTROM_PYTEST";
    const TEST_METADATA_FILE_NAME: &'static str = "maelstrom-pytest.toml";
    const DEFAULT_TEST_METADATA_FILE_CONTENTS: &'static str =
        include_str!("default-test-metadata.toml");

    fn get_listing_mode(extra_options: &ExtraCommandLineOptions) -> ListingMode {
        if extra_options.list {
            ListingMode::Tests
        } else {
            ListingMode::None
        }
    }

    fn get_metadata_and_project_directory(_config: &Config) -> Result<((), RootBuf<ProjectDir>)> {
        Ok(((), RootBuf::new(Path::new(".").canonicalize()?)))
    }

    fn get_directories(_metadata: &(), project: RootBuf<ProjectDir>) -> Directories {
        let build = project.join(".maelstrom-pytest");
        let cache = build.join("cache");
        let state = build.join("state");
        Directories {
            build,
            cache,
            project,
            state,
        }
    }

    fn get_paths_to_exclude_from_watch(directories: &Directories) -> Vec<PathBuf> {
        vec![directories.build.clone().into_path_buf()]
    }

    fn build_test_collector<'client>(
        client: &'client Client,
        config: &PytestConfig,
        directories: &Directories,
        _log: &slog::Logger,
        _metadata: (),
    ) -> Result<PytestTestCollector<'client>> {
        Ok(PytestTestCollector {
            client,
            config: config.clone(),
            directories: directories.clone(),
            test_layers: Mutex::new(HashMap::new()),
        })
    }
}