testutil

package
v25.0.0-custom-qt-impr... Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 5, 2025 License: Apache-2.0 Imports: 47 Imported by: 0

README

package z

This package is for code that is only used in tests (i.e. "*_test.go" files). It should not be used in non-test code because error handling is usually minimal and usually fatal.

Documentation

Index

Constants

View Source
const (
	Start int = iota
	Stop
)
View Source
const ExportRequest = `mutation {
	export(input: {format: "json"}) {
		response {
			code
			message
		}
	}
}`

Variables

View Source
var (
	COVERAGE_FLAG         = "COVERAGE_OUTPUT"
	EXPECTED_COVERAGE_ENV = "--test.coverprofile=coverage.out"
)
View Source
var (
	// Instance is the instance name of the Alpha.
	DockerPrefix string
	// Global test data directory used to store resources
	TestDataDirectory string
	Instance          string
	MinioInstance     string
	// SockAddr is the address to the gRPC endpoint of the alpha used during tests with localhost
	SockAddrLocalhost string
	// SockAddr is the address to the gRPC endpoint of the alpha used during tests.
	SockAddr string
	// SockAddrHttp is the address to the HTTP of alpha used during tests.
	SockAddrHttp          string
	SockAddrHttpLocalhost string
	// SockAddrZero is the address to the gRPC endpoint of the zero used during tests.
	SockAddrZero string
	// SockAddrZeroHttp is the address to the HTTP endpoint of the zero used during tests.
	SockAddrZeroHttp      string
	SockAddrZeroLocalhost string

	// SockAddrAlpha4 is the address to the gRPC endpoint of the alpha4 used during restore tests.
	SockAddrAlpha4 string
	// SockAddrAlpha4Http is the address to the HTTP of alpha4 used during restore tests.
	SockAddrAlpha4Http string
	// SockAddrZero4 is the address to the gRPC endpoint of the zero4 used during restore tests.
	SockAddrZero4 string
	// SockAddrZero4Http is the address to the HTTP endpoint of the zero4 used during restore tests.
	SockAddrZero4Http string
	// SockAddrAlpha7 is the address to the gRPC endpoint of the alpha4 used during restore tests.
	SockAddrAlpha7 string
	// SockAddrAlpha7Http is the address to the HTTP of alpha7 used during restore tests.
	SockAddrAlpha7Http string
	// SockAddrZero7 is the address to the gRPC endpoint of the zero7 used during restore tests.
	SockAddrZero7 string
	// SockAddrZero7Http is the address to the HTTP endpoint of the zero7 used during restore tests.
	SockAddrZero7Http string
	// SockAddrAlpha8 is the address to the gRPC endpoint of the alpha8 used during restore tests.
	SockAddrAlpha8 string
	// SockAddrAlpha8Http is the address to the HTTP of alpha8 used during restore tests.
	SockAddrAlpha8Http string
	// SockAddrZero8 is the address to the gRPC endpoint of the zero8 used during restore tests.
	SockAddrZero8 string
	// SockAddrZero8Http is the address to the HTTP endpoint of the zero8 used during restore tests.
	SockAddrZero8Http string
)

socket addr = IP address and port number

View Source
var (
	ShowOutput  = os.Getenv("DEBUG_SHOW_OUTPUT") != ""
	ShowError   = os.Getenv("DEBUG_SHOW_ERROR") != ""
	ShowCommand = os.Getenv("DEBUG_SHOW_COMMAND") != ""
)

These are exported so they can also be set directly from outside this package.

View Source
var KeyFile string

KeyFile is set to the path of the file containing the key. Used for testing purposes only.

Functions

func AddData

func AddData(t *testing.T, dg *dgo.Dgraph)

func AddNumberOfTriples

func AddNumberOfTriples(t *testing.T, dg *dgo.Dgraph, start, end int) (*api.Response, error)

func AddRulesToGroup

func AddRulesToGroup(t *testing.T, token *HttpToken, group string, rules []Rule, newGroup bool)

func AddToGroup

func AddToGroup(t *testing.T, token *HttpToken, userName, group string)

func AdminUrl

func AdminUrl() string

func AdminUrlHttps

func AdminUrlHttps() string

func AllContainers

func AllContainers(prefix string) []types.Container

func AppendAuthInfo

func AppendAuthInfo(schema []byte, algo, publicKeyFile string, closedByDefault bool) ([]byte, error)

func AppendAuthInfoWithJWKUrl

func AppendAuthInfoWithJWKUrl(schema []byte) ([]byte, error)

func AppendAuthInfoWithJWKUrlAndWithoutAudience

func AppendAuthInfoWithJWKUrlAndWithoutAudience(schema []byte) ([]byte, error)

func AppendAuthInfoWithMultipleJWKUrls

func AppendAuthInfoWithMultipleJWKUrls(schema []byte) ([]byte, error)

func AppendJWKAndVerificationKey

func AppendJWKAndVerificationKey(schema []byte) ([]byte, error)

Add JWKUrl and (VerificationKey, Algo) in the same Authorization JSON Adding Dummy values as this should result in validation error

func AssertMoveTablet

func AssertMoveTablet(t *testing.T, tablet string, groupId uint32)

func AssertRemoveNode

func AssertRemoveNode(t *testing.T, nodeId uint64, groupId uint32)

func AssignUids

func AssignUids(num uint64) error

AssignUids talks to zero to assign the given number of uids.

func BulkLoad

func BulkLoad(opts BulkOpts) error

func CheckForGraphQLEndpointToReady

func CheckForGraphQLEndpointToReady(t *testing.T) error

func CheckHealthContainer

func CheckHealthContainer(socketAddrHttp string) error

checkHealthContainer checks health of container and determines wheather container is ready to accept request

func CheckIfRace

func CheckIfRace(output []byte) bool

func CheckSchema

func CheckSchema(t *testing.T, preds, types []string)

CheckSchema checks the names of the predicates and types in the schema against the given names.

func CompareJSON

func CompareJSON(t *testing.T, want, got string)

CompareJSON compares two JSON objects (passed as strings).

func CompareJSONMaps

func CompareJSONMaps(t *testing.T, wantMap, gotMap map[string]interface{}) bool

CompareJSONMaps compares two JSON objects (passed as maps).

func ContainerAddr

func ContainerAddr(name string, privatePort uint16) string

func ContainerAddrLocalhost

func ContainerAddrLocalhost(name string, privatePort uint16) string

func ContainerAddrWithHost

func ContainerAddrWithHost(name string, privatePort uint16, host string) string

func CreateGroup

func CreateGroup(t *testing.T, token *HttpToken, name string)

func CreateNamespaceWithRetry

func CreateNamespaceWithRetry(t *testing.T, token *HttpToken) (uint64, error)

func DeleteNamespace

func DeleteNamespace(t *testing.T, token *HttpToken, nsID uint64) error

func DetectIfRaceViolation

func DetectIfRaceViolation(instance ContainerInstance) bool

func DetectRaceInAlphas

func DetectRaceInAlphas(prefix string) bool

func DetectRaceInZeros

func DetectRaceInZeros(prefix string) bool

func DgClientWithLogin

func DgClientWithLogin(t *testing.T, id, password string, ns uint64) *dgo.Dgraph

func DgraphBinaryPath

func DgraphBinaryPath() string

func DgraphClient

func DgraphClient(serviceAddr string) (*dgo.Dgraph, error)

DgraphClient creates a Dgraph client. It is intended to be called from TestMain() to establish a Dgraph connection shared by all tests, so there is no testing.T instance for it to use.

func DgraphClientDropAll

func DgraphClientDropAll(serviceAddr string) (*dgo.Dgraph, error)

DgraphClientDropAll creates a Dgraph client and drops all existing data. It is intended to be called from TestMain() to establish a Dgraph connection shared by all tests, so there is no testing.T instance for it to use.

func DgraphClientWithCerts

func DgraphClientWithCerts(serviceAddr string, conf *viper.Viper) (*dgo.Dgraph, error)

DgraphClientWithCerts creates a Dgraph client with TLS configured using the given viper configuration. It is intended to be called from TestMain() to establish a Dgraph connection shared by all tests, so there is no testing.T instance for it to use.

func DgraphClientWithGroot

func DgraphClientWithGroot(serviceAddr string) (*dgo.Dgraph, error)

DgraphClientWithGroot creates a Dgraph client with groot permissions set up. It is intended to be called from TestMain() to establish a Dgraph connection shared by all tests, so there is no testing.T instance for it to use.

func DiffJSONMaps

func DiffJSONMaps(t *testing.T, wantMap, gotMap map[string]interface{},
	savepath string, quiet bool) bool

DiffJSONMaps compares two JSON maps, optionally printing their differences, and returning true if they are equal.

func DockerCp

func DockerCp(srcPath, dstPath string) error

MARKED FOR DEPRECATION: DockerCp copies from/to a container. Paths inside a container have the format container_name:path.

func DockerCpFromContainer

func DockerCpFromContainer(containerID, srcPath, dstPath string) error

DockerCpFromContainer copies from a container.

func DockerExec

func DockerExec(instance string, cmd ...string) error

DockerExec executes a command inside the given container.

func DockerInspect

func DockerInspect(containerID string) (types.ContainerJSON, error)

func DockerRun

func DockerRun(instance string, op int) error

DockerStart starts the specified services.

func DropAll

func DropAll(t *testing.T, dg *dgo.Dgraph)

DropAll drops all the data in the Dgraph instance associated with the given client.

func EqualJSON

func EqualJSON(t *testing.T, want, got string, savepath string, quiet bool) bool

EqualJSON compares two JSON objects for equality.

func Exec

func Exec(argv ...string) error

Exec runs a single external command.

func ExecWithOpts

func ExecWithOpts(argv []string, opts CmdOpts) error

ExecWithOpts runs a single external command with the given options.

func GeneratePlugins

func GeneratePlugins(raceEnabled bool)

func GetAccessJwt

func GetAccessJwt(t *testing.T, params JwtParams) string

GetAccessJwt constructs an access jwt with the given user id, groupIds, namespace and expiration TTL.

func GetAlphaClientConfig

func GetAlphaClientConfig(t *testing.T) *tls.Config

func GetClientToGroup

func GetClientToGroup(gid string) (*dgo.Dgraph, error)

GetClientToGroup returns a dgraph client connected to an alpha in the given group.

func GetFullSchemaHTTPResponse

func GetFullSchemaHTTPResponse(opts SchemaOptions) string

GetFullSchemaHTTPResponse returns a string representation of the HTTP response returned by the full schema{} query. It uses the user provided predicates and types along with the initial internal schema to generate the string. Example response looks like:

{
	"data": {
		"schema": [ ... ],
		"types": [ ... ]
	}
}

func GetFullSchemaJSON

func GetFullSchemaJSON(opts SchemaOptions) string

GetFullSchemaJSON returns a string representation of the JSON object returned by the full schema{} query. It uses the user provided predicates and types along with the initial internal schema to generate the string. Example response looks like:

{
	"schema": [ ... ],
	"types": [ ... ]
}

func GetGQLSchema

func GetGQLSchema(t *testing.T, sockAddrHttp string) string

func GetHttpsClient

func GetHttpsClient(t *testing.T) http.Client

func GetInternalPreds

func GetInternalPreds(excludeAclPreds bool) string

func GetInternalTypes

func GetInternalTypes(excludeAclTypes bool) string

func GetNodesInGroup

func GetNodesInGroup(gid string) ([]string, error)

func GetPredicateNames

func GetPredicateNames(pdir string) ([]string, error)

GetPredicateNames returns the list of all the predicates stored in the restored pdir.

func GetPredicateValues

func GetPredicateValues(pdir, attr string, readTs uint64) (map[string]string, error)

GetPredicateValues reads the specified p directory and returns the values for the given attribute in a map.

func GetTypeNames

func GetTypeNames(pdir string) ([]string, error)

GetTypeNames returns the list of all the types stored in the restored pdir.

func JsonGet

func JsonGet(j interface{}, components ...string) interface{}

func LiveLoad

func LiveLoad(opts LiveOpts) error

func MakeDirEmpty

func MakeDirEmpty(dir []string) error

func NewMinioClient

func NewMinioClient() (*minio.Client, error)

NewMinioClient returns a minio client.

func Pipeline

func Pipeline(cmds [][]string) (string, error)

Pipeline runs several commands such that the output of one command becomes the input of the next. The first argument should be an two-dimensional array containing the commands. TODO: allow capturing output, sending to terminal, etc

func PollTillPassOrTimeout

func PollTillPassOrTimeout(t *testing.T, dc *dgo.Dgraph, query, want string, timeout time.Duration)

func QueryData

func QueryData(t *testing.T, dg *dgo.Dgraph, query string) []byte

func RequireNoGraphQLErrors

func RequireNoGraphQLErrors(t *testing.T, resp *http.Response)

func RequireUid

func RequireUid(t *testing.T, uid string)

func ResetPassword

func ResetPassword(t *testing.T, token *HttpToken, userID, newPass string, nsID uint64) (string, error)

func RetryAlter

func RetryAlter(dg *dgo.Dgraph, op *api.Operation) error

func RetryBadQuery

func RetryBadQuery(dg *dgo.Dgraph, q string) (*api.Response, error)

RetryBadQuery will retry a query until it failse with a non-retryable error.

func RetryMutation

func RetryMutation(dg *dgo.Dgraph, mu *api.Mutation) error

RetryMutation will retry a mutation until it succeeds or a non-retryable error is received. The mutation should have CommitNow set to true.

func RetryQuery

func RetryQuery(dg *dgo.Dgraph, q string) (*api.Response, error)

RetryQuery will retry a query until it succeeds or a non-retryable error is received.

func RootNsCountKey

func RootNsCountKey(attr string, count uint32, reverse bool) []byte

func RootNsDataKey

func RootNsDataKey(attr string, uid uint64) []byte

func RootNsIndexKey

func RootNsIndexKey(attr, term string) []byte

func RootNsReverseKey

func RootNsReverseKey(attr string, uid uint64) []byte

func RootNsSchemaKey

func RootNsSchemaKey(attr string) []byte

func RootNsTypeKey

func RootNsTypeKey(attr string) []byte

func SnipJSON

func SnipJSON(buf []byte) string

SnipJSON snips the middle of a very long JSON string to make it less than 100 lines

func StartAlphas

func StartAlphas(compose string) error

func StopAlphasAndDetectRace

func StopAlphasAndDetectRace(alphas []string) (raceDetected bool)

func StopAlphasForCoverage

func StopAlphasForCoverage(composeFile string)

func UnmarshalJSON

func UnmarshalJSON(t *testing.T, jsonStr string) map[string]interface{}

UnmarshalJSON unmarshals the given string into a map.

func UpdateGQLSchema

func UpdateGQLSchema(t *testing.T, sockAddrHttp, schema string)

func VerifyCurlCmd

func VerifyCurlCmd(t *testing.T, args []string, failureConfig *CurlFailureConfig)

VerifyCurlCmd executes the curl command with the given arguments and verifies the result against the expected output.

func VerifyQueryResponse

func VerifyQueryResponse(t *testing.T, dg *dgo.Dgraph, query, expectedResponse string)

VerifyQueryResponse executes the given query and verifies that the response of the query is same as the expected response.

func VerifySchema

func VerifySchema(t *testing.T, dg *dgo.Dgraph, opts SchemaOptions)

VerifySchema verifies that the full schema generated using user provided predicates and types is same as the response of the schema{} query.

func WaitForRestore

func WaitForRestore(t *testing.T, dg *dgo.Dgraph, HttpSocket string)

func WaitForTask

func WaitForTask(t *testing.T, taskId string, useHttps bool, socketAddrHttp string)

Types

type AuthMeta

type AuthMeta struct {
	PublicKey       string
	Namespace       string
	Algo            string
	Header          string
	AuthVars        map[string]interface{}
	PrivateKeyPath  string
	ClosedByDefault bool
}

func (*AuthMeta) AddClaimsToContext

func (a *AuthMeta) AddClaimsToContext(ctx context.Context) (context.Context, error)

func (*AuthMeta) GetSignedToken

func (a *AuthMeta) GetSignedToken(privateKeyFile string,
	expireAfter time.Duration) (string, error)

type BulkOpts

type BulkOpts struct {
	Zero          string
	Shards        int
	RdfFile       string
	SchemaFile    string
	GQLSchemaFile string
	Dir           string
	Env           []string
	Namespace     uint64
}

type CmdOpts

type CmdOpts struct {
	Dir string
}

CmdOpts sets the options to run a single command.

type ContainerInstance

type ContainerInstance struct {
	Prefix string
	Name   string
}

func GetContainerInstance

func GetContainerInstance(prefix, name string) ContainerInstance

func (ContainerInstance) BestEffortWaitForHealthy

func (in ContainerInstance) BestEffortWaitForHealthy(privatePort uint16) error

func (ContainerInstance) GetContainer

func (in ContainerInstance) GetContainer() *types.Container

func (ContainerInstance) String

func (in ContainerInstance) String() string

type CurlFailureConfig

type CurlFailureConfig struct {
	ShouldFail   bool
	CurlErrMsg   string
	DgraphErrMsg string
}

CurlFailureConfig stores information about the expected failure of a curl test.

type GraphQLError

type GraphQLError struct {
	Message string
}

type GraphQLParams

type GraphQLParams struct {
	Query     string                 `json:"query"`
	Variables map[string]interface{} `json:"variables"`
}

type GraphQLResponse

type GraphQLResponse struct {
	Data       json.RawMessage        `json:"data,omitempty"`
	Errors     x.GqlErrorList         `json:"errors,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

func CreateUser

func CreateUser(t *testing.T, token *HttpToken, username,
	password string) *GraphQLResponse

func Export

func Export(t *testing.T, token *HttpToken, dest, accessKey, secretKey string) *GraphQLResponse

func MakeGQLRequest

func MakeGQLRequest(t *testing.T, params *GraphQLParams) *GraphQLResponse

func MakeGQLRequestWithAccessJwt

func MakeGQLRequestWithAccessJwt(t *testing.T, params *GraphQLParams, accessToken string) *GraphQLResponse

func MakeGQLRequestWithAccessJwtAndTLS

func MakeGQLRequestWithAccessJwtAndTLS(t *testing.T, params *GraphQLParams,
	tls *tls.Config, accessToken string) *GraphQLResponse

func MakeGQLRequestWithTLS

func MakeGQLRequestWithTLS(t *testing.T, params *GraphQLParams, tls *tls.Config) *GraphQLResponse

func MakeRequest

func MakeRequest(t *testing.T, token *HttpToken, params GraphQLParams) *GraphQLResponse

func (*GraphQLResponse) RequireNoGraphQLErrors

func (resp *GraphQLResponse) RequireNoGraphQLErrors(t *testing.T)

type HttpToken

type HttpToken struct {
	UserId       string
	Password     string
	AccessJwt    string
	RefreshToken string
}

func GrootHttpLogin

func GrootHttpLogin(endpoint string) *HttpToken

GrootHttpLogin logins using the groot account with the default password and returns the access JWT

func GrootHttpLoginNamespace

func GrootHttpLoginNamespace(endpoint string, namespace uint64) *HttpToken

func HttpLogin

func HttpLogin(params *LoginParams) (*HttpToken, error)

HttpLogin sends a HTTP request to the server and returns the access JWT and refresh JWT extracted from the HTTP response

func Login

func Login(t *testing.T, loginParams *LoginParams) (*HttpToken, error)

type JwtParams

type JwtParams struct {
	User   string
	Groups []string
	Ns     uint64
	Exp    time.Duration
	Secret []byte
}

type LiveOpts

type LiveOpts struct {
	Alpha      string
	RdfFile    string
	SchemaFile string
	Dir        string
	Env        []string
	Creds      *LoginParams
	ForceNs    int64
}

type LoginParams

type LoginParams struct {
	Endpoint   string
	UserID     string
	Passwd     string
	Namespace  uint64
	RefreshJwt string
}

LoginParams stores the information needed to perform a login request.

type Member

type Member struct {
	Addr       string `json:"addr"`
	GroupID    int    `json:"groupId"`
	ID         string `json:"id"`
	LastUpdate string `json:"lastUpdate"`
	Leader     bool   `json:"leader"`
}

type Rule

type Rule struct {
	Predicate  string `json:"predicate"`
	Permission int32  `json:"permission"`
}

type SchemaOptions

type SchemaOptions struct {
	UserPreds        string
	UserTypes        string
	ExcludeAclSchema bool
}

type StateResponse

type StateResponse struct {
	Zeros map[string]struct {
		Id string `json:"id"`
	} `json:"zeros"`
	Groups map[string]struct {
		Members map[string]Member `json:"members"`
		Tablets map[string]struct {
			GroupID   int    `json:"groupId"`
			Predicate string `json:"predicate"`
		} `json:"tablets"`
	} `json:"groups"`
	Removed []struct {
		Addr    string `json:"addr"`
		GroupID int    `json:"groupId"`
		ID      string `json:"id"`
	} `json:"removed"`
}

StateResponse represents the structure of the JSON object returned by calling the /state endpoint in zero.

func GetState

func GetState() (*StateResponse, error)

GetState queries the /state endpoint in zero and returns the response.

func GetStateHttps

func GetStateHttps(tlsConfig *tls.Config) (*StateResponse, error)

GetStateHttps queries the /state endpoint in zero and returns the response.

Directories

Path Synopsis
custom_plugins
anagram command
cidr command
factor command
rune command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL