This is an automated email from the ASF dual-hosted git repository.
ocket8888 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/trafficcontrol.git
The following commit(s) were added to refs/heads/master by this push:
new ca8617f9c1 Move duplicate rand functionality to test rand (#6852)
ca8617f9c1 is described below
commit ca8617f9c1726ffb51ede8b89e8aa9aa479f3664
Author: Eric Holguin <[email protected]>
AuthorDate: Wed Jun 8 11:49:26 2022 -0600
Move duplicate rand functionality to test rand (#6852)
* Moved duplicate rand functionality to test rand
* Add GoDocs and functions return value instead of pointer
* Remove dereference and use go-util ptr functionality
* fix import format
* fix import order
---
cache-config/t3c-generate/cfgfile/cfgfile_test.go | 344 +++++++++------------
grove/stat/stats_test.go | 4 +-
traffic_monitor/cache/astats_test.go | 18 +-
traffic_monitor/cache/data_test.go | 146 ++++-----
traffic_monitor/datareq/datareq_test.go | 41 +--
traffic_monitor/ds/stat_test.go | 46 +--
.../threadsafe/resultstathistory_test.go | 47 +--
.../traffic_vault_migrate_test.go | 8 +-
.../traffic_ops_golang/crconfig/config_test.go | 6 +-
.../crconfig/deliveryservice_test.go | 40 +--
.../crconfig/edgelocations_test.go | 17 +-
.../traffic_ops_golang/crconfig/servers_test.go | 106 ++-----
.../traffic_ops_golang/crconfig/stats_test.go | 10 +-
traffic_ops/traffic_ops_golang/test/rand.go | 86 +++++-
14 files changed, 427 insertions(+), 492 deletions(-)
diff --git a/cache-config/t3c-generate/cfgfile/cfgfile_test.go
b/cache-config/t3c-generate/cfgfile/cfgfile_test.go
index 6e633a1353..6b6699280b 100644
--- a/cache-config/t3c-generate/cfgfile/cfgfile_test.go
+++ b/cache-config/t3c-generate/cfgfile/cfgfile_test.go
@@ -21,7 +21,6 @@ package cfgfile
import (
"bytes"
- "math/rand"
"strings"
"testing"
"time"
@@ -31,6 +30,7 @@ import (
"github.com/apache/trafficcontrol/lib/go-atscfg"
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-util"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
)
func TestWriteConfigs(t *testing.T) {
@@ -134,50 +134,10 @@ func removeComments(configs string) string {
return strings.Join(newLines, "\n")
}
-func randBool() *bool {
- b := rand.Int()%2 == 0
- return &b
-}
-
-func randStr() *string {
- chars :=
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
- num := 100
- s := ""
- for i := 0; i < num; i++ {
- s += string(chars[rand.Intn(len(chars))])
- }
- return &s
-}
-
-func randInt() *int {
- i := rand.Int()
- return &i
-}
-
-func randInt64() *int64 {
- i := int64(rand.Int63())
- return &i
-}
-
-func randUint64() *uint64 {
- i := uint64(rand.Int63())
- return &i
-}
-
-func randUint() *uint {
- i := uint(rand.Int())
- return &i
-}
-
-func randFloat64() *float64 {
- f := rand.Float64()
- return &f
-}
-
func randDSS() tc.DeliveryServiceServer {
return tc.DeliveryServiceServer{
- Server: randInt(),
- DeliveryService: randInt(),
+ Server: util.IntPtr(test.RandInt()),
+ DeliveryService: util.IntPtr(test.RandInt()),
}
}
@@ -186,49 +146,49 @@ func randDS() *atscfg.DeliveryService {
dsTypeHTTP := tc.DSTypeHTTP
protocol := tc.DSProtocolHTTP
ds := atscfg.DeliveryService{}
- ds.EcsEnabled = *randBool()
- ds.RangeSliceBlockSize = randInt()
- ds.ConsistentHashRegex = randStr()
+ ds.EcsEnabled = test.RandBool()
+ ds.RangeSliceBlockSize = util.IntPtr(test.RandInt())
+ ds.ConsistentHashRegex = util.StrPtr(test.RandStr())
ds.ConsistentHashQueryParams = []string{
- *randStr(),
- *randStr(),
+ test.RandStr(),
+ test.RandStr(),
}
- ds.MaxOriginConnections = randInt()
+ ds.MaxOriginConnections = util.IntPtr(test.RandInt())
ds.DeepCachingType = &deepCachingTypeNever
- ds.FQPacingRate = randInt()
- ds.SigningAlgorithm = randStr()
- ds.Tenant = randStr()
- ds.TRResponseHeaders = randStr()
- ds.TRRequestHeaders = randStr()
- ds.Active = randBool()
- ds.AnonymousBlockingEnabled = randBool()
- ds.CCRDNSTTL = randInt()
- ds.CDNID = randInt()
- ds.CDNName = randStr()
- ds.CheckPath = randStr()
- ds.DisplayName = randStr()
- ds.DNSBypassCNAME = randStr()
- ds.DNSBypassIP = randStr()
- ds.DNSBypassIP6 = randStr()
- ds.DNSBypassTTL = randInt()
- ds.DSCP = randInt()
- ds.EdgeHeaderRewrite = randStr()
- ds.GeoLimit = randInt()
+ ds.FQPacingRate = util.IntPtr(test.RandInt())
+ ds.SigningAlgorithm = util.StrPtr(test.RandStr())
+ ds.Tenant = util.StrPtr(test.RandStr())
+ ds.TRResponseHeaders = util.StrPtr(test.RandStr())
+ ds.TRRequestHeaders = util.StrPtr(test.RandStr())
+ ds.Active = util.BoolPtr(test.RandBool())
+ ds.AnonymousBlockingEnabled = util.BoolPtr(test.RandBool())
+ ds.CCRDNSTTL = util.IntPtr(test.RandInt())
+ ds.CDNID = util.IntPtr(test.RandInt())
+ ds.CDNName = util.StrPtr(test.RandStr())
+ ds.CheckPath = util.StrPtr(test.RandStr())
+ ds.DisplayName = util.StrPtr(test.RandStr())
+ ds.DNSBypassCNAME = util.StrPtr(test.RandStr())
+ ds.DNSBypassIP = util.StrPtr(test.RandStr())
+ ds.DNSBypassIP6 = util.StrPtr(test.RandStr())
+ ds.DNSBypassTTL = util.IntPtr(test.RandInt())
+ ds.DSCP = util.IntPtr(test.RandInt())
+ ds.EdgeHeaderRewrite = util.StrPtr(test.RandStr())
+ ds.GeoLimit = util.IntPtr(test.RandInt())
ds.GeoLimitCountries = nil
- ds.GeoLimitRedirectURL = randStr()
- ds.GeoProvider = randInt()
- ds.GlobalMaxMBPS = randInt()
- ds.GlobalMaxTPS = randInt()
- ds.HTTPBypassFQDN = randStr()
- ds.ID = randInt()
- ds.InfoURL = randStr()
- ds.InitialDispersion = randInt()
- ds.IPV6RoutingEnabled = randBool()
+ ds.GeoLimitRedirectURL = util.StrPtr(test.RandStr())
+ ds.GeoProvider = util.IntPtr(test.RandInt())
+ ds.GlobalMaxMBPS = util.IntPtr(test.RandInt())
+ ds.GlobalMaxTPS = util.IntPtr(test.RandInt())
+ ds.HTTPBypassFQDN = util.StrPtr(test.RandStr())
+ ds.ID = util.IntPtr(test.RandInt())
+ ds.InfoURL = util.StrPtr(test.RandStr())
+ ds.InitialDispersion = util.IntPtr(test.RandInt())
+ ds.IPV6RoutingEnabled = util.BoolPtr(test.RandBool())
ds.LastUpdated = &tc.TimeNoMod{Time: time.Now()}
- ds.LogsEnabled = randBool()
- ds.LongDesc = randStr()
- ds.LongDesc1 = randStr()
- ds.LongDesc2 = randStr()
+ ds.LogsEnabled = util.BoolPtr(test.RandBool())
+ ds.LongDesc = util.StrPtr(test.RandStr())
+ ds.LongDesc1 = util.StrPtr(test.RandStr())
+ ds.LongDesc2 = util.StrPtr(test.RandStr())
ds.MatchList = &[]tc.DeliveryServiceMatch{
{
Type: tc.DSMatchTypeHostRegex,
@@ -236,68 +196,68 @@ func randDS() *atscfg.DeliveryService {
Pattern: `\.*foo\.*`,
},
}
- ds.MaxDNSAnswers = randInt()
- ds.MidHeaderRewrite = randStr()
- ds.MissLat = randFloat64()
- ds.MissLong = randFloat64()
- ds.MultiSiteOrigin = randBool()
- ds.OriginShield = randStr()
- ds.OrgServerFQDN = util.StrPtr("http://" + *(randStr()))
- ds.ProfileDesc = randStr()
- ds.ProfileID = randInt()
- ds.ProfileName = randStr()
+ ds.MaxDNSAnswers = util.IntPtr(test.RandInt())
+ ds.MidHeaderRewrite = util.StrPtr(test.RandStr())
+ ds.MissLat = util.FloatPtr(test.RandFloat64())
+ ds.MissLong = util.FloatPtr(test.RandFloat64())
+ ds.MultiSiteOrigin = util.BoolPtr(test.RandBool())
+ ds.OriginShield = util.StrPtr(test.RandStr())
+ ds.OrgServerFQDN = util.StrPtr("http://" + test.RandStr())
+ ds.ProfileDesc = util.StrPtr(test.RandStr())
+ ds.ProfileID = util.IntPtr(test.RandInt())
+ ds.ProfileName = util.StrPtr(test.RandStr())
ds.Protocol = &protocol
- ds.QStringIgnore = randInt()
- ds.RangeRequestHandling = randInt()
- ds.RegexRemap = randStr()
- ds.RegionalGeoBlocking = randBool()
- ds.RemapText = randStr()
- ds.RoutingName = randStr()
- ds.Signed = *randBool()
- ds.SSLKeyVersion = randInt()
- ds.TenantID = randInt()
+ ds.QStringIgnore = util.IntPtr(test.RandInt())
+ ds.RangeRequestHandling = util.IntPtr(test.RandInt())
+ ds.RegexRemap = util.StrPtr(test.RandStr())
+ ds.RegionalGeoBlocking = util.BoolPtr(test.RandBool())
+ ds.RemapText = util.StrPtr(test.RandStr())
+ ds.RoutingName = util.StrPtr(test.RandStr())
+ ds.Signed = *util.BoolPtr(test.RandBool())
+ ds.SSLKeyVersion = util.IntPtr(test.RandInt())
+ ds.TenantID = util.IntPtr(test.RandInt())
ds.Type = &dsTypeHTTP
- ds.TypeID = randInt()
- ds.XMLID = randStr()
+ ds.TypeID = util.IntPtr(test.RandInt())
+ ds.XMLID = util.StrPtr(test.RandStr())
ds.ExampleURLs = []string{
- *randStr(),
- *randStr(),
+ test.RandStr(),
+ test.RandStr(),
}
return &ds
}
func randServer() *atscfg.Server {
sv := &atscfg.Server{}
- sv.Cachegroup = randStr()
- sv.CachegroupID = randInt()
- sv.CDNID = randInt()
- sv.CDNName = randStr()
- sv.DomainName = randStr()
- sv.FQDN = randStr()
+ sv.Cachegroup = util.StrPtr(test.RandStr())
+ sv.CachegroupID = util.IntPtr(test.RandInt())
+ sv.CDNID = util.IntPtr(test.RandInt())
+ sv.CDNName = util.StrPtr(test.RandStr())
+ sv.DomainName = util.StrPtr(test.RandStr())
+ sv.FQDN = util.StrPtr(test.RandStr())
sv.FqdnTime = time.Now()
- sv.GUID = randStr()
- sv.HostName = randStr()
- sv.HTTPSPort = randInt()
- sv.ID = randInt()
- sv.ILOIPAddress = randStr()
- sv.ILOIPGateway = randStr()
- sv.ILOIPNetmask = randStr()
- sv.ILOPassword = randStr()
- sv.ILOUsername = randStr()
+ sv.GUID = util.StrPtr(test.RandStr())
+ sv.HostName = util.StrPtr(test.RandStr())
+ sv.HTTPSPort = util.IntPtr(test.RandInt())
+ sv.ID = util.IntPtr(test.RandInt())
+ sv.ILOIPAddress = util.StrPtr(test.RandStr())
+ sv.ILOIPGateway = util.StrPtr(test.RandStr())
+ sv.ILOIPNetmask = util.StrPtr(test.RandStr())
+ sv.ILOPassword = util.StrPtr(test.RandStr())
+ sv.ILOUsername = util.StrPtr(test.RandStr())
sv.Interfaces = []tc.ServerInterfaceInfoV40{}
{
ssi := tc.ServerInterfaceInfoV40{}
- ssi.Name = *randStr()
+ ssi.Name = test.RandStr()
ssi.IPAddresses = []tc.ServerIPAddress{
tc.ServerIPAddress{
- Address: *randStr(),
- Gateway: randStr(),
+ Address: test.RandStr(),
+ Gateway: util.StrPtr(test.RandStr()),
ServiceAddress: true,
},
tc.ServerIPAddress{
- Address: *randStr(),
- Gateway: randStr(),
+ Address: test.RandStr(),
+ Gateway: util.StrPtr(test.RandStr()),
ServiceAddress: true,
},
}
@@ -305,53 +265,53 @@ func randServer() *atscfg.Server {
}
sv.LastUpdated = &tc.TimeNoMod{Time: time.Now()}
- sv.MgmtIPAddress = randStr()
- sv.MgmtIPGateway = randStr()
- sv.MgmtIPNetmask = randStr()
- sv.OfflineReason = randStr()
- sv.PhysLocation = randStr()
- sv.PhysLocationID = randInt()
- sv.ProfileNames = []string{*randStr()}
- sv.Rack = randStr()
- sv.RevalPending = randBool()
- sv.Status = randStr()
- sv.StatusID = randInt()
- sv.TCPPort = randInt()
- sv.Type = *randStr()
- sv.TypeID = randInt()
- sv.UpdPending = randBool()
- sv.XMPPID = randStr()
- sv.XMPPPasswd = randStr()
+ sv.MgmtIPAddress = util.StrPtr(test.RandStr())
+ sv.MgmtIPGateway = util.StrPtr(test.RandStr())
+ sv.MgmtIPNetmask = util.StrPtr(test.RandStr())
+ sv.OfflineReason = util.StrPtr(test.RandStr())
+ sv.PhysLocation = util.StrPtr(test.RandStr())
+ sv.PhysLocationID = util.IntPtr(test.RandInt())
+ sv.ProfileNames = []string{test.RandStr()}
+ sv.Rack = util.StrPtr(test.RandStr())
+ sv.RevalPending = util.BoolPtr(test.RandBool())
+ sv.Status = util.StrPtr(test.RandStr())
+ sv.StatusID = util.IntPtr(test.RandInt())
+ sv.TCPPort = util.IntPtr(test.RandInt())
+ sv.Type = test.RandStr()
+ sv.TypeID = util.IntPtr(test.RandInt())
+ sv.UpdPending = util.BoolPtr(test.RandBool())
+ sv.XMPPID = util.StrPtr(test.RandStr())
+ sv.XMPPPasswd = util.StrPtr(test.RandStr())
return sv
}
func randCacheGroup() *tc.CacheGroupNullable {
return &tc.CacheGroupNullable{
- ID: randInt(),
- Name: randStr(),
- ShortName: randStr(),
- Latitude: randFloat64(),
- Longitude: randFloat64(),
- // ParentName: randStr(),
- // ParentCachegroupID: randInt(),
- // SecondaryParentName: randStr(),
- // SecondaryParentCachegroupID: randInt(),
- FallbackToClosest: randBool(),
- Type: randStr(),
- TypeID: randInt(),
+ ID: util.IntPtr(test.RandInt()),
+ Name: util.StrPtr(test.RandStr()),
+ ShortName: util.StrPtr(test.RandStr()),
+ Latitude: util.FloatPtr(test.RandFloat64()),
+ Longitude: util.FloatPtr(test.RandFloat64()),
+ // ParentName: util.StrPtr(test.RandStr()),
+ // ParentCachegroupID: util.IntPtr(test.RandInt()),
+ // SecondaryParentName: util.StrPtr(test.RandStr()),
+ // SecondaryParentCachegroupID: util.IntPtr(test.RandInt()),
+ FallbackToClosest: util.BoolPtr(test.RandBool()),
+ Type: util.StrPtr(test.RandStr()),
+ TypeID: util.IntPtr(test.RandInt()),
LastUpdated: &tc.TimeNoMod{Time: time.Now()},
Fallbacks: &[]string{
- *randStr(),
- *randStr(),
+ test.RandStr(),
+ test.RandStr(),
},
}
}
func randParam() *tc.Parameter {
return &tc.Parameter{
- ConfigFile: *randStr(),
- Name: *randStr(),
- Value: *randStr(),
+ ConfigFile: test.RandStr(),
+ Name: test.RandStr(),
+ Value: test.RandStr(),
Profiles: []byte(`[]`),
}
}
@@ -359,21 +319,21 @@ func randParam() *tc.Parameter {
func randJob() *atscfg.InvalidationJob {
now := time.Now()
return &atscfg.InvalidationJob{
- AssetURL: *randStr(),
- CreatedBy: *randStr(),
+ AssetURL: test.RandStr(),
+ CreatedBy: test.RandStr(),
StartTime: now,
- ID: *randUint64(),
- DeliveryService: *randStr(),
- TTLHours: *randUint(),
+ ID: test.RandUint64(),
+ DeliveryService: test.RandStr(),
+ TTLHours: test.RandUint(),
InvalidationType: tc.REFRESH,
}
}
func randCDN() *tc.CDN {
return &tc.CDN{
- DNSSECEnabled: *randBool(),
- DomainName: *randStr(),
- Name: *randStr(),
+ DNSSECEnabled: test.RandBool(),
+ DomainName: test.RandStr(),
+ Name: test.RandStr(),
}
}
@@ -383,26 +343,26 @@ func randDSRs() *tc.DeliveryServiceRegexes {
*randDSR(),
*randDSR(),
},
- DSName: *randStr(),
+ DSName: test.RandStr(),
}
}
func randDSR() *tc.DeliveryServiceRegex {
return &tc.DeliveryServiceRegex{
Type: string(tc.DSMatchTypeHostRegex),
- SetNumber: *randInt(),
+ SetNumber: test.RandInt(),
Pattern: `\.*foo\.*`,
}
}
func randCDNSSLKeys() *tc.CDNSSLKeys {
return &tc.CDNSSLKeys{
- DeliveryService: *randStr(),
+ DeliveryService: test.RandStr(),
Certificate: tc.CDNSSLKeysCertificate{
- Crt: *randStr(),
- Key: *randStr(),
+ Crt: test.RandStr(),
+ Key: test.RandStr(),
},
- Hostname: *randStr(),
+ Hostname: test.RandStr(),
}
}
@@ -501,37 +461,37 @@ func MakeFakeTOData() *t3cutil.ConfigData {
*dsr1,
},
URISigningKeys: map[tc.DeliveryServiceName][]byte{
- tc.DeliveryServiceName(*randStr()): []byte(*randStr()),
- tc.DeliveryServiceName(*randStr()): []byte(*randStr()),
+ tc.DeliveryServiceName(test.RandStr()):
[]byte(test.RandStr()),
+ tc.DeliveryServiceName(test.RandStr()):
[]byte(test.RandStr()),
},
URLSigKeys: map[tc.DeliveryServiceName]tc.URLSigKeys{
- tc.DeliveryServiceName(*randStr()): map[string]string{
- *randStr(): *randStr(),
- *randStr(): *randStr(),
+ tc.DeliveryServiceName(test.RandStr()):
map[string]string{
+ test.RandStr(): test.RandStr(),
+ test.RandStr(): test.RandStr(),
},
- tc.DeliveryServiceName(*randStr()): map[string]string{
- *randStr(): *randStr(),
- *randStr(): *randStr(),
+ tc.DeliveryServiceName(test.RandStr()):
map[string]string{
+ test.RandStr(): test.RandStr(),
+ test.RandStr(): test.RandStr(),
},
},
ServerCapabilities:
map[int]map[atscfg.ServerCapability]struct{}{
- *randInt(): map[atscfg.ServerCapability]struct{}{
- atscfg.ServerCapability(*randStr()): struct{}{},
- atscfg.ServerCapability(*randStr()): struct{}{},
+ test.RandInt(): map[atscfg.ServerCapability]struct{}{
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
},
- *randInt(): map[atscfg.ServerCapability]struct{}{
- atscfg.ServerCapability(*randStr()): struct{}{},
- atscfg.ServerCapability(*randStr()): struct{}{},
+ test.RandInt(): map[atscfg.ServerCapability]struct{}{
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
},
},
DSRequiredCapabilities:
map[int]map[atscfg.ServerCapability]struct{}{
- *randInt(): map[atscfg.ServerCapability]struct{}{
- atscfg.ServerCapability(*randStr()): struct{}{},
- atscfg.ServerCapability(*randStr()): struct{}{},
+ test.RandInt(): map[atscfg.ServerCapability]struct{}{
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
},
- *randInt(): map[atscfg.ServerCapability]struct{}{
- atscfg.ServerCapability(*randStr()): struct{}{},
- atscfg.ServerCapability(*randStr()): struct{}{},
+ test.RandInt(): map[atscfg.ServerCapability]struct{}{
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
+ atscfg.ServerCapability(test.RandStr()):
struct{}{},
},
},
SSLKeys: []tc.CDNSSLKeys{
diff --git a/grove/stat/stats_test.go b/grove/stat/stats_test.go
index 5d24f68ac6..3eedea5472 100644
--- a/grove/stat/stats_test.go
+++ b/grove/stat/stats_test.go
@@ -15,13 +15,13 @@ package stat
*/
import (
- "math/rand"
"net"
"testing"
"time"
"github.com/apache/trafficcontrol/grove/remapdata"
"github.com/apache/trafficcontrol/grove/web"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
)
func StatsInc(m *web.ConnMap, num int, addrs *[]string) {
@@ -73,7 +73,7 @@ func GenGUIDStr() string {
alphabet :=
[]rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_")
s := make([]rune, length)
for i := range s {
- s[i] = alphabet[rand.Intn(len(alphabet))]
+ s[i] = alphabet[test.RandIntn(len(alphabet))]
}
return string(s)
}
diff --git a/traffic_monitor/cache/astats_test.go
b/traffic_monitor/cache/astats_test.go
index 540eee949e..ead6cc3d92 100644
--- a/traffic_monitor/cache/astats_test.go
+++ b/traffic_monitor/cache/astats_test.go
@@ -22,7 +22,6 @@ package cache
import (
"bytes"
"io/ioutil"
- "math/rand"
"net/http"
"os"
"testing"
@@ -30,6 +29,7 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/traffic_monitor/poller"
"github.com/apache/trafficcontrol/traffic_monitor/todata"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
)
func TestAstatsJson(t *testing.T) {
@@ -192,18 +192,18 @@ func getMockTOData(dsNameFQDNs
map[tc.DeliveryServiceName]string) todata.TOData
func getMockRawStats(cacheName string, dsNameFQDNs
map[tc.DeliveryServiceName]string) map[string]interface{} {
st := map[string]interface{}{}
for _, dsFQDN := range dsNameFQDNs {
- st["plugin.remap_stats."+dsFQDN+".in_bytes"] =
float64(rand.Uint64())
- st["plugin.remap_stats."+dsFQDN+".out_bytes"] =
float64(rand.Uint64())
- st["plugin.remap_stats."+dsFQDN+".status_2xx"] =
float64(rand.Uint64())
- st["plugin.remap_stats."+dsFQDN+".status_3xx"] =
float64(rand.Uint64())
- st["plugin.remap_stats."+dsFQDN+".status_4xx"] =
float64(rand.Uint64())
- st["plugin.remap_stats."+dsFQDN+".status_5xx"] =
float64(rand.Uint64())
+ st["plugin.remap_stats."+dsFQDN+".in_bytes"] =
float64(test.RandUint64())
+ st["plugin.remap_stats."+dsFQDN+".out_bytes"] =
float64(test.RandUint64())
+ st["plugin.remap_stats."+dsFQDN+".status_2xx"] =
float64(test.RandUint64())
+ st["plugin.remap_stats."+dsFQDN+".status_3xx"] =
float64(test.RandUint64())
+ st["plugin.remap_stats."+dsFQDN+".status_4xx"] =
float64(test.RandUint64())
+ st["plugin.remap_stats."+dsFQDN+".status_5xx"] =
float64(test.RandUint64())
}
return st
}
func getMockStatistics(infSpeed int64, outBytes uint64) Statistics {
- infName := randStr()
+ infName := test.RandStr()
return Statistics{
Loadavg: Loadavg{
One: 1.2,
@@ -220,7 +220,7 @@ func getMockStatistics(infSpeed int64, outBytes uint64)
Statistics {
BytesIn: 12234567,
},
},
- NotAvailable: randBool(),
+ NotAvailable: test.RandBool(),
}
}
diff --git a/traffic_monitor/cache/data_test.go
b/traffic_monitor/cache/data_test.go
index 9301327994..640f616232 100644
--- a/traffic_monitor/cache/data_test.go
+++ b/traffic_monitor/cache/data_test.go
@@ -22,40 +22,26 @@ package cache
import (
"errors"
"fmt"
- "math/rand"
"reflect"
"testing"
"time"
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/traffic_monitor/dsdata"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
)
-func randBool() bool {
- return rand.Int()%2 == 0
-}
-
-func randStr() string {
- chars :=
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
- num := 100
- s := ""
- for i := 0; i < num; i++ {
- s += string(chars[rand.Intn(len(chars))])
- }
- return s
-}
-
func randAvailableStatuses() AvailableStatuses {
a := AvailableStatuses{}
num := 100
for i := 0; i < num; i++ {
- cacheName := randStr()
+ cacheName := test.RandStr()
a[cacheName] = AvailableStatus{
Available: AvailableTuple{
- IPv4: randBool(),
- IPv6: randBool(),
+ IPv4: test.RandBool(),
+ IPv6: test.RandBool(),
},
- Status: randStr(),
+ Status: test.RandStr(),
}
}
return a
@@ -65,7 +51,7 @@ func randStrIfaceMap() map[string]interface{} {
m := map[string]interface{}{}
num := 5
for i := 0; i < num; i++ {
- m[randStr()] = randStr()
+ m[test.RandStr()] = test.RandStr()
}
return m
}
@@ -77,18 +63,18 @@ func randStats() (Statistics, map[string]interface{}) {
func randStatistics() Statistics {
return Statistics{
Loadavg: Loadavg{
- One: rand.Float64(),
- Five: rand.Float64(),
- Fifteen: rand.Float64(),
- CurrentProcesses: rand.Uint64(),
- TotalProcesses: rand.Uint64(),
- LatestPID: rand.Int63(),
+ One: test.RandFloat64(),
+ Five: test.RandFloat64(),
+ Fifteen: test.RandFloat64(),
+ CurrentProcesses: test.RandUint64(),
+ TotalProcesses: test.RandUint64(),
+ LatestPID: test.RandInt64(),
},
Interfaces: map[string]Interface{
- randStr(): Interface{
- Speed: rand.Int63(),
- BytesIn: rand.Uint64(),
- BytesOut: rand.Uint64(),
+ test.RandStr(): Interface{
+ Speed: test.RandInt64(),
+ BytesIn: test.RandUint64(),
+ BytesOut: test.RandUint64(),
},
},
}
@@ -96,34 +82,34 @@ func randStatistics() Statistics {
func randVitals() Vitals {
return Vitals{
- LoadAvg: rand.Float64(),
- BytesOut: rand.Uint64(),
- BytesIn: rand.Uint64(),
- KbpsOut: rand.Int63(),
- MaxKbpsOut: rand.Int63(),
+ LoadAvg: test.RandFloat64(),
+ BytesOut: test.RandUint64(),
+ BytesIn: test.RandUint64(),
+ KbpsOut: test.RandInt64(),
+ MaxKbpsOut: test.RandInt64(),
}
}
func randStatMeta() dsdata.StatMeta {
- return dsdata.StatMeta{Time: rand.Int63()}
+ return dsdata.StatMeta{Time: test.RandInt64()}
}
func randStatCacheStats() dsdata.StatCacheStats {
return dsdata.StatCacheStats{
- OutBytes: dsdata.StatInt{Value: rand.Int63(), StatMeta:
randStatMeta()},
- IsAvailable: dsdata.StatBool{Value: randBool(), StatMeta:
randStatMeta()},
- Status5xx: dsdata.StatInt{Value: rand.Int63(), StatMeta:
randStatMeta()},
- Status4xx: dsdata.StatInt{Value: rand.Int63(), StatMeta:
randStatMeta()},
- Status3xx: dsdata.StatInt{Value: rand.Int63(), StatMeta:
randStatMeta()},
- Status2xx: dsdata.StatInt{Value: rand.Int63(), StatMeta:
randStatMeta()},
- InBytes: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
- Kbps: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
- Tps5xx: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
- Tps4xx: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
- Tps3xx: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
- Tps2xx: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
- ErrorString: dsdata.StatString{Value: randStr(), StatMeta:
randStatMeta()},
- TpsTotal: dsdata.StatFloat{Value: rand.Float64(), StatMeta:
randStatMeta()},
+ OutBytes: dsdata.StatInt{Value: test.RandInt64(), StatMeta:
randStatMeta()},
+ IsAvailable: dsdata.StatBool{Value: test.RandBool(), StatMeta:
randStatMeta()},
+ Status5xx: dsdata.StatInt{Value: test.RandInt64(), StatMeta:
randStatMeta()},
+ Status4xx: dsdata.StatInt{Value: test.RandInt64(), StatMeta:
randStatMeta()},
+ Status3xx: dsdata.StatInt{Value: test.RandInt64(), StatMeta:
randStatMeta()},
+ Status2xx: dsdata.StatInt{Value: test.RandInt64(), StatMeta:
randStatMeta()},
+ InBytes: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
+ Kbps: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
+ Tps5xx: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
+ Tps4xx: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
+ Tps3xx: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
+ Tps2xx: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
+ ErrorString: dsdata.StatString{Value: test.RandStr(), StatMeta:
randStatMeta()},
+ TpsTotal: dsdata.StatFloat{Value: test.RandFloat64(),
StatMeta: randStatMeta()},
}
}
@@ -131,27 +117,27 @@ func randStatCommon() dsdata.StatCommon {
cachesReporting := map[tc.CacheName]bool{}
num := 5
for i := 0; i < num; i++ {
- cachesReporting[tc.CacheName(randStr())] = randBool()
+ cachesReporting[tc.CacheName(test.RandStr())] = test.RandBool()
}
return dsdata.StatCommon{
- CachesConfiguredNum: dsdata.StatInt{Value: rand.Int63(),
StatMeta: randStatMeta()},
+ CachesConfiguredNum: dsdata.StatInt{Value: test.RandInt64(),
StatMeta: randStatMeta()},
CachesReporting: cachesReporting,
- ErrorStr: dsdata.StatString{Value: randStr(),
StatMeta: randStatMeta()},
- StatusStr: dsdata.StatString{Value: randStr(),
StatMeta: randStatMeta()},
- IsHealthy: dsdata.StatBool{Value: randBool(),
StatMeta: randStatMeta()},
- IsAvailable: dsdata.StatBool{Value: randBool(),
StatMeta: randStatMeta()},
- CachesAvailableNum: dsdata.StatInt{Value: rand.Int63(),
StatMeta: randStatMeta()},
+ ErrorStr: dsdata.StatString{Value: test.RandStr(),
StatMeta: randStatMeta()},
+ StatusStr: dsdata.StatString{Value: test.RandStr(),
StatMeta: randStatMeta()},
+ IsHealthy: dsdata.StatBool{Value: test.RandBool(),
StatMeta: randStatMeta()},
+ IsAvailable: dsdata.StatBool{Value: test.RandBool(),
StatMeta: randStatMeta()},
+ CachesAvailableNum: dsdata.StatInt{Value: test.RandInt64(),
StatMeta: randStatMeta()},
}
}
func randAStat() *DSStat {
return &DSStat{
- InBytes: rand.Uint64(),
- OutBytes: rand.Uint64(),
- Status2xx: rand.Uint64(),
- Status3xx: rand.Uint64(),
- Status4xx: rand.Uint64(),
- Status5xx: rand.Uint64(),
+ InBytes: test.RandUint64(),
+ OutBytes: test.RandUint64(),
+ Status2xx: test.RandUint64(),
+ Status3xx: test.RandUint64(),
+ Status4xx: test.RandUint64(),
+ Status5xx: test.RandUint64(),
}
}
@@ -159,18 +145,18 @@ func randDsStats() map[string]*DSStat {
num := 5
a := map[string]*DSStat{}
for i := 0; i < num; i++ {
- a[randStr()] = randAStat()
+ a[test.RandStr()] = randAStat()
}
return a
}
func randErrs() []error {
- if randBool() {
+ if test.RandBool() {
return []error{}
}
num := 5
errs := []error{}
for i := 0; i < num; i++ {
- errs = append(errs, errors.New(randStr()))
+ errs = append(errs, errors.New(test.RandStr()))
}
return errs
}
@@ -178,26 +164,26 @@ func randErrs() []error {
func randPrecomputedData() PrecomputedData {
return PrecomputedData{
DeliveryServiceStats: randDsStats(),
- OutBytes: rand.Uint64(),
- MaxKbps: rand.Int63(),
+ OutBytes: test.RandUint64(),
+ MaxKbps: test.RandInt64(),
Errors: randErrs(),
- Reporting: randBool(),
+ Reporting: test.RandBool(),
}
}
func randResult() Result {
stats, misc := randStats()
return Result{
- ID: randStr(),
- Error: fmt.Errorf(randStr()),
+ ID: test.RandStr(),
+ Error: fmt.Errorf(test.RandStr()),
Statistics: stats,
Time: time.Now(),
- RequestTime: time.Millisecond * time.Duration(rand.Int()),
+ RequestTime: time.Millisecond *
time.Duration(test.RandInt()),
Vitals: randVitals(),
- PollID: uint64(rand.Int63()),
+ PollID: uint64(test.RandInt64()),
PollFinished: make(chan uint64),
PrecomputedData: randPrecomputedData(),
- Available: randBool(),
+ Available: test.RandBool(),
Miscellaneous: misc,
}
}
@@ -215,7 +201,7 @@ func randResultHistory() ResultHistory {
a := ResultHistory{}
num := 5
for i := 0; i < num; i++ {
- a[tc.CacheName(randStr())] = randResultSlice()
+ a[tc.CacheName(test.RandStr())] = randResultSlice()
}
return a
}
@@ -231,7 +217,7 @@ func TestResultHistoryCopy(t *testing.T) {
}
// verify a and b don't point to the same map
- a[tc.CacheName(randStr())] = randResultSlice()
+ a[tc.CacheName(test.RandStr())] = randResultSlice()
if reflect.DeepEqual(a, b) {
t.Errorf("expected a != b, actual a and b point to the
same map: %+v", a)
}
@@ -248,13 +234,13 @@ func TestAvailableStatusesCopy(t *testing.T) {
t.Errorf("expected a and b DeepEqual, actual copied map
not equal: a: %v b: %v", a, b)
}
- cacheName := randStr()
+ cacheName := test.RandStr()
a[cacheName] = AvailableStatus{
Available: AvailableTuple{
- randBool(),
- randBool(),
+ test.RandBool(),
+ test.RandBool(),
},
- Status: randStr(),
+ Status: test.RandStr(),
}
if reflect.DeepEqual(a, b) {
diff --git a/traffic_monitor/datareq/datareq_test.go
b/traffic_monitor/datareq/datareq_test.go
index 7ed98a2d1d..a7317a793d 100644
--- a/traffic_monitor/datareq/datareq_test.go
+++ b/traffic_monitor/datareq/datareq_test.go
@@ -22,7 +22,6 @@ package datareq
import (
"errors"
"math"
- "math/rand"
"testing"
"time"
@@ -30,6 +29,8 @@ import (
"github.com/apache/trafficcontrol/lib/go-util"
"github.com/apache/trafficcontrol/traffic_monitor/config"
"github.com/apache/trafficcontrol/traffic_monitor/peer"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
+
jsoniter "github.com/json-iterator/go"
)
@@ -55,25 +56,11 @@ func getMockStaticAppData() config.StaticAppData {
}
}
-func randStr() string {
- chars :=
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
- num := 100
- s := ""
- for i := 0; i < num; i++ {
- s += string(chars[rand.Intn(len(chars))])
- }
- return s
-}
-
-func randBool() bool {
- return rand.Int()%2 == 0
-}
-
func getMockLastHealthTimes() map[tc.CacheName]time.Duration {
mockTimes := map[tc.CacheName]time.Duration{}
numCaches := 10
for i := 0; i < numCaches; i++ {
- mockTimes[tc.CacheName(randStr())] = time.Duration(rand.Int())
+ mockTimes[tc.CacheName(test.RandStr())] =
time.Duration(test.RandInt())
}
return mockTimes
}
@@ -81,7 +68,7 @@ func getMockLastHealthTimes() map[tc.CacheName]time.Duration {
func getMockCRStatesDeliveryService() tc.CRStatesDeliveryService {
return tc.CRStatesDeliveryService{
DisabledLocations: []tc.CacheGroupName{},
- IsAvailable: randBool(),
+ IsAvailable: test.RandBool(),
}
}
@@ -90,18 +77,18 @@ func getMockPeerStates() peer.CRStatesThreadsafe {
numCaches := 10
for i := 0; i < numCaches; i++ {
- ps.SetCache(tc.CacheName(randStr()),
tc.IsAvailable{IsAvailable: randBool()})
+ ps.SetCache(tc.CacheName(test.RandStr()),
tc.IsAvailable{IsAvailable: test.RandBool()})
}
numDSes := 10
for i := 0; i < numDSes; i++ {
- ps.SetDeliveryService(tc.DeliveryServiceName(randStr()),
getMockCRStatesDeliveryService())
+ ps.SetDeliveryService(tc.DeliveryServiceName(test.RandStr()),
getMockCRStatesDeliveryService())
}
return ps
}
func getRandDuration() time.Duration {
- return time.Duration(rand.Int63())
+ return time.Duration(test.RandInt64())
}
func getResult(name tc.TrafficMonitorName, availabilityType AvailabilityType)
peer.Result {
@@ -110,7 +97,7 @@ func getResult(name tc.TrafficMonitorName, availabilityType
AvailabilityType) pe
availability := true
if availabilityType == Random {
- availability = randBool()
+ availability = test.RandBool()
} else if availabilityType == Unavailable {
availability = false
}
@@ -118,9 +105,9 @@ func getResult(name tc.TrafficMonitorName, availabilityType
AvailabilityType) pe
return peer.Result{
ID: name,
Available: availability,
- Errors: []error{errors.New(randStr())},
+ Errors: []error{errors.New(test.RandStr())},
PeerStates: peerStates.Get(),
- PollID: rand.Uint64(),
+ PollID: test.RandUint64(),
// PollFinished chan<- uint64,
Time: time.Now(),
}
@@ -133,7 +120,7 @@ func getMockCRStatesPeers(quorumMin int, numPeers int,
availabilityType Availabi
randPeers := map[tc.TrafficMonitorName]struct{}{}
for i := 0; i < numPeers; i++ {
- randPeers[tc.TrafficMonitorName(randStr())] = struct{}{}
+ randPeers[tc.TrafficMonitorName(test.RandStr())] = struct{}{}
}
for peer, _ := range randPeers {
@@ -205,9 +192,9 @@ func TestGetStats(t *testing.T) {
appData := getMockStaticAppData()
pollingInterval := 5 * time.Second
lastHealthTimes := getMockLastHealthTimes()
- fetchCount := uint64(rand.Int())
- healthIteration := uint64(rand.Int())
- errCount := uint64(rand.Int())
+ fetchCount := uint64(test.RandInt())
+ healthIteration := uint64(test.RandInt())
+ errCount := uint64(test.RandInt())
crStatesPeers := getMockCRStatesPeers(1, 10, Random)
statsBts, err := getStats(appData, pollingInterval, lastHealthTimes,
fetchCount, healthIteration, errCount, crStatesPeers)
diff --git a/traffic_monitor/ds/stat_test.go b/traffic_monitor/ds/stat_test.go
index 00e2814858..31024cd820 100644
--- a/traffic_monitor/ds/stat_test.go
+++ b/traffic_monitor/ds/stat_test.go
@@ -25,7 +25,6 @@ import (
"fmt"
"log"
"math"
- "math/rand"
"regexp"
"testing"
@@ -37,6 +36,7 @@ import (
"github.com/apache/trafficcontrol/traffic_monitor/peer"
"github.com/apache/trafficcontrol/traffic_monitor/threadsafe"
"github.com/apache/trafficcontrol/traffic_monitor/todata"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
)
func checkLogOutput(t *testing.T, buffer *bytes.Buffer, toData todata.TOData,
caches []tc.CacheName) {
@@ -309,23 +309,23 @@ func getMockTOData() todata.TOData {
caches := []tc.CacheName{}
for i := 0; i < numCaches; i++ {
- caches = append(caches, tc.CacheName(randStr()))
+ caches = append(caches, tc.CacheName(test.RandStr()))
}
dses := []tc.DeliveryServiceName{}
for i := 0; i < numDSes; i++ {
- dses = append(dses, tc.DeliveryServiceName(randStr()))
+ dses = append(dses, tc.DeliveryServiceName(test.RandStr()))
}
cgs := []tc.CacheGroupName{}
for i := 0; i < numCGs; i++ {
- cgs = append(cgs, tc.CacheGroupName(randStr()))
+ cgs = append(cgs, tc.CacheGroupName(test.RandStr()))
}
serverDSes := map[tc.CacheName][]tc.DeliveryServiceName{}
for _, ca := range caches {
for i := 0; i < numCacheDSes; i++ {
- serverDSes[ca] = append(serverDSes[ca],
dses[rand.Intn(len(dses))])
+ serverDSes[ca] = append(serverDSes[ca],
dses[test.RandIntn(len(dses))])
}
}
@@ -338,12 +338,12 @@ func getMockTOData() todata.TOData {
serverCGs := map[tc.CacheName]tc.CacheGroupName{}
for _, cache := range caches {
- serverCGs[cache] = cgs[rand.Intn(len(cgs))]
+ serverCGs[cache] = cgs[test.RandIntn(len(cgs))]
}
serverTypes := map[tc.CacheName]tc.CacheType{}
for _, cache := range caches {
- serverTypes[cache] = types[rand.Intn(len(types))]
+ serverTypes[cache] = types[test.RandIntn(len(types))]
}
tod := todata.New()
@@ -371,7 +371,7 @@ func randPrecomputedData(toData todata.TOData)
cache.PrecomputedData {
return cache.PrecomputedData{
DeliveryServiceStats: dsStats,
OutBytes: dsTotal,
- MaxKbps: rand.Int63(),
+ MaxKbps: test.RandInt64(),
Errors: randErrs(),
Reporting: true,
}
@@ -387,41 +387,27 @@ func randDsStats(toData todata.TOData)
map[string]*cache.DSStat {
func randAStat() *cache.DSStat {
return &cache.DSStat{
- InBytes: uint64(rand.Intn(1000)),
- OutBytes: uint64(rand.Intn(1000)),
- Status2xx: uint64(rand.Intn(1000)),
- Status3xx: uint64(rand.Intn(1000)),
- Status4xx: uint64(rand.Intn(1000)),
- Status5xx: uint64(rand.Intn(1000)),
+ InBytes: uint64(test.RandIntn(1000)),
+ OutBytes: uint64(test.RandIntn(1000)),
+ Status2xx: uint64(test.RandIntn(1000)),
+ Status3xx: uint64(test.RandIntn(1000)),
+ Status4xx: uint64(test.RandIntn(1000)),
+ Status5xx: uint64(test.RandIntn(1000)),
}
}
func randErrs() []error {
- if randBool() {
+ if test.RandBool() {
return []error{}
}
num := 5
errs := []error{}
for i := 0; i < num; i++ {
- errs = append(errs, errors.New(randStr()))
+ errs = append(errs, errors.New(test.RandStr()))
}
return errs
}
-func randBool() bool {
- return rand.Int()%2 == 0
-}
-
-func randStr() string {
- chars :=
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
- num := 100
- s := ""
- for i := 0; i < num; i++ {
- s += string(chars[rand.Intn(len(chars))])
- }
- return s
-}
-
func TestAddLastStatsToStatCacheStatsNilVals(t *testing.T) {
// test that addLastStatsToStatCacheStats doesn't panic with nil values
addLastStatsToStatCacheStats(nil, nil)
diff --git a/traffic_monitor/threadsafe/resultstathistory_test.go
b/traffic_monitor/threadsafe/resultstathistory_test.go
index a39467d4b8..881fef133b 100644
--- a/traffic_monitor/threadsafe/resultstathistory_test.go
+++ b/traffic_monitor/threadsafe/resultstathistory_test.go
@@ -21,7 +21,6 @@ package threadsafe
import (
"fmt"
- "math/rand"
"net/url"
"strings"
"testing"
@@ -30,6 +29,8 @@ import (
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/traffic_monitor/cache"
"github.com/apache/trafficcontrol/traffic_monitor/srvhttp"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
+
jsoniter "github.com/json-iterator/go"
)
@@ -38,7 +39,7 @@ func randResultStatHistory() ResultStatHistory {
num := 5
for i := 0; i < num; i++ {
- hist.Store(tc.CacheName(randStr()), randResultStatValHistory())
+ hist.Store(tc.CacheName(test.RandStr()),
randResultStatValHistory())
}
return hist
}
@@ -48,7 +49,7 @@ func randResultStatValHistory() ResultStatValHistory {
num := 5
numSlice := 5
for i := 0; i < num; i++ {
- cacheName := randStr()
+ cacheName := test.RandStr()
vals := []tc.ResultStatVal{}
for j := 0; j < numSlice; j++ {
vals = append(vals, randResultStatVal())
@@ -60,9 +61,9 @@ func randResultStatValHistory() ResultStatValHistory {
func randResultStatVal() tc.ResultStatVal {
return tc.ResultStatVal{
- Val: uint64(rand.Int63()),
+ Val: uint64(test.RandInt64()),
Time: time.Now(),
- Span: uint64(rand.Int63()),
+ Span: uint64(test.RandInt64()),
}
}
@@ -72,7 +73,7 @@ func randResultInfoHistory() cache.ResultInfoHistory {
num := 5
infNum := 5
for i := 0; i < num; i++ {
- cacheName := tc.CacheName(randStr())
+ cacheName := tc.CacheName(test.RandStr())
for j := 0; j < infNum; j++ {
hist[cacheName] = append(hist[cacheName],
randResultInfo())
}
@@ -82,40 +83,26 @@ func randResultInfoHistory() cache.ResultInfoHistory {
func randResultInfo() cache.ResultInfo {
return cache.ResultInfo{
- ID: randStr(),
- Error: fmt.Errorf(randStr()),
+ ID: test.RandStr(),
+ Error: fmt.Errorf(test.RandStr()),
Time: time.Now(),
- RequestTime: time.Millisecond * time.Duration(rand.Int()),
+ RequestTime: time.Millisecond * time.Duration(test.RandInt()),
Vitals: randVitals(),
- PollID: uint64(rand.Int63()),
- Available: randBool(),
+ PollID: uint64(test.RandInt64()),
+ Available: test.RandBool(),
}
}
func randVitals() cache.Vitals {
return cache.Vitals{
- LoadAvg: rand.Float64(),
- BytesOut: rand.Uint64(),
- BytesIn: rand.Uint64(),
- KbpsOut: rand.Int63(),
- MaxKbpsOut: rand.Int63(),
+ LoadAvg: test.RandFloat64(),
+ BytesOut: test.RandUint64(),
+ BytesIn: test.RandUint64(),
+ KbpsOut: test.RandInt64(),
+ MaxKbpsOut: test.RandInt64(),
}
}
-func randStr() string {
- chars :=
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
- num := 100
- s := ""
- for i := 0; i < num; i++ {
- s += string(chars[rand.Intn(len(chars))])
- }
- return s
-}
-
-func randBool() bool {
- return rand.Int()%2 == 0
-}
-
type DummyFilterNever struct {
}
diff --git
a/traffic_ops/app/db/traffic_vault_migrate/traffic_vault_migrate_test.go
b/traffic_ops/app/db/traffic_vault_migrate/traffic_vault_migrate_test.go
index d131c8f775..7776696f4e 100644
--- a/traffic_ops/app/db/traffic_vault_migrate/traffic_vault_migrate_test.go
+++ b/traffic_ops/app/db/traffic_vault_migrate/traffic_vault_migrate_test.go
@@ -20,16 +20,16 @@ package main
*/
import (
- "math/rand"
"reflect"
"strconv"
"strings"
"testing"
- "github.com/lestrrat-go/jwx/jwk"
-
"github.com/apache/trafficcontrol/lib/go-tc"
"github.com/apache/trafficcontrol/lib/go-util"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
+
+ "github.com/lestrrat-go/jwx/jwk"
)
func testBackend(t *testing.T, backend TVBackend) {
@@ -187,7 +187,7 @@ func TestRiakBackend(t *testing.T) {
func TestPGBackend(t *testing.T) {
data := make([]byte, 32)
for i, _ := range data {
- data[i] = byte('a' + rune(rand.Intn(26)))
+ data[i] = byte('a' + rune(test.RandIntn(26)))
}
pg := PGBackend{
cfg: PGConfig{
diff --git a/traffic_ops/traffic_ops_golang/crconfig/config_test.go
b/traffic_ops/traffic_ops_golang/crconfig/config_test.go
index 816ace781f..2dfa5fd436 100644
--- a/traffic_ops/traffic_ops_golang/crconfig/config_test.go
+++ b/traffic_ops/traffic_ops_golang/crconfig/config_test.go
@@ -26,13 +26,15 @@ import (
"testing"
"time"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
+
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
func ExpectedGetConfigParams(domain string) []CRConfigConfigParameter {
return []CRConfigConfigParameter{
- {"tld.ttls.foo" + *randStr(), *randStr()},
- {"tld.soa.bar" + *randStr(), *randStr()},
+ {"tld.ttls.foo" + test.RandStr(), test.RandStr()},
+ {"tld.soa.bar" + test.RandStr(), test.RandStr()},
{"domain_name", domain},
}
}
diff --git a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go
b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go
index 5ff78ee2b8..fe0744e77e 100644
--- a/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go
+++ b/traffic_ops/traffic_ops_golang/crconfig/deliveryservice_test.go
@@ -29,6 +29,8 @@ import (
"time"
"github.com/apache/trafficcontrol/lib/go-tc"
+ "github.com/apache/trafficcontrol/lib/go-util"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
@@ -42,7 +44,7 @@ func randDS() tc.CRConfigDeliveryService {
ttlMinimum := "30"
ttlRefresh := "28800"
ttlRetry := "7200"
- ttl := randInt()
+ ttl := util.IntPtr(test.RandInt())
ttlStr := strconv.Itoa(*ttl)
ttlNS := "3600"
ttlSOA := "86400"
@@ -60,8 +62,8 @@ func randDS() tc.CRConfigDeliveryService {
GeoLocationProvider: &geoProviderStr,
// MatchSets: randMatchsetArr(),
MissLocation: &tc.CRConfigLatitudeLongitudeShort{
- Lat: *randFloat64(),
- Lon: *randFloat64(),
+ Lat: test.RandFloat64(),
+ Lon: test.RandFloat64(),
},
Protocol: &tc.CRConfigDeliveryServiceProtocol{
// AcceptHTTP: &truePtr,
@@ -71,7 +73,7 @@ func randDS() tc.CRConfigDeliveryService {
RegionalGeoBlocking: &falseStrPtr,
ResponseHeaders: nil,
RequestHeaders: nil,
- RequiredCapabilities: randStrArray(),
+ RequiredCapabilities: test.RandStrArray(),
Soa: &tc.SOA{
Admin: &ttlAdmin,
ExpireSeconds: &ttlExpire,
@@ -81,7 +83,7 @@ func randDS() tc.CRConfigDeliveryService {
},
SSLEnabled: false,
EcsEnabled: &ecsEnabled,
- Topology: randStr(),
+ Topology: util.StrPtr(test.RandStr()),
TTL: ttl,
TTLs: &tc.CRConfigTTL{
ASeconds: &ttlStr,
@@ -89,28 +91,28 @@ func randDS() tc.CRConfigDeliveryService {
NSSeconds: &ttlNS,
SOASeconds: &ttlSOA,
},
- // MaxDNSIPsForLocation: randInt(),
- IP6RoutingEnabled: randBool(),
- RoutingName: randStr(),
+ // MaxDNSIPsForLocation: util.IntPtr(test.RandInt()),
+ IP6RoutingEnabled: util.BoolPtr(test.RandBool()),
+ RoutingName: util.StrPtr(test.RandStr()),
BypassDestination: map[string]*tc.CRConfigBypassDestination{
"HTTP": &tc.CRConfigBypassDestination{
- // IP: randStr(),
- // IP6: randStr(),
- // CName: randStr(),
- // TTL: randInt(),
- FQDN: randStr(),
- // Port: randStr(),
+ // IP: util.StrPtr(test.RandStr()),
+ // IP6: util.StrPtr(test.RandStr()),
+ // CName: util.StrPtr(test.RandStr()),
+ // TTL: util.IntPtr(test.RandInt()),
+ FQDN: util.StrPtr(test.RandStr()),
+ // Port: util.StrPtr(test.RandStr()),
},
},
DeepCachingType: nil,
GeoEnabled: nil,
- // GeoLimitRedirectURL: randStr(),
+ // GeoLimitRedirectURL: util.StrPtr(test.RandStr()),
StaticDNSEntries: []tc.CRConfigStaticDNSEntry{
tc.CRConfigStaticDNSEntry{
- Name: *randStr(),
- TTL: *randInt(),
- Type: *randStr(),
- Value: *randStr(),
+ Name: test.RandStr(),
+ TTL: test.RandInt(),
+ Type: test.RandStr(),
+ Value: test.RandStr(),
},
},
}
diff --git a/traffic_ops/traffic_ops_golang/crconfig/edgelocations_test.go
b/traffic_ops/traffic_ops_golang/crconfig/edgelocations_test.go
index 217f3b78d3..6e3523f5e6 100644
--- a/traffic_ops/traffic_ops_golang/crconfig/edgelocations_test.go
+++ b/traffic_ops/traffic_ops_golang/crconfig/edgelocations_test.go
@@ -26,6 +26,7 @@ import (
"time"
"github.com/apache/trafficcontrol/lib/go-tc"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
@@ -33,25 +34,25 @@ import (
func ExpectedMakeLocations() (map[string]tc.CRConfigLatitudeLongitude,
map[string]tc.CRConfigLatitudeLongitude) {
return map[string]tc.CRConfigLatitudeLongitude{
"cache0": tc.CRConfigLatitudeLongitude{
- Lat: *randFloat64(),
- Lon: *randFloat64(),
+ Lat: test.RandFloat64(),
+ Lon: test.RandFloat64(),
LocalizationMethods:
[]tc.LocalizationMethod{tc.LocalizationMethodCZ},
},
"cache1": tc.CRConfigLatitudeLongitude{
- Lat: *randFloat64(),
- Lon: *randFloat64(),
+ Lat: test.RandFloat64(),
+ Lon: test.RandFloat64(),
LocalizationMethods:
[]tc.LocalizationMethod{tc.LocalizationMethodCZ},
},
},
map[string]tc.CRConfigLatitudeLongitude{
"router0": tc.CRConfigLatitudeLongitude{
- Lat: *randFloat64(),
- Lon: *randFloat64(),
+ Lat: test.RandFloat64(),
+ Lon: test.RandFloat64(),
LocalizationMethods:
[]tc.LocalizationMethod{tc.LocalizationMethodGeo, tc.LocalizationMethodCZ,
tc.LocalizationMethodDeepCZ},
},
"router1": tc.CRConfigLatitudeLongitude{
- Lat: *randFloat64(),
- Lon: *randFloat64(),
+ Lat: test.RandFloat64(),
+ Lon: test.RandFloat64(),
LocalizationMethods:
[]tc.LocalizationMethod{tc.LocalizationMethodGeo, tc.LocalizationMethodCZ,
tc.LocalizationMethodDeepCZ},
},
}
diff --git a/traffic_ops/traffic_ops_golang/crconfig/servers_test.go
b/traffic_ops/traffic_ops_golang/crconfig/servers_test.go
index 1fa51984bf..117596a483 100644
--- a/traffic_ops/traffic_ops_golang/crconfig/servers_test.go
+++ b/traffic_ops/traffic_ops_golang/crconfig/servers_test.go
@@ -21,9 +21,6 @@ package crconfig
import (
"context"
- "fmt"
- "math/rand"
- "net"
"reflect"
"strings"
"testing"
@@ -37,108 +34,53 @@ import (
"gopkg.in/DATA-DOG/go-sqlmock.v1"
)
-// TODO: move all these rand functions to traffic_ops_golang/test/rand.go
-func randBool() *bool {
- b := rand.Int()%2 == 0
- return &b
-}
-func randStr() *string {
- return test.RandStr()
-}
-func randStrArray() []string {
- return test.RandStrArray()
-}
-func randInt() *int {
- i := rand.Int()
- return &i
-}
-func randInt64() *int64 {
- i := int64(rand.Int63())
- return &i
-}
-func randFloat64() *float64 {
- f := rand.Float64()
- return &f
-}
-
-func randomIPv4() *string {
- first := rand.Int31n(256)
- second := rand.Int31n(256)
- third := rand.Int31n(256)
- fourth := rand.Int31n(256)
- str := fmt.Sprintf("%d.%d.%d.%d", first, second, third, fourth)
- return &str
-}
-
-func randomIPv6() *string {
- ip := net.IP([]byte{
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- uint8(rand.Int31n(256)),
- }).String()
- return &ip
-}
-
func randServer(ipService bool, ip6Service bool) tc.CRConfigTrafficOpsServer {
- status := tc.CRConfigServerStatus(*randStr())
- cachegroup := randStr()
+ status := tc.CRConfigServerStatus(test.RandStr())
+ cachegroup := util.StrPtr(test.RandStr())
ip := new(string)
ip6 := new(string)
inf := new(string)
if ipService {
- ip = randomIPv4()
- inf = randStr()
+ ip = util.StrPtr(test.RandomIPv4())
+ inf = util.StrPtr(test.RandStr())
}
if ip6Service {
- ip6 = randomIPv6()
- inf = randStr()
+ ip6 = util.StrPtr(test.RandomIPv6())
+ inf = util.StrPtr(test.RandStr())
}
return tc.CRConfigTrafficOpsServer{
CacheGroup: cachegroup,
- Capabilities: randStrArray(),
- Fqdn: randStr(),
- HashCount: randInt(),
- HashId: randStr(),
- HttpsPort: randInt(),
+ Capabilities: test.RandStrArray(),
+ Fqdn: util.StrPtr(test.RandStr()),
+ HashCount: util.IntPtr(test.RandInt()),
+ HashId: util.StrPtr(test.RandStr()),
+ HttpsPort: util.IntPtr(test.RandInt()),
InterfaceName: inf,
Ip: ip,
Ip6: ip6,
LocationId: cachegroup,
- Port: randInt(),
- Profile: randStr(),
+ Port: util.IntPtr(test.RandInt()),
+ Profile: util.StrPtr(test.RandStr()),
ServerStatus: &status,
- ServerType: randStr(),
- RoutingDisabled: *randInt64(),
+ ServerType: util.StrPtr(test.RandStr()),
+ RoutingDisabled: test.RandInt64(),
}
}
func ExpectedGetServerParams() map[string]ServerParams {
return map[string]ServerParams{
"cache0": ServerParams{
- APIPort: randStr(),
- SecureAPIPort: randStr(),
- Weight: randFloat64(),
- WeightMultiplier: randFloat64(),
+ APIPort: util.StrPtr(test.RandStr()),
+ SecureAPIPort: util.StrPtr(test.RandStr()),
+ Weight: util.FloatPtr(test.RandFloat64()),
+ WeightMultiplier: util.FloatPtr(test.RandFloat64()),
},
"cache1": ServerParams{
- APIPort: randStr(),
- Weight: randFloat64(),
- WeightMultiplier: randFloat64(),
+ APIPort: util.StrPtr(test.RandStr()),
+ Weight: util.FloatPtr(test.RandFloat64()),
+ WeightMultiplier: util.FloatPtr(test.RandFloat64()),
},
}
}
@@ -599,7 +541,7 @@ func TestGetServerDSes(t *testing.T) {
}
func ExpectedGetCDNInfo() (string, bool) {
- return *randStr(), *randBool()
+ return test.RandStr(), test.RandBool()
}
func MockGetCDNInfo(mock sqlmock.Sqlmock, expectedDomain string,
expectedDNSSECEnabled bool, cdn string) {
@@ -644,7 +586,7 @@ func TestGetCDNInfo(t *testing.T) {
}
func ExpectedGetCDNNameFromID() string {
- return *randStr()
+ return test.RandStr()
}
func MockGetCDNNameFromID(mock sqlmock.Sqlmock, expected string, cdnID int) {
diff --git a/traffic_ops/traffic_ops_golang/crconfig/stats_test.go
b/traffic_ops/traffic_ops_golang/crconfig/stats_test.go
index 96e66f96e6..920e14e16e 100644
--- a/traffic_ops/traffic_ops_golang/crconfig/stats_test.go
+++ b/traffic_ops/traffic_ops_golang/crconfig/stats_test.go
@@ -25,14 +25,16 @@ import (
"time"
"github.com/apache/trafficcontrol/lib/go-tc"
+ "github.com/apache/trafficcontrol/lib/go-util"
+ "github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/test"
)
func ExpectedMakeStats() tc.CRConfigStats {
return tc.CRConfigStats{
- CDNName: randStr(),
- TMHost: randStr(),
- TMUser: randStr(),
- TMVersion: randStr(),
+ CDNName: util.StrPtr(test.RandStr()),
+ TMHost: util.StrPtr(test.RandStr()),
+ TMUser: util.StrPtr(test.RandStr()),
+ TMVersion: util.StrPtr(test.RandStr()),
}
}
diff --git a/traffic_ops/traffic_ops_golang/test/rand.go
b/traffic_ops/traffic_ops_golang/test/rand.go
index ab0456765d..2549643b94 100644
--- a/traffic_ops/traffic_ops_golang/test/rand.go
+++ b/traffic_ops/traffic_ops_golang/test/rand.go
@@ -16,23 +16,103 @@ package test
*/
import (
+ "fmt"
"math/rand"
+ "net"
)
-func RandStr() *string {
+// RandStr returns, as a string, a random 100 character alphanumeric,
including '-' and '_'.
+func RandStr() string {
chars :=
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_"
num := 100
s := ""
for i := 0; i < num; i++ {
s += string(chars[rand.Intn(len(chars))])
}
- return &s
+ return s
}
+
+// RandStrArray returns, as an array of 100 strings, with 100 character random
alphanumeric, including '-' and '_'.
func RandStrArray() []string {
num := 100
sArray := make([]string, num)
for i := 0; i < num; i++ {
- sArray[i] = *RandStr()
+ sArray[i] = RandStr()
}
return sArray
}
+
+// RandBool returns a random boolean value.
+func RandBool() bool {
+ b := rand.Int()%2 == 0
+ return b
+}
+
+// RandInt returns a random int.
+func RandInt() int {
+ i := rand.Int()
+ return i
+}
+
+// RandInt64 returns a random signed 64-bit int.
+func RandInt64() int64 {
+ i := rand.Int63()
+ return i
+}
+
+// RandUint64 returns a random unsigned 64-bit int.
+func RandUint64() uint64 {
+ i := uint64(rand.Int63())
+ return i
+}
+
+// RandUint returns a random unsigned int.
+func RandUint() uint {
+ i := uint(rand.Int())
+ return i
+}
+
+// RandIntn returns a random int in the half-open interval [0,n).
+func RandIntn(n int) int {
+ i := rand.Intn(n)
+ return i
+}
+
+// RandFloat64 returns a random float64.
+func RandFloat64() float64 {
+ f := rand.Float64()
+ return f
+}
+
+// RandomIPv4 returns, as a string, a random IP address.
+func RandomIPv4() string {
+ first := rand.Int31n(256)
+ second := rand.Int31n(256)
+ third := rand.Int31n(256)
+ fourth := rand.Int31n(256)
+ str := fmt.Sprintf("%d.%d.%d.%d", first, second, third, fourth)
+ return str
+}
+
+// RandomIPv6 returns, as a string, a random IPv6 address.
+func RandomIPv6() string {
+ ip := net.IP([]byte{
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ uint8(rand.Int31n(256)),
+ }).String()
+ return ip
+}