Skip to content

Commit

Permalink
feat: Add RemoveProvider public method (bxcodec#115)
Browse files Browse the repository at this point in the history
* Add RemoveProvider public method

This method removes existing customization added with AddProvider.
This can be useful if you need to reset your customization and add
a new one with the same name.

* Check AddProvider return value

* Update go.mod

* Revert go.mod

Co-authored-by: Iman Tumorang <iman.tumorang@gmail.com>
  • Loading branch information
pioz and bxcodec committed Jun 26, 2020
1 parent 5a7150e commit b0be786
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ var mapperTag = map[string]TaggedFunction{
// ErrValueNotPtr: Error when value is not pointer
// ErrTagNotSupported: Error when tag is not supported
// ErrTagAlreadyExists: Error when tag exists and call AddProvider
// ErrTagDoesNotExist: Error when tag does not exist and call RemoveProvider
// ErrMoreArguments: Error on passing more arguments
// ErrNotSupportedPointer: Error when passing unsupported pointer
var (
Expand All @@ -235,6 +236,7 @@ var (
ErrValueNotPtr = "Not a pointer value"
ErrTagNotSupported = "Tag unsupported: %s"
ErrTagAlreadyExists = "Tag exists"
ErrTagDoesNotExist = "Tag does not exist"
ErrMoreArguments = "Passed more arguments than is possible : (%d)"
ErrNotSupportedPointer = "Use sample:=new(%s)\n faker.FakeData(sample) instead"
ErrSmallerThanZero = "Size:%d is smaller than zero."
Expand Down Expand Up @@ -391,6 +393,17 @@ func AddProvider(tag string, provider TaggedFunction) error {
return nil
}

// RemoveProvider removes existing customization added with AddProvider
func RemoveProvider(tag string) error {
if _, ok := mapperTag[tag]; !ok {
return errors.New(ErrTagDoesNotExist)
}

delete(mapperTag, tag)

return nil
}

func getValue(a interface{}) (reflect.Value, error) {
t := reflect.TypeOf(a)
if t == nil {
Expand Down
22 changes: 22 additions & 0 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,28 @@ func TestTagAlreadyExists(t *testing.T) {
}
}

func TestRemoveProvider(t *testing.T) {
err := AddProvider("new_test_tag", func(v reflect.Value) (interface{}, error) {
return "test", nil
})
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}

err = RemoveProvider("new_test_tag")
if err != nil {
t.Error("Expected Not Error, But Got: ", err)
}
}

func TestTagDoesNotExist(t *testing.T) {
err := RemoveProvider("not_existing_test_tag")

if err == nil || err.Error() != ErrTagDoesNotExist {
t.Error("Expected ErrTagDoesNotExist Error, But Got: ", err)
}
}

func TestTagWithPointer(t *testing.T) {

type TestStruct struct {
Expand Down

0 comments on commit b0be786

Please sign in to comment.