From 88acc731085cec5a4767cbf29159ca9a7233eff3 Mon Sep 17 00:00:00 2001 From: itchyny Date: Mon, 13 Nov 2023 19:27:15 +0900 Subject: [PATCH] implement BulkUpdateHostStatuses to update status of the hosts --- hosts.go | 7 +++++++ hosts_test.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/hosts.go b/hosts.go index 4cc05cd..6fbcd08 100644 --- a/hosts.go +++ b/hosts.go @@ -249,6 +249,13 @@ func (c *Client) UpdateHostStatus(hostID string, status string) error { return err } +// BulkUpdateHostStatuses updates status of the hosts. +func (c *Client) BulkUpdateHostStatuses(ids []string, status string) error { + _, err := requestPost[any](c, "/api/v0/hosts/bulk-update-statuses", + map[string]any{"ids": ids, "status": status}) + return err +} + // UpdateHostRoleFullnames updates host roles. func (c *Client) UpdateHostRoleFullnames(hostID string, roleFullnames []string) error { path := fmt.Sprintf("/api/v0/hosts/%s/role-fullnames", hostID) diff --git a/hosts_test.go b/hosts_test.go index 8e4d05e..da5cdd2 100644 --- a/hosts_test.go +++ b/hosts_test.go @@ -372,6 +372,54 @@ func TestUpdateHostStatus(t *testing.T) { } } +func TestBulkUpdateHostStatuses(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + if req.URL.Path != "/api/v0/hosts/bulk-update-statuses" { + t.Error("request URL should be /api/v0/hosts/bulk-update-statuses but: ", req.URL.Path) + } + + if req.Method != "POST" { + t.Error("request method should be POST but: ", req.Method) + } + + body, _ := io.ReadAll(req.Body) + + var data struct { + IDs []string `json:"ids"` + Status string `json:"status"` + } + + err := json.Unmarshal(body, &data) + if err != nil { + t.Fatal("request body should be decoded as json", string(body)) + } + + if reflect.DeepEqual(data.IDs, []string{"123456ABCD", "789012EFGH"}) != true { + t.Errorf("request IDs should be []string{\"123456ABCD\", \"789012EFGH\"} but: %+v", data.IDs) + } + + if data.Status != "maintenance" { + t.Error("request sends json including status but: ", data.Status) + } + + respJSON, _ := json.Marshal(map[string]bool{ + "success": true, + }) + + res.Header()["Content-Type"] = []string{"application/json"} + fmt.Fprint(res, string(respJSON)) + })) + defer ts.Close() + + client, _ := NewClientWithOptions("dummy-key", ts.URL, false) + ids := []string{"123456ABCD", "789012EFGH"} + err := client.BulkUpdateHostStatuses(ids, "maintenance") + + if err != nil { + t.Error("err should be nil but: ", err) + } +} + func TestUpdateHostRoleFullnames(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { if req.URL.Path != "/api/v0/hosts/9rxGOHfVF8F/role-fullnames" {