nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: prometheus/common
Pull request #193 (2019-05-16 15:20:03)

Fix unmarshal of negative times
While adding tests in https://github.com/prometheus/client_golang/pull/570 I noticed that this `model.Time` doesn't properly unmarshal negative times.

brian-brazil: Could you add a unittest for this?
jacksontj: There weren't any tests for time marshal/Unmarshal, so I added a couple.

Patch:
diff --git a/model/time.go b/model/time.go
index 46259b1..7b0064f 100644
--- a/model/time.go
+++ b/model/time.go
@@ -150,7 +150,13 @@ func (t *Time) UnmarshalJSON(b []byte) error {
 			return err
 		}
 
-		*t = Time(v + va)
+		// If the value was something like -0.1 the negative is lost in the
+		// parsing because of the leading zero, this ensures that we capture it.
+		if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 {
+			*t = Time(v+va) * -1
+		} else {
+			*t = Time(v + va)
+		}
 
 	default:
 		return fmt.Errorf("invalid time %q", string(b))


Test patch:
diff --git a/model/time_test.go b/model/time_test.go
index 3efdd65..315bc4e 100644
--- a/model/time_test.go
+++ b/model/time_test.go
@@ -14,6 +14,7 @@
 package model
 
 import (
+	"strconv"
 	"testing"
 	"time"
 )
@@ -130,3 +131,37 @@ func TestParseDuration(t *testing.T) {
 		}
 	}
 }
+
+func TestTimeJSON(t *testing.T) {
+	tests := []struct {
+		in  Time
+		out string
+	}{
+		{Time(1), `0.001`},
+		{Time(-1), `-0.001`},
+	}
+
+	for i, test := range tests {
+		t.Run(strconv.Itoa(i), func(t *testing.T) {
+			b, err := test.in.MarshalJSON()
+			if err != nil {
+				t.Fatalf("Error marshaling time: %v", err)
+			}
+
+			if string(b) != test.out {
+				t.Errorf("Mismatch in marshal expected=%s actual=%s", test.out, b)
+			}
+
+			var tm Time
+			if err := tm.UnmarshalJSON(b); err != nil {
+				t.Fatalf("Error Unmarshaling time: %v", err)
+			}
+
+			if !test.in.Equal(tm) {
+				t.Fatalf("Mismatch after Unmarshal expected=%v actual=%v", test.in, tm)
+			}
+
+		})
+	}
+
+}
Repository: prometheus/common
Pull request #208 (2019-09-05 12:41:07)

Check for upper case float variants too.
Error messages should be lower case.

@beorn7 


Patch:
diff --git a/expfmt/text_parse.go b/expfmt/text_parse.go
index be1ae2f..342e594 100644
--- a/expfmt/text_parse.go
+++ b/expfmt/text_parse.go
@@ -757,8 +757,8 @@ func histogramMetricName(name string) string {
 }
 
 func parseFloat(s string) (float64, error) {
-	if strings.ContainsAny(s, "p_") {
-		return 0, fmt.Errorf("Unsupported character in float")
+	if strings.ContainsAny(s, "pP_") {
+		return 0, fmt.Errorf("unsupported character in float")
 	}
 	return strconv.ParseFloat(s, 64)
 }


Test patch:
diff --git a/expfmt/text_parse_test.go b/expfmt/text_parse_test.go
index c3159b6..ba23c55 100644
--- a/expfmt/text_parse_test.go
+++ b/expfmt/text_parse_test.go
@@ -576,25 +576,50 @@ metric_bucket{le="bla"} 3.14
 		},
 		// 22: Check for various other literals variants, just in case.
 		{
-			in:  "foo 0b1\n",
+			in:  "foo 0x1P-3\n",
 			err: "text format parsing error in line 1: expected float as value",
 		},
 		// 23:
 		{
-			in:  "foo 0o1\n",
+			in:  "foo 0B1\n",
 			err: "text format parsing error in line 1: expected float as value",
 		},
 		// 24:
 		{
-			in:  "foo 0x1\n",
+			in:  "foo 0O1\n",
 			err: "text format parsing error in line 1: expected float as value",
 		},
 		// 25:
+		{
+			in:  "foo 0X1\n",
+			err: "text format parsing error in line 1: expected float as value",
+		},
+		// 26:
+		{
+			in:  "foo 0x1\n",
+			err: "text format parsing error in line 1: expected float as value",
+		},
+		// 27:
+		{
+			in:  "foo 0b1\n",
+			err: "text format parsing error in line 1: expected float as value",
+		},
+		// 28:
+		{
+			in:  "foo 0o1\n",
+			err: "text format parsing error in line 1: expected float as value",
+		},
+		// 29:
+		{
+			in:  "foo 0x1\n",
+			err: "text format parsing error in line 1: expected float as value",
+		},
+		// 30:
 		{
 			in:  "foo 0x1\n",
 			err: "text format parsing error in line 1: expected float as value",
 		},
-		// 26: Check histogram label.
+		// 31: Check histogram label.
 		{
 			in: `
 # TYPE metric histogram
@@ -602,7 +627,7 @@ metric_bucket{le="0x1p-3"} 3.14
 `,
 			err: "text format parsing error in line 3: expected float as value for 'le' label",
 		},
-		// 27: Check quantile label.
+		// 32: Check quantile label.
 		{
 			in: `
 # TYPE metric summary
Repository: prometheus/common
Pull request #225 (2020-03-03 08:28:27)

promlog: Avoid panic for new logger with empty config
Make sure that

```golang
promlog.New(&promlog.Config{})
```

doesn't panic. Instead, create a logger with reasonable defaults.

Signed-off-by: Benoît Knecht <bknecht@protonmail.ch>


Patch:
diff --git a/promlog/log.go b/promlog/log.go
index 45fcbc4..5062e28 100644
--- a/promlog/log.go
+++ b/promlog/log.go
@@ -94,13 +94,15 @@ type Config struct {
 // with a timestamp. The output always goes to stderr.
 func New(config *Config) log.Logger {
 	var l log.Logger
-	if config.Format.s == "logfmt" {
-		l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
-	} else {
+	if config.Format != nil && config.Format.s == "json" {
 		l = log.NewJSONLogger(log.NewSyncWriter(os.Stderr))
+	} else {
+		l = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
 	}
 
-	l = level.NewFilter(l, config.Level.o)
+	if config.Level != nil {
+		l = level.NewFilter(l, config.Level.o)
+	}
 	l = log.With(l, "ts", timestampFormat, "caller", log.DefaultCaller)
 	return l
 }


Test patch:
diff --git a/promlog/log_test.go b/promlog/log_test.go
new file mode 100644
index 0000000..ff51fd3
--- /dev/null
+++ b/promlog/log_test.go
@@ -0,0 +1,28 @@
+// Copyright 2020 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package promlog
+
+import (
+	"testing"
+)
+
+// Make sure creating and using a logger with an empty configuration doesn't
+// result in a panic.
+func TestDefaultConfig(t *testing.T) {
+	logger := New(&Config{})
+
+	if err := logger.Log("hello", "world"); err != nil {
+		t.Fatal(err)
+	}
+}
Repository: prometheus/common
Pull request #247 (2020-08-03 13:19:30)

model.Duration: disallow empty string
Signed-off-by: Julien Pivotto <roidelapluie@inuits.eu>

brian-brazil: :+1: 

Patch:
diff --git a/model/time.go b/model/time.go
index 57bd661..c40e640 100644
--- a/model/time.go
+++ b/model/time.go
@@ -186,9 +186,12 @@ var durationRE = regexp.MustCompile("^(([0-9]+)y)?(([0-9]+)w)?(([0-9]+)d)?(([0-9
 // ParseDuration parses a string into a time.Duration, assuming that a year
 // always has 365d, a week always has 7d, and a day always has 24h.
 func ParseDuration(durationStr string) (Duration, error) {
-	// Allow 0 without a unit.
-	if durationStr == "0" {
+	switch durationStr {
+	case "0":
+		// Allow 0 without a unit.
 		return 0, nil
+	case "":
+		return 0, fmt.Errorf("empty duration string")
 	}
 	matches := durationRE.FindStringSubmatch(durationStr)
 	if matches == nil {


Test patch:
diff --git a/model/time_test.go b/model/time_test.go
index cf7da71..d9c6789 100644
--- a/model/time_test.go
+++ b/model/time_test.go
@@ -163,6 +163,8 @@ func TestParseBadDuration(t *testing.T) {
 		"1y1m1d",
 		"-1w",
 		"1.5d",
+		"d",
+		"",
 	}
 
 	for _, c := range cases {
Repository: prometheus/common
Pull request #263 (2020-11-06 19:37:04)

Add unique label validation
Originally created as a PR in the
[client_golang](https://github.com/prometheus/client_golang/pull/812)
repo however was suggested to move it here.

Signed-off-by: Jarod Watkins <jarod@42lines.net>


Patch:
diff --git a/expfmt/text_parse.go b/expfmt/text_parse.go
index 342e594..b6079b3 100644
--- a/expfmt/text_parse.go
+++ b/expfmt/text_parse.go
@@ -299,6 +299,17 @@ func (p *TextParser) startLabelName() stateFn {
 		p.parseError(fmt.Sprintf("expected '=' after label name, found %q", p.currentByte))
 		return nil
 	}
+	// Check for duplicate label names.
+	labels := make(map[string]struct{})
+	for _, l := range p.currentMetric.Label {
+		lName := l.GetName()
+		if _, exists := labels[lName]; !exists {
+			labels[lName] = struct{}{}
+		} else {
+			p.parseError(fmt.Sprintf("duplicate label names for metric %q", p.currentMF.GetName()))
+			return nil
+		}
+	}
 	return p.startLabelValue
 }
 


Test patch:
diff --git a/expfmt/text_parse_test.go b/expfmt/text_parse_test.go
index ba23c55..949bbd6 100644
--- a/expfmt/text_parse_test.go
+++ b/expfmt/text_parse_test.go
@@ -635,6 +635,11 @@ metric{quantile="0x1p-3"} 3.14
 `,
 			err: "text format parsing error in line 3: expected float as value for 'quantile' label",
 		},
+		// 33: Check duplicate label.
+		{
+			in:  `metric{label="bla",label="bla"} 3.14`,
+			err: "text format parsing error in line 1: duplicate label names for metric",
+		},
 	}
 
 	for i, scenario := range scenarios {
Repository: prometheus/common
Pull request #360 (2022-03-15 23:46:21)

Make HTTP2 user visible
We still get reports from users that have issues with HTTP2. Let's make
it explicitly possible to disable it.

Because we previously introduced FollowRedirects, most lib users already
use our defaults.

Signed-off-by: Julien Pivotto <roidelapluie@inuits.eu>


Patch:
diff --git a/config/http_config.go b/config/http_config.go
index bf52ce3..69d0d95 100644
--- a/config/http_config.go
+++ b/config/http_config.go
@@ -28,7 +28,6 @@ import (
 	"net"
 	"net/http"
 	"net/url"
-	"os"
 	"strings"
 	"sync"
 	"time"
@@ -43,6 +42,7 @@ import (
 // DefaultHTTPClientConfig is the default HTTP client configuration.
 var DefaultHTTPClientConfig = HTTPClientConfig{
 	FollowRedirects: true,
+	EnableHTTP2:     true,
 }
 
 // defaultHTTPClientOptions holds the default HTTP client options.
@@ -198,6 +198,10 @@ type HTTPClientConfig struct {
 	// The omitempty flag is not set, because it would be hidden from the
 	// marshalled configuration when set to false.
 	FollowRedirects bool `yaml:"follow_redirects" json:"follow_redirects"`
+	// EnableHTTP2 specifies whether the client should configure HTTP2.
+	// The omitempty flag is not set, because it would be hidden from the
+	// marshalled configuration when set to false.
+	EnableHTTP2 bool `yaml:"enable_http2" json:"enable_http2"`
 }
 
 // SetDirectory joins any relative file paths with dir.
@@ -401,7 +405,7 @@ func NewRoundTripperFromConfig(cfg HTTPClientConfig, name string, optFuncs ...HT
 			ExpectContinueTimeout: 1 * time.Second,
 			DialContext:           dialContext,
 		}
-		if opts.http2Enabled && os.Getenv("PROMETHEUS_COMMON_DISABLE_HTTP2") == "" {
+		if opts.http2Enabled && cfg.EnableHTTP2 {
 			// HTTP/2 support is golang had many problematic cornercases where
 			// dead connections would be kept and used in connection pools.
 			// https://github.com/golang/go/issues/32388


Test patch:
diff --git a/config/testdata/http.conf.good.yml b/config/testdata/http.conf.good.yml
index 46ca639..2eafc78 100644
--- a/config/testdata/http.conf.good.yml
+++ b/config/testdata/http.conf.good.yml
@@ -2,3 +2,4 @@ basic_auth:
   username: username
   password: "mysecret"
 proxy_url: "http://remote.host"
+enable_http2: true
Repository: prometheus/common
Pull request #405 (2022-10-05 22:24:46)

Implement Stringer on TLSVersion
https://github.com/prometheus/prometheus/issues/11417

Signed-off-by: Julien Pivotto <roidelapluie@o11y.eu>


Patch:
diff --git a/config/http_config.go b/config/http_config.go
index c771b2e..e0959e4 100644
--- a/config/http_config.go
+++ b/config/http_config.go
@@ -80,7 +80,7 @@ func (tv *TLSVersion) UnmarshalYAML(unmarshal func(interface{}) error) error {
 }
 
 func (tv *TLSVersion) MarshalYAML() (interface{}, error) {
-	if tv != nil || *tv == 0 {
+	if tv == nil || *tv == 0 {
 		return []byte("null"), nil
 	}
 	for s, v := range TLSVersions {
@@ -106,7 +106,7 @@ func (tv *TLSVersion) UnmarshalJSON(data []byte) error {
 
 // MarshalJSON implements the json.Marshaler interface for TLSVersion.
 func (tv *TLSVersion) MarshalJSON() ([]byte, error) {
-	if tv != nil || *tv == 0 {
+	if tv == nil || *tv == 0 {
 		return []byte("null"), nil
 	}
 	for s, v := range TLSVersions {
@@ -117,6 +117,19 @@ func (tv *TLSVersion) MarshalJSON() ([]byte, error) {
 	return nil, fmt.Errorf("unknown TLS version: %d", tv)
 }
 
+// String implements the fmt.Stringer interface for TLSVersion.
+func (tv *TLSVersion) String() string {
+	if tv == nil || *tv == 0 {
+		return ""
+	}
+	for s, v := range TLSVersions {
+		if *tv == v {
+			return s
+		}
+	}
+	return fmt.Sprintf("%d", tv)
+}
+
 // BasicAuth contains basic HTTP authentication credentials.
 type BasicAuth struct {
 	Username     string `yaml:"username" json:"username"`


Test patch:
diff --git a/config/tls_config_test.go b/config/tls_config_test.go
index 662c710..8799d7e 100644
--- a/config/tls_config_test.go
+++ b/config/tls_config_test.go
@@ -90,3 +90,9 @@ func TestValidTLSConfig(t *testing.T) {
 		}
 	}
 }
+
+func TestStringer(t *testing.T) {
+	if s := (TLSVersion)(tls.VersionTLS13); s.String() != "TLS13" {
+		t.Fatalf("tls.VersionTLS13 string should be TLS13, got %s", s.String())
+	}
+}
Repository: prometheus/common
Pull request #407 (2022-11-03 11:45:06)

Remove ioutil after merging check client certificates
Signed-off-by: Julien Pivotto <roidelapluie@o11y.eu>


Patch:
diff --git a/.yamllint b/.yamllint
index 281c946..3878a31 100644
--- a/.yamllint
+++ b/.yamllint
@@ -14,6 +14,7 @@ rules:
   document-start: disable
   indentation:
     spaces: consistent
+    indent-sequences: consistent
   key-duplicates:
     ignore: |
       config/testdata/section_key_dup.bad.yml
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 9a1aff4..d325872 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,3 +1,3 @@
-## Prometheus Community Code of Conduct
+# Prometheus Community Code of Conduct
 
-Prometheus follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).
+Prometheus follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md).
diff --git a/SECURITY.md b/SECURITY.md
index 67741f0..fed02d8 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -3,4 +3,4 @@
 The Prometheus security policy, including how to report vulnerabilities, can be
 found here:
 
-https://prometheus.io/docs/operating/security/
+<https://prometheus.io/docs/operating/security/>
diff --git a/config/http_config.go b/config/http_config.go
index 69c0b67..c07f696 100644
--- a/config/http_config.go
+++ b/config/http_config.go
@@ -846,12 +846,12 @@ func (c *TLSConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
 
 // readCertAndKey reads the cert and key files from the disk.
 func readCertAndKey(certFile, keyFile string) ([]byte, []byte, error) {
-	certData, err := ioutil.ReadFile(certFile)
+	certData, err := os.ReadFile(certFile)
 	if err != nil {
 		return nil, nil, err
 	}
 
-	keyData, err := ioutil.ReadFile(keyFile)
+	keyData, err := os.ReadFile(keyFile)
 	if err != nil {
 		return nil, nil, err
 	}


Test patch:
diff --git a/config/http_config_test.go b/config/http_config_test.go
index 036fd2d..89594cd 100644
--- a/config/http_config_test.go
+++ b/config/http_config_test.go
@@ -1536,7 +1536,7 @@ func TestOAuth2Proxy(t *testing.T) {
 func TestModifyTLSCertificates(t *testing.T) {
 	bs := getCertificateBlobs(t)
 
-	tmpDir, err := ioutil.TempDir("", "modifytlscertificates")
+	tmpDir, err := os.MkdirTemp("", "modifytlscertificates")
 	if err != nil {
 		t.Fatal("Failed to create tmp dir", err)
 	}
@@ -1632,7 +1632,7 @@ func TestModifyTLSCertificates(t *testing.T) {
 				t.Fatalf("Expected no error, got %q", err)
 			}
 
-			b, err := ioutil.ReadAll(r.Body)
+			b, err := io.ReadAll(r.Body)
 			r.Body.Close()
 			if err != nil {
 				t.Errorf("Can't read the server response body")
Repository: prometheus/common
Pull request #415 (2022-11-26 09:56:10)

feat: make LoadHTTPConfigFile set directory and move from tests file
Move away the functions from the test files since they are not only test helper.
For motivation, see https://github.com/prometheus/prometheus/pull/11487

Also add setting directory `cfg.SetDirectory(filepath.Dir(filepath.Dir(filename)))` as used in Alertmanager see 
https://github.com/prometheus/alertmanager/blob/1a9f55b939ab81b86428c013ae294ad80779c9b6/cli/config/http_config.go#L36

Prometheus does not use the `LoadHTTPConfigFile` function AFAIK, so the change in setting the directory won't break anything, hopefully. 

Other possibility is to avoid setting the directory and fix this on the Alertmanager side outside the common library. 
That might be safer (function is exported, so it could be breaking change for someone, possibly?) 

@roidelapluie PTAL


Patch:
diff --git a/config/http_config.go b/config/http_config.go
index c07f696..6a668dd 100644
--- a/config/http_config.go
+++ b/config/http_config.go
@@ -25,6 +25,7 @@ import (
 	"net/http"
 	"net/url"
 	"os"
+	"path/filepath"
 	"strings"
 	"sync"
 	"time"
@@ -248,6 +249,30 @@ func (a *OAuth2) SetDirectory(dir string) {
 	a.TLSConfig.SetDirectory(dir)
 }
 
+// LoadHTTPConfig parses the YAML input s into a HTTPClientConfig.
+func LoadHTTPConfig(s string) (*HTTPClientConfig, error) {
+	cfg := &HTTPClientConfig{}
+	err := yaml.UnmarshalStrict([]byte(s), cfg)
+	if err != nil {
+		return nil, err
+	}
+	return cfg, nil
+}
+
+// LoadHTTPConfigFile parses the given YAML file into a HTTPClientConfig.
+func LoadHTTPConfigFile(filename string) (*HTTPClientConfig, []byte, error) {
+	content, err := os.ReadFile(filename)
+	if err != nil {
+		return nil, nil, err
+	}
+	cfg, err := LoadHTTPConfig(string(content))
+	if err != nil {
+		return nil, nil, err
+	}
+	cfg.SetDirectory(filepath.Dir(filepath.Dir(filename)))
+	return cfg, content, nil
+}
+
 // HTTPClientConfig configures an HTTP client.
 type HTTPClientConfig struct {
 	// The HTTP basic authentication credentials for the targets.


Test patch:
diff --git a/config/http_config_test.go b/config/http_config_test.go
index 89594cd..f608447 100644
--- a/config/http_config_test.go
+++ b/config/http_config_test.go
@@ -1125,29 +1125,6 @@ func TestInvalidHTTPConfigs(t *testing.T) {
 	}
 }
 
-// LoadHTTPConfig parses the YAML input s into a HTTPClientConfig.
-func LoadHTTPConfig(s string) (*HTTPClientConfig, error) {
-	cfg := &HTTPClientConfig{}
-	err := yaml.UnmarshalStrict([]byte(s), cfg)
-	if err != nil {
-		return nil, err
-	}
-	return cfg, nil
-}
-
-// LoadHTTPConfigFile parses the given YAML file into a HTTPClientConfig.
-func LoadHTTPConfigFile(filename string) (*HTTPClientConfig, []byte, error) {
-	content, err := os.ReadFile(filename)
-	if err != nil {
-		return nil, nil, err
-	}
-	cfg, err := LoadHTTPConfig(string(content))
-	if err != nil {
-		return nil, nil, err
-	}
-	return cfg, content, nil
-}
-
 type roundTrip struct {
 	theResponse *http.Response
 	theError    error
Repository: GoogleChrome/lighthouse
Pull request #12680 (2021-06-21 20:21:01)

core(fr): add timespan support to viewport-dimensions
[Opportunity conversion doc](https://docs.google.com/document/d/1z6Cm4jJmN-1i5S2ryfC1hLPyo46NlW6X8QMXRDqq1_Y/edit?resourcekey=0-r0zHmcvw4Y2Wg4DI96d4KA#)

This is some pretty low-hanging fruit. We are just getting viewport dimensions from the end of the timespan.

Only issue would be if viewport changes during the timespan, but such an event could also affect the dimensions in navigation mode. We could surface a warning if the viewport changes.


Patch:
diff --git a/lighthouse-core/gather/gatherers/viewport-dimensions.js b/lighthouse-core/gather/gatherers/viewport-dimensions.js
index eebf63893..71df65998 100644
--- a/lighthouse-core/gather/gatherers/viewport-dimensions.js
+++ b/lighthouse-core/gather/gatherers/viewport-dimensions.js
@@ -30,7 +30,7 @@ function getViewportDimensions() {
 class ViewportDimensions extends FRGatherer {
   /** @type {LH.Gatherer.GathererMeta} */
   meta = {
-    supportedModes: ['snapshot', 'navigation'],
+    supportedModes: ['snapshot', 'timespan', 'navigation'],
   }
 
   /**


Test patch:
diff --git a/lighthouse-core/test/config/config-test.js b/lighthouse-core/test/config/config-test.js
index 3d8b473af..e2b43d16e 100644
--- a/lighthouse-core/test/config/config-test.js
+++ b/lighthouse-core/test/config/config-test.js
@@ -1297,7 +1297,7 @@ describe('Config', () => {
 
       const expectedInstance = {
         meta: {
-          supportedModes: ['snapshot', 'navigation'],
+          supportedModes: ['snapshot', 'timespan', 'navigation'],
         },
       };
       assert.deepEqual(mergedJson[0].gatherers,
diff --git a/lighthouse-core/test/fraggle-rock/api-test-pptr.js b/lighthouse-core/test/fraggle-rock/api-test-pptr.js
index ef65f48b0..21a1ec3f6 100644
--- a/lighthouse-core/test/fraggle-rock/api-test-pptr.js
+++ b/lighthouse-core/test/fraggle-rock/api-test-pptr.js
@@ -121,7 +121,7 @@ describe('Fraggle Rock API', () => {
 
       const {auditResults, erroredAudits, failedAudits} = getAuditsBreakdown(lhr);
       // TODO(FR-COMPAT): This assertion can be removed when full compatibility is reached.
-      expect(auditResults.length).toMatchInlineSnapshot(`38`);
+      expect(auditResults.length).toMatchInlineSnapshot(`40`);
 
       expect(erroredAudits).toHaveLength(0);
       expect(failedAudits.map(audit => audit.id)).toContain('errors-in-console');
Repository: GoogleChrome/lighthouse
Pull request #12801 (2021-07-19 15:37:08)

core(csp-xss): make n/a with empty results
Closes https://github.com/GoogleChrome/lighthouse/issues/12777https://github.com/GoogleChrome/lighthouse/issues/12777


Patch:
diff --git a/lighthouse-core/audits/csp-xss.js b/lighthouse-core/audits/csp-xss.js
index 93f83b488..e45fb0d8f 100644
--- a/lighthouse-core/audits/csp-xss.js
+++ b/lighthouse-core/audits/csp-xss.js
@@ -176,7 +176,7 @@ class CspXss extends Audit {
 
     return {
       score,
-      notApplicable: false,
+      notApplicable: !results.length,
       details,
     };
   }


Test patch:
diff --git a/lighthouse-core/test/audits/csp-xss-test.js b/lighthouse-core/test/audits/csp-xss-test.js
index 957a97d19..0cc3c66d4 100644
--- a/lighthouse-core/test/audits/csp-xss-test.js
+++ b/lighthouse-core/test/audits/csp-xss-test.js
@@ -89,6 +89,7 @@ it('audit basic header', async () => {
     },
   };
   const results = await CspXss.audit(artifacts, {computedCache: new Map()});
+  expect(results.notApplicable).toBeFalsy();
   expect(results.details.items).toMatchObject(
     [
       {
@@ -117,6 +118,28 @@ it('audit basic header', async () => {
   );
 });
 
+it('marked N/A if no warnings found', async () => {
+  const artifacts = {
+    URL: 'https://example.com',
+    MetaElements: [],
+    devtoolsLogs: {
+      defaultPass: networkRecordsToDevtoolsLog([
+        {
+          url: 'https://example.com',
+          responseHeaders: [
+            {
+              name: 'Content-Security-Policy',
+              value: `script-src 'none'; object-src 'none'; base-uri 'none'; report-uri https://csp.example.com`},
+          ],
+        },
+      ]),
+    },
+  };
+  const results = await CspXss.audit(artifacts, {computedCache: new Map()});
+  expect(results.details.items).toHaveLength(0);
+  expect(results.notApplicable).toBeTruthy();
+});
+
 describe('getRawCsps', () => {
   it('basic case', async () => {
     const artifacts = {