github.com/crowdsecurity/crowdsec@v1.6.1/pkg/csplugin/broker_win_test.go (about) 1 //go:build windows 2 3 package csplugin 4 5 import ( 6 "bytes" 7 "encoding/json" 8 "io" 9 "os" 10 "testing" 11 "time" 12 13 "github.com/stretchr/testify/assert" 14 "github.com/stretchr/testify/require" 15 "gopkg.in/tomb.v2" 16 17 "github.com/crowdsecurity/go-cs-lib/cstest" 18 19 "github.com/crowdsecurity/crowdsec/pkg/csconfig" 20 "github.com/crowdsecurity/crowdsec/pkg/models" 21 ) 22 23 /* 24 Due to the complexity of file permission modification with go on windows, we only test the basic behavior the broker, 25 not if it will actually reject plugins with invalid permissions 26 */ 27 28 func (s *PluginSuite) TestBrokerInit() { 29 tests := []struct { 30 name string 31 action func(*testing.T) 32 procCfg csconfig.PluginCfg 33 expectedErr string 34 }{ 35 { 36 name: "valid config", 37 }, 38 { 39 name: "no plugin dir", 40 expectedErr: cstest.PathNotFoundMessage, 41 action: func(t *testing.T) { 42 err := os.RemoveAll(s.runDir) 43 require.NoError(t, err) 44 }, 45 }, 46 { 47 name: "no plugin binary", 48 expectedErr: "binary for plugin dummy_default not found", 49 action: func(t *testing.T) { 50 err := os.Remove(s.pluginBinary) 51 require.NoError(t, err) 52 }, 53 }, 54 } 55 56 for _, tc := range tests { 57 tc := tc 58 s.Run(tc.name, func() { 59 t := s.T() 60 if tc.action != nil { 61 tc.action(t) 62 } 63 _, err := s.InitBroker(&tc.procCfg) 64 cstest.RequireErrorContains(t, err, tc.expectedErr) 65 }) 66 } 67 } 68 69 func (s *PluginSuite) TestBrokerRun() { 70 t := s.T() 71 72 pb, err := s.InitBroker(nil) 73 require.NoError(t, err) 74 75 tomb := tomb.Tomb{} 76 go pb.Run(&tomb) 77 78 assert.NoFileExists(t, "./out") 79 defer os.Remove("./out") 80 81 pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} 82 pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}} 83 time.Sleep(time.Second * 4) 84 85 assert.FileExists(t, ".\\out") 86 87 content, err := os.ReadFile("./out") 88 require.NoError(t, err, "Error reading file") 89 90 decoder := json.NewDecoder(bytes.NewReader(content)) 91 92 var alerts []models.Alert 93 94 // two notifications, one alert each 95 96 err = decoder.Decode(&alerts) 97 require.NoError(t, err) 98 assert.Len(t, alerts, 1) 99 100 err = decoder.Decode(&alerts) 101 require.NoError(t, err) 102 assert.Len(t, alerts, 1) 103 104 err = decoder.Decode(&alerts) 105 assert.Equal(t, err, io.EOF) 106 }