package middleware import ( "encoding/json" "net/url" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) func UrlMustParse(s string) *url.URL { u, err := url.Parse(s) if err != nil { panic(err) } return u } type ContentSecurityPolicyConfigSuite struct { suite.Suite } func TestContentSecurityPolicyConfigSuite(t *testing.T) { suite.Run(t, &ContentSecurityPolicyConfigSuite{}) } func (s *ContentSecurityPolicyConfigSuite) TestBoolField() { c := &ContentSecurityPolicyConfig{ DefaultSrc: []CSPDirective{ CSPSelf, CSPHost("https://example.com"), }, UpgradeInsecureRequests: true, } assert.Equal( s.T(), "default-src 'self' https://example.com; upgrade-insecure-requests;", c.String(), ) } func (s *ContentSecurityPolicyConfigSuite) TestListOfStrings() { c := &ContentSecurityPolicyConfig{ DefaultSrc: []CSPDirective{ CSPSelf, CSPHost("https://example.com"), }, ConnectSrc: []CSPDirective{ CSPData, CSPHost("https://*.example.com"), }, } assert.Equal( s.T(), "default-src 'self' https://example.com; connect-src data: https://*.example.com;", c.String(), ) } func (s *ContentSecurityPolicyConfigSuite) TestListOfUrls() { c := &ContentSecurityPolicyConfig{ ReportUri: []*url.URL{ UrlMustParse("https://example.com/report"), UrlMustParse("https://example.com/report2"), }, } assert.Equal( s.T(), "report-uri https://example.com/report https://example.com/report2;", c.String(), ) } func TestReportToMarshalJSON(t *testing.T) { c := &CSPReportTo{ GroupName: "group", MaxAge: 24 * time.Hour, Endpoints: []*url.URL{ UrlMustParse("https://example.com/report"), UrlMustParse("https://example.com/report2"), }, } b, err := json.Marshal(c) if err != nil { t.Fail() } assert.Equal( t, `{"endpoints":[{"url":"https://example.com/report"},{"url":"https://example.com/report2"}],"group":"group","max_age":86400}`, string(b), ) }