Best Got code snippet using example_test.TestUtils
mock_runner.go
Source:mock_runner.go
1package shell2import (3 "fmt"4 "github.com/broadinstitute/thelma/internal/thelma/utils/testutils"5 "github.com/davecgh/go-spew/spew"6 "github.com/rs/zerolog/log"7 "github.com/stretchr/testify/mock"8 "io"9 "os"10 "strings"11 "sync"12 "testing"13)14//15// The shellmock package makes it easy to mock shell commands in unit tests with testify/mock.16//17// See example_test.go for example usage.18//19// Shellmock contains a mock implementation of the shell.Runner interface, called MockRunner.20// Unlike testify's out-of-the-box mock implementation, MockRunner can verify that shell21// commands are run in a specific order.22//23// CmdDumpStyle how to style commands when they are printed to the console24type CmdDumpStyle int25// Default prints the command using "%v"26// Pretty formats commands using PrettyFormat27// Spew uses the spew library to spew the entire struct28const (29 Default CmdDumpStyle = iota30 Pretty31 Spew32)33// options for a MockRunner34type MockOptions struct {35 VerifyOrder bool // VerifyOrder If true, verify commands are run in the order they were declared36 DumpStyle CmdDumpStyle // DumpStyle how to style the dump37 IgnoreEnvVars []string // Array of environment variable names to strip when matching shell.Command arguments38 IgnoreDir bool // If true, ignore Dir field of shell.Command arguments39}40// MockRunner is an implementation of Runner interface for use with testify/mock.41type MockRunner struct {42 options MockOptions43 ignoreEnvVars map[string]struct{}44 expectedCommands []*expectedCommand45 runCounter int46 t *testing.T47 mutex sync.Mutex48 mock.Mock49}50type expectedCommand struct {51 cmd Command52 matchCount int53}54// DefaultMockRunner returns a new mock runner instance with default settings55func DefaultMockRunner() *MockRunner {56 options := MockOptions{57 VerifyOrder: true,58 }59 return NewMockRunner(options)60}61// NewMockRunner constructor for MockRunner62func NewMockRunner(options MockOptions) *MockRunner {63 m := new(MockRunner)64 m.options = options65 // convert ignoreEnvVars from array to map for fast lookups66 m.ignoreEnvVars = make(map[string]struct{}, len(m.options.IgnoreEnvVars))67 for _, name := range m.options.IgnoreEnvVars {68 m.ignoreEnvVars[name] = struct{}{}69 }70 return m71}72// CmdFromFmt Convenience function to build a shell.Command from a format string and arguments73//74// Eg. CmdFromFmt("HOME=%s FOO=BAR ls -al %s", "/tmp", "Documents")75// ->76// Command{77// Env: []string{"HOME=/tmp", "FOO=BAR"},78// Prog: "ls",79// Args: []string{"-al", "Documents},80// Dir: ""81// }82func CmdFromFmt(fmt string, args ...interface{}) Command {83 tokens := testutils.Args(fmt, args...)84 return CmdFromArgs(tokens...)85}86// CmdFromArgs Convenience function to build a shell.Command from a list of arguments87//88// Eg. CmdFromArgs("FOO=BAR", "ls", "-al", ".")89// ->90// Command{91// Env: []string{"FOO=BAR"},92// Prog: "ls",93// Args: []string{"-al", "."},94// Dir: ""95// }96func CmdFromArgs(args ...string) Command {97 // count number of leading NAME=VALUE environment var pairs preceding command98 var i int99 for i = 0; i < len(args); i++ {100 if !strings.Contains(args[i], "=") {101 // if this is not a NAME=VALUE pair, exit102 break103 }104 }105 numEnvVars := i106 progIndex := i107 numArgs := len(args) - (numEnvVars + 1)108 var cmd Command109 if numEnvVars > 0 {110 cmd.Env = args[0:numEnvVars]111 }112 if progIndex < len(args) {113 cmd.Prog = args[progIndex]114 }115 if numArgs > 0 {116 cmd.Args = args[progIndex+1:]117 }118 return cmd119}120// Run Instead of executing the command, logs an info message and registers the call with testify mock121func (m *MockRunner) Run(cmd Command, options ...RunOption) error {122 // collate options123 opts := defaultRunOptions()124 for _, option := range options {125 option(&opts)126 }127 log.Info().Msgf("[MockRunner] Command: %q\n", cmd.PrettyFormat())128 // Remove ignored attributes129 cmd = m.applyIgnores(cmd)130 // we synchronize Run calls on the mock because testify mock isn't safe for concurrent access, and neither are our131 // order verification callback hooks132 m.mutex.Lock()133 defer m.mutex.Unlock()134 args := m.Mock.Called(cmd, opts)135 if len(args) > 0 {136 return args.Error(0)137 }138 return nil139}140// ExpectCmd sets an expectation for a command that should be run.141func (m *MockRunner) ExpectCmd(cmd Command) *Call {142 cmd = m.applyIgnores(cmd)143 mockCall := m.Mock.On("Run", cmd, mock.AnythingOfType("RunOptions"))144 callWrapper := &Call{145 command: cmd,146 Call: mockCall,147 }148 order := len(m.expectedCommands)149 expected := &expectedCommand{cmd: cmd}150 m.expectedCommands = append(m.expectedCommands, expected)151 callWrapper.Run(func(args mock.Arguments) {152 if m.options.VerifyOrder {153 if m.runCounter != order { // this command is out of order154 if m.runCounter < len(m.expectedCommands) { // we have remaining expectations155 err := fmt.Errorf(156 "Command received out of order (%d instead of %d). Expected:\n%v\nReceived:\n%v",157 m.runCounter,158 order,159 m.expectedCommands[m.runCounter].cmd,160 cmd,161 )162 m.panicOrFailNow(err)163 }164 }165 }166 if err := callWrapper.writeMockOutput(args); err != nil {167 m.panicOrFailNow(err)168 }169 expected.matchCount++170 m.runCounter++171 }).Once()172 return callWrapper173}174// Test decorates Testify's mock.Mock#Test() function by adding a cleanup hook to the test object175// that dumps the set of expected command matchers to stderr in the event of a test failure.176// This is useful because most command matchers are functions and so Testify can't generate177// a pretty diff for them; you end up with:178// (shell.Command={...}) not matched by func(Command) bool179//180func (m *MockRunner) Test(t *testing.T) {181 m.t = t182 t.Cleanup(func() {183 if t.Failed() {184 if err := m.dumpExpectedCmds(os.Stderr); err != nil {185 t.Error(err)186 }187 }188 })189 m.Mock.Test(t)190}191func (m *MockRunner) applyIgnores(cmd Command) Command {192 if m.options.IgnoreDir {193 cmd.Dir = ""194 }195 if len(m.ignoreEnvVars) == 0 {196 return cmd197 }198 var env []string199 for _, pair := range cmd.Env {200 tokens := strings.SplitN(pair, "=", 2)201 name := tokens[0]202 // if env var is not in ignore list, keep it203 if _, exists := m.ignoreEnvVars[name]; !exists {204 env = append(env, pair)205 }206 }207 cmd.Env = env208 return cmd209}210func (m *MockRunner) dumpExpectedCmds(w io.Writer) error {211 if _, err := fmt.Fprint(w, "\n\nExpected commands:\n\n"); err != nil {212 return err213 }214 for i, ec := range m.expectedCommands {215 if err := m.dumpExpectedCmd(w, i, ec); err != nil {216 return err217 }218 }219 return nil220}221func (m *MockRunner) dumpExpectedCmd(w io.Writer, index int, expected *expectedCommand) error {222 cmd := expected.cmd223 switch m.options.DumpStyle {224 case Default:225 if _, err := fmt.Fprintf(w, "\t%d (%d matches):\n\t%#v\n\n", index, expected.matchCount, cmd); err != nil {226 return err227 }228 case Pretty:229 if _, err := fmt.Fprintf(w, "\t%d (%d matches): %s\n\n", index, expected.matchCount, cmd.PrettyFormat()); err != nil {230 return err231 }232 case Spew:233 if _, err := fmt.Fprintf(w, "\t%d (%d matches): %s\n\n", index, expected.matchCount, cmd.PrettyFormat()); err != nil {234 return err235 }236 scs := spew.ConfigState{237 Indent: "\t",238 DisableCapacities: true,239 DisablePointerAddresses: true,240 }241 scs.Fdump(w, cmd)242 if _, err := fmt.Fprintln(w); err != nil {243 return err244 }245 fmt.Println()246 }247 return nil248}249func (m *MockRunner) panicOrFailNow(err error) {250 if m.t == nil {251 panic(err)252 }253 m.t.Error(err)254 m.t.FailNow()255}...
02_advanced_test.go
Source:02_advanced_test.go
...6func TestChainMethods(t *testing.T) {7 g := setup(t)8 g.Desc("1 must equal 1").Must().Eq(example.Sum("1", "2"), "3")9}10func TestUtils(t *testing.T) {11 g := setup(t)12 // Run "go doc got.Utils" to list available helpers13 s := g.Serve()14 s.Mux.HandleFunc("/", example.ServeSum)15 val := g.Req("", s.URL("?a=1&b=2")).Bytes().String()16 g.Eq(val, "3")17}18func TestTableDriven(t *testing.T) {19 testCases := []struct{ desc, a, b, expected string }{{20 "first",21 "1", "2", "3",22 }, {23 "second",24 "2", "3", "5",...
proof_test.go
Source:proof_test.go
1package example_test2import (3 "fmt"4 "github.com/elliotcourant/arkdb/internal/testutils"5 "github.com/stretchr/testify/assert"6 "testing"7)8func BenchmarkBadgerMassiveInsert(b *testing.B) {9 db, cleanup := testutils.NewDB(b)10 defer cleanup()11 b.ResetTimer()12 for i := 0; i < b.N; i++ {13 tx := db.NewTransaction(true)14 if err := tx.Set(15 []byte(fmt.Sprintf("this would end up being a very large path %d", i)),16 []byte(fmt.Sprintf("asghjsakjgdasgds"))); !assert.NoError(b, err) {17 panic(err)18 }19 tx.Commit()20 }21}...
TestUtils
Using AI Code Generation
1import (2func main() {3 fmt.Println(TestUtils(2))4}5func TestUtils(i int) int {6}7import (8func TestTestUtils(t *testing.T) {9 if TestUtils(2) != 3 {10 t.Error("Expected 3")11 }12}13import (14func TestTestUtils(t *testing.T) {15 if TestUtils(2) != 3 {16 t.Error("Expected 3")17 }18}19import (20func TestTestUtils(t *testing.T) {21 if TestUtils(2) != 3 {22 t.Error("Expected 3")23 }24}25import (26func TestTestUtils(t *testing.T) {27 if TestUtils(2) != 3 {28 t.Error("Expected 3")29 }30}31import (32func TestTestUtils(t *testing.T) {33 if TestUtils(2) != 3 {34 t.Error("Expected 3")35 }36}37import (38func TestTestUtils(t *testing.T) {39 if TestUtils(2) != 3 {40 t.Error("Expected 3")41 }42}43import (44func TestTestUtils(t *testing.T) {45 if TestUtils(2) != 3 {46 t.Error("Expected 3")47 }48}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!