File: parser_roundtrip.rs

package info (click to toggle)
python-libcst 1.8.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,240 kB
  • sloc: python: 78,096; makefile: 15; sh: 2
file content (55 lines) | stat: -rw-r--r-- 1,641 bytes parent folder | download | duplicates (5)
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
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree

use difference::assert_diff;
use itertools::Itertools;
use libcst_native::{parse_module, prettify_error, Codegen};
use std::{
    iter::once,
    path::{Component, PathBuf},
};

fn all_fixtures() -> impl Iterator<Item = (PathBuf, String)> {
    let mut path = PathBuf::from(file!());
    path.pop();
    path = path
        .components()
        .skip(1)
        .chain(once(Component::Normal("fixtures".as_ref())))
        .collect();

    path.read_dir().expect("read_dir").into_iter().map(|file| {
        let path = file.unwrap().path();
        let contents = std::fs::read_to_string(&path).expect("reading file");
        (path, contents)
    })
}

#[test]
fn roundtrip_fixtures() {
    for (path, input) in all_fixtures() {
        let input = if let Some(stripped) = input.strip_prefix('\u{feff}') {
            stripped
        } else {
            &input
        };
        let m = match parse_module(input, None) {
            Ok(m) => m,
            Err(e) => panic!("{}", prettify_error(e, format!("{:#?}", path).as_ref())),
        };
        let mut state = Default::default();
        m.codegen(&mut state);
        let generated = state.to_string();
        if generated != input {
            let got = visualize(&generated);
            let expected = visualize(input);
            assert_diff!(expected.as_ref(), got.as_ref(), "", 0);
        }
    }
}

fn visualize(s: &str) -> String {
    s.replace(' ', "▩").lines().join("↩\n")
}