Skip to content
This repository has been archived by the owner on Dec 17, 2024. It is now read-only.

Testing serde with HashMap #27

Closed
maxtremblay opened this issue Jul 15, 2020 · 3 comments
Closed

Testing serde with HashMap #27

maxtremblay opened this issue Jul 15, 2020 · 3 comments

Comments

@maxtremblay
Copy link

maxtremblay commented Jul 15, 2020

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.

@nausicaea

This comment has been minimized.

@BratSinot
Copy link

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);
}

@dtolnay
Copy link
Contributor

dtolnay commented Jan 23, 2022

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

4 participants