Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A library for generating fake data in Rust.

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
NotificationsYou must be signed in to change notification settings

cksac/fake-rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

RustDocs StatusLatest Version

A Rust library and command line tool for generating fake data in different languages. Currently supports:

LanguageCode
Englishen
Frenchfr_fr
Arabicar_sa
Traditional Chinesezh_tw
Simplified Chinesezh_cn
Japaneseja_jp
Portugese (Brazilian)pt_br
Portugese (Portugal)pt_pt
Germande_de
Italianit_it
Cymraeg (Welsh)cy_gb

Installation

Library:

[dependencies]fake = {version ="4",features = ["derive"] }

Available library features:

  • derive: if you want to use#[derive(Dummy)]
  • supported crates feature flags:
    • chrono
    • chrono-tz
    • http
    • ulid
    • uuid
    • bigdecimal (viabigdecimal-rs)
    • rust_decimal
    • random_color
    • geo
    • semver
    • serde_json
    • time
    • zerocopy
    • glam
    • url
    • indexmap
  • always-true-rng: expose AlwaysTrueRng
  • maybe-non-empty-collections: allow to use AlwaysTrueRng to generate non-empty collections

CLI:

cargo install --features=cli --git https://github.com/cksac/fake-rs.git

Access cli usingfake command. Below are the currently available fake generators.

❯ fakeAn easy to use library andcommand linefor generating fake data like name, number, address, lorem, dates, etc.Usage: fake [OPTIONS] [COMMAND]Commands:  CityPrefix              CitySuffix              CityName                CountryName             CountryCode             StreetSuffix            StreetName              TimeZone                StateName               StateAbbr               SecondaryAddressType    SecondaryAddress        ZipCode                 PostCode                BuildingNumber          Latitude                Longitude               Geohash                 Isbn                    Isbn10                  Isbn13                  CreditCardNumber        CompanySuffix           CompanyName             Buzzword                BuzzwordMiddle          BuzzwordTail            CatchPhrase             BsVerb                  BsAdj                   BsNoun                  Bs                      Profession              Industry                FreeEmailProvider       DomainSuffix            FreeEmail               SafeEmail               Username                Password                IPv4                    IPv6                    IP                      MACAddress              UserAgent               Seniority               Field                   Position                Word                    Words                   Sentence                Sentences               Paragraph               Paragraphs   ItalicWord              BoldWord                Link                    BulletPoints            ListItems               BlockQuoteSingleLine    BlockQuoteMultiLine     Code               FirstName               LastName                Title                   Suffix                  Name                    NameWithTitle           PhoneNumber             CellNumber              FilePath                FileName                FileExtension           DirPath                 MimeType                Semver                  SemverStable            SemverUnstable          CurrencyCode            CurrencyName            CurrencySymbol          Bic                     Isin                    HexColor                RgbColor                RgbaColor               HslColor                HslaColor               Color                   Time                    Date                    DateTime                RfcStatusCode           ValidStatusCodehelp                  Print this message or thehelp of the given subcommand(s)Options:  -r, --repeat<repeat>  [default: 1]  -l, --locale<locale>  [default: EN]  -h, --help             Printhelp  -V, --version          Print version

Usage

In rust code

use fake::{Dummy,Fake,Faker};use fake::rand::rngs::StdRng;use fake::rand::SeedableRng;#[derive(Debug,Dummy)]pubstructFoo{#[dummy(faker ="1000..2000")]order_id:usize,customer:String,paid:bool,}#[derive(Debug,Dummy)]structBar<T>{field:Vec<T>,}fnmain(){// type derived Dummylet f:Foo =Faker.fake();println!("{:?}", f);let b:Bar<Foo> =Faker.fake();println!("{:?}", b);// using `Faker` to generate default fake value of given typelet 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 localesuse 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 localeuse fake::faker::lorem::en::*;let words:Vec<String> =Words(3..5).fake();println!("words {:?}", words);// using macro to generate nested collectionlet name_vec = fake::vec![StringasName(EN);4,3..5,2];println!("random nested vec {:?}", name_vec);// fixed seed rnglet 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,];letrefmut r =StdRng::from_seed(seed);for _in0..5{let v:usize =Faker.fake_with_rng(r);println!("value from fixed seed {}", v);}}

Command line

Generate random name (defaults to EN locale)

❯ ./fake NameGenerating 1 fakesfor EN localeTheresa Walker

Generate 5 chinese random names by mentioning locale to zh_cn

❯ ./fake -r5 -lzh_cn NameGenerating 5 fakesfor ZH_CN locale何丹华尹雅瑾于金福郭雨珍龙菲霞

Generate 5 random passwords with minimum 10 characters

❯ ./fake -r5 Password --min 10Generating 5 fakesfor EN localeQ6eeXHfC3uzSRqtZwB6fDHAOh3I7Ah77duLLR8ygoTLmd4i1z1Z5Uxj3RdEK5O4Af3ow2XWsGT0lUaDnMZTb7

Arguments can be sent to fake generators like password that accept different ranges

❯ ./fake Password --helpUsage: fake Password [OPTIONS]Options:      --max<max>  [default: 20]      --min<min>  [default: 10]  -h, --help       Printhelp

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();// Format is a &str such that:// - `^` will be subsituted by a random number 1-9.// - `#` will be subsituted by a random number 0-9.// - Any other character will be left as-is.NumberWithFormat<'a>(fmt:&'a str);

Boolean

Boolean(ratio:u8);

Internet

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

HTTP

RfcStatusCode();ValidStatusCode();

Color

HexColor();RgbColor();RgbaColor();HslColor();HslaColor();Color();

Company

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

Currency

CurrencyCode();CurrencyName();CurrencySymbol();

Creditcard

CreditCardNumber();

Address

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

Administrative

HealthInsuranceCode();

Automotive

LicencePlate();

Barcode

Isbn();Isbn13();Isbn10();

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();Isin();

UUID

UUIDv1();UUIDv3();UUIDv4();UUIDv5();

Decimal

Decimal();PositiveDecimal();NegativeDecimal();NoDecimalPoints();

Bigdecimal

BigDecimal();PositiveBigDecimal();NegativeBigDecimal();NoBigDecimalPoints();

Markdown

ItalicWord();BoldWord();Link();BulletPoints();ListItems();BlockQuoteSingleLine();BlockQuoteMultiLine();Code();

Utils

Either

use fake::faker::phone_number::en::{CellNumber,PhoneNumber};use fake::{utils::{either,WrappedVal},Dummy,Fake,Faker};#[derive(Debug,Dummy)]structFoo{#[dummy(faker ="either(PhoneNumber(), CellNumber())", wrapper ="WrappedVal")]phone_number:String,}

LICENSE

This project is licensed under either of

at your option.

About

A library for generating fake data in Rust.

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors62

Languages


[8]ページ先頭

©2009-2025 Movatter.jp