Best Rod code snippet using launcher.Has
launcher.go
Source:launcher.go
...148 return list[0]149 }150 return ""151}152// Has flag or not153func (l *Launcher) Has(name flags.Flag) bool {154 _, has := l.GetFlags(name)155 return has156}157// GetFlags from settings158func (l *Launcher) GetFlags(name flags.Flag) ([]string, bool) {159 flag, has := l.Flags[l.normalizeFlag(name)]160 return flag, has161}162// Append values to the flag163func (l *Launcher) Append(name flags.Flag, values ...string) *Launcher {164 flags, has := l.GetFlags(name)165 if !has {166 flags = []string{}167 }168 return l.Set(name, append(flags, values...)...)169}170// Delete a flag171func (l *Launcher) Delete(name flags.Flag) *Launcher {172 delete(l.Flags, l.normalizeFlag(name))173 return l174}175// Bin of the browser binary path to launch, if the path is not empty the auto download will be disabled176func (l *Launcher) Bin(path string) *Launcher {177 return l.Set(flags.Bin, path)178}179// Revision of the browser to auto download180func (l *Launcher) Revision(rev int) *Launcher {181 l.browser.Revision = rev182 return l183}184// Headless switch. Whether to run browser in headless mode. A mode without visible UI.185func (l *Launcher) Headless(enable bool) *Launcher {186 if enable {187 return l.Set(flags.Headless)188 }189 return l.Delete(flags.Headless)190}191// NoSandbox switch. Whether to run browser in no-sandbox mode.192// Linux users may face "running as root without --no-sandbox is not supported" in some Linux/Chrome combinations. This function helps switch mode easily.193// Be aware disabling sandbox is not trivial. Use at your own risk.194// Related doc: https://bugs.chromium.org/p/chromium/issues/detail?id=638180195func (l *Launcher) NoSandbox(enable bool) *Launcher {196 if enable {197 return l.Set(flags.NoSandbox)198 }199 return l.Delete(flags.NoSandbox)200}201// XVFB enables to run browser in by XVFB. Useful when you want to run headful mode on linux.202func (l *Launcher) XVFB(args ...string) *Launcher {203 return l.Set(flags.XVFB, args...)204}205// Leakless switch. If enabled, the browser will be force killed after the Go process exits.206// The doc of leakless: https://github.com/ysmood/leakless.207func (l *Launcher) Leakless(enable bool) *Launcher {208 if enable {209 return l.Set(flags.Leakless)210 }211 return l.Delete(flags.Leakless)212}213// Devtools switch to auto open devtools for each tab214func (l *Launcher) Devtools(autoOpenForTabs bool) *Launcher {215 if autoOpenForTabs {216 return l.Set("auto-open-devtools-for-tabs")217 }218 return l.Delete("auto-open-devtools-for-tabs")219}220// UserDataDir is where the browser will look for all of its state, such as cookie and cache.221// When set to empty, browser will use current OS home dir.222// Related doc: https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md223func (l *Launcher) UserDataDir(dir string) *Launcher {224 if dir == "" {225 l.Delete(flags.UserDataDir)226 } else {227 l.Set(flags.UserDataDir, dir)228 }229 return l230}231// ProfileDir is the browser profile the browser will use.232// When set to empty, the profile 'Default' is used.233// Related article: https://superuser.com/a/377195234func (l *Launcher) ProfileDir(dir string) *Launcher {235 if dir == "" {236 l.Delete("profile-directory")237 } else {238 l.Set("profile-directory", dir)239 }240 return l241}242// RemoteDebuggingPort to launch the browser. Zero for a random port. Zero is the default value.243// If it's not zero and the Launcher.Leakless is disabled, the launcher will try to reconnect to it first,244// if the reconnection fails it will launch a new browser.245func (l *Launcher) RemoteDebuggingPort(port int) *Launcher {246 return l.Set(flags.RemoteDebuggingPort, fmt.Sprintf("%d", port))247}248// Proxy switch. When disabled leakless will be disabled.249func (l *Launcher) Proxy(host string) *Launcher {250 return l.Set(flags.ProxyServer, host)251}252// WorkingDir to launch the browser process.253func (l *Launcher) WorkingDir(path string) *Launcher {254 return l.Set(flags.WorkingDir, path)255}256// Env to launch the browser process. The default value is os.Environ().257// Usually you use it to set the timezone env. Such as:258// Env(append(os.Environ(), "TZ=Asia/Tokyo")...)259func (l *Launcher) Env(env ...string) *Launcher {260 return l.Set(flags.Env, env...)261}262// StartURL to launch263func (l *Launcher) StartURL(u string) *Launcher {264 return l.Set("", u)265}266// FormatArgs returns the formated arg list for cli267func (l *Launcher) FormatArgs() []string {268 execArgs := []string{}269 for k, v := range l.Flags {270 if k == flags.Arguments {271 continue272 }273 if strings.HasPrefix(string(k), "rod-") {274 continue275 }276 // fix a bug of chrome, if path is not absolute chrome will hang277 if k == flags.UserDataDir {278 abs, err := filepath.Abs(v[0])279 utils.E(err)280 v[0] = abs281 }282 str := "--" + string(k)283 if v != nil {284 str += "=" + strings.Join(v, ",")285 }286 execArgs = append(execArgs, str)287 }288 execArgs = append(execArgs, l.Flags[flags.Arguments]...)289 sort.Strings(execArgs)290 return execArgs291}292// Logger to handle stdout and stderr from browser.293// For example, pipe all browser output to stdout: launcher.New().Logger(os.Stdout)294func (l *Launcher) Logger(w io.Writer) *Launcher {295 l.logger = w296 return l297}298// MustLaunch is similar to Launch299func (l *Launcher) MustLaunch() string {300 u, err := l.Launch()301 utils.E(err)302 return u303}304// Launch a standalone temp browser instance and returns the debug url.305// bin and profileDir are optional, set them to empty to use the default values.306// If you want to reuse sessions, such as cookies, set the UserDataDir to the same location.307func (l *Launcher) Launch() (string, error) {308 defer l.ctxCancel()309 bin, err := l.getBin()310 if err != nil {311 return "", err312 }313 var ll *leakless.Launcher314 var cmd *exec.Cmd315 if l.Has(flags.Leakless) && leakless.Support() {316 ll = leakless.New()317 cmd = ll.Command(bin, l.FormatArgs()...)318 } else {319 port := l.Get(flags.RemoteDebuggingPort)320 u, err := ResolveURL(port)321 if err == nil {322 return u, nil323 }324 cmd = exec.Command(bin, l.FormatArgs()...)325 }326 l.setupCmd(cmd)327 err = cmd.Start()328 if err != nil {329 return "", err...
launcher_test.go
Source:launcher_test.go
...21)22var setup = got.Setup(nil)23func TestDownloadHosts(t *testing.T) {24 g := setup(t)25 g.Has(launcher.HostGoogle(launcher.RevisionDefault), "https://storage.googleapis.com/chromium-browser-snapshots")26 g.Has(launcher.HostNPM(launcher.RevisionDefault), "https://registry.npmmirror.com/-/binary/chromium-browser-snapshots")27 g.Has(launcher.HostPlaywright(launcher.RevisionDefault), "https://playwright.azureedge.net/")28}29func TestDownload(t *testing.T) {30 g := setup(t)31 s := g.Serve()32 s.Mux.HandleFunc("/fast/", func(rw http.ResponseWriter, r *http.Request) {33 buf := bytes.NewBuffer(nil)34 zw := zip.NewWriter(buf)35 // folder "to"36 h := &zip.FileHeader{Name: "to/"}37 h.SetMode(0755)38 _, err := zw.CreateHeader(h)39 g.E(err)40 // file "file.txt"41 w, err := zw.CreateHeader(&zip.FileHeader{Name: "to/file.txt"})42 g.E(err)43 b := []byte(g.RandStr(2 * 1024 * 1024))44 g.E(w.Write(b))45 g.E(zw.Close())46 rw.Header().Add("Content-Length", fmt.Sprintf("%d", buf.Len()))47 _, _ = io.Copy(rw, buf)48 })49 s.Mux.HandleFunc("/slow/", func(rw http.ResponseWriter, r *http.Request) {50 t := time.NewTimer(3 * time.Second)51 select {52 case <-t.C:53 case <-r.Context().Done():54 t.Stop()55 }56 })57 b, cancel := newBrowser()58 b.Logger = utils.LoggerQuiet59 defer cancel()60 b.Hosts = []launcher.Host{launcher.HostTest(s.URL("/slow")), launcher.HostTest(s.URL("/fast"))}61 b.Dir = filepath.Join("tmp", "browser-from-mirror", g.RandStr(16))62 g.E(b.Download())63 g.Nil(os.Stat(b.Dir))64}65func TestBrowserGet(t *testing.T) {66 g := setup(t)67 g.Nil(os.Stat(launcher.NewBrowser().MustGet()))68 b := launcher.NewBrowser()69 b.Revision = 070 b.Logger = utils.LoggerQuiet71 _, err := b.Get()72 g.Eq(err.Error(), "Can't find a browser binary for your OS, the doc might help https://go-rod.github.io/#/compatibility?id=os")73}74func TestLaunch(t *testing.T) {75 g := setup(t)76 defaults.Proxy = "test.com"77 defer func() { defaults.ResetWith("") }()78 l := launcher.New()79 defer l.Kill()80 u := l.MustLaunch()81 g.Regex(`\Aws://.+\z`, u)82 parsed, _ := url.Parse(u)83 { // test GetWebSocketDebuggerURL84 for _, prefix := range []string{"", ":", "127.0.0.1:", "ws://127.0.0.1:"} {85 u2 := launcher.MustResolveURL(prefix + parsed.Port())86 g.Regex(u, u2)87 }88 _, err := launcher.ResolveURL("")89 g.Err(err)90 }91 {92 _, err := launcher.NewManaged("")93 g.Err(err)94 _, err = launcher.NewManaged("1://")95 g.Err(err)96 _, err = launcher.NewManaged("ws://not-exists")97 g.Err(err)98 }99 {100 g.Panic(func() { launcher.New().Set("a=b") })101 }102}103func TestLaunchUserMode(t *testing.T) {104 g := setup(t)105 l := launcher.NewUserMode()106 defer l.Kill()107 l.Kill() // empty kill should do nothing108 has := l.Has("not-exists")109 g.False(has)110 l.Append("test-append", "a")111 f := l.Get("test-append")112 g.Eq("a", f)113 dir := l.Get(flags.UserDataDir)114 port := 58472115 l = l.Context(g.Context()).Delete("test").Bin("").116 Revision(launcher.RevisionDefault).117 Logger(ioutil.Discard).118 Leakless(false).Leakless(true).119 Headless(false).Headless(true).RemoteDebuggingPort(port).120 NoSandbox(true).NoSandbox(false).121 Devtools(true).Devtools(false).122 StartURL("about:blank")....
Has
Using AI Code Generation
1import (2func main() {3 auth, err := aws.EnvAuth()4 if err != nil {5 panic(err)6 }7 client := s3.New(auth, aws.USEast)8 bucket := client.Bucket("test-bucket")9 if bucket == nil {10 fmt.Println("bucket is nil")11 }12 if bucket != nil {13 fmt.Println("bucket is not nil")14 }15 exists, err := bucket.Exists("example.txt")16 if err != nil {17 fmt.Println("error while checking existence of file:", err)18 }19 if exists {
Has
Using AI Code Generation
1import (2func main() {3 mc := memcache.New("localhost:11211")4 mc.Set(&memcache.Item{Key: "my-key", Value: []byte("my value")})5 item, err := mc.Get("my-key")6 if err != nil {7 panic(err)8 }9 fmt.Printf("Item value: %s10 mc.Delete("my-key")11 item, err = mc.Get("my-key")12 if err != nil {13 fmt.Printf("Item not found: %s14 }15}
Has
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}5 fmt.Println(l.Has("a"))6 fmt.Println(l.Has("d"))7}8import "fmt"9func main() {10 fmt.Println("Hello, playground")11 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}12 fmt.Println(l.Has("a"))13 fmt.Println(l.Has("d"))14}15import "fmt"16func main() {17 fmt.Println("Hello, playground")18 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}19 fmt.Println(l.Has("a"))20 fmt.Println(l.Has("d"))21}22import "fmt"23func main() {24 fmt.Println("Hello, playground")25 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}26 fmt.Println(l.Has("a"))27 fmt.Println(l.Has("d"))28}29import "fmt"30func main() {31 fmt.Println("Hello, playground")32 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}33 fmt.Println(l.Has("a"))34 fmt.Println(l.Has("d"))35}36import "fmt"37func main() {38 fmt.Println("Hello, playground")39 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}40 fmt.Println(l.Has("a"))41 fmt.Println(l.Has("d"))42}43import "fmt"44func main() {45 fmt.Println("Hello, playground")46 l := launcher{map[string]bool{"a": true, "b": true, "c": true}}
Has
Using AI Code Generation
1import (2func main() {3 l := launcher.New()4 if l.Has("weapon") {5 l.Fire("weapon")6 } else {7 fmt.Println("No weapon available")8 }9}10Add(name string, weapon func())11import (12func main() {13 l := launcher.New()14 l.Add("weapon", func() {15 fmt.Println("Firing weapon")16 })17 if l.Has("weapon") {18 l.Fire("weapon")19 } else {20 fmt.Println("No weapon available")21 }22}23Fire(name string)24import (
Has
Using AI Code Generation
1import (2func main() {3 fmt.Println("start")4 l := launcher.New()5 fmt.Println("Has: ", l.Has("firefox"))6}
Has
Using AI Code Generation
1import (2func main() {3 ldClient, _ := ld.MakeClient("sdk-9d6e0c6f-6c2b-4a3f-8d3e-3c6c9d6e0c6f", 5)4 user := ld.NewUser("userkey")5 showFeature, _ := ldClient.BoolVariation("new-feature", user, false)6 if showFeature {7 fmt.Println("Showing your feature to this user")8 } else {9 fmt.Println("Not showing your feature to this user")10 }11}
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!!