Skip to content

Feature for easier test bootstrapping #70

@pitaj

Description

@pitaj

While implementing a recent parser, I came upon an annoyance: manually slicing spans when writing test cases was very tedious.

So I modified nom_locate with a feature that allows for much easier testing by ignoring location information during test. It works by utilizing the fact that line should never be zero in normal operation:

    /// Create a span for use in testing
    /// 
    /// Spans created this way will be tested for equality purely on the fragment,
    /// ignoring the `offset` and `line`.
    #[cfg(feature = "easy-test")]
    pub fn test_new_extra(program: T, extra: X) -> LocatedSpan<T, X> {
        LocatedSpan {
            offset: 0,
            line: 0,
            fragment: program,
            extra,
        }
    }

#[cfg(feature = "easy-test")]
impl<T: AsBytes + PartialEq, X> PartialEq for LocatedSpan<T, X> {
    fn eq(&self, other: &Self) -> bool {
        if self.line == 0 || other.line == 0 {
            self.fragment == other.fragment
        } else {
            self.line == other.line && self.offset == other.offset && self.fragment == other.fragment
        }
    }
}

This allows me to define a function to easily use in tests:

function sp(s: &str) -> Span {
    Span::test_new_extra(s, Default::default())
}

And use it in a test like so:

assert_eq!(
    path(sp("a.b.c, what")),
    Ok((
        sp(", what"),
        Expression::Path {
            span: sp("a.b.c"),
            path: vec![
                PathPart::Part(sp("a")),
                PathPart::Part(sp("b")),
                PathPart::Part(sp("c"))
            ]
        }
    ))
);

I've never run into a case where span location was an issue, since it's always automatically derived correctly. So testing it in tests is a lot of tedium for very little if any benefit.

Let me know if there's a way of doing this I'm missing.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions