|
| 1 | +package command |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/DefangLabs/secret-detector/pkg/scanner" |
| 7 | +) |
| 8 | + |
| 9 | +func TestCreateRandomConfigValue(t *testing.T) { |
| 10 | + // create a scanner config |
| 11 | + cfg := scanner.NewConfigWithDefaults() |
| 12 | + |
| 13 | + // adjust the entropy threshold value for the "high_entropy_string" detector. |
| 14 | + // this will affect the level of randomness that is tolerated in a string |
| 15 | + // (0 = low entropy, 4+ = very high entropy) |
| 16 | + cfg.DetectorConfigs["high_entropy_string"] = []string{"3"} |
| 17 | + |
| 18 | + // create the scanner based on scanner config |
| 19 | + scannerClient, err := scanner.NewScannerFromConfig(cfg) |
| 20 | + if err != nil { |
| 21 | + t.Fatalf("Failed to make a config detector: " + err.Error()) |
| 22 | + } |
| 23 | + |
| 24 | + // a map for storing generated results to check if they are unique |
| 25 | + var uniqueConfigList = make(map[string]bool) |
| 26 | + |
| 27 | + var testIterations = 5 |
| 28 | + for range testIterations { |
| 29 | + // call the function to create a random config |
| 30 | + randomConfig := CreateRandomConfigValue() |
| 31 | + |
| 32 | + // store generated configs as unique keys in a map |
| 33 | + uniqueConfigList[randomConfig] = true |
| 34 | + |
| 35 | + // scan the config |
| 36 | + ds, err := scannerClient.Scan(randomConfig) |
| 37 | + if err != nil { |
| 38 | + t.Fatalf("Failed to scan input: " + err.Error()) |
| 39 | + } |
| 40 | + |
| 41 | + // the length of ds (detected secrets) should be one |
| 42 | + for _, d := range ds { |
| 43 | + // check if the config meets the threshold for high entropy (randomness) |
| 44 | + if d.Type != "High entropy string" { |
| 45 | + t.Errorf("did not meet the entropy threshold: generated value of %q", randomConfig) |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + // check if the length of the map matches the number of test iterations (should be equal if all keys are unique) |
| 51 | + numOfUniqueConfigs := len(uniqueConfigList) |
| 52 | + if numOfUniqueConfigs < testIterations { |
| 53 | + t.Errorf("generated result was not unique: expected numOfUniqueConfigs to be %d, but got %d", testIterations, numOfUniqueConfigs) |
| 54 | + } |
| 55 | +} |
0 commit comments