不一样的虚假(Bogus)和骗子(Faker)
首先声明,Bogus是一个Nuget包的名称,Faker是它内部的一个类,这个库的作用就是模拟生成实体类的数据,特别适合测试时的场景,不用苦思冥想,辛辛苦苦来造不同的实体类了。当然,造出来的都是虚假的(Bogus),骗人的(Faker)。它家在这里:https://github.com/bchavez/Bogus
假如我有个会员类
enum Sex{男,女}class Memmber{public Guid ID { get; set; }public long NO { get; set; }public string Name { get; set; }public Sex Sex { get; set; }public int Age { get; set; }public string Email { get; set; }public string Phone { get; set; }public decimal Balance { get; set; }public DateTime CreateOn { get; set; }}
这个类在测试时,要手动实例化,穿梭于各个层和方法中间,现在把构建这个类的对象(实例),交给Bogus。
首先引入Bogus包
Install-Package Bogus
接下来就可以告诉Faker怎么来“骗人”了
var options = new JsonSerializerOptions();
options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);
while (true)
{var personFaker = new Faker<Memmber>().RuleFor(x => x.ID, x => x.Random.Guid()).RuleFor(x=>x.NO,x=>x.Random.Long(100000000000,999999999999)).RuleFor(x => x.Name, x => x.Person.LastName + x.Person.FirstName).RuleFor(x => x.Sex, x => x.Random.Enum<Sex>()).RuleFor(x => x.Email, x => x.Person.Email).RuleFor(x => x.Phone, x => x.Person.Phone).RuleFor(x => x.Age, x => x.Random.Int(0, 120)).RuleFor(x=>x.Balance,x=>x.Finance.Amount(0,1000)) .RuleFor(x => x.CreateOn, x => x.Date.Past(1));Console.WriteLine(JsonSerializer.Serialize(personFaker.Generate(), options));Console.ReadLine();
}
看一下效果:
{"ID":"5f3d97f6-52da-7fb6-e73f-153fd3a41bfb","NO":539140308276,"Name":"KoeppErick","Sex":0,"Age":48,"Email":"Erick.Koepp@hotmail.com","Phone":"(899) 392-6546","Balance":45.34,"CreateOn":"2021-02-14T13:32:19.892062+09:00"
}
看来,Faker是通过RuleFor来给每个属性来模拟那种格式的数据的,比如RuleFor(x => x.Email, x => x.Person.Email),告诉Faker,这是一个Email格式,记得骗人的时候,给人家一个email格式的数据,内容随便你,那问题来了,是不是有一大组格式呢?当然,这也是这个库的作用,都有哪些?
Bogus API Support
Address
ZipCode
- Get a zipcode.City
- Get a city name.StreetAddress
- Get a street address.CityPrefix
- Get a city prefix.CitySuffix
- Get a city suffix.StreetName
- Get a street name.BuildingNumber
- Get a building number.StreetSuffix
- Get a street suffix.SecondaryAddress
- Get a secondary address like 'Apt. 2' or 'Suite 321'.County
- Get a county.Country
- Get a country.FullAddress
- Get a full address like Street, City, Country.CountryCode
- Get a random ISO 3166-1 country code.State
- Get a random state state.StateAbbr
- Get a state abbreviation.Latitude
- Get a Latitude.Longitude
- Get a Longitude.Direction
- Generates a cardinal or ordinal direction. IE: Northwest, South, SW, E.CardinalDirection
- Generates a cardinal direction. IE: North, South, E, W.OrdinalDirection
- Generates an ordinal direction. IE: Northwest, Southeast, SW, NE.
Commerce
Department
- Get a random commerce department.Price
- Get a random product price.Categories
- Get random product categories.ProductName
- Get a random product name.Color
- Get a random color.Product
- Get a random product.ProductAdjective
- Random product adjective.ProductMaterial
- Random product material.Ean8
- Get a random EAN-8 barcode number.Ean13
- Get a random EAN-13 barcode number.
Company
CompanySuffix
- Get a company suffix. "Inc" and "LLC" etc.CompanyName
- Get a company name.CatchPhrase
- Get a company catch phrase.Bs
- Get a company BS phrase.
Database
Column
- Generates a column name.Type
- Generates a column type.Collation
- Generates a collation.Engine
- Generates a storage engine.
Date
Past
- Get aDateTime
in the past betweenrefDate
andyearsToGoBack
.PastOffset
- Get aDateTimeOffset
in the past betweenrefDate
andyearsToGoBack
.Soon
- Get aDateTime
that will happen soon.SoonOffset
- Get aDateTimeOffset
that will happen soon.Future
- Get aDateTime
in the future betweenrefDate
andyearsToGoForward
.FutureOffset
- Get aDateTimeOffset
in the future betweenrefDate
andyearsToGoForward
.Between
- Get a randomDateTime
betweenstart
andend
.BetweenOffset
- Get a randomDateTimeOffset
betweenstart
andend
.Recent
- Get a randomDateTime
within the last few days.RecentOffset
- Get a randomDateTimeOffset
within the last few days.Timespan
- Get a randomTimeSpan
.Month
- Get a random monthWeekday
- Get a random weekday
Finance
Account
- Get an account number. Default length is 8 digits.AccountName
- Get an account name. Like "savings", "checking", "Home Loan" etc..Amount
- Get a random amount. Default 0 - 1000.TransactionType
- Get a transaction type: "deposit", "withdrawal", "payment", or "invoice".Currency
- Get a random currency.CreditCardNumber
- Generate a random credit card number with valid Luhn checksum.CreditCardCvv
- Generate a credit card CVVBitcoinAddress
- Generates a random Bitcoin address.EthereumAddress
- Generate a random Ethereum address.RoutingNumber
- Generates an ABA routing number with valid check digit.Bic
- Generates Bank Identifier Code (BIC) code.Iban
- Generates an International Bank Account Number (IBAN).
Hacker
Abbreviation
- Returns an abbreviation.Adjective
- Returns a adjective.Noun
- Returns a noun.Verb
- Returns a verb.IngVerb
- Returns a verb ending with -ing.Phrase
- Returns a phrase.
Images
Abstract
- Gets an abstract looking image.Animals
- Gets an image of an animal.Business
- Gets a business looking image.Cats
- Gets a picture of a cat.City
- Gets a city looking image.Food
- Gets an image of food.Nightlife
- Gets an image with city looking nightlife.Fashion
- Gets an image in the fashion category.People
- Gets an image of humans.Nature
- Gets an image of nature.Sports
- Gets an image related to sports.Technics
- Get a technology related image.Transport
- Get a transportation related image.DataUri
- Get a SVG data URI image with a specific width and height.PicsumUrl
- Get an image from the https://picsum.photos service.PlaceholderUrl
- Get an image from https://placeholder.com service.LoremFlickrUrl
- Get an image from https://loremflickr.com service.LoremPixelUrl
- Creates an image URL with http://lorempixel.com. Note: This service is slow. Consider using PicsumUrl() as a faster alternative.
Internet
Avatar
- Generates a legit Internet URL avatar from twitter accounts.Email
- Generates an email address.ExampleEmail
- Generates an example email with @example.com.UserName
- Generates user names.UserNameUnicode
- Generates a user name preserving Unicode characters.DomainName
- Generates a random domain name.DomainWord
- Generates a domain word used for domain names.DomainSuffix
- Generates a domain name suffix like .com, .net, .orgIp
- Gets a random IPv4 address string.Port
- Generates a random port number.IpAddress
- Gets a random IPv4 IPAddress type.IpEndPoint
- Gets a random IPv4 IPEndPoint.Ipv6
- Generates a random IPv6 address string.Ipv6Address
- Generate a random IPv6 IPAddress type.Ipv6EndPoint
- Gets a random IPv6 IPEndPoint.UserAgent
- Generates a random user agent.Mac
- Gets a random mac address.Password
- Generates a random password.Color
- Gets a random aesthetically pleasing color near the base RGB. See here.Protocol
- Returns a random protocol. HTTP or HTTPS.Url
- Generates a random URL.UrlWithPath
- Get an absolute URL with random path.UrlRootedPath
- Get a rooted URL path like: /foo/bar. Optionally with file extension.
Lorem
Word
- Get a random lorem word.Words
- Get an array of random lorem words.Letter
- Get a character letter.Sentence
- Get a random sentence of specific number of words.Sentences
- Get some sentences.Paragraph
- Get a paragraph.Paragraphs
- Get a specified number of paragraphs.Text
- Get random text on a random lorem methods.Lines
- Get lines of lorem.Slug
- Slugify lorem words.
Name
FirstName
- Get a first name. Getting a gender specific name is only supported on locales that support it.LastName
- Get a last name. Getting a gender specific name is only supported on locales that support it.FullName
- Get a full name, concatenation of calling FirstName and LastName.Prefix
- Gets a random prefix for a name.Suffix
- Gets a random suffix for a name.FindName
- Gets a full name.JobTitle
- Gets a random job title.JobDescriptor
- Get a job description.JobArea
- Get a job area expertise.JobType
- Get a type of job.
Phone
PhoneNumber
- Get a phone number.PhoneNumberFormat
- Gets a phone number based on the locale's phone_number.formats[] array index.
Rant
Review
- Generates a random user review.Reviews
- Generate an array of random reviews.
System
FileName
- Get a random file name.DirectoryPath
- Get a random directory path (Unix).FilePath
- Get a random file path (Unix).CommonFileName
- Generates a random file name with a common file extension.MimeType
- Get a random mime typeCommonFileType
- Returns a commonly used file type.CommonFileExt
- Returns a commonly used file extension.FileType
- Returns any file type available as mime-type.FileExt
- Gets a random extension for the given mime type.Semver
- Get a random semver version string.Version
- Get a randomVersion
.Exception
- Get a randomException
with a fake stack trace.AndroidId
- Get a random GCM registration ID.ApplePushToken
- Get a random Apple Push TokenBlackBerryPin
- Get a random BlackBerry Device PIN
Vehicle
Vin
- Generate a vehicle identification number (VIN).Manufacturer
- Get a vehicle manufacture name. IE: Toyota, Ford, Porsche.Model
- Get a vehicle model. IE: Camry, Civic, Accord.Type
- Get a vehicle type. IE: Minivan, SUV, Sedan.Fuel
- Get a vehicle fuel type. IE: Electric, Gasoline, Diesel.
Random
/Randomizer
Number
- Get an int from 0 to max.Digits
- Get a random sequence of digits.Even
- Returns a random even number.Odd
- Returns a random odd number.Double
- Get a random double, between 0.0 and 1.0.Decimal
- Get a random decimal, between 0.0 and 1.0.Float
- Get a random float, between 0.0 and 1.0.Byte
- Generate a random byte between 0 and 255.Bytes
- Get a random sequence of bytes.SByte
- Generate a random sbyte between -128 and 127.Int
- Generate a random int between MinValue and MaxValue.UInt
- Generate a random uint between MinValue and MaxValue.ULong
- Generate a random ulong between -128 and 127.Long
- Generate a random long between MinValue and MaxValue.Short
- Generate a random short between MinValue and MaxValue.UShort
- Generate a random ushort between MinValue and MaxValue.Char
- Generate a random char between MinValue and MaxValue.Chars
- Generate a random chars between MinValue and MaxValue.String
- Get a string of characters of a specific length.String2
- Get a string of characters with a specific length drawing characters fromchars
.Hash
- Return a random hex hash. Default 40 characters, aka SHA-1.Bool
- Get a random boolean.ArrayElement<T>
- Get a random array element.ArrayElement
- Get a random array element.ArrayElements<T>
- Get a random subset of an array.ListItem<T>
- Get a random list item.ListItems<T>
- Get a random subset of a List.CollectionItem<T>
- Get a random collection item.ReplaceNumbers
- Replaces symbols with numbers.ReplaceSymbols
- Replaces each character instance in a string.Replace
- Replaces symbols with numbers and letters. # = number, ? = letter, * = number or letter.ClampString
- Clamps the length of a string between min and max characters.Enum<T>
- Picks a random Enum of T. Works only with Enums.Shuffle<T>
- Shuffles an IEnumerable source.Word
- Returns a single word or phrase in English.Words
- Gets some random words and phrases in English.WordsArray
- Get a range of words in an array (English).Guid
- Get a random GUID.Uuid
- Get a random GUID. Alias for Randomizer.Guid().RandomLocale
- Returns a random locale.AlphaNumeric
- Returns a random set of alpha numeric characters 0-9, a-z.Hexadecimal
- Generates a random hexadecimal string.WeightedRandom<T>
- Returns a selection of T[] based on a weighted distribution of probability.
是不是挺丰富的,一般场景应该够用了,如果有特殊数据模拟,也只能自已动手了。
对,我是一个祖国的程序员,Member类生成的实例是外国的,这不行,换一下:
var options = new JsonSerializerOptions();options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);while (true){var personFaker = new Faker<Memmber>("zh_CN").RuleFor(x => x.ID, x => x.Random.Guid()).RuleFor(x=>x.NO,x=>x.Random.Long(100000000000,999999999999)).RuleFor(x => x.Name, x => x.Person.LastName + x.Person.FirstName).RuleFor(x => x.Sex, x => x.Random.Enum<Sex>()).RuleFor(x => x.Email, x => x.Person.Email).RuleFor(x => x.Phone, x => x.Person.Phone).RuleFor(x => x.Age, x => x.Random.Int(0, 120)).RuleFor(x=>x.Balance,x=>x.Finance.Amount(0,1000)) .RuleFor(x => x.CreateOn, x => x.Date.Past(1));Console.WriteLine(JsonSerializer.Serialize(personFaker.Generate(), options));Console.ReadLine();}
只需要在new Faker<T>时告这个骗子是要骗祖国的程序,就可以了,看结果吧:
{"ID":"219d56ca-ea21-3a02-84b5-d9950ae8f384","NO":362783628351,"Name":"徐思远","Sex":0,"Age":100,"Email":"40@gmail.com","Phone":"024-65735687","Balance":623.22,"CreateOn":"2021-01-19T19:38:30.1504231+09:00"
}
其中的名字还真像个真人名,电话号也换成祖国的了。
那还支持其他国家吗?当然
Locale Code |
Language |
Locale Code |
Language |
|
af_ZA |
Afrikaans |
fr_CH |
French (Switzerland) |
|
ar |
Arabic |
ge |
Georgian |
|
az |
Azerbaijani |
hr |
Hrvatski |
|
cz |
Czech |
id_ID |
Indonesia |
|
de |
German |
it |
Italian |
|
de_AT |
German (Austria) |
ja |
Japanese |
|
de_CH |
German (Switzerland) |
ko |
Korean |
|
el |
Greek |
lv |
Latvian |
|
en |
English |
nb_NO |
Norwegian |
|
en_AU |
English (Australia) |
ne |
Nepalese |
|
en_AU_ocker |
English (Australia Ocker) |
nl |
Dutch |
|
en_BORK |
English (Bork) |
nl_BE |
Dutch (Belgium) |
|
en_CA |
English (Canada) |
pl |
Polish |
|
en_GB |
English (Great Britain) |
pt_BR |
Portuguese (Brazil) |
|
en_IE |
English (Ireland) |
pt_PT |
Portuguese (Portugal) |
|
en_IND |
English (India) |
ro |
Romanian |
|
en_NG |
Nigeria (English) |
ru |
Russian |
|
en_US |
English (United States) |
sk |
Slovakian |
|
en_ZA |
English (South Africa) |
sv |
Swedish |
|
es |
Spanish |
tr |
Turkish |
|
es_MX |
Spanish (Mexico) |
uk |
Ukrainian |
|
fa |
Farsi |
vi |
Vietnamese |
|
fi |
Finnish |
zh_CN |
Chinese |
|
fr |
French |
zh_TW |
Chinese (Taiwan) |
|
fr_CA |
French (Canada) |
zu_ZA |
Zulu (South Africa) |
其实还有Bogus有很多其他功能,大家可以自行探索。
不一样的虚假(Bogus)和骗子(Faker)相关推荐
- 数据生成器Bogus的使用以及基于声明的扩展
引言 最近在整理代码,发现以前写的一个数据填充器写了一半没实现,而偏偏这段时间就要用到类似的功能,所以正好实现下. 目标 这个工具的目标是能够在项目初期快速搭建一个"数据提供器", ...
- 马斯克为什么这么厉害?底层有一套强大的思维方式!
点击"技术领导力"关注∆ 每天早上8:30推送 埃隆·马斯克创造了历史. 北京时间5月31日凌晨3时22分,SpaceX公司研发的载人龙飞船通过猎鹰9号火箭,在美国肯尼迪航天 ...
- 一文解析推特上最常见的加密骗局
推特是加密用户最常用的社交媒体之一,在方便我们及时同步行业最新消息的同时,也成为了不少加密骗局的媒介.这篇文章将为大家解析推特上最常见的加密货币和NFT骗局,帮助大家识别和避开这些骗局. 虚假链接骗局 ...
- 【论文阅读】查询搜索中的安全和效率权衡(ACM 10.1145)
英文标题: Privacy and Efficiency Tradeoffs for Multiword Top K Searchwith Linear Additive Rank Scoring 中 ...
- 世界首富马斯克,底层有一套强大的思维方式
本文转载自 混沌大学 1月8日,彭博社发文称,美国特斯拉公司首席执行官埃隆·马斯克超越亚马逊创始人杰夫·贝佐斯成为世界新首富. 彭博社称,在过去的一年里,得益于其持续的利润,特斯拉的股价飙升.马斯克的 ...
- 你是通过什么渠道获取一般人不知道的知识和信息的?
作者:未某人 链接:https://www.zhihu.com/question/24326030/answer/116568697 来源:知乎 著作权归作者所有,转载请联系作者获得授权. 你知道 z ...
- 又一程序员被骗,支付宝余额为0,却被骗28万!
前两天 杭州一程序员小宋 接到了一个电话 支付宝里一分钱都没有的他 却被骗走了28万多 问题是通过支付宝转账骗的! 看完他被骗的过程 简直把神经码给惊呆了-- 接到电话说他的医保卡涉嫌非法诈骗 小宋是 ...
- python 对excel的交互工具的使用
python 对excel的 读入 与 改写 (对比xlwt.openpyxl.xlrd) xlwt不支持写xlsx文件. openpyxl不支持读xls文件. 计划任务xlrd支持读xls,xlsx ...
- 2.8 万 Star!生成虚假内容的神器:faker.js
[导语]:当你需要初始化数据库,或者要做压力测试的时候,如果手头没有足够多的真实数据,那你会很需要 Faker 类工具. 和此前我们介绍的 PHP 版 Faker 一样,faker.js 是一个同类工 ...
最新文章
- flutter离线源码安装包最新版本下载地址
- mysql char 和varchar哪种效率高_MySQL数据库中的字段类型varchar和char的主要区别是什么?那种字段的查找效率要高,为什么?...
- 关于 ESP,EBP,EIP
- 【转】软件需求分析方法
- 工业互联网的两种极端想法和两点反思
- JDK1.8中如何用ScriptEngine动态执行JS
- docker mysql输入中文_Docker解决终端无法输入中文的问题
- ascll编码表图片_ASCII码一览表,ASCII码对照表
- js实现表格任意框选_[R] 在表格中插入图形 - formattable + htmlwidgets
- 数学分析思维导图整理(四)单变量积分学
- android应用程序在哪找,找不到应用程序的错误android
- 手机微信开发上传图片到服务器,微信开发之通过微信接口上传图片到本地服务器...
- 【bat】bat批处理安装与卸载软件,自动安装
- c语言 %x,%d,%c,%s,%x各代表什么
- 威联通文件传输服务器,威联通QTS文件传输体验
- Python学习总结(10) python中数据的常用操作之切片和迭代
- 【Docker】Registry搭建私有仓库、证书认证、用户登录认证
- 【minimal problem】资料整理
- python 定义函数 返回值只取其中一个
- Vijos——同学排序
热门文章
- 剖析3种类型的抖音剧情号,都有什么优缺点?
- 战舰世界手游微信登录不上服务器失败,战舰世界闪击战登不进去怎么办?无法连接服务器解决方法...
- 小学四年级计算机课程教学内容,2015-2016年度第一学期四年级小学信息技术教学工作计划...
- 覆盖5亿手机用户 乐播投屏有怎样的域名表现?
- sql查询技巧之记录数
- 2017 年度最佳 JavaScript 和 CSS 开源库推荐!
- 使用DTS从MySQL 8.0迁移到达梦数据库
- 为什么程序员特别讨厌产品改需求?
- 一文带你回顾go语言常见语法现象
- 【最新版下载】Android studio教程与问题汇总