From 6bf96ecbd7640850a525999360f9a9385e8c5c38 Mon Sep 17 00:00:00 2001 From: Livio Amstutz Date: Wed, 25 Mar 2020 09:32:52 +0100 Subject: [PATCH] add duration type --- internal/config/types/duration.go | 15 +++++++++ internal/config/types/duration_test.go | 46 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 internal/config/types/duration.go create mode 100644 internal/config/types/duration_test.go diff --git a/internal/config/types/duration.go b/internal/config/types/duration.go new file mode 100644 index 000000000..6413aea83 --- /dev/null +++ b/internal/config/types/duration.go @@ -0,0 +1,15 @@ +package types + +import ( + "time" +) + +type Duration struct { + time.Duration +} + +func (d *Duration) UnmarshalText(data []byte) error { + var err error + d.Duration, err = time.ParseDuration(string(data)) + return err +} diff --git a/internal/config/types/duration_test.go b/internal/config/types/duration_test.go new file mode 100644 index 000000000..8058d07a4 --- /dev/null +++ b/internal/config/types/duration_test.go @@ -0,0 +1,46 @@ +package types + +import ( + "testing" + "time" +) + +func TestDuration_UnmarshalText(t *testing.T) { + type args struct { + data []byte + } + tests := []struct { + name string + args args + wantErr bool + want time.Duration + }{ + { + "ok", + args{ + data: []byte("10s"), + }, + false, + time.Duration(10 * time.Second), + }, + { + "error", + args{ + data: []byte("10"), + }, + true, + time.Duration(0), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + d := &Duration{} + if err := d.UnmarshalText(tt.args.data); (err != nil) != tt.wantErr { + t.Errorf("UnmarshalText() error = %v, wantErr %v", err, tt.wantErr) + } + if d.Duration != tt.want { + t.Errorf("UnmarshalText() got = %v, want %v", d.Duration, tt.want) + } + }) + } +}