1// Copyright 2012-present Oliver Eilhard. All rights reserved.
2// Use of this source code is governed by a MIT-license.
3// See http://olivere.mit-license.org/license.txt for details.
4
5package elastic
6
7import (
8	"context"
9	"testing"
10)
11
12func TestPutScript(t *testing.T) {
13	client := setupTestClientAndCreateIndex(t)
14
15	scriptID := "example-put-script-id"
16
17	// Ensure the script does not exist
18	_, err := client.PerformRequest(
19		context.Background(),
20		PerformRequestOptions{
21			Method: "DELETE",
22			Path:   "/_scripts/" + scriptID,
23		})
24	if err != nil && !IsNotFound(err) {
25		t.Fatal(err)
26	}
27
28	// PutScript API
29	script := `{
30		"script": {
31			"lang": "painless",
32			"source": "ctx._source.message = params.new_message"
33		}
34	}`
35	res, err := client.PutScript().
36		Id(scriptID).
37		BodyString(script).
38		Do(context.Background())
39	if err != nil {
40		t.Fatal(err)
41	}
42	if res == nil {
43		t.Errorf("expected result to be != nil; got: %v", res)
44	}
45	if !res.Acknowledged {
46		t.Errorf("expected ack for PutScript op; got %v", res.Acknowledged)
47	}
48
49	// Must exist now
50	_, err = client.PerformRequest(
51		context.Background(),
52		PerformRequestOptions{
53			Method: "GET",
54			Path:   "/_scripts/" + scriptID,
55		})
56	if err != nil {
57		t.Fatal(err)
58	}
59	// Cleanup
60	client.PerformRequest(
61		context.Background(),
62		PerformRequestOptions{
63			Method: "DELETE",
64			Path:   "/_scripts/" + scriptID,
65		})
66}
67