From 63d7a4d201d2b9616f38edb5d89999fd9d60ccce Mon Sep 17 00:00:00 2001 From: Michael de Sa Date: Tue, 10 Oct 2017 11:40:33 -0700 Subject: [PATCH] Update only fields with diff; add test for that Signed-off-by: Jared Scheib --- server/users.go | 13 +++++++++---- server/users_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/server/users.go b/server/users.go index 9733e116f6..c1c1e34086 100644 --- a/server/users.go +++ b/server/users.go @@ -162,10 +162,15 @@ func (s *Service) UpdateUser(w http.ResponseWriter, r *http.Request) { Error(w, http.StatusNotFound, err.Error(), s.Logger) } - // TODO: should we diff and only set non-nil fields? - u.Name = req.Name - u.Provider = req.Provider - u.Scheme = req.Scheme + if req.Name != "" { + u.Name = req.Name + } + if req.Provider != "" { + u.Provider = req.Provider + } + if req.Scheme != "" { + u.Scheme = req.Scheme + } err = s.UsersStore.Update(ctx, u) if err != nil { diff --git a/server/users_test.go b/server/users_test.go index 5b7f37e2fd..868e24c5c6 100644 --- a/server/users_test.go +++ b/server/users_test.go @@ -334,6 +334,47 @@ func TestService_UpdateUser(t *testing.T) { wantContentType: "application/json", wantBody: `{"id":1336,"name":"bobbetta","provider":"Google","scheme":"OAuth2","links":{"self":"/chronograf/v1/users/1336"}}`, }, + + { + name: "Update only one field of a Chronograf user", + fields: fields{ + Logger: log.New(log.DebugLevel), + UsersStore: &mocks.UsersStore{ + UpdateF: func(ctx context.Context, user *chronograf.User) error { + return nil + }, + GetF: func(ctx context.Context, ID string) (*chronograf.User, error) { + switch ID { + case "1336": + return &chronograf.User{ + ID: 1336, + Name: "bobbetta2", + Provider: "GitHub", + Scheme: "OAuth2", + }, nil + default: + return nil, fmt.Errorf("User with ID %v not found", ID) + } + }, + }, + }, + args: args{ + w: httptest.NewRecorder(), + r: httptest.NewRequest( + "PATCH", + "http://any.url", + nil, + ), + user: &chronograf.User{ + ID: 1336, + Name: "burnetta", + }, + }, + id: "1336", + wantStatus: http.StatusOK, + wantContentType: "application/json", + wantBody: `{"id":1336,"name":"burnetta","provider":"GitHub","scheme":"OAuth2","links":{"self":"/chronograf/v1/users/1336"}}`, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {