Token De/Serializer for testing De/Serialize implementations

Related tags

Testing test
Overview

serde_test   Build Status Latest Version

This crate provides a convenient concise way to write unit tests for implementations of Serialize and Deserialize.

The Serialize impl for a value can be characterized by the sequence of Serializer calls that are made in the course of serializing the value, so serde_test provides a [Token] abstraction which corresponds roughly to Serializer method calls. There is an [assert_ser_tokens] function to test that a value serializes to a particular sequence of method calls, an [assert_de_tokens] function to test that a value can be deserialized from a particular sequence of method calls, and an [assert_tokens] function to test both directions. There are also functions to test expected failure conditions.

Here is an example from the linked-hash-map crate.

use linked_hash_map::LinkedHashMap;
use serde_test::{assert_tokens, Token};

#[test]
fn test_ser_de_empty() {
    let map = LinkedHashMap::<char, u32>::new();

    assert_tokens(
        &map,
        &[
            Token::Map { len: Some(0) },
            Token::MapEnd,
        ],
    );
}

#[test]
fn test_ser_de() {
    let mut map = LinkedHashMap::new();
    map.insert('b', 20);
    map.insert('a', 10);
    map.insert('c', 30);

    assert_tokens(
        &map,
        &[
            Token::Map { len: Some(3) },
            Token::Char('b'),
            Token::I32(20),
            Token::Char('a'),
            Token::I32(10),
            Token::Char('c'),
            Token::I32(30),
            Token::MapEnd,
        ],
    );
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Comments
  • Add `assert_de_tokens_error2` that shows deserialized value in the message

    Add `assert_de_tokens_error2` that shows deserialized value in the message

    Continuation of https://github.com/serde-rs/serde/pull/2460 in new repo.

    Instead of changing assert_de_tokens_error I've added a new function which does the same, but outputs deserialized value in case of failure

    opened by Mingun 0
  • Why `Token::Enum` + smth and `Token::...Variant` is exist?

    Why `Token::Enum` + smth and `Token::...Variant` is exist?

    I found, that there are two ways to express how the enum should be serialized:

    #[derive(Deserialize, Serialize, Debug, PartialEq)]
    enum Enum {
      Unit,
    }
    
    assert_tokens(
      &Enum::Unit,
      &[
        Token::Enum { name: "Enum" },
        Token::Str("Unit"),
        Token::Unit,
      ],
    );
    
    assert_tokens(
      &Enum::Unit,
      &[
        Token::UnitVariant { name: "Enum", variant: "Unit" },
      ],
    );
    

    Surprisely, both of that asserts are passed, although is is obvious that serialization can give only one of that results. After examining code I've found this very confusing check: https://github.com/serde-rs/serde/blob/0c6a2bbf794abe966a4763f5b7ff23acb535eb7f/serde_test/src/ser.rs#L184-L190 That means that tester will change it's behavior depending on the testing data, that is not expected from the testing tool.

    So the questions are:

    • why both variants are exist?
    • what one should use?
    • isn't it necessary to keep only one of them?
    opened by Mingun 2
  • `serde_test`: Don't forward (almost) everything to `deserialize_any`

    `serde_test`: Don't forward (almost) everything to `deserialize_any`

    By forwarding things like deserialize_bool to deserialize_any, the deserialize_bool behavior can then deserialize a string, for example. This is unexpected and lets through a ton of stuff that, in my opinion, shouldn't be. serde_test is for testing, not general purpose use, so it should remain strict in what it accepts. deserialize_bool should reject everything other than true or false, unless there's some reason I'm missing?

    opened by jhpratt 3
  • Flatten Option permits deserialization without Token::Some in the token stream, but non-flatten not

    Flatten Option permits deserialization without Token::Some in the token stream, but non-flatten not

    I found that test in the sources: https://github.com/serde-rs/serde/blob/e6f086d85edfa3bde3f4486142301962ec5f1c8c/test_suite/tests/test_annotations.rs#L1824-L1925

    Can anybody explain, why deserialize tokens don't match the serialized one (Token::Some is missed)? For me that seems as an error, because non-flatten option can't be deserialized in the same manner:

    use serde::Deserialize;
    use serde_test::{assert_de_tokens, Token};
    
    #[derive(Debug, PartialEq, Deserialize)]
    struct Outer {
      #[serde(flatten)]
      inner: Inner,
    }
    
    #[derive(Debug, PartialEq, Deserialize)]
    struct Inner {
      option: Option<u64>,
    }
    
    /// Failed with
    /// tokens failed to deserialize: invalid type: integer `2`, expected option
    #[test]
    fn ordinal() {
      assert_de_tokens(
        &Inner {
          option: Some(2),
        },
        &[
          Token::Map { len: None },
          Token::Str("option"),
          Token::U64(2),
          Token::MapEnd,
        ],
      );
    }
    /// Success (!?)
    #[test]
    fn flatten() {
      assert_de_tokens(
        &Outer {
          inner: Inner {
            option: Some(2),
          },
        },
        &[
          Token::Map { len: None },
          Token::Str("option"),
          Token::U64(2),
          Token::MapEnd,
        ],
      );
    }
    
    opened by Mingun 0
  • Add assert_de_tokens_error examples for Compact and Readable representation

    Add assert_de_tokens_error examples for Compact and Readable representation

    I had a hard time finding out about how to use assert_de_tokens_error in combination with types having both readable and compact representation.

    If one simply uses assert_de_tokens_error::<Foo> for a type Foo with both readable and compact representation, the following error message is provided:

    Types which have different human-readable and compact representations 
    must explicitly mark their test cases with `serde_test::Configure`
    

    This makes sense in general but isn't really that helpful.

    It took me way too long to realize that the correct calls to achieve this are assert_de_tokens_error::<Compact<Foo>> and assert_de_tokens_error::<Readable<Foo>>.

    This, again, makes sense but isn't that obvious, especially given the original error message.

    It would be nice to provide some examples for this use case in the documentation of assert_de_tokens_error.

    opened by huxi 1
Releases(1.0.176)
Owner
Serialization framework for Rust
null
Testing Framework for Rust

Polish Polish is Test-Driven Development done right Getting Started Installing the Package The crates.io package is kept up-to-date with all the major

Fadi Hanna Al-Kass 49 Dec 18, 2022
ArchTest is a rule based architecture testing tool for rust

ArchTest is a rule based architecture testing tool. It applies static analyses on the specified rust project to extract use relationships.

Tom Dymel 7 Sep 26, 2021
Rnp - A simple cloud-friendly tool for testing network reachability.

Rnp - A simple cloud-friendly tool for testing network reachability. Release Status Crates.io Github release Nuget packages NOTE: This project is in e

Riff 50 Dec 13, 2022
Automated property based testing for Rust (with shrinking).

quickcheck QuickCheck is a way to do property based testing using randomly generated input. This crate comes with the ability to randomly generate and

Andrew Gallant 2k Jan 2, 2023
Hypothesis-like property testing for Rust

Proptest Introduction Proptest is a property testing framework (i.e., the QuickCheck family) inspired by the Hypothesis framework for Python. It allow

Jason Lingle 1.1k Jan 1, 2023
Simple assertion library for unit testing in python with a fluent API

Simple assertions library for unit testing in Python with a nice fluent API. Supports both Python 2 and 3.

snakedye 19 Sep 10, 2022
Viceroy provides local testing for developers working with Compute@Edge.

Viceroy provides local testing for developers working with Compute@Edge. It allows you to run services written against the Compute@Edge APIs on your local development machine, and allows you to configure testing backends for your service to communicate with.

Fastly 99 Jan 7, 2023
Simple goldenfile testing in Rust.

?? Rust Goldenfile Simple goldenfile testing in Rust. Goldenfile tests generate one or more output files as they run. At the end of the test, the gene

Calder Coalson 24 Nov 26, 2022
Declarative Testing Framework

Demonstrate allows tests to be written without as a much repetitive code within the demonstrate! macro, which will generate the corresponding full tests.

Austin Baugh 41 Aug 17, 2022
Cucumber testing framework for Rust. Fully native, no external test runners or dependencies.

An implementation of the Cucumber testing framework for Rust. Fully native, no external test runners or dependencies.

Brendan Molloy 394 Jan 1, 2023
🧵 Generate self-describing strings of a given length to help aid software testing

rust-counter-strings Counter strings generator written in rust to help aid software testing What is a counterstring? "A counterstring is a graduated s

Thomas Chaplin 23 Jun 24, 2022
Loom is a concurrency permutation testing tool for Rust.

Loom is a testing tool for concurrent Rust code

Tokio 1.4k Jan 9, 2023
Drill is an HTTP load testing application written in Rust inspired by Ansible syntax

Drill is an HTTP load testing application written in Rust inspired by Ansible syntax

Ferran Basora 1.5k Jan 1, 2023
assay - A super powered testing macro for Rust

assay - A super powered testing macro for Rust as·say /ˈaˌsā,aˈsā/ noun - the testing of a metal or ore to determine its ingredients and quality. Rust

Michael Gattozzi 105 Dec 4, 2022
🔥 Unit testing framework for Subgraph development on The Graph protocol. ⚙️

?? Welcome to Matchstick - a unit testing framework for The Graph protocol. Try out your mapping logic in a sandboxed environment and ensure your hand

null 157 Dec 20, 2022
This is a tiny (but delightful!) utility library for exhaustive testing.

Exhaustigen This is a tiny (but delightful!) utility library for exhaustive testing. It is based (directly) on the idea and code in the following blog

Graydon Hoare 34 Dec 14, 2022
Rust testing library

K9 - Rust Testing Library Snapshot testing + better assertions Available test macros snapshot assert_equal assert_greater_than assert_greater_than_or_

Aaron Abramov 269 Dec 10, 2022
Testing Framework for Rust

Polish Polish is Test-Driven Development done right Getting Started Installing the Package The crates.io package is kept up-to-date with all the major

Fadi Hanna Al-Kass 49 Dec 18, 2022
Rustress - stress testing library in Rust. For fun

rustress Simple network stress testing library. To get familiar with Rust Planned features (Subject to change) Multithreaded client/server Throughput

Hakan Sönmez 7 Sep 22, 2022