Best Rod code snippet using rod.Text
rods.go
Source:rods.go
1package main2import (3 "errors"4 "fmt"5)6type rod int7const (8 RodDigging rod = iota9 RodBlink10 RodTeleportOther11 RodFireBolt12 RodFireBall13 RodLightning14 RodFog15 RodObstruction16 RodShatter17 RodSleeping18 RodLignification19 RodHope20 RodSwapping21)22const NumRods = int(RodSwapping) + 123func (r rod) Letter() rune {24 return '/'25}26func (r rod) Name() string {27 var text string28 switch r {29 case RodDigging:30 text = "digging"31 case RodBlink:32 text = "blinking"33 case RodTeleportOther:34 text = "teleport other"35 case RodFog:36 text = "fog"37 case RodFireBall:38 text = "fireball"39 case RodFireBolt:40 text = "fire bolt"41 case RodLightning:42 text = "lightning"43 case RodObstruction:44 text = "obstruction"45 case RodShatter:46 text = "shatter"47 case RodSleeping:48 text = "sleeping"49 case RodLignification:50 text = "lignification"51 case RodHope:52 text = "last hope"53 case RodSwapping:54 text = "swapping"55 }56 return text57}58func (r rod) String() string {59 return "rod of " + r.Name()60}61func (r rod) Desc() string {62 var text string63 switch r {64 case RodDigging:65 text = "digs through up to 3 walls in a given direction."66 case RodBlink:67 text = "makes you blink away within your line of sight. The rod is more susceptible to send you to the cells thar are most far from you."68 case RodTeleportOther:69 text = "teleports away one of your foes. Note that the monster remembers where it saw you last time."70 case RodFog:71 text = "creates a dense fog that reduces your line of sight. Monsters at more than 1 cell away from you will not be able to see you."72 case RodFireBall:73 text = "throws a 1-radius fireball at your foes. You cannot use it against yourself. It can burn foliage and doors."74 case RodFireBolt:75 text = "throws a fire bolt through one or more enemies. It can burn foliage and doors."76 case RodLightning:77 text = "deals electrical damage to foes connected to you. It can burn foliage and doors."78 case RodObstruction:79 text = "creates a temporary wall at targeted location."80 case RodShatter:81 text = "induces an explosion around a wall, hurting adjacent monsters. The wall can disintegrate. You cannot use against yourself."82 case RodSleeping:83 text = "induces deep sleeping and exhaustion for monsters in the targeted area. You cannot use it against yourself."84 case RodLignification:85 text = "lignifies a monster, so that it cannot move, but can still fight with improved resistance."86 case RodHope:87 text = "creates an energy channel against a targeted monster. The damage done is inversely proportional to your health. It can burn foliage and doors."88 case RodSwapping:89 text = "makes you swap positions with a targeted monster."90 }91 return fmt.Sprintf("The %s %s Rods sometimes regain charges as you go deeper. This rod can have up to %d charges.", r, text, r.MaxCharge())92}93type rodProps struct {94 Charge int95}96func (r rod) MaxCharge() (charges int) {97 switch r {98 case RodBlink:99 charges = 5100 case RodDigging, RodShatter:101 charges = 3102 default:103 charges = 4104 }105 return charges106}107func (r rod) Rate() int {108 rate := r.MaxCharge() - 2109 if rate < 1 {110 rate = 1111 }112 return rate113}114func (r rod) MPCost() (mp int) {115 return 1116 //switch r {117 //case RodBlink:118 //mp = 3119 //case RodTeleportOther, RodDigging, RodShatter:120 //mp = 5121 //default:122 //mp = 4123 //}124 //return mp125}126func (r rod) Use(g *game, ev event) error {127 rods := g.Player.Rods128 if rods[r].Charge <= 0 {129 return errors.New("No charges remaining on this rod.")130 }131 if r.MPCost() > g.Player.MP {132 return errors.New("Not enough magic points for using this rod.")133 }134 if g.Player.HasStatus(StatusBerserk) {135 return errors.New("You cannot use rods while berserk.")136 }137 var err error138 switch r {139 case RodBlink:140 err = g.EvokeRodBlink(ev)141 case RodTeleportOther:142 err = g.EvokeRodTeleportOther(ev)143 case RodFireBolt:144 err = g.EvokeRodFireBolt(ev)145 case RodFireBall:146 err = g.EvokeRodFireball(ev)147 case RodLightning:148 err = g.EvokeRodLightning(ev)149 case RodFog:150 err = g.EvokeRodFog(ev)151 case RodDigging:152 err = g.EvokeRodDigging(ev)153 case RodObstruction:154 err = g.EvokeRodObstruction(ev)155 case RodShatter:156 err = g.EvokeRodShatter(ev)157 case RodSleeping:158 err = g.EvokeRodSleeping(ev)159 case RodLignification:160 err = g.EvokeRodLignification(ev)161 case RodHope:162 err = g.EvokeRodHope(ev)163 case RodSwapping:164 err = g.EvokeRodSwapping(ev)165 }166 if err != nil {167 return err168 }169 rp := rods[r]170 rp.Charge--171 rods[r] = rp172 g.Player.MP -= r.MPCost()173 g.StoryPrintf("Evoked your %s.", r)174 g.Stats.UsedRod[r]++175 g.Stats.Evocations++176 g.FunAction()177 ev.Renew(g, 7)178 return nil179}180func (g *game) EvokeRodBlink(ev event) error {181 if g.Player.HasStatus(StatusLignification) {182 return errors.New("You cannot blink while lignified.")183 }184 g.Blink(ev)185 return nil186}187func (g *game) BlinkPos() position {188 losPos := []position{}189 for pos, b := range g.Player.LOS {190 if !b {191 continue192 }193 if g.Dungeon.Cell(pos).T != FreeCell {194 continue195 }196 mons := g.MonsterAt(pos)197 if mons.Exists() {198 continue199 }200 losPos = append(losPos, pos)201 }202 if len(losPos) == 0 {203 return InvalidPos204 }205 npos := losPos[RandInt(len(losPos))]206 for i := 0; i < 4; i++ {207 pos := losPos[RandInt(len(losPos))]208 if npos.Distance(g.Player.Pos) < pos.Distance(g.Player.Pos) {209 npos = pos210 }211 }212 return npos213}214func (g *game) Blink(ev event) {215 if g.Player.HasStatus(StatusLignification) {216 return217 }218 npos := g.BlinkPos()219 if !npos.valid() {220 // should not happen221 g.Print("You could not blink.")222 return223 }224 opos := g.Player.Pos225 g.Print("You blink away.")226 g.ui.TeleportAnimation(opos, npos, true)227 g.PlacePlayerAt(npos)228}229func (g *game) EvokeRodTeleportOther(ev event) error {230 if err := g.ui.ChooseTarget(&chooser{}); err != nil {231 return err232 }233 mons := g.MonsterAt(g.Player.Target)234 // mons not nil (check done in the targeter)235 mons.TeleportAway(g)236 return nil237}238func (g *game) EvokeRodSleeping(ev event) error {239 if err := g.ui.ChooseTarget(&chooser{area: true, minDist: true}); err != nil {240 return err241 }242 neighbors := g.Dungeon.FreeNeighbors(g.Player.Target)243 g.Print("A sleeping ball emerges straight out of the rod.")244 g.ui.ProjectileTrajectoryAnimation(g.Ray(g.Player.Target), ColorFgSleepingMonster)245 for _, pos := range append(neighbors, g.Player.Target) {246 mons := g.MonsterAt(pos)247 if !mons.Exists() {248 continue249 }250 if mons.State != Resting {251 g.Printf("%s falls asleep.", mons.Kind.Definite(true))252 }253 mons.State = Resting254 mons.ExhaustTime(g, 40+RandInt(10))255 }256 return nil257}258func (g *game) EvokeRodFireBolt(ev event) error {259 if err := g.ui.ChooseTarget(&chooser{flammable: true}); err != nil {260 return err261 }262 ray := g.Ray(g.Player.Target)263 g.MakeNoise(MagicCastNoise, g.Player.Pos)264 g.Print("Whoosh! A fire bolt emerges straight out of the rod.")265 g.ui.FireBoltAnimation(ray)266 for _, pos := range ray {267 g.Burn(pos, ev)268 mons := g.MonsterAt(pos)269 if !mons.Exists() {270 continue271 }272 dmg := 0273 for i := 0; i < 2; i++ {274 dmg += RandInt(21)275 }276 dmg /= 2277 mons.HP -= dmg278 if mons.HP <= 0 {279 g.Printf("%s is killed by the bolt.", mons.Kind.Indefinite(true))280 g.HandleKill(mons, ev)281 }282 g.MakeNoise(MagicHitNoise, mons.Pos)283 g.HandleStone(mons)284 mons.MakeHuntIfHurt(g)285 }286 return nil287}288func (g *game) EvokeRodFireball(ev event) error {289 if err := g.ui.ChooseTarget(&chooser{area: true, minDist: true, flammable: true}); err != nil {290 return err291 }292 neighbors := g.Dungeon.FreeNeighbors(g.Player.Target)293 g.MakeNoise(MagicExplosionNoise, g.Player.Target)294 g.Printf("A fireball emerges straight out of the rod... %s", g.ExplosionSound())295 g.ui.ProjectileTrajectoryAnimation(g.Ray(g.Player.Target), ColorFgExplosionStart)296 g.ui.ExplosionAnimation(FireExplosion, g.Player.Target)297 for _, pos := range append(neighbors, g.Player.Target) {298 g.Burn(pos, ev)299 mons := g.MonsterAt(pos)300 if mons == nil {301 continue302 }303 dmg := 0304 for i := 0; i < 2; i++ {305 dmg += RandInt(24)306 }307 dmg /= 2308 mons.HP -= dmg309 if mons.HP <= 0 {310 g.Printf("%s is killed by the fireball.", mons.Kind.Indefinite(true))311 g.HandleKill(mons, ev)312 }313 g.MakeNoise(MagicHitNoise, mons.Pos)314 g.HandleStone(mons)315 mons.MakeHuntIfHurt(g)316 }317 return nil318}319func (g *game) EvokeRodLightning(ev event) error {320 d := g.Dungeon321 conn := map[position]bool{}322 nb := make([]position, 0, 8)323 nb = g.Player.Pos.Neighbors(nb, func(npos position) bool {324 return npos.valid() && d.Cell(npos).T != WallCell325 })326 stack := []position{}327 for _, pos := range nb {328 mons := g.MonsterAt(pos)329 if !mons.Exists() {330 continue331 }332 stack = append(stack, pos)333 conn[pos] = true334 }335 if len(stack) == 0 {336 return errors.New("There are no adjacent monsters.")337 }338 g.MakeNoise(MagicCastNoise, g.Player.Pos)339 g.Print("Whoosh! Lightning emerges straight out of the rod.")340 var pos position341 targets := []position{}342 for len(stack) > 0 {343 pos = stack[len(stack)-1]344 stack = stack[:len(stack)-1]345 g.Burn(pos, ev)346 mons := g.MonsterAt(pos)347 if !mons.Exists() {348 continue349 }350 targets = append(targets, pos)351 dmg := 0352 for i := 0; i < 2; i++ {353 dmg += RandInt(17)354 }355 dmg /= 2356 mons.HP -= dmg357 if mons.HP <= 0 {358 g.Printf("%s is killed by lightning.", mons.Kind.Indefinite(true))359 g.HandleKill(mons, ev)360 }361 g.MakeNoise(MagicHitNoise, mons.Pos)362 g.HandleStone(mons)363 mons.MakeHuntIfHurt(g)364 nb = pos.Neighbors(nb, func(npos position) bool {365 return npos.valid() && d.Cell(npos).T != WallCell366 })367 for _, npos := range nb {368 if !conn[npos] {369 conn[npos] = true370 stack = append(stack, npos)371 }372 }373 }374 g.ui.LightningHitAnimation(targets)375 return nil376}377type cloud int378const (379 CloudFog cloud = iota380 CloudFire381 CloudNight382)383func (g *game) EvokeRodFog(ev event) error {384 g.Fog(g.Player.Pos, 3, ev)385 g.Print("You are surrounded by a dense fog.")386 return nil387}388func (g *game) Fog(at position, radius int, ev event) {389 dij := &normalPath{game: g}390 nm := Dijkstra(dij, []position{at}, radius)391 for pos := range nm {392 _, ok := g.Clouds[pos]393 if !ok {394 g.Clouds[pos] = CloudFog395 g.PushEvent(&cloudEvent{ERank: ev.Rank() + 100 + RandInt(100), EAction: CloudEnd, Pos: pos})396 }397 }398 g.ComputeLOS()399}400func (g *game) EvokeRodDigging(ev event) error {401 if err := g.ui.ChooseTarget(&wallChooser{}); err != nil {402 return err403 }404 pos := g.Player.Target405 for i := 0; i < 3; i++ {406 g.Dungeon.SetCell(pos, FreeCell)407 g.Stats.Digs++408 g.MakeNoise(WallNoise, pos)409 g.Fog(pos, 1, ev)410 pos = pos.To(pos.Dir(g.Player.Pos))411 if !g.Player.LOS[pos] {412 g.WrongWall[pos] = true413 }414 if !pos.valid() || g.Dungeon.Cell(pos).T != WallCell {415 break416 }417 }418 g.Print("You see the wall disintegrate with a crash.")419 g.ComputeLOS()420 g.MakeMonstersAware()421 return nil422}423func (g *game) EvokeRodShatter(ev event) error {424 if err := g.ui.ChooseTarget(&wallChooser{minDist: true}); err != nil {425 return err426 }427 neighbors := g.Dungeon.FreeNeighbors(g.Player.Target)428 g.Dungeon.SetCell(g.Player.Target, FreeCell)429 g.Stats.Digs++430 g.ComputeLOS()431 g.MakeMonstersAware()432 g.MakeNoise(WallNoise, g.Player.Target)433 g.Printf("%s The wall disappeared.", g.CrackSound())434 g.ui.ProjectileTrajectoryAnimation(g.Ray(g.Player.Target), ColorFgExplosionWallStart)435 g.ui.ExplosionAnimation(WallExplosion, g.Player.Target)436 g.Fog(g.Player.Target, 2, ev)437 for _, pos := range neighbors {438 mons := g.MonsterAt(pos)439 if !mons.Exists() {440 continue441 }442 dmg := 0443 for i := 0; i < 3; i++ {444 dmg += RandInt(30)445 }446 dmg /= 3447 mons.HP -= dmg448 if mons.HP <= 0 {449 g.Printf("%s is killed by the explosion.", mons.Kind.Indefinite(true))450 g.HandleKill(mons, ev)451 }452 g.MakeNoise(ExplosionHitNoise, mons.Pos)453 g.HandleStone(mons)454 mons.MakeHuntIfHurt(g)455 }456 return nil457}458func (g *game) EvokeRodObstruction(ev event) error {459 if err := g.ui.ChooseTarget(&chooser{free: true}); err != nil {460 return err461 }462 g.TemporalWallAt(g.Player.Target, ev)463 g.Printf("You see a wall appear out of thin air.")464 return nil465}466func (g *game) EvokeRodLignification(ev event) error {467 if err := g.ui.ChooseTarget(&chooser{}); err != nil {468 return err469 }470 mons := g.MonsterAt(g.Player.Target)471 // mons not nil (check done in targeter)472 if mons.Status(MonsLignified) {473 return errors.New("You cannot target a lignified monster.")474 }475 mons.EnterLignification(g, ev)476 return nil477}478func (g *game) TemporalWallAt(pos position, ev event) {479 if g.Dungeon.Cell(pos).T == WallCell {480 return481 }482 if !g.Player.LOS[pos] {483 g.WrongWall[pos] = true484 }485 g.CreateTemporalWallAt(pos, ev)486 g.ComputeLOS()487}488func (g *game) CreateTemporalWallAt(pos position, ev event) {489 g.Dungeon.SetCell(pos, WallCell)490 delete(g.Clouds, pos)491 g.TemporalWalls[pos] = true492 g.PushEvent(&cloudEvent{ERank: ev.Rank() + 200 + RandInt(50), Pos: pos, EAction: ObstructionEnd})493}494func (g *game) EvokeRodHope(ev event) error {495 if err := g.ui.ChooseTarget(&chooser{needsFreeWay: true}); err != nil {496 return err497 }498 g.MakeNoise(MagicCastNoise, g.Player.Pos)499 g.ui.ProjectileTrajectoryAnimation(g.Ray(g.Player.Target), ColorFgExplosionStart)500 mons := g.MonsterAt(g.Player.Target)501 // mons not nil (check done in the targeter)502 attack := -20 + 30*DefaultHealth/g.Player.HP503 if attack > 130 {504 attack = 130505 }506 dmg := 0507 for i := 0; i < 5; i++ {508 dmg += RandInt(attack)509 }510 dmg /= 5511 if dmg < 0 {512 // should not happen513 dmg = 0514 }515 mons.HP -= dmg516 g.Burn(g.Player.Target, ev)517 g.ui.HitAnimation(g.Player.Target, true)518 g.Printf("An energy channel hits %s (%d dmg).", mons.Kind.Definite(false), dmg)519 if mons.HP <= 0 {520 g.Printf("%s dies.", mons.Kind.Indefinite(true))521 g.HandleKill(mons, ev)522 }523 return nil524}525func (g *game) EvokeRodSwapping(ev event) error {526 if g.Player.HasStatus(StatusLignification) {527 return errors.New("You cannot use this rod while lignified.")528 }529 if err := g.ui.ChooseTarget(&chooser{}); err != nil {530 return err531 }532 mons := g.MonsterAt(g.Player.Target)533 // mons not nil (check done in the targeter)534 if mons.Status(MonsLignified) {535 return errors.New("You cannot target a lignified monster.")536 }537 g.SwapWithMonster(mons)538 return nil539}540func (g *game) SwapWithMonster(mons *monster) {541 ompos := mons.Pos542 g.Printf("You swap positions with the %s.", mons.Kind)543 g.ui.SwappingAnimation(mons.Pos, g.Player.Pos)544 mons.MoveTo(g, g.Player.Pos)545 g.PlacePlayerAt(ompos)546 mons.MakeAware(g)547}548func (g *game) GeneratedRodsCount() int {549 count := 0550 for _, b := range g.GeneratedRods {551 if b {552 count++553 }554 }555 return count556}557func (g *game) RandomRod() rod {558 r := rod(RandInt(NumRods))559 return r560}561func (g *game) GenerateRod() {562 count := 0563 for {564 count++565 if count > 1000 {566 panic("GenerateRod")567 }568 pos := g.FreeCellForStatic()569 r := g.RandomRod()570 if _, ok := g.Player.Rods[r]; !ok && !g.GeneratedRods[r] {571 g.GeneratedRods[r] = true572 g.Rods[pos] = r573 return574 }575 }576}577func (g *game) RechargeRods() {578 for r, props := range g.Player.Rods {579 max := r.MaxCharge()580 if g.Player.Armour == CelmistRobe {581 max += 2582 }583 if props.Charge < max {584 rchg := RandInt(1 + r.Rate())585 if rchg == 0 && RandInt(2) == 0 {586 rchg++587 }588 if g.Player.Armour == CelmistRobe {589 if RandInt(10) > 0 {590 rchg++591 }592 if RandInt(3) == 0 {593 rchg++594 }595 }596 props.Charge += rchg597 g.Player.Rods[r] = props598 }599 if props.Charge > max {600 props.Charge = max601 g.Player.Rods[r] = props602 }603 }604}...
query_test.go
Source:query_test.go
...16 g.page.MustNavigate(g.srcFile("fixtures/input.html"))17 g.page.MustElement("input")18 list := g.page.MustElements("input")19 g.Eq("input", list.First().MustDescribe().LocalName)20 g.Eq("submit", list.Last().MustText())21}22func TestPagesQuery(t *testing.T) {23 g := setup(t)24 b := g.browser25 b.MustPage(g.srcFile("fixtures/click.html")).MustWaitLoad()26 pages := b.MustPages()27 g.True(pages.MustFind("button").MustHas("button"))28 g.Panic(func() { rod.Pages{}.MustFind("____") })29 g.True(pages.MustFindByURL("click.html").MustHas("button"))30 g.Panic(func() { rod.Pages{}.MustFindByURL("____") })31 _, err := pages.Find("____")32 g.Err(err)33 g.Eq(err.Error(), "cannot find page")34 g.Panic(func() {35 pages.MustFindByURL("____")36 })37 g.Panic(func() {38 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})39 pages.MustFind("button")40 })41 g.Panic(func() {42 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})43 pages.MustFindByURL("____")44 })45}46func TestPagesOthers(t *testing.T) {47 g := setup(t)48 list := rod.Pages{}49 g.Nil(list.First())50 g.Nil(list.Last())51 list = append(list, &rod.Page{})52 g.NotNil(list.First())53 g.NotNil(list.Last())54}55func TestPageHas(t *testing.T) {56 g := setup(t)57 g.page.MustNavigate(g.srcFile("fixtures/selector.html"))58 g.page.MustElement("body")59 g.True(g.page.MustHas("span"))60 g.False(g.page.MustHas("a"))61 g.True(g.page.MustHasX("//span"))62 g.False(g.page.MustHasX("//a"))63 g.True(g.page.MustHasR("button", "03"))64 g.False(g.page.MustHasR("button", "11"))65 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})66 g.Err(g.page.HasX("//a"))67 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})68 g.Err(g.page.HasR("button", "03"))69}70func TestElementHas(t *testing.T) {71 g := setup(t)72 g.page.MustNavigate(g.srcFile("fixtures/selector.html"))73 b := g.page.MustElement("body")74 g.True(b.MustHas("span"))75 g.False(b.MustHas("a"))76 g.True(b.MustHasX("//span"))77 g.False(b.MustHasX("//a"))78 g.True(b.MustHasR("button", "03"))79 g.False(b.MustHasR("button", "11"))80}81func TestSearch(t *testing.T) {82 g := setup(t)83 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))84 el := p.MustSearch("click me")85 g.Eq("click me", el.MustText())86 g.True(el.MustClick().MustMatches("[a=ok]"))87 _, err := p.Sleeper(rod.NotFoundSleeper).Search("not-exists")88 g.True(errors.Is(err, &rod.ErrElementNotFound{}))89 g.Eq(err.Error(), "cannot find element")90 // when search result is not ready91 {92 g.mc.stub(1, proto.DOMGetSearchResults{}, func(send StubSend) (gson.JSON, error) {93 return gson.New(nil), cdp.ErrCtxNotFound94 })95 p.MustSearch("click me")96 }97 // when node id is zero98 {99 g.mc.stub(1, proto.DOMGetSearchResults{}, func(send StubSend) (gson.JSON, error) {100 return gson.New(proto.DOMGetSearchResultsResult{101 NodeIds: []proto.DOMNodeID{0},102 }), nil103 })104 p.MustSearch("click me")105 }106 g.Panic(func() {107 g.mc.stubErr(1, proto.DOMPerformSearch{})108 p.MustSearch("click me")109 })110 g.Panic(func() {111 g.mc.stubErr(1, proto.DOMGetSearchResults{})112 p.MustSearch("click me")113 })114 g.Panic(func() {115 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})116 p.MustSearch("click me")117 })118}119func TestSearchElements(t *testing.T) {120 g := setup(t)121 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))122 {123 res, err := p.Search("button")124 g.E(err)125 c, err := res.All()126 g.E(err)127 g.Len(c, 4)128 g.mc.stubErr(1, proto.DOMGetSearchResults{})129 g.Err(res.All())130 g.mc.stubErr(1, proto.DOMResolveNode{})131 g.Err(res.All())132 }133 { // disable retry134 sleeper := func() utils.Sleeper { return utils.CountSleeper(1) }135 _, err := p.Sleeper(sleeper).Search("not-exists")136 g.Err(err)137 }138}139func TestSearchIframes(t *testing.T) {140 g := setup(t)141 p := g.page.MustNavigate(g.srcFile("fixtures/click-iframes.html"))142 el := p.MustSearch("button[onclick]")143 g.Eq("click me", el.MustText())144 g.True(el.MustClick().MustMatches("[a=ok]"))145}146func TestSearchIframesAfterReload(t *testing.T) {147 g := setup(t)148 p := g.page.MustNavigate(g.srcFile("fixtures/click-iframes.html"))149 frame := p.MustElement("iframe").MustFrame().MustElement("iframe").MustFrame()150 frame.MustReload()151 el := p.MustSearch("button[onclick]")152 g.Eq("click me", el.MustText())153 g.True(el.MustClick().MustMatches("[a=ok]"))154}155func TestPageRace(t *testing.T) {156 g := setup(t)157 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))158 p.Race().Element("button").MustHandle(func(e *rod.Element) { g.Eq("01", e.MustText()) }).MustDo()159 g.Eq("01", p.Race().Element("button").MustDo().MustText())160 p.Race().ElementX("//button").MustHandle(func(e *rod.Element) { g.Eq("01", e.MustText()) }).MustDo()161 g.Eq("01", p.Race().ElementX("//button").MustDo().MustText())162 p.Race().ElementR("button", "02").MustHandle(func(e *rod.Element) { g.Eq("02", e.MustText()) }).MustDo()163 g.Eq("02", p.Race().ElementR("button", "02").MustDo().MustText())164 p.Race().MustElementByJS("() => document.querySelector('button')", nil).165 MustHandle(func(e *rod.Element) { g.Eq("01", e.MustText()) }).MustDo()166 g.Eq("01", p.Race().MustElementByJS("() => document.querySelector('button')", nil).MustDo().MustText())167 raceFunc := func(p *rod.Page) (*rod.Element, error) {168 el := p.MustElement("button")169 g.Eq("01", el.MustText())170 return el, nil171 }172 p.Race().ElementFunc(raceFunc).MustHandle(func(e *rod.Element) { g.Eq("01", e.MustText()) }).MustDo()173 g.Eq("01", p.Race().ElementFunc(raceFunc).MustDo().MustText())174 el, err := p.Sleeper(func() utils.Sleeper { return utils.CountSleeper(2) }).Race().175 Element("not-exists").MustHandle(func(e *rod.Element) {}).176 ElementX("//not-exists").177 ElementR("not-exists", "test").MustHandle(func(e *rod.Element) {}).178 Do()179 g.Err(err)180 g.Nil(el)181 el, err = p.Race().MustElementByJS(`() => notExists()`, nil).Do()182 g.Err(err)183 g.Nil(el)184}185func TestPageRaceRetryInHandle(t *testing.T) {186 g := setup(t)187 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))188 p.Race().Element("div").MustHandle(func(e *rod.Element) {189 go func() {190 utils.Sleep(0.5)191 e.MustElement("button").MustEval(`() => this.innerText = '04'`)192 }()193 e.MustElement("button").MustWait("() => this.innerText === '04'")194 }).MustDo()195}196func TestPageElementX(t *testing.T) {197 g := setup(t)198 g.page.MustNavigate(g.srcFile("fixtures/selector.html"))199 g.page.MustElement("body")200 txt := g.page.MustElementX("//div").MustElementX("./button").MustText()201 g.Eq(txt, "02")202}203func TestPageElementsX(t *testing.T) {204 g := setup(t)205 g.page.MustNavigate(g.srcFile("fixtures/selector.html"))206 g.page.MustElement("body")207 list := g.page.MustElementsX("//button")208 g.Len(list, 4)209}210func TestElementR(t *testing.T) {211 g := setup(t)212 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))213 el := p.MustElementR("button", `\d1`)214 g.Eq("01", el.MustText())215 el = p.MustElement("div").MustElementR("button", `03`)216 g.Eq("03", el.MustText())217 p = g.page.MustNavigate(g.srcFile("fixtures/input.html"))218 el = p.MustElementR("input", `submit`)219 g.Eq("submit", el.MustText())220 el = p.MustElementR("input", `placeholder`)221 g.Eq("blur", *el.MustAttribute("id"))222 el = p.MustElementR("option", `/cc/i`)223 g.Eq("CC", el.MustText())224}225func TestElementFromElement(t *testing.T) {226 g := setup(t)227 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))228 el := p.MustElement("div").MustElement("button")229 g.Eq("02", el.MustText())230}231func TestElementsFromElement(t *testing.T) {232 g := setup(t)233 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))234 el := p.MustElement("form")235 list := p.MustElement("form").MustElements("option")236 g.Len(list, 4)237 g.Eq("B", list[1].MustText())238 g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})239 g.Err(el.Elements("input"))240}241func TestElementParent(t *testing.T) {242 g := setup(t)243 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))244 el := p.MustElement("input").MustParent()245 g.Eq("FORM", el.MustEval(`() => this.tagName`).String())246}247func TestElementParents(t *testing.T) {248 g := setup(t)249 p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))250 g.Len(p.MustElement("option").MustParents("*"), 4)251 g.Len(p.MustElement("option").MustParents("form"), 1)252}253func TestElementSiblings(t *testing.T) {254 g := setup(t)255 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))256 el := p.MustElement("div")257 a := el.MustPrevious()258 b := el.MustNext()259 g.Eq(a.MustText(), "01")260 g.Eq(b.MustText(), "04")261}262func TestElementFromElementX(t *testing.T) {263 g := setup(t)264 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))265 el := p.MustElement("div").MustElementX("./button")266 g.Eq("02", el.MustText())267}268func TestElementsFromElementsX(t *testing.T) {269 g := setup(t)270 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html"))271 list := p.MustElement("div").MustElementsX("./button")272 g.Len(list, 2)273}274func TestElementTracing(t *testing.T) {275 g := setup(t)276 g.browser.Trace(true)277 g.browser.Logger(utils.LoggerQuiet)278 defer func() {279 g.browser.Trace(defaults.Trace)280 g.browser.Logger(rod.DefaultLogger)281 }()282 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))283 g.Eq(`rod.element("code") html`, p.MustElement("html").MustElement("code").MustText())284}285func TestPageElementByJS(t *testing.T) {286 g := setup(t)287 p := g.page.MustNavigate(g.srcFile("fixtures/click.html"))288 g.Eq(p.MustElementByJS(`() => document.querySelector('button')`).MustText(), "click me")289 _, err := p.ElementByJS(rod.Eval(`() => 1`))290 g.Is(err, &rod.ErrExpectElement{})291 g.Eq(err.Error(), "expect js to return an element, but got: {\"type\":\"number\",\"value\":1,\"description\":\"1\"}")292}293func TestPageElementsByJS(t *testing.T) {294 g := setup(t)295 p := g.page.MustNavigate(g.srcFile("fixtures/selector.html")).MustWaitLoad()296 g.Len(p.MustElementsByJS("() => document.querySelectorAll('button')"), 4)297 _, err := p.ElementsByJS(rod.Eval(`() => [1]`))298 g.Is(err, &rod.ErrExpectElements{})299 g.Eq(err.Error(), "expect js to return an array of elements, but got: {\"type\":\"number\",\"value\":1,\"description\":\"1\"}")300 _, err = p.ElementsByJS(rod.Eval(`() => 1`))301 g.Eq(err.Error(), "expect js to return an array of elements, but got: {\"type\":\"number\",\"value\":1,\"description\":\"1\"}")302 _, err = p.ElementsByJS(rod.Eval(`() => foo()`))...
examples_test.go
Source:examples_test.go
1package stealth_test2import (3 "crypto/md5"4 "fmt"5 "strings"6 "time"7 "github.com/go-rod/rod"8 "github.com/go-rod/rod/lib/launcher"9 "github.com/go-rod/stealth"10)11func init() {12 launcher.NewBrowser().MustGet()13}14func Example_main() {15 browser := rod.New().Timeout(time.Minute).MustConnect()16 defer browser.MustClose()17 // You can also use stealth.JS directly without rod18 fmt.Printf("js: %x\n\n", md5.Sum([]byte(stealth.JS)))19 page := stealth.MustPage(browser)20 page.MustNavigate("https://bot.sannysoft.com")21 printReport(page)22 /*23 Output:24 js: 173d23e3db48bf47441b2f4735bbc63125 User Agent (Old): true26 WebDriver (New): missing (passed)27 WebDriver Advanced: passed28 Chrome (New): present (passed)29 Permissions (New): prompt30 Plugins Length (Old): 331 Plugins is of type PluginArray: passed32 Languages (Old): en-US,en33 WebGL Vendor: Intel Inc.34 WebGL Renderer: Intel Iris OpenGL Engine35 Broken Image Dimensions: 16x1636 */37}38func printReport(page *rod.Page) {39 el := page.MustElement("#broken-image-dimensions.passed")40 for _, row := range el.MustParents("table").First().MustElements("tr:nth-child(n+2)") {41 cells := row.MustElements("td")42 key := cells[0].MustProperty("textContent")43 if strings.HasPrefix(key.String(), "User Agent") {44 fmt.Printf("\t\t%s: %t\n\n", key, !strings.Contains(cells[1].MustProperty("textContent").String(), "HeadlessChrome/"))45 } else if strings.HasPrefix(key.String(), "Hairline Feature") {46 // Detects support for hidpi/retina hairlines, which are CSS borders with less than 1px in width, for being physically 1px on hidpi screens.47 // Not all the machine suppports it.48 continue49 } else {50 fmt.Printf("\t\t%s: %s\n\n", key, cells[1].MustProperty("textContent"))51 }52 }53 page.MustScreenshot("")54}...
Text
Using AI Code Generation
1import (2func main() {3 browser := rod.New().Connect()4 e := page.Element("input[name=q]")5 e.Input("hello world")6 e.Call(proto.InputDispatchKeyEvent, proto.InputDispatchKeyEvent{7 })8 fmt.Println(page.Element("#resultStats").Text())9 browser.Close()10}11import (12func main() {13 browser := rod.New().Connect()14 e := page.Element("input[name=q]")15 e.Input("hello world")16 e.Call(proto.InputDispatchKeyEvent, proto.InputDispatchKeyEvent{17 })18 fmt.Println(page.Element("#resultStats").Text())19 browser.Close()20}21import (22func main() {23 browser := rod.New().Connect()24 e := page.Element("input[name=q]")25 e.Input("hello world")26 e.Call(proto.InputDispatchKeyEvent, proto.InputDispatchKeyEvent{27 })28 fmt.Println(page.Element("#resultStats").Text())29 browser.Close()30}31import (
Text
Using AI Code Generation
1import (2func main() {3 fmt.Println(page.MustElement("h1").MustText())4}5import (6func main() {7 page.MustScreenshot("screenshot.png")8 fmt.Println("Screenshot saved to screenshot.png")9}10import (11func main() {12 browser := rod.New().MustConnect()13 page.MustElement("a").MustClick()14 fmt.Println(page.MustTitle())15}16import (17func main() {18 fmt.Println(page.MustElementR("a", "About").MustText())19}20import (21func main() {22 fmt.Println(page.MustElementR("a", "About").MustText())23}24import (25func main() {26 fmt.Println(page.MustElementR("a", "About").MustText())27}28import (29func main() {30 fmt.Println(page.MustElementR("a", "About").MustText())31}
Text
Using AI Code Generation
1import "fmt"2type Rod struct {3}4func (r Rod) Text() string {5return fmt.Sprintf("length of rod is %f", r.length)6}7func main() {8r := Rod{1.5}9fmt.Println(r.Text())10}11import "fmt"12type Rod struct {13}14func (r Rod) Text() string {15return fmt.Sprintf("length of rod is %f", r.length)16}17func (r Rod) String() string {18return fmt.Sprintf("length of rod is %f", r.length)19}20func main() {21r := Rod{1.5}22fmt.Println(r.Text())23fmt.Println(r)24}25import "fmt"26type Rod struct {27}28func (r Rod) Text() string {29return fmt.Sprintf("length of rod is %f", r.length)30}31func (r Rod) String() string {32return fmt.Sprintf("length of rod is %f", r.length)33}34func (r Rod) String() string {35return fmt.Sprintf("length of rod is %f", r.length)36}37func main() {38r := Rod{1.5}39fmt.Println(r.Text())40fmt.Println(r)41}42import "fmt"43type Rod struct {44}45func (r Rod) Text() string {46return fmt.Sprintf("length of rod is %f", r.length)47}48func (r Rod) String() string {49return fmt.Sprintf("length of rod is %f", r.length)50}51func (r Rod) String() string {52return fmt.Sprintf("length of rod is %f", r.length)53}54func main() {55r := Rod{1.5}
Text
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, world.")4}5import "fmt"6func main() {7 fmt.Println("Hello, world.")8}9import "fmt"10func main() {11 fmt.Println("Hello, world.")12}13import "fmt"14func main() {15 fmt.Println("Hello, world.")16}17import "fmt"18func main() {19 fmt.Println("Hello, world.")20}21import "fmt"22func main() {23 fmt.Println("Hello, world.")24}25import "fmt"26func main() {27 fmt.Println("Hello, world.")28}29import "fmt"30func main() {31 fmt.Println("Hello, world.")32}33import "fmt"34func main() {35 fmt.Println("Hello, world.")36}37import "fmt"38func main() {39 fmt.Println("Hello, world.")40}41import "fmt"42func main() {43 fmt.Println("Hello, world.")44}45import "fmt"46func main() {47 fmt.Println("Hello, world.")48}49import "fmt"50func main() {51 fmt.Println("Hello, world.")52}53import "fmt"54func main() {55 fmt.Println("Hello,
Text
Using AI Code Generation
1import "fmt"2type rod struct {3}4func (r rod) Text() string {5 return fmt.Sprintf("length = %f, radius = %f", r.length, r.radius)6}7func main() {8 r := rod{length: 3.4, radius: 0.5}9 fmt.Println(r.Text())10}11import "fmt"12type rod struct {13}14func (r *rod) Text() string {15 return fmt.Sprintf("length = %f, radius = %f", r.length, r.radius)16}17func main() {18 r := rod{length: 3.4, radius: 0.5}19 fmt.Println(r.Text())20}21import "fmt"22type rod struct {23}24func (r *rod) Text() string {25 return fmt.Sprintf("length = %f, radius = %f", r.length, r.radius)26}27func main() {28 r := rod{length: 3.4, radius: 0.5}29 fmt.Println((&r).Text())30}31import "fmt"32type rod struct {33}34func (r *rod) Text() string {35 return fmt.Sprintf("length = %f, radius = %f", r.length, r.radius)36}37func main() {38 r := rod{length: 3.4, radius: 0.5}39 fmt.Println(r.Text())40}41import "
Text
Using AI Code Generation
1import (2func main() {3 rod := Rod{"Rod"}4 fmt.Println(rod.Text())5}6import (7func main() {8 rod := Rod{"Rod"}9 fmt.Println(rod.Text())10}11import (12func main() {13 rod := Rod{"Rod"}14 fmt.Println(rod.Text())15}16import (17func main() {18 rod := Rod{"Rod"}19 fmt.Println(rod.Text())20}21import (22func main() {23 rod := Rod{"Rod"}24 fmt.Println(rod.Text())25}26import (27func main() {28 rod := Rod{"Rod"}29 fmt.Println(rod.Text())30}31import (32func main() {33 rod := Rod{"Rod"}34 fmt.Println(rod.Text())35}36import (37func main() {38 rod := Rod{"Rod"}39 fmt.Println(rod.Text())40}41import (42func main() {43 rod := Rod{"Rod"}44 fmt.Println(rod.Text())45}46import (47func main() {48 rod := Rod{"Rod"}49 fmt.Println(rod.Text())50}51import (52func main() {53 rod := Rod{"Rod"}54 fmt.Println(rod.Text())55}
Text
Using AI Code Generation
1import (2func main() {3 text := robotgo.GetTitle()4 fmt.Println("text:", text)5 text = robotgo.GetActive()6 fmt.Println("text:", text)7 text = robotgo.GetPID()8 fmt.Println("text:", text)9 text = robotgo.GetBID()10 fmt.Println("text:", text)11 text = robotgo.GetText()12 fmt.Println("text:", text)13 text = robotgo.GetPID()14 fmt.Println("text:", text)15 text = robotgo.GetBID()16 fmt.Println("text:", text)17 text = robotgo.GetFocus()18 fmt.Println("text:", text)19 text = robotgo.GetHandle()20 fmt.Println("text:", text)21 text = robotgo.GetFront()22 fmt.Println("text:", text)23}24import (25func main() {26 text := robotgo.GetTitle()27 fmt.Println("text:", text)28 text = robotgo.GetActive()29 fmt.Println("text:", text)30 text = robotgo.GetPID()31 fmt.Println("text:", text)32 text = robotgo.GetBID()33 fmt.Println("text:", text)34 text = robotgo.GetFront()35 fmt.Println("text:", text)36 text = robotgo.GetHandle()37 fmt.Println("text:", text)
Text
Using AI Code Generation
1import "fmt"2func main() {3rod.Text()4}5import "fmt"6func main() {7var text func()8text()9}10import "fmt"11func main() {12var text func()13text()14}15import "fmt"16func main() {17var text func()18text()19}20import "fmt"21func main() {22var text func()23text()24}25import "fmt"26func main() {27var text func()28text()29}
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!!