A library for generating fake data in Rust.

Related tags

Testing fake-rs
Overview

Fake

Rust Docs Status Latest Version

A Rust library for generating fake data.

Installation

Default (rand is required):

[dependencies]
fake = "2.4"
rand = "0.8"

If you want to use #[derive(Dummy)]:

fake = { version = "2.4", features=['derive']}

If you want the date and time features from chrono:

fake = { version = "2.4", features=['chrono']}

If you want http faker features:

fake = { version = "2.4", features=['http']}

Usage

use fake::{Dummy, Fake, Faker};
use rand::rngs::StdRng;
use rand::SeedableRng;

#[derive(Debug, Dummy)]
pub struct Foo {
    #[dummy(faker = "1000..2000")]
    order_id: usize,
    customer: String,
    paid: bool,
}

fn main() {
    // type derived Dummy
    let f: Foo = Faker.fake();
    println!("{:?}", f);

    // using `Faker` to generate default fake value of given type
    let tuple = Faker.fake::<(u8, u32, f32)>();
    println!("tuple {:?}", tuple);
    println!("String {:?}", Faker.fake::<String>());

    // types U can used to generate fake value T, if `T: Dummy<U>`
    println!("String {:?}", (8..20).fake::<String>());
    println!("u32 {:?}", (8..20).fake::<u32>());

    // using `faker` module with locales
    use fake::faker::name::raw::*;
    use fake::locales::*;

    let name: String = Name(EN).fake();
    println!("name {:?}", name);

    let name: String = Name(ZH_TW).fake();
    println!("name {:?}", name);

    // using convenient function without providing locale
    use fake::faker::lorem::en::*;
    let words: Vec<String> = Words(3..5).fake();
    println!("words {:?}", words);

    // using macro to generate nested collection
    let name_vec = fake::vec![String as Name(EN); 4, 3..5, 2];
    println!("random nested vec {:?}", name_vec);

    // fixed seed rng
    let seed = [
        1, 0, 0, 0, 23, 0, 0, 0, 200, 1, 0, 0, 210, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0,
    ];
    let ref mut r = StdRng::from_seed(seed);
    for _ in 0..5 {
        let v: usize = Faker.fake_with_rng(r);
        println!("value from fixed seed {}", v);
    }
}

Fakers with locale

Lorem

Word();
Words(count: Range<usize>);
Sentence(count: Range<usize>);
Sentences(count: Range<usize>);
Paragraph(count: Range<usize>);
Paragraphs(count: Range<usize>);

Name

FirstName();
LastName();
Title();
Suffix();
Name();
NameWithTitle();

Number

Digit();
NumberWithFormat(fmt: &'static str);

Boolean

Boolean(ratio: u8);

Internet

FreeEmailProvider();
DomainSuffix();
FreeEmail();
SafeEmail();
Username();
Password(len_range: Range<usize>);
IPv4();
IPv6();
IP();
MACAddress();
Color();
UserAgent();

HTTP

RfcStatusCode();
ValidStatusCode();

Company

CompanySuffix();
CompanyName();
Buzzword();
BuzzwordMiddle();
BuzzwordTail();
CatchPhase();
BsVerb();
BsAdj();
BsNoun();
Bs();
Profession();
Industry();

Address

CityPrefix();
CitySuffix();
CityName();
CountryName();
CountryCode();
StreetSuffix();
StreetName();
TimeZone();
StateName();
StateAbbr();
SecondaryAddressType();
SecondaryAddress();
ZipCode();
PostCode();
BuildingNumber();
Latitude();
Longitude();

Phone Number

PhoneNumber();
CellNumber();

Date/Time

Time();
Date();
DateTime();
Duration();
DateTimeBefore(dt: DateTime<Utc>);
DateTimeAfter(dt: DateTime<Utc>);
DateTimeBetween(start: DateTime<Utc>, end: DateTime<Utc>);

Filesystem

FilePath();
FileName();
FileExtension();
DirPath();

Finance

Bic();

LICENSE

This project is licensed under either of

at your option.

Comments
  • add uuid feature

    add uuid feature

    Add uuid feature flag, based on uuid crate.

    I originally opened, wrongly, a feature request #524 there but then realized it should be part of this crate instead.

    I tried to implement it by mimicking how the other supported data are implemented,

    but I would like additional review because some inner mechanisms I didn't really grasp (at least it seemed, when I had the test passes something doesn't seem right, does it ?)

    opened by Roms1383 12
  • Issue with Faker on Enums

    Issue with Faker on Enums

    I'm receiving the following error when trying to use Dummy trait on a struct that contains an emum.

    proc-macro derive panicked
    
    help: message: called `Result::unwrap()` on an `Err` value: Error { kind: UnsupportedShape("enum"), locations: [], span: None }
    

    From reviewing the crate, it seems like enums should be "fakeable", but minor tweaking doesn't help. If this is not the case, a use case on implementing the Dummy Trait would be great to have in the docs or examples.

    enhancement help wanted 
    opened by ToferC 7
  • Add rust_decimal faking capabilities

    Add rust_decimal faking capabilities

    Thank you for providing this excellent tool!

    This PR introduces Decimal faking. I chose not to localize it and go with an enum for configuation. I will most likely supply more configuration options in the future :)

    opened by ASAPHAANING 6
  • Semver : WIP

    Semver : WIP

    I think, filtering on stable/unstable version is an important feature.

    I added a choice but i'm not really satisfied (breaking changed) : Ideally i wish i could do :

    Semver(filter: crate::faker::SemverFilter);
    

    and

    Semver();
    

    I didn't find an elegant solution.

    opened by mothsART 6
  • Implement (optional) datetime feature using chrono

    Implement (optional) datetime feature using chrono

    This should implement issue #11 . This is implemented using an optional Cargo feature, so it's disabled by default to minimize unnecessary dependencies and compile time. That can be changed.

    @svenstaro , can you take a look over this and let me know if this is what you had in mind? The tests in src/lib.rs are instructive, and the implementation is all in src/faker/time.rs

    opened by mekagoza 5
  • Remove unsafe code at creditcard.rs

    Remove unsafe code at creditcard.rs

    Hi team,

    From scanning the repo, I detected below unsafe code, and it can be convert to safe version: unsafe { String::from_utf8_unchecked(bytes) } https://github.com/cksac/fake-rs/blob/5a26c9c3b7f81f5dcc5cbec999e8025e7399676d/fake/src/faker/impls/creditcard.rs#L43

    Safe version: String::from_utf8(bytes).unwrap()

    opened by yzhang71 4
  • Add some top level docs

    Add some top level docs

    I just realized that there are crate examples, not quite discoverable.

    Usually I need to do stuff offline so I think having offline documentation is good, since it is not easy to browse the README or the examples as compared to each specific items generated by rustdoc, having some explanation for the traits can roughly describes how the trait works.

    Fix #46

    opened by pickfire 4
  • Fix country names

    Fix country names

    I have fixed some typos in the ADDRESS_COUNTRY constant:

    • "Democratic People's Republic of Korea Republic of Korea Kuwait Kyrgyz Republic Lao People's Democratic Republic" was in one word.
    • "'Virgin Islands, British'" and "'Virgin Islands, U.S.'" had additional quotes.
    opened by evgeniy-r 4
  • Feat better dummy

    Feat better dummy

    @cksac Thanks for merging my other PRs.

    As I was using the 'dummy" enhancement PR locally I found a few other niceties and expanded the test.

    • this adds a "default" field option as well that will use Default:::default()
    #[derive(Dummy)]
    struct Obj(
        #[dummy(default)]
        String,
    );
    
    Then the second commit (please let me know if it is ok, or should be named different) adds a derive-level option of default_impl that will generate an impl of the Default trait that will simply call Faker.faker() (helpful for my test only structs)
    #[derive(Dummy)]
    #[dummy(default_impl)]
    struct Obj {
        pub value: i32,
    }
    
    let a : Obj = Default::default();
    
    opened by urkle 3
  • Extend fake-rs to cover more of Faker's functionality

    Extend fake-rs to cover more of Faker's functionality

    Hi there! We are currently using faker (via pyo3) in synth and want to move to use fake-rs. However, to do that, we'd want fake-rs to match more of the functionality faker provides.

    So we'd like to give this project a boost by trying to speed up that implementation work on that (I did the creditcardnumber stuff to check how hard that is). But before we go that route (and risk overwhelming you with PRs) I wanted to openly address you to learn your needs as a maintainer of this project and how we can best work together to our mutual benefit.

    opened by llogiq 3
  • How do I expose implementation of Dummy when using cfg(test)?

    How do I expose implementation of Dummy when using cfg(test)?

    I am using Dummy to create an object for testing so I've used [cfg_attr(test, derive(Dummy)] for the struct I want to fake. I have a "domain" crate where I have my models and then an "http_api" crate which depends on "domain". When I try to get a fake instance of my model struct, I get an error saying that Dummy is not implemented. Is there a way to "expose" that I've implemented the trait here that I'm missing or is this not possible when using cfg(test)? It works perfectly fine if I remove the #[cfg_attr(test, derive(Dummy)] from the struct and just derive it normally.

    error[E0277]: the trait bound `domain::models::api_requests::PutRequest: Dummy<Faker>` is not satisfied
       --> http_api/src/local/filters.rs:154:48
        |
    154 |         let request: PutRequest = Faker.fake();
        |                                                ^^^^ the trait `Dummy<Faker>` is not implemented for `domain::models::api_requests::PutRequest`
    
    opened by SpyMachine 3
  • Added foundation for DE_DE data

    Added foundation for DE_DE data

    Hi @cksac, I've been using your library thanks to LukeMathWalker/zero-to-production

    Since I've had the need to generate a bit of german fake data I took a closer look into the project.

    I added a de_de.rs module to provide a few basic attributes like State,Company Type,Names and so on from the official government ID test card data

    https://persosim.secunet.com/fileadmin/user_upload/PersoSim_Personalisierungsdaten_eID_UB.pdf

    It's working with the check_determinism test as far as I can tell.

    To verify the data that gets generated I added a de_manual_test.rs just so see some generic company struct on the terminal.

    Run via cargo test de_manual_test -- --nocapture it produces some results like

    Company { name: "Schuster e.V.", street: "Hillebrandtgang", zipcode: "29346", city: "Musterfrau land", state: "Berlin" }
    

    So far so good. :smile:

    But that is the reason I opened the PR.

    "Musterfrau land" is not a valid city name in german.

    Most city names would consist of two nouns or names and a suffix.

    Germany and to further extend the "DACH" Region (Germany, Austria, Switzerland) all have a pretty different layout for thinks like street names and addresses.

    And I would like to discuss how I could implement it in a way it suites the library and their users.

    For example a street name might be separated by dashes if it contains one or multiple names e.g. Karl-Marx-Allee https://en.wikipedia.org/wiki/Karl-Marx-Allee or can contain an apostrophe as seen here in https://de.wikipedia.org/wiki/Stra%C3%9Fenname in Laehr'scher Jagdweg

    There are already some impl with random branching for data generation https://github.com/cksac/fake-rs/blob/32646496eba2918f133c31e594e46ee907577c50/fake/src/faker/impls/address.rs#L108

    And I don't know if I should start adding impls special for the DE_DE locale or how it would fit the overall project structure.

    Any feedback or guidance is appreciated and I would gladly implement more of the german locale.

    Cheers xoryouyou

    opened by xoryouyou 6
  • Dynamic locale

    Dynamic locale

    All the examples I can find fix the locale to a specific one:

    let val: String = Name(EN).fake();
    let val: String = Name(ZH_TW).fake();
    

    I'd like to generate data based on user-supplied argument, e.g

    enum Locale {
        English,
        Taiwan,
        ...etc..
    }
    
    fn enthusiastic_fake_data(lo: Locale) -> String {
        format!("{}!!!", ...)
    }
    

    I couldn't find a neat way to do this - I can of course just do

    let val: String = match {
        English => Name(EN).fake(),
        Taiwan => Name(ZH_TW).fake(),
    }
    

    ..but this gets very repetitive if you also have a similar match for type of data (e.g Name, Country, etc)

    I was hoping to do something like

    let lo = match locale_arg {
        Locale::English => fake::locales::EN,
        Locale::Taiwan => fake::Local::ZH_TW,
    };
    let val: String = Name(lo).fake();
    

    However this doesn't work as each local is it's own struct. I tried let lo: Box<dyn fake::locale::Data> = match ... and started running into more complex errors, so I started wondering if I was missing a simpler way to do this

    Thanks!

    opened by dbr 2
  • feat: ratio for Option<T> WIP

    feat: ratio for Option WIP

    Option<T> is something like Boolean (it has Some(T) value or None). So I'd like to use ratio for this. But now we have a 50:50 ratio (look at percentage on 1 screenshot).
    I have a code something like this:

        let mut rng = rand::thread_rng();
        let file = File::create("data.csv")?;
        let mut wtr = csv::Writer::from_writer(file);
        let mut i = 0;
        let rows = rng.gen_range(10000..100000);
        loop {
            wtr.serialize(Faker.fake::<Foo>())?;
            if i == rows {
                break;
            }
            i += 1;
        }
        wtr.flush()?;
    

    Current behavior - we have 50:50 ration: pic1

    After this commit: pic2

    P.S. Of course to start it working we should add #[dummy(faker = 'Opt((), 98)') to our struct's members like this

        #[dummy(faker = "Opt(0..2000, 93)")]
        order_id: Option<u64>,
        #[dummy(faker = "Opt(0..2000, 81)")]
        make_id: Option<u64>,
        #[dummy(faker = "Opt(0..2000, 98)")]
        time_id: Option<u64>,
        #[dummy(faker = "Opt(0..2000, 90)")]
        this_id: Option<u64>,
        #[dummy(faker = "Opt(0.0..2000.0, 78)")]
        my_float: Option<f64>,
    
    opened by tujh2 0
Owner
cksac
cksac
Hopper is a tool for generating fuzzing test cases for libraries automatically using interpretative fuzzing.

Hopper Hopper is an tool for generating fuzzing test cases for libraries automatically using interpretative fuzzing. It transforms the problem of libr

FuzzAnything 118 Nov 15, 2023
Hopper is a tool for generating fuzzing test cases for libraries automatically using interpretative fuzzing.

Hopper Hopper is an tool for generating fuzzing test cases for libraries automatically using interpretative fuzzing. It transforms the problem of libr

FuzzAnything 124 Nov 24, 2023
QuickCheck bug hunting in Rust standard library data structures

BugHunt, Rust This project is aiming to provide "stateful" QuickCheck models for Rust's standard library. That is, we build up a random list of operat

Brian L. Troutwine 161 Dec 15, 2022
TestDrive automatically scrapes input/output data from BOJ(Baekjoon Online Judge) and runs tests for your executable binary file!

?? TestDrive What does it do? TestDrive automatically scrapes input/output data from BOJ(Baekjoon Online Judge) and runs tests for your executable bin

Hyeonseok Jung 3 Mar 5, 2022
Playwright is a rust library to automate Chromium, Firefox and WebKit built on top of Node.js library.

?? Playwright for Rust Playwright is a rust library to automate Chromium, Firefox and WebKit built on top of Node.js library. Installation [dependenci

octaltree 132 Jan 6, 2023
HTTP mocking library for Rust.

httpmock HTTP mocking library for Rust. Documentation · Crate · Report Bug · Request Feature · Changelog Features Simple, expressive, fluent API. Many

Alexander Liesenfeld 320 Dec 21, 2022
Advanced Fuzzing Library - Slot your Fuzzer together in Rust! Scales across cores and machines. For Windows, Android, MacOS, Linux, no_std, ...

LibAFL, the fuzzer library. Advanced Fuzzing Library - Slot your own fuzzers together and extend their features using Rust. LibAFL is written and main

Advanced Fuzzing League ++ 1.2k Dec 29, 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
Struct mocking library for Rust

faux   A library to create mocks out of structs. faux allows you to mock the methods of structs for testing without complicating or polluting your cod

Andres 322 Dec 20, 2022
beaver is a library for setting up Rust objects inspired by factory_bot.

beaver is a library for setting up Rust objects inspired by factory_bot. Usage | Examples | Docs Dependencies [dependenci

Takayuki Maeda 40 Sep 6, 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
insta: a snapshot testing library for Rust

insta: a snapshot testing library for Rust Introduction Snapshots tests (also sometimes called approval tests) are tests that assert values against a

Armin Ronacher 1.4k 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
A tiny, super simple and portable benchmarking library.

benchmark-simple A tiny benchmarking library for Rust. Trivial to use Works pretty much everywhere, including WebAssembly (WASI, but also in-browser)

Frank Denis 3 Dec 26, 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
A minimalist property-based testing library based on the arbitrary crate.

A minimalist property-based testing library based on the arbitrary crate.

Aleksey Kladov 61 Dec 21, 2022
A structure-aware HTTP fuzzing library

?? FeroxFuzz ?? A structure-aware HTTP fuzzing library ?? Another ferox? why? ?? Chill, it's not another command-line tool, this one's a library! ?? M

epi 141 Dec 27, 2022
An unofficial client library for the fuzz-introspector API.

fuzz-introspector-client An unofficial client library for the fuzz-introspector API. Quickstart Add package as a dependency; cargo add fuzz-introspect

Nathaniel Brough 4 Nov 25, 2023
Handle some lichess.org/tournament load with Rust, while learning Rust

lila-http Take some of the HTTP load away from lila. WIP! Arena tournaments Clients connected to a tournament page request new data about the tourname

Lichess 22 Jan 2, 2023