2021-08-27 14:15:36 +00:00
package webhooks
import (
"context"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/fleetdm/fleet/v4/server/fleet"
"github.com/fleetdm/fleet/v4/server/mock"
kitlog "github.com/go-kit/kit/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTriggerHostStatusWebhook ( t * testing . T ) {
ds := new ( mock . Store )
requestBody := ""
ts := httptest . NewServer ( http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
requestBodyBytes , err := ioutil . ReadAll ( r . Body )
require . NoError ( t , err )
requestBody = string ( requestBodyBytes )
} ) )
defer ts . Close ( )
ac := & fleet . AppConfig {
WebhookSettings : fleet . WebhookSettings {
HostStatusWebhook : fleet . HostStatusWebhookSettings {
Enable : true ,
DestinationURL : ts . URL ,
HostPercentage : 43 ,
DaysCount : 2 ,
} ,
} ,
}
2022-09-20 19:26:36 +00:00
ds . AppConfigFunc = func ( context . Context ) ( * fleet . AppConfig , error ) {
return ac , nil
}
2021-09-14 12:11:07 +00:00
ds . TotalAndUnseenHostsSinceFunc = func ( ctx context . Context , daysCount int ) ( int , int , error ) {
2021-08-27 14:15:36 +00:00
assert . Equal ( t , 2 , daysCount )
return 10 , 6 , nil
}
2022-09-20 19:26:36 +00:00
require . NoError ( t , TriggerHostStatusWebhook ( context . Background ( ) , ds , kitlog . NewNopLogger ( ) ) )
2021-08-27 14:15:36 +00:00
assert . Equal (
t ,
2021-11-09 21:58:22 +00:00
` { "data": { "days_unseen":2,"total_hosts":10,"unseen_hosts":6},"text":"More than 60.00% of your hosts have not checked into Fleet for more than 2 days. You've been sent this message because the Host status webhook is enabled in your Fleet instance."} ` ,
2021-08-27 14:15:36 +00:00
requestBody ,
)
requestBody = ""
2021-09-14 12:11:07 +00:00
ds . TotalAndUnseenHostsSinceFunc = func ( ctx context . Context , daysCount int ) ( int , int , error ) {
2021-08-27 14:15:36 +00:00
assert . Equal ( t , 2 , daysCount )
return 10 , 1 , nil
}
2022-09-20 19:26:36 +00:00
require . NoError ( t , TriggerHostStatusWebhook ( context . Background ( ) , ds , kitlog . NewNopLogger ( ) ) )
2021-08-27 14:15:36 +00:00
assert . Equal ( t , "" , requestBody )
}