Skip to content
This repository has been archived by the owner on Mar 9, 2022. It is now read-only.

add a Clone function #16

Merged
merged 3 commits into from
Dec 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,19 @@ func ToMap(conf *Config) (map[string]interface{}, error) {
}
return m, nil
}

// Clone copies the config. Use when updating.
func (c *Config) Clone() (*Config, error) {
var newConfig Config
var buf bytes.Buffer

if err := json.NewEncoder(&buf).Encode(c); err != nil {
return nil, fmt.Errorf("failure to encode config: %s", err)
}

if err := json.NewDecoder(&buf).Decode(&newConfig); err != nil {
return nil, fmt.Errorf("failure to decode config: %s", err)
}

return &newConfig, nil
}
29 changes: 29 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package config

import (
"testing"
)

func TestClone(t *testing.T) {
c := new(Config)
c.Identity.PeerID = "faketest"
c.API.HTTPHeaders = map[string][]string{"foo": {"bar"}}

newCfg, err := c.Clone()
if err != nil {
t.Fatal(err)
}
if newCfg.Identity.PeerID != c.Identity.PeerID {
t.Fatal("peer ID not preserved")
}

c.API.HTTPHeaders["foo"] = []string{"baz"}
if newCfg.API.HTTPHeaders["foo"][0] != "bar" {
t.Fatal("HTTP headers not preserved")
}

delete(c.API.HTTPHeaders, "foo")
if newCfg.API.HTTPHeaders["foo"][0] != "bar" {
t.Fatal("HTTP headers not preserved")
}
}
53 changes: 53 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package config

import (
"encoding/json"
"testing"
)

func TestOneStrings(t *testing.T) {
out, err := json.Marshal(Strings{"one"})
if err != nil {
t.Fatal(err)

}
expected := "\"one\""
if string(out) != expected {
t.Fatalf("expected %s, got %s", expected, string(out))
}
}

func TestNoStrings(t *testing.T) {
out, err := json.Marshal(Strings{})
if err != nil {
t.Fatal(err)

}
expected := "null"
if string(out) != expected {
t.Fatalf("expected %s, got %s", expected, string(out))
}
}

func TestManyStrings(t *testing.T) {
out, err := json.Marshal(Strings{"one", "two"})
if err != nil {
t.Fatal(err)

}
expected := "[\"one\",\"two\"]"
if string(out) != expected {
t.Fatalf("expected %s, got %s", expected, string(out))
}
}

func TestFunkyStrings(t *testing.T) {
toParse := " [ \"one\", \"two\" ] "
var s Strings
if err := json.Unmarshal([]byte(toParse), &s); err != nil {
t.Fatal(err)
}
if len(s) != 2 || s[0] != "one" && s[1] != "two" {
t.Fatalf("unexpected result: %v", s)
}
}