serde-rs/test

Testing serde with HashMap

maxtremblay opened this issue · 3 comments

Hello!

The following test will often fails since HashMap does not guarantees ordering of the data.

use serde_test::{assert_tokens, Token};
use std::collections::HashMap;

#[test]
fn test_ser_de() {
    let mut map = HashMap::new();
    map.insert('a', 10);
    map.insert('b', 20);
    
    assert_tokens(
        &map,            
        &[
                Token::Map { len: Some(2) }, 
                Token::Char('a'),
                Token::I32(10),
                Token::Char('b'),
                Token::I32(20),
                Token::MapEnd,
        ],
    );
}

Is there a way to test that the results contains the sequence of tokens Token::Char('a'), Token::I32(10) between Token::Map(...) and Token::MapEnd?

Thanks.

I know that +1's don't usually help, but I am facing the same issue and am hoping to find some guidance on how to deal with the problem.

More than HashMap, HashSet have same problem =(

use serde_test::{assert_ser_tokens, Token};
use std::collections::{HashMap, HashSet};

fn main() {
    let mut data: HashMap<String, HashSet<String>> = Default::default();
    data.insert(
        "foo".to_owned(),
        HashSet::from_iter(["id1".to_owned(), "id0".to_owned()]),
    );
    data.insert("bar".to_owned(), HashSet::from_iter(["id0".to_owned()]));

    println!("{:?}", data);

    assert_ser_tokens(
        &data,
        &[
            Token::Map { len: Some(2) },
            Token::String("foo"),
            Token::Seq { len: Some(2) },
            Token::String("id1"),
            Token::String("id0"),
            Token::SeqEnd,
            Token::String("bar"),
            Token::Seq { len: Some(1) },
            Token::String("id0"),
            Token::SeqEnd,
            Token::MapEnd,
        ],
    );

    let mut data: HashMap<String, HashSet<String>> = Default::default();
    data.insert(
        "id0".to_owned(),
        HashSet::from_iter(["foo".to_owned(), "bar".to_owned()]),
    );
    data.insert("id1".to_owned(), HashSet::from_iter(["foo".to_owned()]));

    println!("{:?}", data);
}

Please take this question to one of the resources listed in https://github.com/serde-rs/serde/tree/v1.0.135#getting-help. Sorry that no one was able to provide guidance here.