scroll icon indicating copy to clipboard operation
scroll copied to clipboard

ctx: add tests for `StrCtx`

Open kkent030315 opened this issue 4 months ago • 4 comments

Relevant issue:

  • #117

This PR adds tests for StrCtx variants that was previously uncovered.

kkent030315 avatar Aug 24 '25 11:08 kkent030315

During tests I discovered some odd behaviors. @m4b Could you take a look?

(These tests all pass)

1. Empty input actually consumes one char for empty input

#[test]
fn strctx_delimiter_empty_input() {
    let data = b"";
    let (s, consumed) = <&str>::try_from_ctx(data, StrCtx::Delimiter(0)).unwrap();
    assert_eq!(s, "");
    assert_eq!(consumed, 1);
}
#[test]
fn strctx_delimiter_until_empty_input() {
    let data: &'static [u8; 0] = b"";
    let (s, consumed) = <&str>::try_from_ctx(data, StrCtx::DelimiterUntil(0, 0)).unwrap();
    assert_eq!(s, "");
    assert_eq!(consumed, 1);
}

2. DelimiterUntil with zero limit consumes one char

  1. Returning a string when
#[test]
fn strctx_delimiter_until_zero() {
    let data = b"hello";
    let (s, consumed) = <&str>::try_from_ctx(data, StrCtx::DelimiterUntil(0, 0)).unwrap();
    assert_eq!(s, "");
    assert_eq!(consumed, 1);
}

3. Returning a string when no delimiter was present in the input

I'm thinking that it is a little unusual however to return the string if a delimiter isn't found https://github.com/m4b/scroll/issues/108#issuecomment-3217264990

#[test]
fn strctx_delimiter_not_found() {
    let data = b"hello world";
    let (s, consumed) = <&str>::try_from_ctx(data, StrCtx::Delimiter(0)).unwrap();
    assert_eq!(s, "hello world");
    assert_eq!(consumed, 12); // full string + 1 for missing delimiter
}
#[test]
fn strctx_delimiter_until_limit_reached() {
    let data = b"hello world";
    let (s, consumed) = <&str>::try_from_ctx(data, StrCtx::DelimiterUntil(0, 5)).unwrap();
    assert_eq!(s, "hello");
    assert_eq!(consumed, 6); // "hello" + delimiter
}

kkent030315 avatar Aug 24 '25 12:08 kkent030315

I think some discussed before in #96. It is still good to add tests however.

kkent030315 avatar Aug 24 '25 12:08 kkent030315

nvm, I overlooked the tests in pread_str and such, closing :man_shrugging:

kkent030315 avatar Aug 24 '25 12:08 kkent030315

Reopening because I think this will be useful to have separately. I’m going to take it and put it into another file though I think. Don’t feel obligated to work on this, I’m sure you have other things to do.

and yes I think my next task is to resurvey why goblin depends on empty str parsing returning 1 length, ideally fix it, and have the patch in #96 reopened and merged before a 0.14 release.

alongside that I’ll also add that new strctx for strings or update the current one, or more likely if updating it deprecate it first then swap the behavior in a 0.15 release

m4b avatar Aug 24 '25 17:08 m4b