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 TestGetScript(t *testing.T) {
13	client := setupTestClientAndCreateIndex(t)
14
15	scriptID := "example-get-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	putRes, err := client.PutScript().
36		Id(scriptID).
37		BodyString(script).
38		Do(context.Background())
39	if err != nil {
40		t.Fatal(err)
41	}
42	if putRes == nil {
43		t.Errorf("expected result to be != nil; got: %v", putRes)
44	}
45	if !putRes.Acknowledged {
46		t.Errorf("expected ack for PutScript op; got %v", putRes.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
60	// GetScript API
61	res, err := client.GetScript().
62		Id(scriptID).
63		Do(context.Background())
64	if err != nil {
65		t.Fatal(err)
66	}
67	if res == nil {
68		t.Errorf("expected result to be != nil; got: %v", res)
69	}
70	if want, have := scriptID, res.Id; want != have {
71		t.Fatalf("expected _id = %q; got: %q", want, have)
72	}
73	if want, have := true, res.Found; want != have {
74		t.Fatalf("expected found = %v; got: %v", want, have)
75	}
76	if res.Script == nil {
77		t.Fatal("expected script; got: nil")
78	}
79	outScript := `{"lang":"painless","source":"ctx._source.message = params.new_message"}`
80	if want, have := outScript, string(res.Script); want != have {
81		t.Fatalf("expected script = %q; got: %q", want, have)
82	}
83
84	// Cleanup
85	client.PerformRequest(
86		context.Background(),
87		PerformRequestOptions{
88			Method: "DELETE",
89			Path:   "/_scripts/" + scriptID,
90		})
91}
92