repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertion_format.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_format.go#L514-L519
go
train
// Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted")
func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool
// Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } return Subset(t, list, subset, append([]interface{}{msg}, args...)...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertion_format.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_format.go#L524-L529
go
train
// Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted")
func Truef(t TestingT, value bool, msg string, args ...interface{}) bool
// Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } return True(t, value, append([]interface{}{msg}, args...)...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertion_format.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_format.go#L534-L539
go
train
// WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")
func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool
// WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertion_format.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertion_format.go#L542-L547
go
train
// Zerof asserts that i is the zero value for its type.
func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool
// Zerof asserts that i is the zero value for its type. func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } return Zero(t, i, append([]interface{}{msg}, args...)...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
_codegen/main.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/_codegen/main.go#L174-L213
go
train
// parsePackageSource returns the types scope and the package documentation from the package
func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error)
// parsePackageSource returns the types scope and the package documentation from the package func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error)
{ pd, err := build.Import(pkg, ".", 0) if err != nil { return nil, nil, err } fset := token.NewFileSet() files := make(map[string]*ast.File) fileList := make([]*ast.File, len(pd.GoFiles)) for i, fname := range pd.GoFiles { src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) if err != nil { return nil, nil, err } f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) if err != nil { return nil, nil, err } files[fname] = f fileList[i] = f } cfg := types.Config{ Importer: importer.Default(), } info := types.Info{ Defs: make(map[*ast.Ident]types.Object), } tp, err := cfg.Check(pkg, fset, fileList, &info) if err != nil { return nil, nil, err } scope := tp.Scope() ap, _ := ast.NewPackage(fset, files, nil, nil) docs := doc.New(ap, pkg, 0) return scope, docs, nil }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L56-L74
go
train
/* Helper functions */ // ObjectsAreEqual determines if two objects are considered equal. // // This function does no assertion of any kind.
func ObjectsAreEqual(expected, actual interface{}) bool
/* Helper functions */ // ObjectsAreEqual determines if two objects are considered equal. // // This function does no assertion of any kind. func ObjectsAreEqual(expected, actual interface{}) bool
{ if expected == nil || actual == nil { return expected == actual } exp, ok := expected.([]byte) if !ok { return reflect.DeepEqual(expected, actual) } act, ok := actual.([]byte) if !ok { return false } if exp == nil || act == nil { return exp == nil && act == nil } return bytes.Equal(exp, act) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L78-L94
go
train
// ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal.
func ObjectsAreEqualValues(expected, actual interface{}) bool
// ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal. func ObjectsAreEqualValues(expected, actual interface{}) bool
{ if ObjectsAreEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) if actualType == nil { return false } expectedValue := reflect.ValueOf(expected) if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { // Attempt comparison after type conversion return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) } return false }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L103-L160
go
train
/* CallerInfo is necessary because the assert functions use the testing object internally, causing it to print the file:line of the assert method, rather than where the problem actually occurred in calling code.*/ // CallerInfo returns an array of strings containing the file and line number // of each stack frame leading from the current test to the assert call that // failed.
func CallerInfo() []string
/* CallerInfo is necessary because the assert functions use the testing object internally, causing it to print the file:line of the assert method, rather than where the problem actually occurred in calling code.*/ // CallerInfo returns an array of strings containing the file and line number // of each stack frame leading from the current test to the assert call that // failed. func CallerInfo() []string
{ pc := uintptr(0) file := "" line := 0 ok := false name := "" callers := []string{} for i := 0; ; i++ { pc, file, line, ok = runtime.Caller(i) if !ok { // The breaks below failed to terminate the loop, and we ran off the // end of the call stack. break } // This is a huge edge case, but it will panic if this is the case, see #180 if file == "<autogenerated>" { break } f := runtime.FuncForPC(pc) if f == nil { break } name = f.Name() // testing.tRunner is the standard library function that calls // tests. Subtests are called directly by tRunner, without going through // the Test/Benchmark/Example function that contains the t.Run calls, so // with subtests we should break when we hit tRunner, without adding it // to the list of callers. if name == "testing.tRunner" { break } parts := strings.Split(file, "/") file = parts[len(parts)-1] if len(parts) > 1 { dir := parts[len(parts)-2] if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { callers = append(callers, fmt.Sprintf("%s:%d", file, line)) } } // Drop the package segments := strings.Split(name, ".") name = segments[len(segments)-1] if isTest(name, "Test") || isTest(name, "Benchmark") || isTest(name, "Example") { break } } return callers }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L198-L211
go
train
// Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the // basis on which the alignment occurs).
func indentMessageLines(message string, longestLabelLen int) string
// Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the // basis on which the alignment occurs). func indentMessageLines(message string, longestLabelLen int) string
{ outBuf := new(bytes.Buffer) for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { // no need to align first line because it starts at the correct location (after the label) if i != 0 { // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") } outBuf.WriteString(scanner.Text()) } return outBuf.String() }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L218-L236
go
train
// FailNow fails test
func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
// FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } Fail(t, failureMessage, msgAndArgs...) // We cannot extend TestingT with FailNow() and // maintain backwards compatibility, so we fallback // to panicking when FailNow is not available in // TestingT. // See issue #263 if t, ok := t.(failNower); ok { t.FailNow() } else { panic("test failed and t is missing `FailNow()`") } return false }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L239-L263
go
train
// Fail reports a failure through
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
// Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } content := []labeledContent{ {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, {"Error", failureMessage}, } // Add test name if the Go version supports it if n, ok := t.(interface { Name() string }); ok { content = append(content, labeledContent{"Test", n.Name()}) } message := messageFromMsgAndArgs(msgAndArgs...) if len(message) > 0 { content = append(content, labeledContent{"Messages", message}) } t.Errorf("\n%s", ""+labeledOutput(content...)) return false }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L279-L291
go
train
// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: // // \t{{label}}:{{align_spaces}}\t{{content}}\n // // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this // alignment is achieved, "\t{{content}}\n" is added for the output. // // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line.
func labeledOutput(content ...labeledContent) string
// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: // // \t{{label}}:{{align_spaces}}\t{{content}}\n // // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this // alignment is achieved, "\t{{content}}\n" is added for the output. // // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. func labeledOutput(content ...labeledContent) string
{ longestLabel := 0 for _, v := range content { if len(v.label) > longestLabel { longestLabel = len(v.label) } } var output string for _, v := range content { output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" } return output }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L296-L310
go
train
// Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject))
func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool
// Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } interfaceType := reflect.TypeOf(interfaceObject).Elem() if object == nil { return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) } if !reflect.TypeOf(object).Implements(interfaceType) { return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L313-L323
go
train
// IsType asserts that the specified objects are of the same type.
func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool
// IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L332-L351
go
train
// Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail.
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
// Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", expected, actual, err), msgAndArgs...) } if !ObjectsAreEqual(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L359-L382
go
train
// Same asserts that two pointers reference the same object. // // assert.Same(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value.
func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
// Same asserts that two pointers reference the same object. // // assert.Same(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } expectedPtr, actualPtr := reflect.ValueOf(expected), reflect.ValueOf(actual) if expectedPtr.Kind() != reflect.Ptr || actualPtr.Kind() != reflect.Ptr { return Fail(t, "Invalid operation: both arguments must be pointers", msgAndArgs...) } expectedType, actualType := reflect.TypeOf(expected), reflect.TypeOf(actual) if expectedType != actualType { return Fail(t, fmt.Sprintf("Pointer expected to be of type %v, but was %v", expectedType, actualType), msgAndArgs...) } if expected != actual { return Fail(t, fmt.Sprintf("Not same: \n"+ "expected: %p %#v\n"+ "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L390-L398
go
train
// formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed // with the type name, and the value will be enclosed in parenthesis similar // to a type conversion in the Go grammar.
func formatUnequalValues(expected, actual interface{}) (e string, a string)
// formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed // with the type name, and the value will be enclosed in parenthesis similar // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string)
{ if reflect.TypeOf(expected) != reflect.TypeOf(actual) { return fmt.Sprintf("%T(%#v)", expected, expected), fmt.Sprintf("%T(%#v)", actual, actual) } return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L404-L419
go
train
// EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123))
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
// EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if !ObjectsAreEqualValues(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L424-L438
go
train
// Exactly asserts that two objects are equal in value and type. // // assert.Exactly(t, int32(123), int64(123))
func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
// Exactly asserts that two objects are equal in value and type. // // assert.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } aType := reflect.TypeOf(expected) bType := reflect.TypeOf(actual) if aType != bType { return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) } return Equal(t, expected, actual, msgAndArgs...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L443-L451
go
train
// NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err)
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
// NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if !isNil(object) { return true } return Fail(t, "Expected value not to be nil.", msgAndArgs...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L454-L462
go
train
// containsKind checks if a specified kind in the slice of kinds.
func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool
// containsKind checks if a specified kind in the slice of kinds. func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool
{ for i := 0; i < len(kinds); i++ { if kind == kinds[i] { return true } } return false }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L465-L484
go
train
// isNil checks if a specified object is nil or not, without Failing.
func isNil(object interface{}) bool
// isNil checks if a specified object is nil or not, without Failing. func isNil(object interface{}) bool
{ if object == nil { return true } value := reflect.ValueOf(object) kind := value.Kind() isNilableKind := containsKind( []reflect.Kind{ reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice}, kind) if isNilableKind && value.IsNil() { return true } return false }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L489-L497
go
train
// Nil asserts that the specified object is nil. // // assert.Nil(t, err)
func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
// Nil asserts that the specified object is nil. // // assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if isNil(object) { return true } return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L500-L525
go
train
// isEmpty gets whether the specified object is considered empty or not.
func isEmpty(object interface{}) bool
// isEmpty gets whether the specified object is considered empty or not. func isEmpty(object interface{}) bool
{ // get nil case out of the way if object == nil { return true } objValue := reflect.ValueOf(object) switch objValue.Kind() { // collection types are empty when they have no element case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: return objValue.Len() == 0 // pointers are empty if nil or if the value they point to is empty case reflect.Ptr: if objValue.IsNil() { return true } deref := objValue.Elem().Interface() return isEmpty(deref) // for all other types, compare against the zero value default: zero := reflect.Zero(objValue.Type()) return reflect.DeepEqual(object, zero.Interface()) } }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L531-L543
go
train
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj)
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } pass := isEmpty(object) if !pass { Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) } return pass }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L567-L575
go
train
// getLen try to get length of object. // return (false, 0) if impossible.
func getLen(x interface{}) (ok bool, length int)
// getLen try to get length of object. // return (false, 0) if impossible. func getLen(x interface{}) (ok bool, length int)
{ v := reflect.ValueOf(x) defer func() { if e := recover(); e != nil { ok = false } }() return true, v.Len() }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L599-L615
go
train
// True asserts that the specified value is true. // // assert.True(t, myBool)
func True(t TestingT, value bool, msgAndArgs ...interface{}) bool
// True asserts that the specified value is true. // // assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if h, ok := t.(interface { Helper() }); ok { h.Helper() } if value != true { return Fail(t, "Should be true", msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L620-L631
go
train
// False asserts that the specified value is false. // // assert.False(t, myBool)
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool
// False asserts that the specified value is false. // // assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if value != false { return Fail(t, "Should be false", msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L660-L693
go
train
// containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. // return (true, true) if element was found.
func includeElement(list interface{}, element interface{}) (ok, found bool)
// containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. // return (true, true) if element was found. func includeElement(list interface{}, element interface{}) (ok, found bool)
{ listValue := reflect.ValueOf(list) listKind := reflect.TypeOf(list).Kind() defer func() { if e := recover(); e != nil { ok = false found = false } }() if listKind == reflect.String { elementValue := reflect.ValueOf(element) return true, strings.Contains(listValue.String(), elementValue.String()) } if listKind == reflect.Map { mapKeys := listValue.MapKeys() for i := 0; i < len(mapKeys); i++ { if ObjectsAreEqual(mapKeys[i].Interface(), element) { return true, true } } return true, false } for i := 0; i < listValue.Len(); i++ { if ObjectsAreEqual(listValue.Index(i).Interface(), element) { return true, true } } return true, false }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L701-L716
go
train
// Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello")
func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
// Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L745-L783
go
train
// Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]")
func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool)
// Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool)
{ if h, ok := t.(tHelper); ok { h.Helper() } if subset == nil { return true // we consider nil to be equal to the nil set } subsetValue := reflect.ValueOf(subset) defer func() { if e := recover(); e != nil { ok = false } }() listKind := reflect.TypeOf(list).Kind() subsetKind := reflect.TypeOf(subset).Kind() if listKind != reflect.Array && listKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } if subsetKind != reflect.Array && subsetKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } for i := 0; i < subsetValue.Len(); i++ { element := subsetValue.Index(i).Interface() ok, found := includeElement(list, element) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) } } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L834-L884
go
train
// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool)
// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool)
{ if h, ok := t.(tHelper); ok { h.Helper() } if isEmpty(listA) && isEmpty(listB) { return true } aKind := reflect.TypeOf(listA).Kind() bKind := reflect.TypeOf(listB).Kind() if aKind != reflect.Array && aKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...) } if bKind != reflect.Array && bKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...) } aValue := reflect.ValueOf(listA) bValue := reflect.ValueOf(listB) aLen := aValue.Len() bLen := bValue.Len() if aLen != bLen { return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...) } // Mark indexes in bValue that we already used visited := make([]bool, bLen) for i := 0; i < aLen; i++ { element := aValue.Index(i).Interface() found := false for j := 0; j < bLen; j++ { if visited[j] { continue } if ObjectsAreEqual(bValue.Index(j).Interface(), element) { visited[j] = true found = true break } } if !found { return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...) } } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L887-L896
go
train
// Condition uses a Comparison to assert a complex condition.
func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool
// Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } result := comp() if !result { Fail(t, "Condition failed!", msgAndArgs...) } return result }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L903-L922
go
train
// didPanic returns true if the function passed to it panics. Otherwise, it returns false.
func didPanic(f PanicTestFunc) (bool, interface{})
// didPanic returns true if the function passed to it panics. Otherwise, it returns false. func didPanic(f PanicTestFunc) (bool, interface{})
{ didPanic := false var message interface{} func() { defer func() { if message = recover(); message != nil { didPanic = true } }() // call the target function f() }() return didPanic, message }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L927-L937
go
train
// Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ GoCrazy() })
func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
// Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ GoCrazy() }) func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L943-L957
go
train
// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })
func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool
// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } funcDidPanic, panicValue := didPanic(f) if !funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) } if panicValue != expected { return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v", f, expected, panicValue), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1082-L1123
go
train
// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.
func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool
// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Map || reflect.TypeOf(expected).Kind() != reflect.Map { return Fail(t, "Arguments must be maps", msgAndArgs...) } expectedMap := reflect.ValueOf(expected) actualMap := reflect.ValueOf(actual) if expectedMap.Len() != actualMap.Len() { return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) } for _, k := range expectedMap.MapKeys() { ev := expectedMap.MapIndex(k) av := actualMap.MapIndex(k) if !ev.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) } if !av.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) } if !InDelta( t, ev.Interface(), av.Interface(), delta, msgAndArgs..., ) { return false } } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1142-L1156
go
train
// InEpsilon asserts that expected and actual have a relative error less than epsilon
func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool
// InEpsilon asserts that expected and actual have a relative error less than epsilon func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } actualEpsilon, err := calcRelativeError(expected, actual) if err != nil { return Fail(t, err.Error(), msgAndArgs...) } if actualEpsilon > epsilon { return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1192-L1201
go
train
/* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, expectedObj, actualObj) // }
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
/* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, expectedObj, actualObj) // } func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if err != nil { return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1209-L1219
go
train
// Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err) { // assert.Equal(t, expectedError, err) // }
func Error(t TestingT, err error, msgAndArgs ...interface{}) bool
// Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err) { // assert.Equal(t, expectedError, err) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if err == nil { return Fail(t, "An error is expected but got nil.", msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1226-L1242
go
train
// EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualError(t, err, expectedErrorString)
func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool
// EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualError(t, err, expectedErrorString) func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if !Error(t, theError, msgAndArgs...) { return false } expected := errString actual := theError.Error() // don't need to use deep equals here, we know they are both strings if expected != actual { return Fail(t, fmt.Sprintf("Error message not equal:\n"+ "expected: %q\n"+ "actual : %q", expected, actual), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1245-L1256
go
train
// matchRegexp return true if a specified regexp matches a string.
func matchRegexp(rx interface{}, str interface{}) bool
// matchRegexp return true if a specified regexp matches a string. func matchRegexp(rx interface{}, str interface{}) bool
{ var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) } return (r.FindStringIndex(fmt.Sprint(str)) != nil) }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1280-L1292
go
train
// NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting")
func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool
// NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } match := matchRegexp(rx, str) if match { Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) } return !match }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1295-L1303
go
train
// Zero asserts that i is the zero value for its type.
func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
// Zero asserts that i is the zero value for its type. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1317-L1332
go
train
// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.
func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
// FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
{ if h, ok := t.(tHelper); ok { h.Helper() } info, err := os.Lstat(path) if err != nil { if os.IsNotExist(err) { return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) } return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) } if info.IsDir() { return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...) } return true }
stretchr/testify
34c6fa2dc70986bccbbffcc6130f6920a924b075
assert/assertions.go
https://github.com/stretchr/testify/blob/34c6fa2dc70986bccbbffcc6130f6920a924b075/assert/assertions.go#L1425-L1430
go
train
// validateEqualArgs checks whether provided arguments can be safely used in the // Equal/NotEqual functions.
func validateEqualArgs(expected, actual interface{}) error
// validateEqualArgs checks whether provided arguments can be safely used in the // Equal/NotEqual functions. func validateEqualArgs(expected, actual interface{}) error
{ if isFunction(expected) || isFunction(actual) { return errors.New("cannot take func type as argument") } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
guest/file_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/guest/file_manager.go#L124-L196
go
train
// TransferURL rewrites the url with a valid hostname and adds the host's thumbprint. // The InitiateFileTransfer{From,To}Guest methods return a URL with the host set to "*" when connected directly to ESX, // but return the address of VM's runtime host when connected to vCenter.
func (m FileManager) TransferURL(ctx context.Context, u string) (*url.URL, error)
// TransferURL rewrites the url with a valid hostname and adds the host's thumbprint. // The InitiateFileTransfer{From,To}Guest methods return a URL with the host set to "*" when connected directly to ESX, // but return the address of VM's runtime host when connected to vCenter. func (m FileManager) TransferURL(ctx context.Context, u string) (*url.URL, error)
{ turl, err := url.Parse(u) if err != nil { return nil, err } needsHostname := turl.Hostname() == "*" if needsHostname { turl.Host = m.c.URL().Host // Also use Client's port, to support port forwarding } if !m.c.IsVC() { return turl, nil // we already connected to the ESX host and have its thumbprint } name := turl.Hostname() port := turl.Port() m.mu.Lock() mname, ok := m.hosts[name] m.mu.Unlock() if ok && needsHostname { turl.Host = net.JoinHostPort(mname, port) return turl, nil } c := property.DefaultCollector(m.c) var vm mo.VirtualMachine err = c.RetrieveOne(ctx, m.vm, []string{"runtime.host"}, &vm) if err != nil { return nil, err } if vm.Runtime.Host == nil { return turl, nil // won't matter if the VM was powered off since the call to InitiateFileTransfer } props := []string{"summary.config.sslThumbprint", "config.virtualNicManagerInfo.netConfig"} var host mo.HostSystem err = c.RetrieveOne(ctx, *vm.Runtime.Host, props, &host) if err != nil { return nil, err } kind := string(types.HostVirtualNicManagerNicTypeManagement) // prefer an ESX management IP, as the hostname used when adding to VC may not be valid for this client for _, nc := range host.Config.VirtualNicManagerInfo.NetConfig { if len(nc.CandidateVnic) > 0 && nc.NicType == kind { ip := net.ParseIP(nc.CandidateVnic[0].Spec.Ip.IpAddress) if ip != nil { mname = ip.String() m.mu.Lock() m.hosts[name] = mname m.mu.Unlock() name = mname break } } } if needsHostname { turl.Host = net.JoinHostPort(name, port) } m.c.SetThumbprint(turl.Host, host.Summary.Config.SslThumbprint) return turl, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L44-L57
go
train
// SCSIControllerTypes are used for adding a new SCSI controller to a VM.
func SCSIControllerTypes() VirtualDeviceList
// SCSIControllerTypes are used for adding a new SCSI controller to a VM. func SCSIControllerTypes() VirtualDeviceList
{ // Return a mutable list of SCSI controller types, initialized with defaults. return VirtualDeviceList([]types.BaseVirtualDevice{ &types.VirtualLsiLogicController{}, &types.VirtualBusLogicController{}, &types.ParaVirtualSCSIController{}, &types.VirtualLsiLogicSASController{}, }).Select(func(device types.BaseVirtualDevice) bool { c := device.(types.BaseVirtualSCSIController).GetVirtualSCSIController() c.SharedBus = types.VirtualSCSISharingNoSharing c.BusNumber = -1 return true }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L60-L73
go
train
// EthernetCardTypes are used for adding a new ethernet card to a VM.
func EthernetCardTypes() VirtualDeviceList
// EthernetCardTypes are used for adding a new ethernet card to a VM. func EthernetCardTypes() VirtualDeviceList
{ return VirtualDeviceList([]types.BaseVirtualDevice{ &types.VirtualE1000{}, &types.VirtualE1000e{}, &types.VirtualVmxnet2{}, &types.VirtualVmxnet3{}, &types.VirtualPCNet32{}, &types.VirtualSriovEthernetCard{}, }).Select(func(device types.BaseVirtualDevice) bool { c := device.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard() c.GetVirtualDevice().Key = -1 return true }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L76-L86
go
train
// Select returns a new list containing all elements of the list for which the given func returns true.
func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList
// Select returns a new list containing all elements of the list for which the given func returns true. func (l VirtualDeviceList) Select(f func(device types.BaseVirtualDevice) bool) VirtualDeviceList
{ var found VirtualDeviceList for _, device := range l { if f(device) { found = append(found, device) } } return found }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L89-L107
go
train
// SelectByType returns a new list with devices that are equal to or extend the given type.
func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList
// SelectByType returns a new list with devices that are equal to or extend the given type. func (l VirtualDeviceList) SelectByType(deviceType types.BaseVirtualDevice) VirtualDeviceList
{ dtype := reflect.TypeOf(deviceType) if dtype == nil { return nil } dname := dtype.Elem().Name() return l.Select(func(device types.BaseVirtualDevice) bool { t := reflect.TypeOf(device) if t == dtype { return true } _, ok := t.Elem().FieldByName(dname) return ok }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L111-L153
go
train
// SelectByBackingInfo returns a new list with devices matching the given backing info. // If the value of backing is nil, any device with a backing of the same type will be returned.
func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList
// SelectByBackingInfo returns a new list with devices matching the given backing info. // If the value of backing is nil, any device with a backing of the same type will be returned. func (l VirtualDeviceList) SelectByBackingInfo(backing types.BaseVirtualDeviceBackingInfo) VirtualDeviceList
{ t := reflect.TypeOf(backing) return l.Select(func(device types.BaseVirtualDevice) bool { db := device.GetVirtualDevice().Backing if db == nil { return false } if reflect.TypeOf(db) != t { return false } if reflect.ValueOf(backing).IsNil() { // selecting by backing type return true } switch a := db.(type) { case *types.VirtualEthernetCardNetworkBackingInfo: b := backing.(*types.VirtualEthernetCardNetworkBackingInfo) return a.DeviceName == b.DeviceName case *types.VirtualEthernetCardDistributedVirtualPortBackingInfo: b := backing.(*types.VirtualEthernetCardDistributedVirtualPortBackingInfo) return a.Port.SwitchUuid == b.Port.SwitchUuid && a.Port.PortgroupKey == b.Port.PortgroupKey case *types.VirtualDiskFlatVer2BackingInfo: b := backing.(*types.VirtualDiskFlatVer2BackingInfo) if a.Parent != nil && b.Parent != nil { return a.Parent.FileName == b.Parent.FileName } return a.FileName == b.FileName case *types.VirtualSerialPortURIBackingInfo: b := backing.(*types.VirtualSerialPortURIBackingInfo) return a.ServiceURI == b.ServiceURI case types.BaseVirtualDeviceFileBackingInfo: b := backing.(types.BaseVirtualDeviceFileBackingInfo) return a.GetVirtualDeviceFileBackingInfo().FileName == b.GetVirtualDeviceFileBackingInfo().FileName default: return false } }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L156-L163
go
train
// Find returns the device matching the given name.
func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice
// Find returns the device matching the given name. func (l VirtualDeviceList) Find(name string) types.BaseVirtualDevice
{ for _, device := range l { if l.Name(device) == name { return device } } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L166-L173
go
train
// FindByKey returns the device matching the given key.
func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice
// FindByKey returns the device matching the given key. func (l VirtualDeviceList) FindByKey(key int32) types.BaseVirtualDevice
{ for _, device := range l { if device.GetVirtualDevice().Key == key { return device } } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L178-L196
go
train
// FindIDEController will find the named IDE controller if given, otherwise will pick an available controller. // An error is returned if the named controller is not found or not an IDE controller. Or, if name is not // given and no available controller can be found.
func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error)
// FindIDEController will find the named IDE controller if given, otherwise will pick an available controller. // An error is returned if the named controller is not found or not an IDE controller. Or, if name is not // given and no available controller can be found. func (l VirtualDeviceList) FindIDEController(name string) (*types.VirtualIDEController, error)
{ if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(*types.VirtualIDEController); ok { return c, nil } return nil, fmt.Errorf("%s is not an IDE controller", name) } c := l.PickController((*types.VirtualIDEController)(nil)) if c == nil { return nil, errors.New("no available IDE controller") } return c.(*types.VirtualIDEController), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L199-L203
go
train
// CreateIDEController creates a new IDE controller.
func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error)
// CreateIDEController creates a new IDE controller. func (l VirtualDeviceList) CreateIDEController() (types.BaseVirtualDevice, error)
{ ide := &types.VirtualIDEController{} ide.Key = l.NewKey() return ide, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L208-L226
go
train
// FindSCSIController will find the named SCSI controller if given, otherwise will pick an available controller. // An error is returned if the named controller is not found or not an SCSI controller. Or, if name is not // given and no available controller can be found.
func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error)
// FindSCSIController will find the named SCSI controller if given, otherwise will pick an available controller. // An error is returned if the named controller is not found or not an SCSI controller. Or, if name is not // given and no available controller can be found. func (l VirtualDeviceList) FindSCSIController(name string) (*types.VirtualSCSIController, error)
{ if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(types.BaseVirtualSCSIController); ok { return c.GetVirtualSCSIController(), nil } return nil, fmt.Errorf("%s is not an SCSI controller", name) } c := l.PickController((*types.VirtualSCSIController)(nil)) if c == nil { return nil, errors.New("no available SCSI controller") } return c.(types.BaseVirtualSCSIController).GetVirtualSCSIController(), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L229-L256
go
train
// CreateSCSIController creates a new SCSI controller of type name if given, otherwise defaults to lsilogic.
func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error)
// CreateSCSIController creates a new SCSI controller of type name if given, otherwise defaults to lsilogic. func (l VirtualDeviceList) CreateSCSIController(name string) (types.BaseVirtualDevice, error)
{ ctypes := SCSIControllerTypes() if name == "" || name == "scsi" { name = ctypes.Type(ctypes[0]) } else if name == "virtualscsi" { name = "pvscsi" // ovf VirtualSCSI mapping } found := ctypes.Select(func(device types.BaseVirtualDevice) bool { return l.Type(device) == name }) if len(found) == 0 { return nil, fmt.Errorf("unknown SCSI controller type '%s'", name) } c, ok := found[0].(types.BaseVirtualSCSIController) if !ok { return nil, fmt.Errorf("invalid SCSI controller type '%s'", name) } scsi := c.GetVirtualSCSIController() scsi.BusNumber = l.newSCSIBusNumber() scsi.Key = l.NewKey() scsi.ScsiCtlrUnitNumber = 7 return c.(types.BaseVirtualDevice), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L262-L281
go
train
// newSCSIBusNumber returns the bus number to use for adding a new SCSI bus device. // -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newSCSIBusNumber() int32
// newSCSIBusNumber returns the bus number to use for adding a new SCSI bus device. // -1 is returned if there are no bus numbers available. func (l VirtualDeviceList) newSCSIBusNumber() int32
{ var used []int for _, d := range l.SelectByType((*types.VirtualSCSIController)(nil)) { num := d.(types.BaseVirtualSCSIController).GetVirtualSCSIController().BusNumber if num >= 0 { used = append(used, int(num)) } // else caller is creating a new vm using SCSIControllerTypes } sort.Ints(used) for i, n := range scsiBusNumbers { if i == len(used) || n != used[i] { return int32(n) } } return -1 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L307-L313
go
train
// CreateNVMEController creates a new NVMWE controller.
func (l VirtualDeviceList) CreateNVMEController() (types.BaseVirtualDevice, error)
// CreateNVMEController creates a new NVMWE controller. func (l VirtualDeviceList) CreateNVMEController() (types.BaseVirtualDevice, error)
{ nvme := &types.VirtualNVMEController{} nvme.BusNumber = l.newNVMEBusNumber() nvme.Key = l.NewKey() return nvme, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L319-L338
go
train
// newNVMEBusNumber returns the bus number to use for adding a new NVME bus device. // -1 is returned if there are no bus numbers available.
func (l VirtualDeviceList) newNVMEBusNumber() int32
// newNVMEBusNumber returns the bus number to use for adding a new NVME bus device. // -1 is returned if there are no bus numbers available. func (l VirtualDeviceList) newNVMEBusNumber() int32
{ var used []int for _, d := range l.SelectByType((*types.VirtualNVMEController)(nil)) { num := d.(types.BaseVirtualController).GetVirtualController().BusNumber if num >= 0 { used = append(used, int(num)) } // else caller is creating a new vm using NVMEControllerTypes } sort.Ints(used) for i, n := range nvmeBusNumbers { if i == len(used) || n != used[i] { return int32(n) } } return -1 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L341-L355
go
train
// FindDiskController will find an existing ide or scsi disk controller.
func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error)
// FindDiskController will find an existing ide or scsi disk controller. func (l VirtualDeviceList) FindDiskController(name string) (types.BaseVirtualController, error)
{ switch { case name == "ide": return l.FindIDEController("") case name == "scsi" || name == "": return l.FindSCSIController("") case name == "nvme": return l.FindNVMEController("") default: if c, ok := l.Find(name).(types.BaseVirtualController); ok { return c, nil } return nil, fmt.Errorf("%s is not a valid controller", name) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L359-L380
go
train
// PickController returns a controller of the given type(s). // If no controllers are found or have no available slots, then nil is returned.
func (l VirtualDeviceList) PickController(kind types.BaseVirtualController) types.BaseVirtualController
// PickController returns a controller of the given type(s). // If no controllers are found or have no available slots, then nil is returned. func (l VirtualDeviceList) PickController(kind types.BaseVirtualController) types.BaseVirtualController
{ l = l.SelectByType(kind.(types.BaseVirtualDevice)).Select(func(device types.BaseVirtualDevice) bool { num := len(device.(types.BaseVirtualController).GetVirtualController().Device) switch device.(type) { case types.BaseVirtualSCSIController: return num < 15 case *types.VirtualIDEController: return num < 2 case *types.VirtualNVMEController: return num < 8 default: return true } }) if len(l) == 0 { return nil } return l[0].(types.BaseVirtualController) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L383-L409
go
train
// newUnitNumber returns the unit number to use for attaching a new device to the given controller.
func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController) int32
// newUnitNumber returns the unit number to use for attaching a new device to the given controller. func (l VirtualDeviceList) newUnitNumber(c types.BaseVirtualController) int32
{ units := make([]bool, 30) switch sc := c.(type) { case types.BaseVirtualSCSIController: // The SCSI controller sits on its own bus units[sc.GetVirtualSCSIController().ScsiCtlrUnitNumber] = true } key := c.GetVirtualController().Key for _, device := range l { d := device.GetVirtualDevice() if d.ControllerKey == key && d.UnitNumber != nil { units[int(*d.UnitNumber)] = true } } for unit, used := range units { if !used { return int32(unit) } } return -1 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L416-L427
go
train
// NewKey returns the key to use for adding a new device to the device list. // The device list we're working with here may not be complete (e.g. when // we're only adding new devices), so any positive keys could conflict with device keys // that are already in use. To avoid this type of conflict, we can use negative keys // here, which will be resolved to positive keys by vSphere as the reconfiguration is done.
func (l VirtualDeviceList) NewKey() int32
// NewKey returns the key to use for adding a new device to the device list. // The device list we're working with here may not be complete (e.g. when // we're only adding new devices), so any positive keys could conflict with device keys // that are already in use. To avoid this type of conflict, we can use negative keys // here, which will be resolved to positive keys by vSphere as the reconfiguration is done. func (l VirtualDeviceList) NewKey() int32
{ var key int32 = -200 for _, device := range l { d := device.GetVirtualDevice() if d.Key < key { key = d.Key } } return key - 1 }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L430-L438
go
train
// AssignController assigns a device to a controller.
func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController)
// AssignController assigns a device to a controller. func (l VirtualDeviceList) AssignController(device types.BaseVirtualDevice, c types.BaseVirtualController)
{ d := device.GetVirtualDevice() d.ControllerKey = c.GetVirtualController().Key d.UnitNumber = new(int32) *d.UnitNumber = l.newUnitNumber(c) if d.Key == 0 { d.Key = -1 } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L441-L463
go
train
// CreateDisk creates a new VirtualDisk device which can be added to a VM.
func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk
// CreateDisk creates a new VirtualDisk device which can be added to a VM. func (l VirtualDeviceList) CreateDisk(c types.BaseVirtualController, ds types.ManagedObjectReference, name string) *types.VirtualDisk
{ // If name is not specified, one will be chosen for you. // But if when given, make sure it ends in .vmdk, otherwise it will be treated as a directory. if len(name) > 0 && filepath.Ext(name) != ".vmdk" { name += ".vmdk" } device := &types.VirtualDisk{ VirtualDevice: types.VirtualDevice{ Backing: &types.VirtualDiskFlatVer2BackingInfo{ DiskMode: string(types.VirtualDiskModePersistent), ThinProvisioned: types.NewBool(true), VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: name, Datastore: &ds, }, }, }, } l.AssignController(device, c) return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L466-L485
go
train
// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM.
func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk
// ChildDisk creates a new VirtualDisk device, linked to the given parent disk, which can be added to a VM. func (l VirtualDeviceList) ChildDisk(parent *types.VirtualDisk) *types.VirtualDisk
{ disk := *parent backing := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo) p := new(DatastorePath) p.FromString(backing.FileName) p.Path = "" // Use specified disk as parent backing to a new disk. disk.Backing = &types.VirtualDiskFlatVer2BackingInfo{ VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: p.String(), Datastore: backing.Datastore, }, Parent: backing, DiskMode: backing.DiskMode, ThinProvisioned: backing.ThinProvisioned, } return &disk }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L500-L502
go
train
// Connect changes the device to connected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error
// Connect changes the device to connected, returns an error if the device is not connectable. func (l VirtualDeviceList) Connect(device types.BaseVirtualDevice) error
{ return l.connectivity(device, true) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L505-L507
go
train
// Disconnect changes the device to disconnected, returns an error if the device is not connectable.
func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error
// Disconnect changes the device to disconnected, returns an error if the device is not connectable. func (l VirtualDeviceList) Disconnect(device types.BaseVirtualDevice) error
{ return l.connectivity(device, false) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L510-L528
go
train
// FindCdrom finds a cdrom device with the given name, defaulting to the first cdrom device if any.
func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error)
// FindCdrom finds a cdrom device with the given name, defaulting to the first cdrom device if any. func (l VirtualDeviceList) FindCdrom(name string) (*types.VirtualCdrom, error)
{ if name != "" { d := l.Find(name) if d == nil { return nil, fmt.Errorf("device '%s' not found", name) } if c, ok := d.(*types.VirtualCdrom); ok { return c, nil } return nil, fmt.Errorf("%s is not a cdrom device", name) } c := l.SelectByType((*types.VirtualCdrom)(nil)) if len(c) == 0 { return nil, errors.New("no cdrom device found") } return c[0].(*types.VirtualCdrom), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L531-L545
go
train
// CreateCdrom creates a new VirtualCdrom device which can be added to a VM.
func (l VirtualDeviceList) CreateCdrom(c *types.VirtualIDEController) (*types.VirtualCdrom, error)
// CreateCdrom creates a new VirtualCdrom device which can be added to a VM. func (l VirtualDeviceList) CreateCdrom(c *types.VirtualIDEController) (*types.VirtualCdrom, error)
{ device := &types.VirtualCdrom{} l.AssignController(device, c) l.setDefaultCdromBacking(device) device.Connectable = &types.VirtualDeviceConnectInfo{ AllowGuestControl: true, Connected: true, StartConnected: true, } return device, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L548-L556
go
train
// InsertIso changes the cdrom device backing to use the given iso file.
func (l VirtualDeviceList) InsertIso(device *types.VirtualCdrom, iso string) *types.VirtualCdrom
// InsertIso changes the cdrom device backing to use the given iso file. func (l VirtualDeviceList) InsertIso(device *types.VirtualCdrom, iso string) *types.VirtualCdrom
{ device.Backing = &types.VirtualCdromIsoBackingInfo{ VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: iso, }, } return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L559-L562
go
train
// EjectIso removes the iso file based backing and replaces with the default cdrom backing.
func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom
// EjectIso removes the iso file based backing and replaces with the default cdrom backing. func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom
{ l.setDefaultCdromBacking(device) return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L595-L614
go
train
// CreateFloppy creates a new VirtualFloppy device which can be added to a VM.
func (l VirtualDeviceList) CreateFloppy() (*types.VirtualFloppy, error)
// CreateFloppy creates a new VirtualFloppy device which can be added to a VM. func (l VirtualDeviceList) CreateFloppy() (*types.VirtualFloppy, error)
{ device := &types.VirtualFloppy{} c := l.PickController((*types.VirtualSIOController)(nil)) if c == nil { return nil, errors.New("no available SIO controller") } l.AssignController(device, c) l.setDefaultFloppyBacking(device) device.Connectable = &types.VirtualDeviceConnectInfo{ AllowGuestControl: true, Connected: true, StartConnected: true, } return device, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L617-L625
go
train
// InsertImg changes the floppy device backing to use the given img file.
func (l VirtualDeviceList) InsertImg(device *types.VirtualFloppy, img string) *types.VirtualFloppy
// InsertImg changes the floppy device backing to use the given img file. func (l VirtualDeviceList) InsertImg(device *types.VirtualFloppy, img string) *types.VirtualFloppy
{ device.Backing = &types.VirtualFloppyImageBackingInfo{ VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: img, }, } return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L628-L631
go
train
// EjectImg removes the img file based backing and replaces with the default floppy backing.
func (l VirtualDeviceList) EjectImg(device *types.VirtualFloppy) *types.VirtualFloppy
// EjectImg removes the img file based backing and replaces with the default floppy backing. func (l VirtualDeviceList) EjectImg(device *types.VirtualFloppy) *types.VirtualFloppy
{ l.setDefaultFloppyBacking(device) return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L664-L679
go
train
// CreateSerialPort creates a new VirtualSerialPort device which can be added to a VM.
func (l VirtualDeviceList) CreateSerialPort() (*types.VirtualSerialPort, error)
// CreateSerialPort creates a new VirtualSerialPort device which can be added to a VM. func (l VirtualDeviceList) CreateSerialPort() (*types.VirtualSerialPort, error)
{ device := &types.VirtualSerialPort{ YieldOnPoll: true, } c := l.PickController((*types.VirtualSIOController)(nil)) if c == nil { return nil, errors.New("no available SIO controller") } l.AssignController(device, c) l.setDefaultSerialPortBacking(device) return device, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L682-L707
go
train
// ConnectSerialPort connects a serial port to a server or client uri.
func (l VirtualDeviceList) ConnectSerialPort(device *types.VirtualSerialPort, uri string, client bool, proxyuri string) *types.VirtualSerialPort
// ConnectSerialPort connects a serial port to a server or client uri. func (l VirtualDeviceList) ConnectSerialPort(device *types.VirtualSerialPort, uri string, client bool, proxyuri string) *types.VirtualSerialPort
{ if strings.HasPrefix(uri, "[") { device.Backing = &types.VirtualSerialPortFileBackingInfo{ VirtualDeviceFileBackingInfo: types.VirtualDeviceFileBackingInfo{ FileName: uri, }, } return device } direction := types.VirtualDeviceURIBackingOptionDirectionServer if client { direction = types.VirtualDeviceURIBackingOptionDirectionClient } device.Backing = &types.VirtualSerialPortURIBackingInfo{ VirtualDeviceURIBackingInfo: types.VirtualDeviceURIBackingInfo{ Direction: string(direction), ServiceURI: uri, ProxyURI: proxyuri, }, } return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L710-L713
go
train
// DisconnectSerialPort disconnects the serial port backing.
func (l VirtualDeviceList) DisconnectSerialPort(device *types.VirtualSerialPort) *types.VirtualSerialPort
// DisconnectSerialPort disconnects the serial port backing. func (l VirtualDeviceList) DisconnectSerialPort(device *types.VirtualSerialPort) *types.VirtualSerialPort
{ l.setDefaultSerialPortBacking(device) return device }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L725-L748
go
train
// CreateEthernetCard creates a new VirtualEthernetCard of the given name name and initialized with the given backing.
func (l VirtualDeviceList) CreateEthernetCard(name string, backing types.BaseVirtualDeviceBackingInfo) (types.BaseVirtualDevice, error)
// CreateEthernetCard creates a new VirtualEthernetCard of the given name name and initialized with the given backing. func (l VirtualDeviceList) CreateEthernetCard(name string, backing types.BaseVirtualDeviceBackingInfo) (types.BaseVirtualDevice, error)
{ ctypes := EthernetCardTypes() if name == "" { name = ctypes.deviceName(ctypes[0]) } found := ctypes.Select(func(device types.BaseVirtualDevice) bool { return l.deviceName(device) == name }) if len(found) == 0 { return nil, fmt.Errorf("unknown ethernet card type '%s'", name) } c, ok := found[0].(types.BaseVirtualEthernetCard) if !ok { return nil, fmt.Errorf("invalid ethernet card type '%s'", name) } c.GetVirtualEthernetCard().Backing = backing return c.(types.BaseVirtualDevice), nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L751-L759
go
train
// PrimaryMacAddress returns the MacAddress field of the primary VirtualEthernetCard
func (l VirtualDeviceList) PrimaryMacAddress() string
// PrimaryMacAddress returns the MacAddress field of the primary VirtualEthernetCard func (l VirtualDeviceList) PrimaryMacAddress() string
{ eth0 := l.Find("ethernet-0") if eth0 == nil { return "" } return eth0.(types.BaseVirtualEthernetCard).GetVirtualEthernetCard().MacAddress }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L787-L814
go
train
// BootOrder returns a list of devices which can be used to set boot order via VirtualMachine.SetBootOptions. // The order can be any of "ethernet", "cdrom", "floppy" or "disk" or by specific device name. // A value of "-" will clear the existing boot order on the VC/ESX side.
func (l VirtualDeviceList) BootOrder(order []string) []types.BaseVirtualMachineBootOptionsBootableDevice
// BootOrder returns a list of devices which can be used to set boot order via VirtualMachine.SetBootOptions. // The order can be any of "ethernet", "cdrom", "floppy" or "disk" or by specific device name. // A value of "-" will clear the existing boot order on the VC/ESX side. func (l VirtualDeviceList) BootOrder(order []string) []types.BaseVirtualMachineBootOptionsBootableDevice
{ var devices []types.BaseVirtualMachineBootOptionsBootableDevice for _, name := range order { if kind, ok := bootableDevices[name]; ok { if name == DeviceTypeNone { // Not covered in the API docs, nor obvious, but this clears the boot order on the VC/ESX side. devices = append(devices, new(types.VirtualMachineBootOptionsBootableDevice)) continue } for _, device := range l { if l.Type(device) == name { devices = append(devices, kind(device)) } } continue } if d := l.Find(name); d != nil { if kind, ok := bootableDevices[l.Type(d)]; ok { devices = append(devices, kind(d)) } } } return devices }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L817-L831
go
train
// SelectBootOrder returns an ordered list of devices matching the given bootable device order
func (l VirtualDeviceList) SelectBootOrder(order []types.BaseVirtualMachineBootOptionsBootableDevice) VirtualDeviceList
// SelectBootOrder returns an ordered list of devices matching the given bootable device order func (l VirtualDeviceList) SelectBootOrder(order []types.BaseVirtualMachineBootOptionsBootableDevice) VirtualDeviceList
{ var devices VirtualDeviceList for _, bd := range order { for _, device := range l { if kind, ok := bootableDevices[l.Type(device)]; ok { if reflect.DeepEqual(kind(device), bd) { devices = append(devices, device) } } } } return devices }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L834-L840
go
train
// TypeName returns the vmodl type name of the device
func (l VirtualDeviceList) TypeName(device types.BaseVirtualDevice) string
// TypeName returns the vmodl type name of the device func (l VirtualDeviceList) TypeName(device types.BaseVirtualDevice) string
{ dtype := reflect.TypeOf(device) if dtype == nil { return "" } return dtype.Elem().Name() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L857-L870
go
train
// Type returns a human-readable name for the given device
func (l VirtualDeviceList) Type(device types.BaseVirtualDevice) string
// Type returns a human-readable name for the given device func (l VirtualDeviceList) Type(device types.BaseVirtualDevice) string
{ switch device.(type) { case types.BaseVirtualEthernetCard: return DeviceTypeEthernet case *types.ParaVirtualSCSIController: return "pvscsi" case *types.VirtualLsiLogicSASController: return "lsilogic-sas" case *types.VirtualNVMEController: return "nvme" default: return l.deviceName(device) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L873-L892
go
train
// Name returns a stable, human-readable name for the given device
func (l VirtualDeviceList) Name(device types.BaseVirtualDevice) string
// Name returns a stable, human-readable name for the given device func (l VirtualDeviceList) Name(device types.BaseVirtualDevice) string
{ var key string var UnitNumber int32 d := device.GetVirtualDevice() if d.UnitNumber != nil { UnitNumber = *d.UnitNumber } dtype := l.Type(device) switch dtype { case DeviceTypeEthernet: key = fmt.Sprintf("%d", UnitNumber-7) case DeviceTypeDisk: key = fmt.Sprintf("%d-%d", d.ControllerKey, UnitNumber) default: key = fmt.Sprintf("%d", d.Key) } return fmt.Sprintf("%s-%s", dtype, key) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/virtual_device_list.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/virtual_device_list.go#L896-L937
go
train
// ConfigSpec creates a virtual machine configuration spec for // the specified operation, for the list of devices in the device list.
func (l VirtualDeviceList) ConfigSpec(op types.VirtualDeviceConfigSpecOperation) ([]types.BaseVirtualDeviceConfigSpec, error)
// ConfigSpec creates a virtual machine configuration spec for // the specified operation, for the list of devices in the device list. func (l VirtualDeviceList) ConfigSpec(op types.VirtualDeviceConfigSpecOperation) ([]types.BaseVirtualDeviceConfigSpec, error)
{ var fop types.VirtualDeviceConfigSpecFileOperation switch op { case types.VirtualDeviceConfigSpecOperationAdd: fop = types.VirtualDeviceConfigSpecFileOperationCreate case types.VirtualDeviceConfigSpecOperationEdit: fop = types.VirtualDeviceConfigSpecFileOperationReplace case types.VirtualDeviceConfigSpecOperationRemove: fop = types.VirtualDeviceConfigSpecFileOperationDestroy default: panic("unknown op") } var res []types.BaseVirtualDeviceConfigSpec for _, device := range l { config := &types.VirtualDeviceConfigSpec{ Device: device, Operation: op, } if disk, ok := device.(*types.VirtualDisk); ok { config.FileOperation = fop // Special case to attach an existing disk if op == types.VirtualDeviceConfigSpecOperationAdd && disk.CapacityInKB == 0 { childDisk := false if b, ok := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo); ok { childDisk = b.Parent != nil } if !childDisk { // Existing disk, clear file operation config.FileOperation = "" } } } res = append(res, config) } return res, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/session/login.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/session/login.go#L134-L139
go
train
// Logout is called by cli.Run() // We override ClientFlag's Logout impl to avoid ending a session when -persist-session=false, // otherwise Logout would invalidate the cookie and/or ticket.
func (cmd *login) Logout(ctx context.Context) error
// Logout is called by cli.Run() // We override ClientFlag's Logout impl to avoid ending a session when -persist-session=false, // otherwise Logout would invalidate the cookie and/or ticket. func (cmd *login) Logout(ctx context.Context) error
{ if cmd.long || cmd.clone || cmd.issue { return nil } return cmd.ClientFlag.Logout(ctx) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/opaque_network.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/opaque_network.go#L39-L57
go
train
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n OpaqueNetwork) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network func (n OpaqueNetwork) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
{ var net mo.OpaqueNetwork if err := n.Properties(ctx, n.Reference(), []string{"summary"}, &net); err != nil { return nil, err } summary, ok := net.Summary.(*types.OpaqueNetworkSummary) if !ok { return nil, fmt.Errorf("%s unsupported network type: %T", n, net.Summary) } backing := &types.VirtualEthernetCardOpaqueNetworkBackingInfo{ OpaqueNetworkId: summary.OpaqueNetworkId, OpaqueNetworkType: summary.OpaqueNetworkType, } return backing, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L36-L41
go
train
// NewHostCertificateManager creates a new HostCertificateManager helper
func NewHostCertificateManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostCertificateManager
// NewHostCertificateManager creates a new HostCertificateManager helper func NewHostCertificateManager(c *vim25.Client, ref types.ManagedObjectReference, host types.ManagedObjectReference) *HostCertificateManager
{ return &HostCertificateManager{ Common: NewCommon(c, ref), Host: NewHostSystem(c, host), } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L45-L62
go
train
// CertificateInfo wraps the host CertificateManager certificateInfo property with the HostCertificateInfo helper. // The ThumbprintSHA1 field is set to HostSystem.Summary.Config.SslThumbprint if the host system is managed by a vCenter.
func (m HostCertificateManager) CertificateInfo(ctx context.Context) (*HostCertificateInfo, error)
// CertificateInfo wraps the host CertificateManager certificateInfo property with the HostCertificateInfo helper. // The ThumbprintSHA1 field is set to HostSystem.Summary.Config.SslThumbprint if the host system is managed by a vCenter. func (m HostCertificateManager) CertificateInfo(ctx context.Context) (*HostCertificateInfo, error)
{ var hs mo.HostSystem var cm mo.HostCertificateManager pc := property.DefaultCollector(m.Client()) err := pc.RetrieveOne(ctx, m.Reference(), []string{"certificateInfo"}, &cm) if err != nil { return nil, err } _ = pc.RetrieveOne(ctx, m.Host.Reference(), []string{"summary.config.sslThumbprint"}, &hs) return &HostCertificateInfo{ HostCertificateManagerCertificateInfo: cm.CertificateInfo, ThumbprintSHA1: hs.Summary.Config.SslThumbprint, }, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L67-L79
go
train
// GenerateCertificateSigningRequest requests the host system to generate a certificate-signing request (CSR) for itself. // The CSR is then typically provided to a Certificate Authority to sign and issue the SSL certificate for the host system. // Use InstallServerCertificate to import this certificate.
func (m HostCertificateManager) GenerateCertificateSigningRequest(ctx context.Context, useIPAddressAsCommonName bool) (string, error)
// GenerateCertificateSigningRequest requests the host system to generate a certificate-signing request (CSR) for itself. // The CSR is then typically provided to a Certificate Authority to sign and issue the SSL certificate for the host system. // Use InstallServerCertificate to import this certificate. func (m HostCertificateManager) GenerateCertificateSigningRequest(ctx context.Context, useIPAddressAsCommonName bool) (string, error)
{ req := types.GenerateCertificateSigningRequest{ This: m.Reference(), UseIpAddressAsCommonName: useIPAddressAsCommonName, } res, err := methods.GenerateCertificateSigningRequest(ctx, m.Client(), &req) if err != nil { return "", err } return res.Returnval, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L83-L95
go
train
// GenerateCertificateSigningRequestByDn requests the host system to generate a certificate-signing request (CSR) for itself. // Alternative version similar to GenerateCertificateSigningRequest but takes a Distinguished Name (DN) as a parameter.
func (m HostCertificateManager) GenerateCertificateSigningRequestByDn(ctx context.Context, distinguishedName string) (string, error)
// GenerateCertificateSigningRequestByDn requests the host system to generate a certificate-signing request (CSR) for itself. // Alternative version similar to GenerateCertificateSigningRequest but takes a Distinguished Name (DN) as a parameter. func (m HostCertificateManager) GenerateCertificateSigningRequestByDn(ctx context.Context, distinguishedName string) (string, error)
{ req := types.GenerateCertificateSigningRequestByDn{ This: m.Reference(), DistinguishedName: distinguishedName, } res, err := methods.GenerateCertificateSigningRequestByDn(ctx, m.Client(), &req) if err != nil { return "", err } return res.Returnval, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L98-L121
go
train
// InstallServerCertificate imports the given SSL certificate to the host system.
func (m HostCertificateManager) InstallServerCertificate(ctx context.Context, cert string) error
// InstallServerCertificate imports the given SSL certificate to the host system. func (m HostCertificateManager) InstallServerCertificate(ctx context.Context, cert string) error
{ req := types.InstallServerCertificate{ This: m.Reference(), Cert: cert, } _, err := methods.InstallServerCertificate(ctx, m.Client(), &req) if err != nil { return err } // NotifyAffectedService is internal, not exposing as we don't have a use case other than with InstallServerCertificate // Without this call, hostd needs to be restarted to use the updated certificate // Note: using Refresh as it has the same struct/signature, we just need to use different xml name tags body := struct { Req *types.Refresh `xml:"urn:vim25 NotifyAffectedServices,omitempty"` Res *types.RefreshResponse `xml:"urn:vim25 NotifyAffectedServicesResponse,omitempty"` methods.RefreshBody }{ Req: &types.Refresh{This: m.Reference()}, } return m.Client().RoundTrip(ctx, &body, &body) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L124-L135
go
train
// ListCACertificateRevocationLists returns the SSL CRLs of Certificate Authorities that are trusted by the host system.
func (m HostCertificateManager) ListCACertificateRevocationLists(ctx context.Context) ([]string, error)
// ListCACertificateRevocationLists returns the SSL CRLs of Certificate Authorities that are trusted by the host system. func (m HostCertificateManager) ListCACertificateRevocationLists(ctx context.Context) ([]string, error)
{ req := types.ListCACertificateRevocationLists{ This: m.Reference(), } res, err := methods.ListCACertificateRevocationLists(ctx, m.Client(), &req) if err != nil { return nil, err } return res.Returnval, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
object/host_certificate_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/object/host_certificate_manager.go#L153-L162
go
train
// ReplaceCACertificatesAndCRLs replaces the trusted CA certificates and CRL used by the host system. // These determine whether the server can verify the identity of an external entity.
func (m HostCertificateManager) ReplaceCACertificatesAndCRLs(ctx context.Context, caCert []string, caCrl []string) error
// ReplaceCACertificatesAndCRLs replaces the trusted CA certificates and CRL used by the host system. // These determine whether the server can verify the identity of an external entity. func (m HostCertificateManager) ReplaceCACertificatesAndCRLs(ctx context.Context, caCert []string, caCrl []string) error
{ req := types.ReplaceCACertificatesAndCRLs{ This: m.Reference(), CaCert: caCert, CaCrl: caCrl, } _, err := methods.ReplaceCACertificatesAndCRLs(ctx, m.Client(), &req) return err }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/session_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/session_manager.go#L265-L271
go
train
// mapSession maps an HTTP cookie to a Session.
func (c *Context) mapSession()
// mapSession maps an HTTP cookie to a Session. func (c *Context) mapSession()
{ if cookie, err := c.req.Cookie(soap.SessionCookieName); err == nil { if val, ok := c.svc.sm.sessions[cookie.Value]; ok { c.SetSession(val, false) } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/session_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/session_manager.go#L274-L296
go
train
// SetSession should be called after successful authentication.
func (c *Context) SetSession(session Session, login bool)
// SetSession should be called after successful authentication. func (c *Context) SetSession(session Session, login bool)
{ session.UserAgent = c.req.UserAgent() session.IpAddress = strings.Split(c.req.RemoteAddr, ":")[0] session.LastActiveTime = time.Now() session.CallCount++ c.svc.sm.sessions[session.Key] = session c.Session = &session if login { http.SetCookie(c.res, &http.Cookie{ Name: soap.SessionCookieName, Value: session.Key, }) c.postEvent(&types.UserLoginSessionEvent{ SessionId: session.Key, IpAddress: session.IpAddress, UserAgent: session.UserAgent, Locale: session.Locale, }) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/session_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/session_manager.go#L299-L306
go
train
// WithLock holds a lock for the given object while then given function is run.
func (c *Context) WithLock(obj mo.Reference, f func())
// WithLock holds a lock for the given object while then given function is run. func (c *Context) WithLock(obj mo.Reference, f func())
{ if c.Caller != nil && *c.Caller == obj.Reference() { // Internal method invocation, obj is already locked f() return } Map.WithLock(obj, f) }