github.com/shravanasati/hydra@v1.0.1-0.20240122045627-1082d2ed50d2/src/config_test.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "math/rand" 6 "testing" 7 "time" 8 ) 9 10 func generateRandom(value string) string { 11 letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" 12 rand.Seed(time.Now().UnixNano()) 13 14 if value == "name" { 15 // * generating random values for configurations 16 17 var rname string 18 // * generating random name 19 for len(rname) <= 8 { 20 rname += string(letters[rand.Intn(len(letters))]) 21 } 22 return rname 23 24 } else if value == "githubUsername" { 25 // * generating random github usename 26 var rgithub string 27 for len(rgithub) <= 10 { 28 rgithub += string(letters[rand.Intn(len(letters))]) 29 } 30 return rgithub 31 32 } else if value == "lang" { 33 // * random choice of languages 34 rlang := supportedLangs[rand.Intn(len(supportedLangs))] 35 return rlang 36 37 } else if value == "license" { 38 // * random supported license 39 licenses := []string{} 40 for k := range supportedLicenses { 41 licenses = append(licenses, k) 42 } 43 rlicense := licenses[rand.Intn(len(licenses))] 44 return rlicense 45 46 } else { 47 panic(fmt.Sprintf("Invalid value for random generation: %v.", value)) 48 } 49 } 50 51 func TestConfig(t *testing.T) { 52 // * the below line is to ensure the `config.json` file exists 53 config("default", "default", "default", "default") 54 55 // * getting all initial values so that after the tests, the cleanup function can restore the configuration 56 initialName := getConfig("fullName") 57 initialGithubUsername := getConfig("githubUsername") 58 initialLang := getConfig("defaultLang") 59 initialLicense := getConfig("defaultLicense") 60 61 // * storing random values 62 rname := generateRandom("name") 63 rgithub := generateRandom("githubUsername") 64 rlang := generateRandom("lang") 65 rlicense := generateRandom("license") 66 67 // * setting configuration 68 config(rname, rgithub, rlang, rlicense) 69 70 // * checking fullname 71 gotName := getConfig("fullName") 72 if gotName != rname { 73 t.Errorf("Got %v, expected %v", gotName, rname) 74 } 75 76 // * checking github username 77 gotGithub := getConfig("githubUsername") 78 if gotGithub != rgithub { 79 t.Errorf("Got %v, expected %v", gotGithub, rgithub) 80 } 81 82 // * checking default language 83 gotLang := getConfig("defaultLang") 84 if gotLang != rlang { 85 t.Errorf("Got %v, expected %v", gotLang, rlang) 86 } 87 88 // * checking default license 89 gotLicense := getConfig("defaultLicense") 90 if gotLicense != rlicense { 91 t.Errorf("Got %v, expected %v", gotLicense, rlicense) 92 } 93 94 // * cleaning up 95 t.Cleanup(func() { 96 t.Log("\nCleaning up...\n") 97 config(initialName, initialGithubUsername, initialLang, initialLicense) 98 }) 99 }