How to use Eighteen method of source Package

Best Mock code snippet using source.Eighteen

Run Mock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

bench_test.go

Source: bench_test.go Github

copy
1// This file is part of the guanguans/id-validator.
2// (c) guanguans <[email protected]>
3// This source file is subject to the MIT license that is bundled.
4
5package idvalidator
6
7import (
8	"testing"
9)
10
11func BenchmarkIsValid(b *testing.B) {
12	benchmarks1 := []struct {
13		name string
14		id   string
15	}{
16		{id: "440308199902301512"}, // 无效(出生日期码不合法)
17		{id: "11010119900307867X"}, // 无效(校验位不合法)
18		{id: "441282198101011230"}, // 特殊(历史遗留数据)
19		{id: "370620199505100123"}, // 特殊(出生日期在地址码发布之前)
20		{id: "110101199003078670"}, // 正常
21	}
22	for _, bm := range benchmarks1 {
23		b.Run(bm.name, func(b *testing.B) {
24			for i := 0; i < b.N; i++ {
25				IsValid(bm.id, false)
26			}
27		})
28	}
29
30	benchmarks2 := []struct {
31		name string
32		id   string
33	}{
34		{id: "370620199505100123"}, // 特殊(出生日期在地址码发布之前)
35	}
36	for _, bm := range benchmarks2 {
37		b.Run(bm.name, func(b *testing.B) {
38			for i := 0; i < b.N; i++ {
39				IsValid(bm.id, true)
40			}
41		})
42	}
43}
44
45func BenchmarkGetInfo(b *testing.B) {
46	benchmarks1 := []struct {
47		name string
48		id   string
49	}{
50		{id: "11010119900307867X"}, // 无效(校验位不合法)
51		{id: "441282198101011230"}, // 特殊(历史遗留数据:广东省肇庆市罗定市)
52		{id: "370620199505100123"}, // 特殊(出生日期在地址码发布之前)
53		{id: "110101199003078670"}, // 正常
54
55	}
56	for _, bm := range benchmarks1 {
57		b.Run(bm.name, func(b *testing.B) {
58			for i := 0; i < b.N; i++ {
59				GetInfo(bm.id, false)
60			}
61		})
62	}
63
64	benchmarks2 := []struct {
65		name string
66		id   string
67	}{
68		{id: "500154199301135886"}, // 特殊(出生日期在地址码发布之前)
69
70	}
71	for _, bm := range benchmarks2 {
72		b.Run(bm.name, func(b *testing.B) {
73			for i := 0; i < b.N; i++ {
74				GetInfo(bm.id, true)
75			}
76		})
77	}
78}
79
80func BenchmarkFakeId(b *testing.B) {
81	for i := 0; i < b.N; i++ {
82		FakeId()
83	}
84}
85
86func BenchmarkFakeRequireId(b *testing.B) {
87	benchmarks := []struct {
88		name       string
89		isEighteen bool
90		address    string
91		birthday   string
92		sex        int
93	}{
94		{isEighteen: false, address: "浙江省", birthday: "20000101", sex: 1},
95		{isEighteen: true, address: "台湾省", birthday: "20000101", sex: 1},
96		{isEighteen: true, address: "香港特别行政区", birthday: "20000101", sex: 0},
97	}
98	for _, bm := range benchmarks {
99		b.Run(bm.name, func(b *testing.B) {
100			for i := 0; i < b.N; i++ {
101				FakeRequireId(bm.isEighteen, bm.address, bm.birthday, bm.sex)
102			}
103		})
104	}
105}
106
107func BenchmarkUpgradeId(b *testing.B) {
108	benchmarks := []struct {
109		name string
110		id   string
111	}{
112		{id: "610104620927690"}, // 有效
113		{id: "61010462092769"},  // 无效
114	}
115	for _, bm := range benchmarks {
116		b.Run(bm.name, func(b *testing.B) {
117			for i := 0; i < b.N; i++ {
118				UpgradeId(bm.id)
119			}
120		})
121	}
122}
123
Full Screen

scraper.go

Source: scraper.go Github

copy
1package scraper
2
3import (
4	"encoding/xml"
5	"fmt"
6	"io/ioutil"
7	"net/http"
8	"os"
9	"strconv"
10	"strings"
11	"time"
12
13	"github.com/king-jam/ft-alert-bot/models"
14	//"github.com/sirupsen/logrus"
15)
16
17var timeStamp string
18
19func doEvery(d time.Duration, dataChan chan models.SnowForecasts, f func() (*models.Forecast, error)) error {
20	for range time.Tick(d) {
21		forecast, err := f()
22		if err != nil {
23			return err
24		}
25		if forecast.TimeStamp != timeStamp {
26			Locations, err := Parser(forecast)
27			if err != nil {
28				return err
29			}
30
31			timeStamp = forecast.TimeStamp
32			dataChan <- Locations
33		}
34	}
35	return nil
36}
37
38// ScrapeAndParse goes and gets the data every set duration
39func ScrapeAndParse(d time.Duration, dataChan chan models.SnowForecasts) error {
40	return doEvery(d, dataChan, Scraper)
41}
42
43// Scraper scrapes
44func Scraper() (*models.Forecast, error) {
45	//resp, err := http.Get("https://www.weather.gov/source/box/winter/snow_prob.xml")
46	forecastxml := fmt.Sprintf("http://localhost" + ":" + os.Getenv("PORT") + "/snow_prob.xml")
47	//logrus.Infoln(forecastxml)
48	resp, err := http.Get(forecastxml)
49
50	if err != nil {
51		// handle error
52		return nil, err
53	}
54	if resp.StatusCode != 200 {
55		return nil, fmt.Errorf("status code error: %d %s", resp.StatusCode, resp.Status)
56	}
57	defer resp.Body.Close()
58	body, err := ioutil.ReadAll(resp.Body)
59	if err != nil {
60		return nil, err
61	}
62
63	var forecast models.Forecast
64	xml.Unmarshal(body, &forecast)
65	return &forecast, nil
66}
67
68// Parser parses
69func Parser(forecast *models.Forecast) (models.SnowForecasts, error) {
70	//snowPlaces := make(models.SnowPlaces, 0)
71	snowForecasts := make([]*models.SnowForecast, 0)
72
73	line := strings.Split(forecast.Text, "\n")
74	for _, v := range line {
75
76		// input validation for bad strings from xml parse
77		if v == " " || v == "" {
78			continue
79		}
80		lineItems := strings.Split(v, ",")
81
82		Location := &models.Location{
83			Area: &models.Area{
84				City:   lineItems[0],
85				State:  lineItems[1],
86				County: lineItems[2],
87			},
88		}
89
90		lowEndSnowfall, err := strconv.ParseFloat(lineItems[4], 64)
91		if err != nil {
92			return nil, err
93		}
94		expectedSnowfall, err := strconv.ParseFloat(lineItems[5], 64)
95		if err != nil {
96			return nil, err
97		}
98		highEndSnowfall, err := strconv.ParseFloat(lineItems[6], 64)
99		if err != nil {
100			return nil, err
101		}
102		chanceMoreThanZero, err := strconv.ParseFloat(lineItems[7], 64)
103		if err != nil {
104			return nil, err
105		}
106		chanceMoreThanOne, err := strconv.ParseFloat(lineItems[8], 64)
107		if err != nil {
108			return nil, err
109		}
110		chanceMoreThanTwo, err := strconv.ParseFloat(lineItems[9], 64)
111		if err != nil {
112			return nil, err
113		}
114		chanceMoreThanFour, err := strconv.ParseFloat(lineItems[10], 64)
115		if err != nil {
116			return nil, err
117		}
118		chanceMoreThanSix, err := strconv.ParseFloat(lineItems[11], 64)
119		if err != nil {
120			return nil, err
121		}
122		chanceMoreThanEight, err := strconv.ParseFloat(lineItems[12], 64)
123		if err != nil {
124			return nil, err
125		}
126		chanceMoreThanTwelve, err := strconv.ParseFloat(lineItems[13], 64)
127		if err != nil {
128			return nil, err
129		}
130		chanceMoreThanEighteen, err := strconv.ParseFloat(lineItems[14], 64)
131		if err != nil {
132			return nil, err
133		}
134		snowForecast := &models.SnowForecast{
135			Location:               Location,
136			TimeStamp:              forecast.TimeStamp,
137			LowEndSnowfall:         lowEndSnowfall,
138			ExpectedSnowfall:       expectedSnowfall,
139			HighEndSnowfall:        highEndSnowfall,
140			ChanceMoreThanZero:     chanceMoreThanZero,
141			ChanceMoreThanOne:      chanceMoreThanOne,
142			ChanceMoreThanTwo:      chanceMoreThanTwo,
143			ChanceMoreThanFour:     chanceMoreThanFour,
144			ChanceMoreThanSix:      chanceMoreThanSix,
145			ChanceMoreThanEight:    chanceMoreThanEight,
146			ChanceMoreThanTwelve:   chanceMoreThanTwelve,
147			ChanceMoreThanEighteen: chanceMoreThanEighteen,
148		}
149		snowForecasts = append(snowForecasts, snowForecast)
150	}
151	return snowForecasts, nil
152}
153
154// ScraperService wraps the store interface funcs
155type ScraperService struct {
156	Repo models.Repository
157}
158
159// New returns an initialized ScraperService for making toast
160func New(repo models.Repository) *ScraperService {
161	return &ScraperService{Repo: repo}
162}
163
164func (ss *ScraperService) Store(dataChan chan models.SnowForecasts) error {
165	for snowForecasts := range dataChan {
166		//Loop:
167		for _, snowForecast := range snowForecasts {
168			if err := ss.Repo.Insert(snowForecast); err != nil {
169				return err
170			}
171		}
172	}
173	return nil
174}
175
Full Screen

id_validator.go

Source: id_validator.go Github

copy
1// This file is part of the guanguans/id-validator.
2// (c) guanguans <[email protected]>
3// This source file is subject to the MIT license that is bundled.
4
5package idvalidator
6
7import (
8	"errors"
9	"time"
10
11	"github.com/guanguans/id-validator/data"
12	"github.com/spf13/cast"
13)
14
15// IdInfo 身份证信息
16type IdInfo struct {
17	AddressCode   int
18	Abandoned     int
19	Address       string
20	AddressTree   []string
21	Birthday      time.Time
22	Constellation string
23	ChineseZodiac string
24	Sex           int
25	Length        int
26	CheckBit      string
27}
28
29// IsValid 验证身份证号合法性
30func IsValid(id string, strict bool) bool {
31	code, err := generateCode(id)
32	if err != nil {
33		return false
34	}
35
36	// 检查顺序码、生日码、地址码
37	if !checkOrderCode(code["order"]) || !checkBirthdayCode(code["birthdayCode"]) || !checkAddressCode(code["addressCode"], code["birthdayCode"], strict) {
38		return false
39	}
40
41	// 15位身份证不含校验码
42	if code["type"] == "15" {
43		return true
44	}
45
46	// 校验码
47	return code["checkBit"] == generatorCheckBit(code["body"])
48}
49
50// IsLooseValid 宽松验证身份证号合法性
51func IsLooseValid(id string) bool {
52	return IsValid(id, false)
53}
54
55// IsStrictValid 严格验证身份证号合法性
56func IsStrictValid(id string) bool {
57	return IsValid(id, true)
58}
59
60// GetInfo 获取身份证信息
61func GetInfo(id string, strict bool) (IdInfo, error) {
62	// 验证有效性
63	if !IsValid(id, strict) {
64		return IdInfo{}, errors.New("invalid ID card number")
65	}
66
67	code, _ := generateCode(id)
68	addressCode := cast.ToUint32(code["addressCode"])
69
70	// 地址信息
71	addressInfo := getAddressInfo(code["addressCode"], code["birthdayCode"], strict)
72	addressTree := []string{addressInfo["province"], addressInfo["city"], addressInfo["district"]}
73
74	// 是否废弃
75	abandoned := 0
76	if data.AddressCode()[addressCode] == "" {
77		abandoned = 1
78	}
79
80	// 生日
81	cst, _ := time.LoadLocation("Asia/Shanghai")
82	birthday, _ := time.ParseInLocation("20060102", code["birthdayCode"], cst)
83
84	// 性别
85	sex := 1
86	if (cast.ToInt(code["order"]) % 2) == 0 {
87		sex = 0
88	}
89
90	// 长度
91	length := cast.ToInt(code["type"])
92
93	return IdInfo{
94		AddressCode:   int(addressCode),
95		Abandoned:     abandoned,
96		Address:       addressInfo["province"] + addressInfo["city"] + addressInfo["district"],
97		AddressTree:   addressTree,
98		Birthday:      birthday,
99		Constellation: getConstellation(code["birthdayCode"]),
100		ChineseZodiac: getChineseZodiac(code["birthdayCode"]),
101		Sex:           sex,
102		Length:        length,
103		CheckBit:      code["checkBit"],
104	}, nil
105}
106
107// FakeId 生成假身份证号码
108func FakeId() string {
109	return FakeRequireId(true, "", "", 0)
110}
111
112// FakeRequireId 按要求生成假身份证号码
113// isEighteen 是否生成18位号码
114// address    省市县三级地区官方全称:如`北京市`、`台湾省`、`香港特别行政区`、`深圳市`、`黄浦区`
115// birthday   出生日期:如 `2000`、`198801`、`19990101`
116// sex        性别:1为男性,0为女性
117func FakeRequireId(isEighteen bool, address string, birthday string, sex int) string {
118	// 生成地址码
119	addressCode := ""
120	if address == "" {
121		for i, s := range data.AddressCode() {
122			addressCode = cast.ToString(i)
123			address = s
124			break
125		}
126	} else {
127		addressCode = generatorAddressCode(address)
128	}
129
130	// 出生日期码
131	birthdayCode := generatorBirthdayCode(addressCode, address, birthday)
132
133	// 生成顺序码
134	orderCode := generatorOrderCode(sex)
135
136	if !isEighteen {
137		return addressCode + substr(birthdayCode, 2, 8) + orderCode
138	}
139
140	body := addressCode + birthdayCode + orderCode
141
142	return body + generatorCheckBit(body)
143}
144
145// UpgradeId 15位升级18位号码
146func UpgradeId(id string) (string, error) {
147	if !IsValid(id, true) {
148		return "", errors.New("invalid ID card number")
149	}
150
151	code, _ := generateShortCode(id)
152
153	body := code["addressCode"] + code["birthdayCode"] + code["order"]
154
155	return body + generatorCheckBit(body), nil
156}
157
Full Screen

dbg.go

Source: dbg.go Github

copy
1package dbg
2
3import (
4	"fmt"
5	"math/rand"
6	"strconv"
7	"time"
8
9	"github.com/varunamachi/patti/pt"
10	"github.com/varunamachi/teak"
11)
12
13func generateUsers(handle func(user *teak.User) error) error {
14
15	s1 := rand.NewSource(time.Now().UnixNano())
16	r1 := rand.New(s1)
17	getRandomRole := func() teak.AuthLevel {
18		i := r1.Intn(5)
19		return teak.AuthLevel(i)
20	}
21	getRandomTitle := func() string {
22		switch r1.Intn(5) {
23		case 0:
24			return "Ms"
25		case 1:
26			return "Mrs"
27		case 2:
28			return "Mr"
29		case 3:
30			return "Dr"
31		case 4:
32			return "Prof"
33		}
34		return "Chief Wizard"
35	}
36
37	for i := 0; i < 100; i++ {
38		num := ToStrNum(i)
39		id := "user_" + num.ID
40		user := teak.User{
41			UserID:     id,
42			Email:      id + "@amail.com",
43			Auth:       getRandomRole(),
44			FirstName:  "User" + strconv.Itoa(i),
45			LastName:   num.Name,
46			Title:      getRandomTitle(),
47			FullName:   "User" + strconv.Itoa(i) + " " + num.Name, //I'm bit lazy
48			State:      teak.Active,
49			VerID:      "",
50			PwdExpiry:  time.Now().AddDate(1, 0, 0),
51			CreatedAt:  time.Now(),
52			CreatedBy:  "auto",
53			ModifiedAt: time.Now(),
54			ModifiedBy: "auto",
55			VerfiedAt:  time.Now(),
56			Props:      teak.M{},
57		}
58		if err := handle(&user); err != nil {
59			return teak.LogError("pt.gen", err)
60
61		}
62	}
63	return nil
64}
65
66func generateTaskList(handler func(tl *pt.TaskList) error) error {
67	s1 := rand.NewSource(time.Now().UnixNano())
68	r1 := rand.New(s1)
69
70	for i := 0; i < 200; i++ {
71		userID := fmt.Sprintf("user_%d", r1.Intn(100))
72		num := ToStrNum(i)
73		tl := pt.TaskList{
74			Item: pt.Item{
75				Heading:     num.Name,
76				Description: num.Name + num.Name,
77				Status:      pt.Active,
78			},
79			UserID:     userID,
80			CreatedOn:  time.Now(),
81			CreatedBy:  userID,
82			ModifiedOn: time.Now(),
83			ModifiedBy: userID,
84		}
85		if err := handler(&tl); err != nil {
86			teak.LogError("pt.gen", err)
87			break
88		}
89	}
90	return nil
91}
92
93// func createTasks() {
94
95// }
96
97// Below code is adapted from:
98// https://github.com/siongui/userpages +
99// /blob/master/content/articles/2017/12/31/ +
100// go-convert-number-to-word-from-1-to-1000%25en.rst
101
102type num struct {
103	ID   string
104	Name string
105}
106
107var numToWord = map[int]num{
108	1:  {ID: "one", Name: "One"},
109	2:  {ID: "two", Name: "Two"},
110	3:  {ID: "three", Name: "Three"},
111	4:  {ID: "four", Name: "Four"},
112	5:  {ID: "five", Name: "Five"},
113	6:  {ID: "six", Name: "Six"},
114	7:  {ID: "seven", Name: "Seven"},
115	8:  {ID: "eight", Name: "Eight"},
116	9:  {ID: "nine", Name: "Nine"},
117	10: {ID: "ten", Name: "Ten"},
118	11: {ID: "eleven", Name: "Eleven"},
119	12: {ID: "twelve", Name: "Twelve"},
120	13: {ID: "thirteen", Name: "Thirteen"},
121	14: {ID: "fourteen", Name: "Fourteen"},
122	15: {ID: "fifteen", Name: "Fifteen"},
123	16: {ID: "sixteen", Name: "Sixteen"},
124	17: {ID: "seventeen", Name: "Seventeen"},
125	18: {ID: "eighteen", Name: "Eighteen"},
126	19: {ID: "nineteen", Name: "Nineteen"},
127	20: {ID: "twenty", Name: "Twenty"},
128	30: {ID: "thirty", Name: "Thirty"},
129	40: {ID: "forty", Name: "Forty"},
130	50: {ID: "fifty", Name: "Fifty"},
131	60: {ID: "sixty", Name: "Sixty"},
132	70: {ID: "seventy", Name: "Seventy"},
133	80: {ID: "eighty", Name: "Eighty"},
134	90: {ID: "ninety", Name: "Ninety"},
135}
136
137func convert1to99(n int) (w num) {
138	if n < 20 {
139		w = numToWord[n]
140		return
141	}
142
143	r := n % 10
144	if r == 0 {
145		w = numToWord[n]
146	} else {
147		w.ID = numToWord[n-r].ID + "_" + numToWord[r].ID
148		w.Name = numToWord[n-r].Name + " " + numToWord[r].Name
149	}
150	return
151}
152
153func convert100to999(n int) (w num) {
154	q := n / 100
155	r := n % 100
156	w.ID = numToWord[q].ID + "_" + "hundred"
157	w.Name = numToWord[q].Name + " " + "Hundred"
158	if r == 0 {
159		return
160	} else {
161		dec := convert1to99(r)
162		w.ID = w.ID + "_" + dec.ID
163		w.Name = w.Name + " and " + dec.Name
164	}
165	return
166}
167
168func ToStrNum(n int) (w num) {
169	if n > 1000 || n < 1 {
170		return num{
171			Name: "Out of Range",
172			ID:   "out_of_range",
173		}
174	}
175
176	if n < 100 {
177		w = convert1to99(n)
178		return
179	}
180	if n == 1000 {
181		w = num{
182			Name: "One Thousand",
183			ID:   "one_thousand",
184		}
185		return
186	}
187	w = convert100to999(n)
188	return
189}
190
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger Eighteen code on LambdaTest Cloud Grid

Execute automation tests with Eighteen on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)