github.com/newrelic/newrelic-client-go@v1.1.0/pkg/alerts/incidents_test.go (about)

     1  //go:build unit
     2  // +build unit
     3  
     4  package alerts
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"net/http"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  var incidentTestAPIHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    16  	response := struct {
    17  		Incidents []Incident `json:"incidents,omitempty"`
    18  	}{}
    19  
    20  	openIncident := Incident{
    21  		ID:                 42,
    22  		OpenedAt:           &testTimestamp,
    23  		IncidentPreference: "PER_CONDITION",
    24  		Links: IncidentLink{
    25  			Violations: []int{123456789},
    26  			PolicyID:   12345,
    27  		},
    28  	}
    29  
    30  	closedIncident := Incident{
    31  		ID:                 24,
    32  		OpenedAt:           &testTimestamp,
    33  		ClosedAt:           &testTimestamp,
    34  		IncidentPreference: "PER_POLICY",
    35  		Links: IncidentLink{
    36  			Violations: []int{987654321},
    37  			PolicyID:   54321,
    38  		},
    39  	}
    40  
    41  	// always including the open incident
    42  	response.Incidents = append(response.Incidents, openIncident)
    43  
    44  	// if not "only open", add the closed incident
    45  	params := r.URL.Query()
    46  	oo, ok := params["only_open"]
    47  	fmt.Printf("Only Open: %+v\n", oo)
    48  	if !ok || (ok && len(oo) > 0 && oo[0] != "true") {
    49  		response.Incidents = append(response.Incidents, closedIncident)
    50  	}
    51  
    52  	// if "exclude violations", remove the violation links
    53  	ev, ok := params["exclude_violations"]
    54  	fmt.Printf("Exclude Violations: %+v\n", oo)
    55  	if ok && len(ev) > 0 && ev[0] == "true" {
    56  		for i := range response.Incidents {
    57  			response.Incidents[i].Links.Violations = nil
    58  		}
    59  	}
    60  	fmt.Printf("Incidents: %+v\n", response.Incidents)
    61  
    62  	// set up response
    63  	w.Header().Set("Content-Type", "application/json")
    64  	w.WriteHeader(http.StatusOK)
    65  
    66  	body, err := json.Marshal(response)
    67  	if err != nil {
    68  		panic(fmt.Errorf("error marshalling json: %w", err))
    69  	}
    70  
    71  	_, err = w.Write(body)
    72  	if err != nil {
    73  		panic(fmt.Errorf("failed to write test response body: %w", err))
    74  	}
    75  })
    76  
    77  var failingTestHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    78  	w.Header().Set("Content-Type", "application/json")
    79  	w.WriteHeader(http.StatusConflict)
    80  })
    81  
    82  func TestListIncidents(t *testing.T) {
    83  	t.Parallel()
    84  
    85  	c := newTestClient(t, incidentTestAPIHandler)
    86  
    87  	expected := []*Incident{
    88  		{
    89  			ID:                 42,
    90  			OpenedAt:           &testTimestamp,
    91  			IncidentPreference: "PER_CONDITION",
    92  			Links: IncidentLink{
    93  				Violations: []int{123456789},
    94  				PolicyID:   12345,
    95  			},
    96  		},
    97  		{
    98  			ID:                 24,
    99  			OpenedAt:           &testTimestamp,
   100  			ClosedAt:           &testTimestamp,
   101  			IncidentPreference: "PER_POLICY",
   102  			Links: IncidentLink{
   103  				Violations: []int{987654321},
   104  				PolicyID:   54321,
   105  			},
   106  		},
   107  	}
   108  
   109  	alertIncidents, err := c.ListIncidents(false, false)
   110  
   111  	assert.NoError(t, err)
   112  	assert.NotNil(t, alertIncidents)
   113  	assert.Equal(t, expected, alertIncidents)
   114  }
   115  
   116  func TestOpenListIncidents(t *testing.T) {
   117  	t.Parallel()
   118  
   119  	c := newTestClient(t, incidentTestAPIHandler)
   120  
   121  	expected := []*Incident{
   122  		{
   123  			ID:                 42,
   124  			OpenedAt:           &testTimestamp,
   125  			IncidentPreference: "PER_CONDITION",
   126  			Links: IncidentLink{
   127  				Violations: []int{123456789},
   128  				PolicyID:   12345,
   129  			},
   130  		},
   131  	}
   132  
   133  	alertIncidents, err := c.ListIncidents(true, false)
   134  
   135  	assert.NoError(t, err)
   136  	assert.NotNil(t, alertIncidents)
   137  	assert.Equal(t, expected, alertIncidents)
   138  }
   139  
   140  func TestListIncidentsWithoutViolations(t *testing.T) {
   141  	t.Parallel()
   142  
   143  	c := newTestClient(t, incidentTestAPIHandler)
   144  
   145  	expected := []*Incident{
   146  		{
   147  			ID:                 42,
   148  			OpenedAt:           &testTimestamp,
   149  			IncidentPreference: "PER_CONDITION",
   150  			Links: IncidentLink{
   151  				PolicyID: 12345,
   152  			},
   153  		},
   154  		{
   155  			ID:                 24,
   156  			OpenedAt:           &testTimestamp,
   157  			ClosedAt:           &testTimestamp,
   158  			IncidentPreference: "PER_POLICY",
   159  			Links: IncidentLink{
   160  				PolicyID: 54321,
   161  			},
   162  		},
   163  	}
   164  
   165  	alertIncidents, err := c.ListIncidents(false, true)
   166  
   167  	assert.NoError(t, err)
   168  	assert.NotNil(t, alertIncidents)
   169  	assert.Equal(t, expected, alertIncidents)
   170  }
   171  
   172  func TestListIncidentFailing(t *testing.T) {
   173  	t.Parallel()
   174  
   175  	c := newTestClient(t, failingTestHandler)
   176  
   177  	_, err := c.ListIncidents(false, false)
   178  
   179  	assert.Error(t, err)
   180  }
   181  
   182  func TestAcknowledgeIncident(t *testing.T) {
   183  	t.Parallel()
   184  
   185  	jsonResponse := `
   186  			{
   187  				"incidents": [
   188  			    {
   189  			      "id": 42,
   190  				  "opened_at": 1575438237690,
   191  			      "incident_preference": "PER_CONDITION",
   192  			      "links": {
   193  			        "violations": [
   194  			          123456789
   195  			        ],
   196  			        "policy_id": 12345
   197  				  }
   198  				}
   199  				]
   200  			}
   201  	`
   202  	alerts := newMockResponse(t, jsonResponse, http.StatusOK)
   203  
   204  	_, err := alerts.AcknowledgeIncident(42)
   205  
   206  	assert.NoError(t, err)
   207  }
   208  
   209  func TestAcknowledgeIncidentFailing(t *testing.T) {
   210  	t.Parallel()
   211  
   212  	c := newTestClient(t, failingTestHandler)
   213  
   214  	_, err := c.CloseIncident(42)
   215  
   216  	assert.Error(t, err)
   217  }
   218  
   219  func TestCloseIncident(t *testing.T) {
   220  	t.Parallel()
   221  
   222  	jsonResponse := `
   223  		{
   224  			"incidents": [
   225  		    	{
   226  		    	  "id": 42,
   227  				  "opened_at": 1575438237690,
   228  				  "closed_at": 1575438237690,
   229  		    	  "incident_preference": "PER_CONDITION",
   230  		    	  "links": {
   231  		    	    "violations": [
   232  		    	      123456789
   233  		    	    ],
   234  		    	    "policy_id": 12345
   235  				  }
   236  				}
   237  			]
   238  		}
   239  	`
   240  
   241  	alerts := newMockResponse(t, jsonResponse, http.StatusOK)
   242  
   243  	_, err := alerts.AcknowledgeIncident(42)
   244  	if err != nil {
   245  		t.Log(err)
   246  		t.Fatal("CloseIncident error")
   247  	}
   248  }
   249  
   250  func TestCloseIncidentFailing(t *testing.T) {
   251  	t.Parallel()
   252  
   253  	c := newTestClient(t, failingTestHandler)
   254  
   255  	_, err := c.CloseIncident(42)
   256  	if err == nil {
   257  		t.Fatal("CloseIncident expected an error")
   258  	}
   259  }