From b0be7860cae4347d3fb9a54ce6fcca037782c356 Mon Sep 17 00:00:00 2001 From: Enrico Date: Fri, 26 Jun 2020 14:23:52 +0200 Subject: [PATCH] feat: Add RemoveProvider public method (#115) * 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 --- faker.go | 13 +++++++++++++ faker_test.go | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/faker.go b/faker.go index 3bdbd44..d10ccd5 100644 --- a/faker.go +++ b/faker.go @@ -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 ( @@ -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." @@ -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 { diff --git a/faker_test.go b/faker_test.go index 8e297e6..e8dce13 100644 --- a/faker_test.go +++ b/faker_test.go @@ -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 {