Skip to content

Commit

Permalink
Add phone provider (bxcodec#10)
Browse files Browse the repository at this point in the history
* Test coverage up
add tests for coverage up

* errors in variables

* return variable in start function

* add internet fake

* refactoring code

* credit cart refactoring
add new type and new file for credit cart

* add test internet
and add helpers function, which check slice string type to has element

* coverage up test internet file

* add payment and add test
done concept

* typo fix

* fix variable internet in struct Internet

* fix

* delete old code

* change init mutex

* merge

* add phone provider and test

* change format in stdout structure

* change format in stdout structure test

* add TollFreePhoneNumber function

* add e_164_phone_number

* fix test

* fix and done phone provider

* test coverage up
  • Loading branch information
agoalofalife authored and bxcodec committed Oct 27, 2017
1 parent 60d8932 commit 34279ec
Show file tree
Hide file tree
Showing 5 changed files with 207 additions and 2 deletions.
38 changes: 38 additions & 0 deletions faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ const (
LONGITUDE = "long"
CREDIT_CARD_NUMBER = "cc_number"
CREDIT_CARD_TYPE = "cc_type"
PHONE_NUMBER = "phone_number"
TOLL_FREE_NUMBER = "tool_free_number"
E164_PHONE_NUMBER = "e_164_phone_number"
)

var mapperTag = map[string]interface{}{
Expand All @@ -45,6 +48,9 @@ var mapperTag = map[string]interface{}{
CREDIT_CARD_NUMBER: getPayment().CreditCardNumber,
LATITUDE: getAddress().Latitude,
LONGITUDE: getAddress().Longitude,
PHONE_NUMBER: getPhoner().PhoneNumber,
TOLL_FREE_NUMBER: getPhoner().TollFreePhoneNumber,
E164_PHONE_NUMBER: getPhoner().E164PhoneNumber,
}

// Error when get fake from ptr
Expand All @@ -59,6 +65,9 @@ var ErrValueNotPtr = "Not a pointer value"
// Error when tag not supported
var ErrTagNotSupported = "String Tag unsupported"

// Error when passed more arguments
var ErrMoreArguments = "Passed more arguments than is possible : (%d)"

// FakeData is the main function. Will generate a fake data based on your struct. You can use this for automation testing, or anything that need automated data.
// You don't need to Create your own data for your testing.
func FakeData(a interface{}) error {
Expand Down Expand Up @@ -259,3 +268,32 @@ func randomStringNumber(n int) string {

return string(b)
}

/**
/ Get three parameters , only first mandatory and the rest are optional
/ --- If only set one parameter : This means the minimum number of digits and the total number
/ --- If only set two parameters : First this is min digit and second max digit and the total number the difference between them
/ --- If only three parameters: the third argument set Max count Digit
*/
func RandomInt(parameters ...int) (p []int, err error) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))

switch len(parameters) {
case 1:
minCount := parameters[0]
p = r.Perm(minCount)
for i := range p {
p[i] += minCount
}
case 2:
minDigit, maxDigit := parameters[0], parameters[1]
p = r.Perm(maxDigit - minDigit + 1)

for i := range p {
p[i] += minDigit
}
default:
err = fmt.Errorf(ErrMoreArguments, len(parameters))
}
return p, err
}
57 changes: 55 additions & 2 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package faker

import (
"fmt"
"math/rand"
"reflect"
"testing"
"time"
Expand Down Expand Up @@ -61,6 +62,30 @@ type TaggedStruct struct {
Email string `faker:"email"`
IPV4 string `faker:"ipv4"`
IPV6 string `faker:"ipv6"`
PhoneNumber string `faker:"phone_number"`
MacAddress string `faker:"mac_address"`
Url string `faker:"url"`
UserName string `faker:"username"`
ToolFreeNumber string `faker:"tool_free_number"`
E164PhoneNumber string `faker:"e_164_phone_number"`
}

func (t TaggedStruct) String() string {
return fmt.Sprintf(`{
Latitude: %f,
Long: %f,
CreditCardNumber: %s,
CreditCardType: %s,
Email: %s,
IPV4: %s,
IPV6: %s,
PhoneNumber: %s,
MacAddress: %s,
Url: %s,
UserName: %s,
ToolFreeNumber: %s,
E164PhoneNumber: %s,
}`, t.Latitude, t.Long, t.CreditCardNumber, t.CreditCardType, t.Email, t.IPV4, t.IPV6, t.PhoneNumber, t.MacAddress, t.Url, t.UserName, t.ToolFreeNumber, t.E164PhoneNumber)
}

type NotTaggedStruct struct {
Expand All @@ -77,12 +102,15 @@ func TestFakerData(t *testing.T) {
var a SomeStruct
err := FakeData(&a)
if err == nil {
fmt.Printf("%+v \n", a)
fmt.Println("SomeStruct:")
fmt.Printf("%+v\n", a)
}
var b TaggedStruct
err = FakeData(&b)
if err == nil {
fmt.Printf("%+v \n", b)
fmt.Println("TaggedStruct:")
fmt.Printf("%+v\n", b)

} else {
fmt.Println(" ER ", err)
}
Expand Down Expand Up @@ -176,3 +204,28 @@ func BenchmarkFakerDataTagged(b *testing.B) {
}
}
}

func TestRandomIntOnlyFirstParameter(t *testing.T) {
r := rand.Intn(100)
res, _ := RandomInt(r)
if len(res) != r {
t.Error("It is expected that the refund amount is equal to the argument (RandomInt)")
}
}

func TestRandomIntOnlySecondParameters(t *testing.T) {
first := rand.Intn(50)
second := rand.Intn(100) + first
res, _ := RandomInt(first, second)
if len(res) != (second - first + 1) {
t.Error("It is expected that the refund amount is equal to the argument (RandomInt)")
}
}

func TestRandomIntOnlyError(t *testing.T) {
arguments := []int{1, 3, 4, 5, 6}
_, err := RandomInt(arguments...)
if err == nil && err.Error() == fmt.Errorf(ErrMoreArguments, len(arguments)).Error() {
t.Error("Expected error from function RandomInt")
}
}
68 changes: 68 additions & 0 deletions phone.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package faker

import (
"fmt"
"github.com/agoalofalife/faker/support/slice"
"math/rand"
"strings"
)

var phone Phoner

// Constructor
func getPhoner() Phoner {
mu.Lock()
defer mu.Unlock()

if phone == nil {
phone = &Phone{}
}
return phone
}

// this set custom Phoner
func SetPhoner(p Phoner) {
phone = p
}

type Phoner interface {
PhoneNumber() string
TollFreePhoneNumber() string
E164PhoneNumber() string
}

type Phone struct{}

// 201-886-0269
func (p Phone) PhoneNumber() string {
randInt, _ := RandomInt(1, 10)
str:= strings.Join(slice.SliceIntToString(randInt), "")
return fmt.Sprintf("%s-%s-%s", str[:3],str[3:6], str[6:10])
}

// example : (888) 937-7238
func (p Phone) TollFreePhoneNumber() string {
out := ""
boxDigitsStart := []string{"777", "888"}

ints, _ := RandomInt(1, 9)
for index, v := range slice.SliceIntToString(ints) {
if index == 3 {
out += "-"
}
out += string(v)
}
return fmt.Sprintf("(%s) %s", boxDigitsStart[rand.Intn(1)], out)
}

// '+27113456789'
func (p Phone) E164PhoneNumber() string {
out := ""
boxDigitsStart := []string{"7", "8"}
ints, _ := RandomInt(1, 10)

for _, v := range slice.SliceIntToString(ints) {
out += string(v)
}
return fmt.Sprintf("+%s%s", boxDigitsStart[rand.Intn(1)], strings.Join(slice.SliceIntToString(ints), ""))
}
32 changes: 32 additions & 0 deletions phone_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package faker

import (
"strings"
"testing"
)

func TestPhoneNumber(t *testing.T) {
ph := getPhoner()
if strings.Count(ph.PhoneNumber(), "-") != 2 {
t.Error("Expected no more than two characters '-'")
}
}

func TestTollFreePhoneNumber(t *testing.T) {
ph := getPhoner()

if !strings.HasPrefix(ph.TollFreePhoneNumber(), "(888)") && !strings.HasPrefix(ph.TollFreePhoneNumber(), "(777)") {
t.Error("Expected character '(888)' or (777), in function TollFreePhoneNumber")
}
}

func TestE164PhoneNumber(t *testing.T) {
ph := getPhoner()
if !strings.HasPrefix(ph.E164PhoneNumber(), "+") {
t.Error("Expected character '(888)', in function TollFreePhoneNumber")
}
}

func TestSetPhoner(t *testing.T) {
SetPhoner(Phone{})
}
14 changes: 14 additions & 0 deletions support/slice/helpers.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package slice

import (
"strconv"
)

// Check item in slice string type
func Contains(slice []string, item string) bool {
set := make(map[string]struct{}, len(slice))
Expand All @@ -10,3 +14,13 @@ func Contains(slice []string, item string) bool {
_, ok := set[item]
return ok
}

// Convert slice int to slice string
func SliceIntToString(intSl []int) (str []string) {
for i := range intSl {
number := intSl[i]
text := strconv.Itoa(number)
str = append(str, text)
}
return str
}

0 comments on commit 34279ec

Please sign in to comment.