Skip to content
Myr

json.rs

This file

Path

tests/json.rs

441 lines · 12.3 KiB · Rust

Last changed by

Not known.

History of this file

Take it

1use std::time;23use serde_derive::Deserialize;4use serde_json as json;56use crate::hay::{SHERLOCK, SHERLOCK_CRLF};7use crate::util::{Dir, TestCommand};89#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]10#[serde(tag = "type", content = "data")]11#[serde(rename_all = "snake_case")]12enum Message {13    Begin(Begin),14    End(End),15    Match(Match),16    Context(Context),17    Summary(Summary),18}1920impl Message {21    fn unwrap_begin(&self) -> Begin {22        match *self {23            Message::Begin(ref x) => x.clone(),24            ref x => panic!("expected Message::Begin but got {x:?}"),25        }26    }2728    fn unwrap_end(&self) -> End {29        match *self {30            Message::End(ref x) => x.clone(),31            ref x => panic!("expected Message::End but got {x:?}"),32        }33    }3435    fn unwrap_match(&self) -> Match {36        match *self {37            Message::Match(ref x) => x.clone(),38            ref x => panic!("expected Message::Match but got {x:?}"),39        }40    }4142    fn unwrap_context(&self) -> Context {43        match *self {44            Message::Context(ref x) => x.clone(),45            ref x => panic!("expected Message::Context but got {x:?}"),46        }47    }4849    fn unwrap_summary(&self) -> Summary {50        match *self {51            Message::Summary(ref x) => x.clone(),52            ref x => panic!("expected Message::Summary but got {x:?}"),53        }54    }55}5657#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]58#[serde(deny_unknown_fields)]59struct Begin {60    path: Option<Data>,61}6263#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]64#[serde(deny_unknown_fields)]65struct End {66    path: Option<Data>,67    binary_offset: Option<u64>,68    stats: Stats,69}7071#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]72#[serde(deny_unknown_fields)]73struct Summary {74    elapsed_total: Duration,75    stats: Stats,76}7778#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]79#[serde(deny_unknown_fields)]80struct Match {81    path: Option<Data>,82    lines: Data,83    line_number: Option<u64>,84    absolute_offset: u64,85    submatches: Vec<SubMatch>,86}8788#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]89#[serde(deny_unknown_fields)]90struct Context {91    path: Option<Data>,92    lines: Data,93    line_number: Option<u64>,94    absolute_offset: u64,95    submatches: Vec<SubMatch>,96}9798#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]99#[serde(deny_unknown_fields)]100struct SubMatch {101    #[serde(rename = "match")]102    m: Data,103    replacement: Option<Data>,104    start: usize,105    end: usize,106}107108#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]109#[serde(untagged)]110enum Data {111    Text { text: String },112    // This variant is used when the data isn't valid UTF-8. The bytes are113    // base64 encoded, so using a String here is OK.114    Bytes { bytes: String },115}116117impl Data {118    fn text(s: &str) -> Data {119        Data::Text { text: s.to_string() }120    }121    fn bytes(s: &str) -> Data {122        Data::Bytes { bytes: s.to_string() }123    }124}125126#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]127#[serde(deny_unknown_fields)]128struct Stats {129    elapsed: Duration,130    searches: u64,131    searches_with_match: u64,132    bytes_searched: u64,133    bytes_printed: u64,134    matched_lines: u64,135    matches: u64,136}137138#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]139#[serde(deny_unknown_fields)]140struct Duration {141    #[serde(flatten)]142    duration: time::Duration,143    human: String,144}145146/// Decode JSON Lines into a Vec<Message>. If there was an error decoding,147/// this function panics.148fn json_decode(jsonlines: &str) -> Vec<Message> {149    json::Deserializer::from_str(jsonlines)150        .into_iter()151        .collect::<Result<Vec<Message>, _>>()152        .unwrap()153}154155rgtest!(basic, |dir: Dir, mut cmd: TestCommand| {156    dir.create("sherlock", SHERLOCK);157    cmd.arg("--json").arg("-B1").arg("Sherlock Holmes").arg("sherlock");158159    let msgs = json_decode(&cmd.stdout());160161    assert_eq!(162        msgs[0].unwrap_begin(),163        Begin { path: Some(Data::text("sherlock")) }164    );165    assert_eq!(166        msgs[1].unwrap_context(),167        Context {168            path: Some(Data::text("sherlock")),169            lines: Data::text(170                "Holmeses, success in the province of \171                 detective work must always\n",172            ),173            line_number: Some(2),174            absolute_offset: 65,175            submatches: vec![],176        }177    );178    assert_eq!(179        msgs[2].unwrap_match(),180        Match {181            path: Some(Data::text("sherlock")),182            lines: Data::text(183                "be, to a very large extent, the result of luck. \184                 Sherlock Holmes\n",185            ),186            line_number: Some(3),187            absolute_offset: 129,188            submatches: vec![SubMatch {189                m: Data::text("Sherlock Holmes"),190                replacement: None,191                start: 48,192                end: 63,193            },],194        }195    );196    assert_eq!(msgs[3].unwrap_end().path, Some(Data::text("sherlock")));197    assert_eq!(msgs[3].unwrap_end().binary_offset, None);198    assert_eq!(msgs[4].unwrap_summary().stats.searches_with_match, 1);199    assert_eq!(msgs[4].unwrap_summary().stats.bytes_printed, 494);200});201202rgtest!(replacement, |dir: Dir, mut cmd: TestCommand| {203    dir.create("sherlock", SHERLOCK);204    cmd.arg("--json")205        .arg("-B1")206        .arg("Sherlock Holmes")207        .args(["-r", "John Watson"])208        .arg("sherlock");209210    let msgs = json_decode(&cmd.stdout());211212    assert_eq!(213        msgs[0].unwrap_begin(),214        Begin { path: Some(Data::text("sherlock")) }215    );216    assert_eq!(217        msgs[1].unwrap_context(),218        Context {219            path: Some(Data::text("sherlock")),220            lines: Data::text(221                "Holmeses, success in the province of \222                 detective work must always\n",223            ),224            line_number: Some(2),225            absolute_offset: 65,226            submatches: vec![],227        }228    );229    assert_eq!(230        msgs[2].unwrap_match(),231        Match {232            path: Some(Data::text("sherlock")),233            lines: Data::text(234                "be, to a very large extent, the result of luck. \235                 Sherlock Holmes\n",236            ),237            line_number: Some(3),238            absolute_offset: 129,239            submatches: vec![SubMatch {240                m: Data::text("Sherlock Holmes"),241                replacement: Some(Data::text("John Watson")),242                start: 48,243                end: 63,244            },],245        }246    );247    assert_eq!(msgs[3].unwrap_end().path, Some(Data::text("sherlock")));248    assert_eq!(msgs[3].unwrap_end().binary_offset, None);249    assert_eq!(msgs[4].unwrap_summary().stats.searches_with_match, 1);250    assert_eq!(msgs[4].unwrap_summary().stats.bytes_printed, 531);251});252253rgtest!(quiet_stats, |dir: Dir, mut cmd: TestCommand| {254    dir.create("sherlock", SHERLOCK);255    cmd.arg("--json")256        .arg("--quiet")257        .arg("--stats")258        .arg("Sherlock Holmes")259        .arg("sherlock");260261    let msgs = json_decode(&cmd.stdout());262    assert_eq!(msgs[0].unwrap_summary().stats.searches_with_match, 1);263    assert_eq!(msgs[0].unwrap_summary().stats.bytes_searched, 367);264});265266#[cfg(unix)]267rgtest!(notutf8, |dir: Dir, mut cmd: TestCommand| {268    use std::ffi::OsStr;269    use std::os::unix::ffi::OsStrExt;270271    // This test does not work with PCRE2 because PCRE2 does not support the272    // `u` flag.273    if dir.is_pcre2() {274        return;275    }276    // macOS doesn't like this either... sigh.277    if cfg!(target_os = "macos") {278        return;279    }280281    let name = &b"foo\xFFbar"[..];282    let contents = &b"quux\xFFbaz"[..];283284    // APFS does not support creating files with invalid UTF-8 bytes, so just285    // skip the test if we can't create our file. Presumably we don't need this286    // check if we're already skipping it on macOS, but maybe other file287    // systems won't like this test either?288    if !dir.try_create_bytes(OsStr::from_bytes(name), contents).is_ok() {289        return;290    }291    cmd.arg("--json").arg(r"(?-u)\xFF");292293    let msgs = json_decode(&cmd.stdout());294295    assert_eq!(296        msgs[0].unwrap_begin(),297        Begin { path: Some(Data::bytes("Zm9v/2Jhcg==")) }298    );299    assert_eq!(300        msgs[1].unwrap_match(),301        Match {302            path: Some(Data::bytes("Zm9v/2Jhcg==")),303            lines: Data::bytes("cXV1eP9iYXo="),304            line_number: Some(1),305            absolute_offset: 0,306            submatches: vec![SubMatch {307                m: Data::bytes("/w=="),308                replacement: None,309                start: 4,310                end: 5,311            },],312        }313    );314});315316rgtest!(notutf8_file, |dir: Dir, mut cmd: TestCommand| {317    use std::ffi::OsStr;318319    // This test does not work with PCRE2 because PCRE2 does not support the320    // `u` flag.321    if dir.is_pcre2() {322        return;323    }324325    let name = "foo";326    let contents = &b"quux\xFFbaz"[..];327328    // APFS does not support creating files with invalid UTF-8 bytes, so just329    // skip the test if we can't create our file.330    if !dir.try_create_bytes(OsStr::new(name), contents).is_ok() {331        return;332    }333    cmd.arg("--json").arg(r"(?-u)\xFF");334335    let msgs = json_decode(&cmd.stdout());336337    assert_eq!(338        msgs[0].unwrap_begin(),339        Begin { path: Some(Data::text("foo")) }340    );341    assert_eq!(342        msgs[1].unwrap_match(),343        Match {344            path: Some(Data::text("foo")),345            lines: Data::bytes("cXV1eP9iYXo="),346            line_number: Some(1),347            absolute_offset: 0,348            submatches: vec![SubMatch {349                m: Data::bytes("/w=="),350                replacement: None,351                start: 4,352                end: 5,353            },],354        }355    );356});357358// See: https://github.com/BurntSushi/ripgrep/issues/416359//360// This test in particular checks that our match does _not_ include the `\r`361// even though the '$' may be rewritten as '(?:\r??$)' and could thus include362// `\r` in the match.363rgtest!(crlf, |dir: Dir, mut cmd: TestCommand| {364    dir.create("sherlock", SHERLOCK_CRLF);365    cmd.arg("--json").arg("--crlf").arg(r"Sherlock$").arg("sherlock");366367    let msgs = json_decode(&cmd.stdout());368369    assert_eq!(370        msgs[1].unwrap_match().submatches[0].clone(),371        SubMatch {372            m: Data::text("Sherlock"),373            replacement: None,374            start: 56,375            end: 64376        },377    );378});379380// See: https://github.com/BurntSushi/ripgrep/issues/1095381//382// This test checks that we don't drop the \r\n in a matching line when --crlf383// mode is enabled.384rgtest!(r1095_missing_crlf, |dir: Dir, mut cmd: TestCommand| {385    dir.create("foo", "test\r\n");386387    // Check without --crlf flag.388    let msgs = json_decode(&cmd.arg("--json").arg("test").stdout());389    assert_eq!(msgs.len(), 4);390    assert_eq!(msgs[1].unwrap_match().lines, Data::text("test\r\n"));391392    // Now check with --crlf flag.393    let msgs = json_decode(&cmd.arg("--crlf").stdout());394    assert_eq!(msgs.len(), 4);395    assert_eq!(msgs[1].unwrap_match().lines, Data::text("test\r\n"));396});397398// See: https://github.com/BurntSushi/ripgrep/issues/1095399//400// This test checks that we don't return empty submatches when matching a `\n`401// in CRLF mode.402rgtest!(r1095_crlf_empty_match, |dir: Dir, mut cmd: TestCommand| {403    dir.create("foo", "test\r\n\n");404405    // Check without --crlf flag.406    let msgs = json_decode(&cmd.arg("-U").arg("--json").arg("\n").stdout());407    assert_eq!(msgs.len(), 4);408409    let m = msgs[1].unwrap_match();410    assert_eq!(m.lines, Data::text("test\r\n\n"));411    assert_eq!(m.submatches[0].m, Data::text("\n"));412    assert_eq!(m.submatches[1].m, Data::text("\n"));413414    // Now check with --crlf flag.415    let msgs = json_decode(&cmd.arg("--crlf").stdout());416    assert_eq!(msgs.len(), 4);417418    let m = msgs[1].unwrap_match();419    assert_eq!(m.lines, Data::text("test\r\n\n"));420    assert_eq!(m.submatches[0].m, Data::text("\n"));421    assert_eq!(m.submatches[1].m, Data::text("\n"));422});423424// See: https://github.com/BurntSushi/ripgrep/issues/1412425rgtest!(r1412_look_behind_match_missing, |dir: Dir, mut cmd: TestCommand| {426    // Only PCRE2 supports look-around.427    if !dir.is_pcre2() {428        return;429    }430431    dir.create("test", "foo\nbar\n");432433    let msgs = json_decode(434        &cmd.arg("-U").arg("--json").arg(r"(?<=foo\n)bar").stdout(),435    );436    assert_eq!(msgs.len(), 4);437438    let m = msgs[1].unwrap_match();439    assert_eq!(m.lines, Data::text("bar\n"));440    assert_eq!(m.submatches.len(), 1);441});