Best K6 code snippet using html.Defer
phantomjs_test.go
Source:phantomjs_test.go
1package phantomjs_test2import (3 "bytes"4 "encoding/base64"5 "fmt"6 "image/png"7 "io/ioutil"8 "net/http"9 "net/http/httptest"10 "path/filepath"11 "reflect"12 "testing"13 "time"14 "github.com/benbjohnson/phantomjs"15)16// Ensure web page can return whether it can navigate forward.17func TestWebPage_CanGoForward(t *testing.T) {18 p := MustOpenNewProcess()19 defer p.MustClose()20 page := p.MustCreateWebPage()21 defer MustClosePage(page)22 if v, err := page.CanGoForward(); err != nil {23 t.Fatal(err)24 } else if v {25 t.Fatal("expected false")26 }27}28// Ensure process can return if the page can navigate back.29func TestWebPage_CanGoBack(t *testing.T) {30 p := MustOpenNewProcess()31 defer p.MustClose()32 page := p.MustCreateWebPage()33 defer MustClosePage(page)34 if v, err := page.CanGoBack(); err != nil {35 t.Fatal(err)36 } else if v {37 t.Fatal("expected false")38 }39}40// Ensure process can set and retrieve the clipping rectangle.41func TestWebPage_ClipRect(t *testing.T) {42 p := MustOpenNewProcess()43 defer p.MustClose()44 page := p.MustCreateWebPage()45 defer MustClosePage(page)46 // Clipping rectangle should be empty initially.47 if v, err := page.ClipRect(); err != nil {48 t.Fatal(err)49 } else if v != (phantomjs.Rect{}) {50 t.Fatalf("expected empty rect: %#v", v)51 }52 // Set a rectangle.53 rect := phantomjs.Rect{Top: 1, Left: 2, Width: 3, Height: 4}54 if err := page.SetClipRect(rect); err != nil {55 t.Fatal(err)56 }57 if v, err := page.ClipRect(); err != nil {58 t.Fatal(err)59 } else if !reflect.DeepEqual(v, rect) {60 t.Fatalf("unexpected value: %#v", v)61 }62}63// Ensure process can set and retrieve cookies.64func TestWebPage_Cookies(t *testing.T) {65 p := MustOpenNewProcess()66 defer p.MustClose()67 page := p.MustCreateWebPage()68 defer MustClosePage(page)69 // Test data.70 cookies := []*http.Cookie{71 {72 Domain: ".example1.com",73 HttpOnly: true,74 Name: "NAME1",75 Path: "/",76 Secure: true,77 Value: "VALUE1",78 },79 {80 Domain: ".example2.com",81 Expires: time.Date(2020, time.January, 2, 3, 4, 5, 0, time.UTC),82 HttpOnly: false,83 Name: "NAME2",84 Path: "/path",85 Secure: false,86 Value: "VALUE2",87 },88 }89 // Set the cookies.90 if err := page.SetCookies(cookies); err != nil {91 t.Fatal(err)92 }93 // Cookie with expiration should have string version set on return.94 cookies[1].RawExpires = "Thu, 02 Jan 2020 03:04:05 GMT"95 // Retrieve and verify the cookies.96 if other, err := page.Cookies(); err != nil {97 t.Fatal(err)98 } else if len(other) != 2 {99 t.Fatalf("unexpected cookie count: %d", len(other))100 } else if !reflect.DeepEqual(other[0], cookies[0]) {101 t.Fatalf("unexpected cookie(0): %#v", other[0])102 } else if !reflect.DeepEqual(other[1], cookies[1]) {103 t.Fatalf("unexpected cookie(1): %#v\n%#v", other[1], cookies[1])104 }105}106// Ensure process can set and retrieve custom headers.107func TestWebPage_CustomHeaders(t *testing.T) {108 p := MustOpenNewProcess()109 defer p.MustClose()110 page := p.MustCreateWebPage()111 defer MustClosePage(page)112 // Test data.113 hdr := make(http.Header)114 hdr.Set("FOO", "BAR")115 hdr.Set("BAZ", "BAT")116 // Set the headers.117 if err := page.SetCustomHeaders(hdr); err != nil {118 t.Fatal(err)119 }120 // Retrieve and verify the headers.121 if other, err := page.CustomHeaders(); err != nil {122 t.Fatal(err)123 } else if !reflect.DeepEqual(other, hdr) {124 t.Fatalf("unexpected value: %#v", other)125 }126}127// Ensure web page can return the name of the currently focused frame.128func TestWebPage_FocusedFrameName(t *testing.T) {129 // Mock external HTTP server.130 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {131 switch r.URL.Path {132 case "/":133 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))134 case "/frame1.html":135 w.Write([]byte(`<html><body>FRAME 1</body></html>`))136 case "/frame2.html":137 w.Write([]byte(`<html><body><input autofocus/></body></html>`))138 default:139 http.NotFound(w, r)140 }141 }))142 defer srv.Close()143 // Start process.144 p := MustOpenNewProcess()145 defer p.MustClose()146 // Create & open page.147 page := p.MustCreateWebPage()148 defer MustClosePage(page)149 if err := page.Open(srv.URL); err != nil {150 t.Fatal(err)151 }152 // Retrieve the focused frame.153 if other, err := page.FocusedFrameName(); err != nil {154 t.Fatal(err)155 } else if other != "FRAME2" {156 t.Fatalf("unexpected value: %#v", other)157 }158}159// Ensure web page can set and retrieve frame content.160func TestWebPage_FrameContent(t *testing.T) {161 // Mock external HTTP server.162 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {163 switch r.URL.Path {164 case "/":165 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))166 case "/frame1.html":167 w.Write([]byte(`<html><body>FOO</body></html>`))168 case "/frame2.html":169 w.Write([]byte(`<html><body>BAR</body></html>`))170 default:171 http.NotFound(w, r)172 }173 }))174 defer srv.Close()175 // Start process.176 p := MustOpenNewProcess()177 defer p.MustClose()178 // Create & open page.179 page := p.MustCreateWebPage()180 defer MustClosePage(page)181 if err := page.Open(srv.URL); err != nil {182 t.Fatal(err)183 }184 // Switch to frame and update content.185 if err := page.SwitchToFrameName("FRAME2"); err != nil {186 t.Fatal(err)187 }188 if err := page.SetFrameContent(`<html><body>NEW CONTENT</body></html>`); err != nil {189 t.Fatal(err)190 }191 if other, err := page.FrameContent(); err != nil {192 t.Fatal(err)193 } else if other != `<html><head></head><body>NEW CONTENT</body></html>` {194 t.Fatalf("unexpected value: %#v", other)195 }196}197// Ensure web page can retrieve the current frame name.198func TestWebPage_FrameName(t *testing.T) {199 // Mock external HTTP server.200 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {201 switch r.URL.Path {202 case "/":203 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))204 case "/frame1.html":205 w.Write([]byte(`<html><body>FOO</body></html>`))206 case "/frame2.html":207 w.Write([]byte(`<html><body>BAR</body></html>`))208 default:209 http.NotFound(w, r)210 }211 }))212 defer srv.Close()213 // Start process.214 p := MustOpenNewProcess()215 defer p.MustClose()216 // Create & open page.217 page := p.MustCreateWebPage()218 defer MustClosePage(page)219 if err := page.Open(srv.URL); err != nil {220 t.Fatal(err)221 }222 // Switch to frame and retrieve name.223 if err := page.SwitchToFrameName("FRAME2"); err != nil {224 t.Fatal(err)225 }226 if other, err := page.FrameName(); err != nil {227 t.Fatal(err)228 } else if other != `FRAME2` {229 t.Fatalf("unexpected value: %#v", other)230 }231}232// Ensure web page can retrieve frame content as plain text.233func TestWebPage_FramePlainText(t *testing.T) {234 // Mock external HTTP server.235 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {236 switch r.URL.Path {237 case "/":238 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))239 case "/frame1.html":240 w.Write([]byte(`<html><body>FOO</body></html>`))241 case "/frame2.html":242 w.Write([]byte(`<html><body>BAR</body></html>`))243 default:244 http.NotFound(w, r)245 }246 }))247 defer srv.Close()248 // Start process.249 p := MustOpenNewProcess()250 defer p.MustClose()251 // Create & open page.252 page := p.MustCreateWebPage()253 defer MustClosePage(page)254 if err := page.Open(srv.URL); err != nil {255 t.Fatal(err)256 }257 // Switch to frame and update content.258 if err := page.SwitchToFrameName("FRAME2"); err != nil {259 t.Fatal(err)260 }261 if other, err := page.FramePlainText(); err != nil {262 t.Fatal(err)263 } else if other != `BAR` {264 t.Fatalf("unexpected value: %#v", other)265 }266}267// Ensure web page can retrieve the frame title.268func TestWebPage_FrameTitle(t *testing.T) {269 // Mock external HTTP server.270 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {271 switch r.URL.Path {272 case "/":273 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))274 case "/frame1.html":275 w.Write([]byte(`<html><body>FOO</body></html>`))276 case "/frame2.html":277 w.Write([]byte(`<html><head><title>TEST TITLE</title><body>BAR</body></html>`))278 default:279 http.NotFound(w, r)280 }281 }))282 defer srv.Close()283 // Start process.284 p := MustOpenNewProcess()285 defer p.MustClose()286 // Create & open page.287 page := p.MustCreateWebPage()288 defer MustClosePage(page)289 if err := page.Open(srv.URL); err != nil {290 t.Fatal(err)291 }292 // Switch to frame and verify title.293 if err := page.SwitchToFrameName("FRAME2"); err != nil {294 t.Fatal(err)295 }296 if other, err := page.FrameTitle(); err != nil {297 t.Fatal(err)298 } else if other != `TEST TITLE` {299 t.Fatalf("unexpected value: %#v", other)300 }301}302// Ensure web page can retrieve the frame URL.303func TestWebPage_FrameURL(t *testing.T) {304 // Mock external HTTP server.305 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {306 switch r.URL.Path {307 case "/":308 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))309 case "/frame1.html":310 w.Write([]byte(`<html><body>FOO</body></html>`))311 case "/frame2.html":312 w.Write([]byte(`<html><body>BAR</body></html>`))313 default:314 http.NotFound(w, r)315 }316 }))317 defer srv.Close()318 // Start process.319 p := MustOpenNewProcess()320 defer p.MustClose()321 // Create & open page.322 page := p.MustCreateWebPage()323 defer MustClosePage(page)324 if err := page.Open(srv.URL); err != nil {325 t.Fatal(err)326 }327 // Switch to frame and verify title.328 if err := page.SwitchToFramePosition(1); err != nil {329 t.Fatal(err)330 }331 if other, err := page.FrameURL(); err != nil {332 t.Fatal(err)333 } else if other != srv.URL+`/frame2.html` {334 t.Fatalf("unexpected value: %#v", other)335 }336}337// Ensure web page can retrieve the total frame count.338func TestWebPage_FrameCount(t *testing.T) {339 // Mock external HTTP server.340 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {341 switch r.URL.Path {342 case "/":343 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))344 case "/frame1.html":345 w.Write([]byte(`<html><body>FOO</body></html>`))346 case "/frame2.html":347 w.Write([]byte(`<html><body>BAR</body></html>`))348 default:349 http.NotFound(w, r)350 }351 }))352 defer srv.Close()353 // Start process.354 p := MustOpenNewProcess()355 defer p.MustClose()356 // Create & open page.357 page := p.MustCreateWebPage()358 defer MustClosePage(page)359 if err := page.Open(srv.URL); err != nil {360 t.Fatal(err)361 }362 // Verify frame count.363 if n, err := page.FrameCount(); err != nil {364 t.Fatal(err)365 } else if n != 2 {366 t.Fatalf("unexpected value: %#v", n)367 }368}369// Ensure web page can retrieve a list of frame names.370func TestWebPage_FrameNames(t *testing.T) {371 // Mock external HTTP server.372 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {373 switch r.URL.Path {374 case "/":375 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))376 case "/frame1.html":377 w.Write([]byte(`<html><body>FOO</body></html>`))378 case "/frame2.html":379 w.Write([]byte(`<html><body>BAR</body></html>`))380 default:381 http.NotFound(w, r)382 }383 }))384 defer srv.Close()385 // Start process.386 p := MustOpenNewProcess()387 defer p.MustClose()388 // Create & open page.389 page := p.MustCreateWebPage()390 defer MustClosePage(page)391 if err := page.Open(srv.URL); err != nil {392 t.Fatal(err)393 }394 // Verify frame count.395 if other, err := page.FrameNames(); err != nil {396 t.Fatal(err)397 } else if !reflect.DeepEqual(other, []string{"FRAME1", "FRAME2"}) {398 t.Fatalf("unexpected value: %#v", other)399 }400}401// Ensure process can set and retrieve the library path.402func TestWebPage_LibraryPath(t *testing.T) {403 p := MustOpenNewProcess()404 defer p.MustClose()405 page := p.MustCreateWebPage()406 defer MustClosePage(page)407 // Verify initial path is equal to process path.408 if v, err := page.LibraryPath(); err != nil {409 t.Fatal(err)410 } else if v != p.Path() {411 t.Fatalf("unexpected path: %s", v)412 }413 // Set the library path & verify it changed.414 if err := page.SetLibraryPath("/tmp"); err != nil {415 t.Fatal(err)416 }417 if v, err := page.LibraryPath(); err != nil {418 t.Fatal(err)419 } else if v != `/tmp` {420 t.Fatalf("unexpected path: %s", v)421 }422}423// Ensure process can set and retrieve whether the navigation is locked.424func TestWebPage_NavigationLocked(t *testing.T) {425 p := MustOpenNewProcess()426 defer p.MustClose()427 page := p.MustCreateWebPage()428 defer MustClosePage(page)429 // Set the navigation lock & verify it changed.430 if err := page.SetNavigationLocked(true); err != nil {431 t.Fatal(err)432 }433 if v, err := page.NavigationLocked(); err != nil {434 t.Fatal(err)435 } else if !v {436 t.Fatal("expected navigation locked")437 }438}439// Ensure process can retrieve the offline storage path.440func TestWebPage_OfflineStoragePath(t *testing.T) {441 p := MustOpenNewProcess()442 defer p.MustClose()443 page := p.MustCreateWebPage()444 defer MustClosePage(page)445 // Retrieve storage path and ensure it's not blank.446 if v, err := page.OfflineStoragePath(); err != nil {447 t.Fatal(err)448 } else if v == `` {449 t.Fatal("expected path")450 }451}452// Ensure process can set and retrieve the offline storage quota.453func TestWebPage_OfflineStorageQuota(t *testing.T) {454 p := MustOpenNewProcess()455 defer p.MustClose()456 page := p.MustCreateWebPage()457 defer MustClosePage(page)458 // Retrieve storage quota and ensure it's non-zero.459 if v, err := page.OfflineStorageQuota(); err != nil {460 t.Fatal(err)461 } else if v == 0 {462 t.Fatal("expected quota")463 }464}465// Ensure process can set and retrieve whether the page owns other opened pages.466func TestWebPage_OwnsPages(t *testing.T) {467 p := MustOpenNewProcess()468 defer p.MustClose()469 page := p.MustCreateWebPage()470 defer MustClosePage(page)471 // Set value & verify it changed.472 if err := page.SetOwnsPages(true); err != nil {473 t.Fatal(err)474 }475 if v, err := page.OwnsPages(); err != nil {476 t.Fatal(err)477 } else if !v {478 t.Fatal("expected true")479 }480}481// Ensure process can retrieve a list of window names opened by the page.482func TestWebPage_PageWindowNames(t *testing.T) {483 p := MustOpenNewProcess()484 defer p.MustClose()485 page := p.MustCreateWebPage()486 defer MustClosePage(page)487 // Set content to open windows.488 if err := page.SetOwnsPages(true); err != nil {489 t.Fatal(err)490 }491 if err := page.SetContent(`<html><body><a id="link" target="win1" href="/win1.html">CLICK ME</a></body></html>`); err != nil {492 t.Fatal(err)493 }494 // Click the link.495 if _, err := page.EvaluateJavaScript(`function() { document.body.querySelector("#link").click() }`); err != nil {496 t.Fatal(err)497 }498 // Retrieve a list of window names.499 if names, err := page.PageWindowNames(); err != nil {500 t.Fatal(err)501 } else if !reflect.DeepEqual(names, []string{"win1"}) {502 t.Fatalf("unexpected names: %+v", names)503 }504}505// Ensure process can retrieve a list of owned web pages.506func TestWebPage_Pages(t *testing.T) {507 // Mock external HTTP server.508 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {509 switch r.URL.Path {510 case "/":511 w.Write([]byte(`<html><body><a id="link" target="win1" href="/win1.html">CLICK ME</a></body></html>`))512 case "/win1.html":513 w.Write([]byte(`<html><body>FOO</body></html>`))514 default:515 http.NotFound(w, r)516 }517 }))518 defer srv.Close()519 p := MustOpenNewProcess()520 defer p.MustClose()521 page := p.MustCreateWebPage()522 defer MustClosePage(page)523 // Open root page.524 if err := page.SetOwnsPages(true); err != nil {525 t.Fatal(err)526 }527 if err := page.Open(srv.URL); err != nil {528 t.Fatal(err)529 }530 // Click the link.531 if _, err := page.EvaluateJavaScript(`function() { document.body.querySelector("#link").click() }`); err != nil {532 t.Fatal(err)533 }534 // Retrieve a list of window names.535 if pages, err := page.Pages(); err != nil {536 t.Fatal(err)537 } else if len(pages) != 1 {538 t.Fatalf("unexpected count: %d", len(pages))539 } else if u, err := pages[0].URL(); err != nil {540 t.Fatal(err)541 } else if u != srv.URL+`/win1.html` {542 t.Fatalf("unexpected url: %s", u)543 } else if name, err := pages[0].WindowName(); err != nil {544 t.Fatal(err)545 } else if name != `win1` {546 t.Fatalf("unexpected window name: %s", name)547 }548}549// Ensure process can set and retrieve the sizing options used for printing.550func TestWebPage_PaperSize(t *testing.T) {551 p := MustOpenNewProcess()552 defer p.MustClose()553 // Ensure initial size is the zero value.554 t.Run("Initial", func(t *testing.T) {555 page := p.MustCreateWebPage()556 defer MustClosePage(page)557 if sz, err := page.PaperSize(); err != nil {558 t.Fatal(err)559 } else if !reflect.DeepEqual(sz, phantomjs.PaperSize{}) {560 t.Fatalf("unexpected size: %#v", sz)561 }562 })563 // Ensure width/height can be set.564 t.Run("WidthHeight", func(t *testing.T) {565 page := p.MustCreateWebPage()566 defer MustClosePage(page)567 sz := phantomjs.PaperSize{Width: "5in", Height: "10in"}568 if err := page.SetPaperSize(sz); err != nil {569 t.Fatal(err)570 }571 if other, err := page.PaperSize(); err != nil {572 t.Fatal(err)573 } else if !reflect.DeepEqual(other, sz) {574 t.Fatalf("unexpected size: %#v", other)575 }576 })577 // Ensure format can be set.578 t.Run("Format", func(t *testing.T) {579 page := p.MustCreateWebPage()580 defer MustClosePage(page)581 sz := phantomjs.PaperSize{Format: "A4"}582 if err := page.SetPaperSize(sz); err != nil {583 t.Fatal(err)584 }585 if other, err := page.PaperSize(); err != nil {586 t.Fatal(err)587 } else if !reflect.DeepEqual(other, sz) {588 t.Fatalf("unexpected size: %#v", other)589 }590 })591 // Ensure orientation can be set.592 t.Run("Orientation", func(t *testing.T) {593 page := p.MustCreateWebPage()594 defer MustClosePage(page)595 sz := phantomjs.PaperSize{Orientation: "landscape"}596 if err := page.SetPaperSize(sz); err != nil {597 t.Fatal(err)598 }599 if other, err := page.PaperSize(); err != nil {600 t.Fatal(err)601 } else if !reflect.DeepEqual(other, sz) {602 t.Fatalf("unexpected size: %#v", other)603 }604 })605 // Ensure margins can be set.606 t.Run("Margin", func(t *testing.T) {607 page := p.MustCreateWebPage()608 defer MustClosePage(page)609 sz := phantomjs.PaperSize{610 Margin: &phantomjs.PaperSizeMargin{611 Top: "1in",612 Bottom: "2in",613 Left: "3in",614 Right: "4in",615 },616 }617 if err := page.SetPaperSize(sz); err != nil {618 t.Fatal(err)619 }620 if other, err := page.PaperSize(); err != nil {621 t.Fatal(err)622 } else if !reflect.DeepEqual(other, sz) {623 t.Fatalf("unexpected size: %#v", other)624 }625 })626}627// Ensure process can retrieve the plain text representation of a page.628func TestWebPage_PlainText(t *testing.T) {629 p := MustOpenNewProcess()630 defer p.MustClose()631 page := p.MustCreateWebPage()632 defer MustClosePage(page)633 // Set content & verify plain text.634 if err := page.SetContent(`<html><body>FOO</body></html>`); err != nil {635 t.Fatal(err)636 }637 if v, err := page.PlainText(); err != nil {638 t.Fatal(err)639 } else if v != `FOO` {640 t.Fatalf("unexpected plain text: %s", v)641 }642}643// Ensure process can set and retrieve the scroll position of the page.644func TestWebPage_ScrollPosition(t *testing.T) {645 p := MustOpenNewProcess()646 defer p.MustClose()647 page := p.MustCreateWebPage()648 defer MustClosePage(page)649 // Set and verify position.650 pos := phantomjs.Position{Top: 10, Left: 20}651 if err := page.SetScrollPosition(pos); err != nil {652 t.Fatal(err)653 }654 if other, err := page.ScrollPosition(); err != nil {655 t.Fatal(err)656 } else if !reflect.DeepEqual(other, pos) {657 t.Fatalf("unexpected position: %#v", pos)658 }659}660// Ensure process can set and retrieve page settings.661func TestWebPage_Settings(t *testing.T) {662 p := MustOpenNewProcess()663 defer p.MustClose()664 page := p.MustCreateWebPage()665 defer MustClosePage(page)666 // Set and verify settings.667 settings := phantomjs.WebPageSettings{668 JavascriptEnabled: true,669 LoadImages: true,670 LocalToRemoteURLAccessEnabled: true,671 UserAgent: "Mozilla/5.0",672 Username: "susy",673 Password: "pass",674 XSSAuditingEnabled: true,675 WebSecurityEnabled: true,676 ResourceTimeout: 10 * time.Second,677 }678 if err := page.SetSettings(settings); err != nil {679 t.Fatal(err)680 }681 if other, err := page.Settings(); err != nil {682 t.Fatal(err)683 } else if !reflect.DeepEqual(other, settings) {684 t.Fatalf("unexpected settings: %#v", other)685 }686}687// Ensure process can retrieve the title of a page.688func TestWebPage_Title(t *testing.T) {689 p := MustOpenNewProcess()690 defer p.MustClose()691 page := p.MustCreateWebPage()692 defer MustClosePage(page)693 // Set & verify title.694 if err := page.SetContent(`<html><head><title>FOO</title></head><body>BAR</body></html>`); err != nil {695 t.Fatal(err)696 }697 if v, err := page.Title(); err != nil {698 t.Fatal(err)699 } else if v != `FOO` {700 t.Fatalf("unexpected plain text: %s", v)701 }702}703// Ensure process can set and retrieve the viewport size.704func TestWebPage_ViewportSize(t *testing.T) {705 p := MustOpenNewProcess()706 defer p.MustClose()707 page := p.MustCreateWebPage()708 defer MustClosePage(page)709 // Set and verify size.710 if err := page.SetViewportSize(100, 200); err != nil {711 t.Fatal(err)712 }713 if w, h, err := page.ViewportSize(); err != nil {714 t.Fatal(err)715 } else if w != 100 || h != 200 {716 t.Fatalf("unexpected size: w=%d, h=%d", w, h)717 }718}719// Ensure process can set and retrieve the zoom factor on the page.720func TestWebPage_ZoomFactor(t *testing.T) {721 p := MustOpenNewProcess()722 defer p.MustClose()723 page := p.MustCreateWebPage()724 defer MustClosePage(page)725 // Set factor & verify it changed.726 if err := page.SetZoomFactor(2.5); err != nil {727 t.Fatal(err)728 }729 if v, err := page.ZoomFactor(); err != nil {730 t.Fatal(err)731 } else if v != 2.5 {732 t.Fatalf("unexpected zoom factor: %f", v)733 }734}735// Ensure process can add a cookie to the page.736func TestWebPage_AddCookie(t *testing.T) {737 p := MustOpenNewProcess()738 defer p.MustClose()739 page := p.MustCreateWebPage()740 defer MustClosePage(page)741 // Test data.742 cookie := &http.Cookie{743 Domain: ".example1.com",744 HttpOnly: true,745 Name: "NAME1",746 Path: "/",747 Secure: true,748 Value: "VALUE1",749 }750 // Add the cookie.751 if v, err := page.AddCookie(cookie); err != nil {752 t.Fatal(err)753 } else if !v {754 t.Fatal("could not add cookie")755 }756 // Retrieve and verify the cookies.757 if other, err := page.Cookies(); err != nil {758 t.Fatal(err)759 } else if len(other) != 1 {760 t.Fatalf("unexpected cookie count: %d", len(other))761 } else if !reflect.DeepEqual(other[0], cookie) {762 t.Fatalf("unexpected cookie(0): %#v", other)763 }764}765// Ensure process can clear all cookies on the page.766func TestWebPage_ClearCookies(t *testing.T) {767 p := MustOpenNewProcess()768 defer p.MustClose()769 page := p.MustCreateWebPage()770 defer MustClosePage(page)771 // Add a cookie.772 if v, err := page.AddCookie(&http.Cookie{Domain: ".example1.com", Name: "NAME1", Path: "/", Value: "VALUE1"}); err != nil {773 t.Fatal(err)774 } else if !v {775 t.Fatal("could not add cookie")776 } else if cookies, err := page.Cookies(); err != nil {777 t.Fatal(err)778 } else if len(cookies) != 1 {779 t.Fatalf("unexpected cookie count: %d", len(cookies))780 }781 // Clear cookies and verify they are gone.782 if err := page.ClearCookies(); err != nil {783 t.Fatal(err)784 }785 if cookies, err := page.Cookies(); err != nil {786 t.Fatal(err)787 } else if len(cookies) != 0 {788 t.Fatalf("unexpected cookie count: %d", len(cookies))789 }790}791// Ensure process can delete a single cookie on the page.792func TestWebPage_DeleteCookie(t *testing.T) {793 p := MustOpenNewProcess()794 defer p.MustClose()795 page := p.MustCreateWebPage()796 defer MustClosePage(page)797 // Add a cookies.798 if v, err := page.AddCookie(&http.Cookie{Domain: ".example1.com", Name: "NAME1", Path: "/", Value: "VALUE1"}); err != nil {799 t.Fatal(err)800 } else if !v {801 t.Fatal("could not add cookie")802 }803 if v, err := page.AddCookie(&http.Cookie{Domain: ".example1.com", Name: "NAME2", Path: "/", Value: "VALUE2"}); err != nil {804 t.Fatal(err)805 } else if !v {806 t.Fatal("could not add cookie")807 }808 if cookies, err := page.Cookies(); err != nil {809 t.Fatal(err)810 } else if len(cookies) != 2 {811 t.Fatalf("unexpected cookie count: %d", len(cookies))812 }813 // Delete first cookie.814 if v, err := page.DeleteCookie("NAME1"); err != nil {815 t.Fatal(err)816 } else if !v {817 t.Fatal("could not delete cookie")818 }819 if cookies, err := page.Cookies(); err != nil {820 t.Fatal(err)821 } else if len(cookies) != 1 {822 t.Fatalf("unexpected cookie count: %d", len(cookies))823 } else if cookies[0].Name != "NAME2" {824 t.Fatalf("unexpected cookie(0) name: %s", cookies[0].Name)825 }826}827// Ensure process can execute JavaScript asynchronously.828// This function relies on time so it is inherently flakey.829func TestWebPage_EvaluateAsync(t *testing.T) {830 p := MustOpenNewProcess()831 defer p.MustClose()832 page := p.MustCreateWebPage()833 defer MustClosePage(page)834 // Execute after one second.835 if err := page.EvaluateAsync(`function() { window.testValue = "OK" }`, 1*time.Second); err != nil {836 t.Fatal(err)837 }838 // Value should not be set immediately.839 if value, err := page.EvaluateJavaScript(`function() { return window.testValue }`); err != nil {840 t.Fatal(err)841 } else if value != nil {842 t.Fatalf("unexpected value: %#v", value)843 }844 // Wait a bit.845 time.Sleep(2 * time.Second)846 // Value should hopefully be set now.847 if value, err := page.EvaluateJavaScript(`function() { return window.testValue }`); err != nil {848 t.Fatal(err)849 } else if value != "OK" {850 t.Fatalf("unexpected value: %#v", value)851 }852}853// Ensure process can execute JavaScript in the context of a web page.854func TestWebPage_Evaluate(t *testing.T) {855 p := MustOpenNewProcess()856 defer p.MustClose()857 page := p.MustCreateWebPage()858 defer MustClosePage(page)859 if err := page.SetContent(`<html><head><title>FOO</title></head><body>BAR</body></html>`); err != nil {860 t.Fatal(err)861 }862 // Retrieve title.863 if value, err := page.EvaluateJavaScript(`function() { return document.title }`); err != nil {864 t.Fatal(err)865 } else if value != "FOO" {866 t.Fatalf("unexpected value: %#v", value)867 }868}869// Ensure process can retrieve a page by window name.870func TestWebPage_Page(t *testing.T) {871 p := MustOpenNewProcess()872 defer p.MustClose()873 page := p.MustCreateWebPage()874 defer MustClosePage(page)875 // Set content to open windows.876 if err := page.SetOwnsPages(true); err != nil {877 t.Fatal(err)878 }879 if err := page.SetContent(`<html><body><a id="link" target="win1" href="/win1.html">CLICK ME</a></body></html>`); err != nil {880 t.Fatal(err)881 }882 // Click the link.883 if _, err := page.EvaluateJavaScript(`function() { document.body.querySelector("#link").click() }`); err != nil {884 t.Fatal(err)885 }886 // Retrieve a window by name.887 if childPage, err := page.Page("win1"); err != nil {888 t.Fatal(err)889 } else if childPage == nil {890 t.Fatalf("unexpected page: %#v", childPage)891 } else if name, err := childPage.WindowName(); err != nil {892 t.Fatal(err)893 } else if name != "win1" {894 t.Fatalf("unexpected page: %#v", childPage)895 }896 // Non-existent pages should return nil.897 if childPage, err := page.Page("bad_page"); err != nil {898 t.Fatal(err)899 } else if childPage != nil {900 t.Fatalf("expected nil page: %#v", childPage)901 }902}903// Ensure process can moves forward and back in history.904func TestWebPage_GoBackForward(t *testing.T) {905 // Mock external HTTP server.906 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {907 switch r.URL.Path {908 case "/":909 w.Write([]byte(`<html><body><a id="link" href="/page1.html">CLICK ME</a></body></html>`))910 case "/page1.html":911 w.Write([]byte(`<html><body>FOO</body></html>`))912 default:913 http.NotFound(w, r)914 }915 }))916 defer srv.Close()917 p := MustOpenNewProcess()918 defer p.MustClose()919 page := p.MustCreateWebPage()920 defer MustClosePage(page)921 // Open root page.922 if err := page.Open(srv.URL); err != nil {923 t.Fatal(err)924 }925 // Click the link and verify location.926 if _, err := page.EvaluateJavaScript(`function() { document.body.querySelector("#link").click() }`); err != nil {927 t.Fatal(err)928 }929 if u, err := page.URL(); err != nil {930 t.Fatal(err)931 } else if u != srv.URL+"/page1.html" {932 t.Fatalf("unexpected page: %s", u)933 }934 // Navigate back & verify location.935 if err := page.GoBack(); err != nil {936 t.Fatal(err)937 }938 if u, err := page.URL(); err != nil {939 t.Fatal(err)940 } else if u != srv.URL+"/" {941 t.Fatalf("unexpected page: %s", u)942 }943 // Navigate forward & verify location.944 if err := page.GoForward(); err != nil {945 t.Fatal(err)946 }947 if u, err := page.URL(); err != nil {948 t.Fatal(err)949 } else if u != srv.URL+"/page1.html" {950 t.Fatalf("unexpected page: %s", u)951 }952}953// Ensure process can move by relative index.954func TestWebPage_Go(t *testing.T) {955 // Mock external HTTP server.956 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {957 switch r.URL.Path {958 case "/":959 w.Write([]byte(`<html><body><a id="link" href="/page1.html">CLICK ME</a></body></html>`))960 case "/page1.html":961 w.Write([]byte(`<html><body><a id="link" href="/page2.html">CLICK ME</a></body></html>`))962 case "/page2.html":963 w.Write([]byte(`<html><body>FOO</body></html>`))964 default:965 http.NotFound(w, r)966 }967 }))968 defer srv.Close()969 p := MustOpenNewProcess()970 defer p.MustClose()971 page := p.MustCreateWebPage()972 defer MustClosePage(page)973 // Open root page.974 if err := page.Open(srv.URL); err != nil {975 t.Fatal(err)976 }977 // Click the links on two pages and verify location.978 if _, err := page.EvaluateJavaScript(`function() { document.body.querySelector("#link").click() }`); err != nil {979 t.Fatal(err)980 }981 if _, err := page.EvaluateJavaScript(`function() { document.body.querySelector("#link").click() }`); err != nil {982 t.Fatal(err)983 }984 if u, err := page.URL(); err != nil {985 t.Fatal(err)986 } else if u != srv.URL+"/page2.html" {987 t.Fatalf("unexpected page: %s", u)988 }989 // Navigate back & verify location.990 if err := page.Go(-2); err != nil {991 t.Fatal(err)992 }993 if u, err := page.URL(); err != nil {994 t.Fatal(err)995 } else if u != srv.URL+"/" {996 t.Fatalf("unexpected page: %s", u)997 }998 // Navigate forward & verify location.999 if err := page.Go(1); err != nil {1000 t.Fatal(err)1001 }1002 if u, err := page.URL(); err != nil {1003 t.Fatal(err)1004 } else if u != srv.URL+"/page1.html" {1005 t.Fatalf("unexpected page: %s", u)1006 }1007}1008// Ensure process include external scripts.1009func TestWebPage_IncludeJS(t *testing.T) {1010 // Mock external HTTP server.1011 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {1012 switch r.URL.Path {1013 case "/":1014 w.Write([]byte(`<html><body>FOO</body></html>`))1015 case "/script.js":1016 w.Write([]byte(`window.testValue = 'INCLUDED'`))1017 default:1018 http.NotFound(w, r)1019 }1020 }))1021 defer srv.Close()1022 p := MustOpenNewProcess()1023 defer p.MustClose()1024 page := p.MustCreateWebPage()1025 defer MustClosePage(page)1026 // Open root page.1027 if err := page.Open(srv.URL); err != nil {1028 t.Fatal(err)1029 }1030 // Include external script.1031 if err := page.IncludeJS(srv.URL + "/script.js"); err != nil {1032 t.Fatal(err)1033 }1034 // Verify that script ran.1035 if v, err := page.Evaluate(`function() { return window.testValue }`); err != nil {1036 t.Fatal(err)1037 } else if v != "INCLUDED" {1038 t.Fatalf("unexpected test value: %#v", v)1039 }1040}1041// Ensure process include local scripts.1042func TestWebPage_InjectJS(t *testing.T) {1043 p := MustOpenNewProcess()1044 defer p.MustClose()1045 page := p.MustCreateWebPage()1046 defer MustClosePage(page)1047 // Write local script.1048 if err := ioutil.WriteFile(filepath.Join(p.Path(), "script.js"), []byte(`window.testValue = 'INCLUDED'`), 0600); err != nil {1049 t.Fatal(err)1050 }1051 // Include local script.1052 if err := page.InjectJS("script.js"); err != nil {1053 t.Fatal(err)1054 }1055 // Verify that script ran.1056 if v, err := page.Evaluate(`function() { return window.testValue }`); err != nil {1057 t.Fatal(err)1058 } else if v != "INCLUDED" {1059 t.Fatalf("unexpected test value: %#v", v)1060 }1061}1062// Ensure web page can open a URL.1063func TestWebPage_Open(t *testing.T) {1064 // Serve web page.1065 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {1066 w.Write([]byte("<html><body>OK</body></html>"))1067 }))1068 defer srv.Close()1069 // Start process.1070 p := MustOpenNewProcess()1071 defer p.MustClose()1072 // Create & open page.1073 page := p.MustCreateWebPage()1074 defer MustClosePage(page)1075 if err := page.Open(srv.URL); err != nil {1076 t.Fatal(err)1077 } else if content, err := page.Content(); err != nil {1078 t.Fatal(err)1079 } else if content != `<html><head></head><body>OK</body></html>` {1080 t.Fatalf("unexpected content: %q", content)1081 }1082}1083// Ensure web page can reload a web page.1084func TestWebPage_Reload(t *testing.T) {1085 // Serve web page.1086 var counter int1087 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {1088 counter++1089 fmt.Fprintf(w, "<html><head></head><body>%d</body></html>", counter)1090 }))1091 defer srv.Close()1092 // Start process.1093 p := MustOpenNewProcess()1094 defer p.MustClose()1095 // Create & open page.1096 page := p.MustCreateWebPage()1097 defer MustClosePage(page)1098 if err := page.Open(srv.URL); err != nil {1099 t.Fatal(err)1100 }1101 // First time the counter should be 1.1102 if content, err := page.Content(); err != nil {1103 t.Fatal(err)1104 } else if content != `<html><head></head><body>1</body></html>` {1105 t.Fatalf("unexpected content: %q", content)1106 }1107 // Reload the page and the counter should increment.1108 if err := page.Reload(); err != nil {1109 t.Fatal(err)1110 }1111 if content, err := page.Content(); err != nil {1112 t.Fatal(err)1113 } else if content != `<html><head></head><body>2</body></html>` {1114 t.Fatalf("unexpected content: %q", content)1115 }1116}1117// Ensure web page can render to a base64 string.1118func TestWebPage_RenderBase64(t *testing.T) {1119 // Start process.1120 p := MustOpenNewProcess()1121 defer p.MustClose()1122 // Create & open page.1123 page := p.MustCreateWebPage()1124 defer MustClosePage(page)1125 if err := page.SetContent(`<html><head></head><body>TEST</body></html>`); err != nil {1126 t.Fatal(err)1127 }1128 if err := page.SetViewportSize(100, 200); err != nil {1129 t.Fatal(err)1130 }1131 // Render page.1132 data, err := page.RenderBase64("png")1133 if err != nil {1134 t.Fatal(err)1135 }1136 // Decode data.1137 buf, err := base64.StdEncoding.DecodeString(data)1138 if err != nil {1139 t.Fatal(err)1140 }1141 // Parse image and verify dimensions.1142 img, err := png.Decode(bytes.NewReader(buf))1143 if err != nil {1144 t.Fatal(err)1145 } else if bounds := img.Bounds(); bounds.Max.X != 100 || bounds.Max.Y != 200 {1146 t.Fatalf("unexpected image dimesions: %dx%d", bounds.Max.X, bounds.Max.Y)1147 }1148}1149// Ensure web page can render to a file.1150func TestWebPage_Render(t *testing.T) {1151 // Start process.1152 p := MustOpenNewProcess()1153 defer p.MustClose()1154 // Create & open page.1155 page := p.MustCreateWebPage()1156 defer MustClosePage(page)1157 if err := page.SetContent(`<html><head></head><body>TEST</body></html>`); err != nil {1158 t.Fatal(err)1159 }1160 if err := page.SetViewportSize(100, 200); err != nil {1161 t.Fatal(err)1162 }1163 // Render page.1164 filename := filepath.Join(p.Path(), "test.png")1165 if err := page.Render(filename, "png", 100); err != nil {1166 t.Fatal(err)1167 }1168 // Read file.1169 buf, err := ioutil.ReadFile(filename)1170 if err != nil {1171 t.Fatal(err)1172 }1173 // Parse image and verify dimensions.1174 img, err := png.Decode(bytes.NewReader(buf))1175 if err != nil {1176 t.Fatal(err)1177 } else if bounds := img.Bounds(); bounds.Max.X != 100 || bounds.Max.Y != 200 {1178 t.Fatalf("unexpected image dimesions: %dx%d", bounds.Max.X, bounds.Max.Y)1179 }1180}1181// Ensure web page can receive mouse events.1182func TestWebPage_SendMouseEvent(t *testing.T) {1183 // Start process.1184 p := MustOpenNewProcess()1185 defer p.MustClose()1186 // Create & open page.1187 page := p.MustCreateWebPage()1188 defer MustClosePage(page)1189 if err := page.SetContent(`<html><head><script>window.onclick = function(e) { window.testX = e.x; window.testY = e.y; window.testButton = e.button }</script></head><body></body></html>`); err != nil {1190 t.Fatal(err)1191 }1192 // Send mouse event.1193 if err := page.SendMouseEvent("click", 100, 200, "middle"); err != nil {1194 t.Fatal(err)1195 }1196 // Verify test variables.1197 if x, err := page.Evaluate(`function() { return window.testX }`); err != nil {1198 t.Fatal(err)1199 } else if x != float64(100) {1200 t.Fatalf("unexpected x: %d", x)1201 }1202 if y, err := page.Evaluate(`function() { return window.testY }`); err != nil {1203 t.Fatal(err)1204 } else if y != float64(200) {1205 t.Fatalf("unexpected y: %d", y)1206 }1207 if button, err := page.Evaluate(`function() { return window.testButton }`); err != nil {1208 t.Fatal(err)1209 } else if button != float64(1) {1210 t.Fatalf("unexpected button: %d", button)1211 }1212}1213// Ensure web page can receive keyboard events.1214func TestWebPage_SendKeyboardEvent(t *testing.T) {1215 // Start process.1216 p := MustOpenNewProcess()1217 defer p.MustClose()1218 // Create & open page.1219 page := p.MustCreateWebPage()1220 defer MustClosePage(page)1221 if err := page.SetContent(`<html><head><script>document.onkeydown = function(e) { window.testKey = e.keyCode; window.testAlt = e.altKey; window.testCtrl = e.ctrlKey; window.testMeta = e.metaKey; window.testShift = e.shiftKey; }</script></head><body></body></html>`); err != nil {1222 t.Fatal(err)1223 }1224 // Send event.1225 if err := page.SendKeyboardEvent("keydown", "A", phantomjs.AltKey|phantomjs.CtrlKey|phantomjs.MetaKey|phantomjs.ShiftKey); err != nil {1226 t.Fatal(err)1227 }1228 // Verify test variables.1229 if key, err := page.Evaluate(`function() { return window.testKey }`); err != nil {1230 t.Fatal(err)1231 } else if key != float64(65) {1232 t.Fatalf("unexpected key: %s", key)1233 }1234 if altKey, err := page.Evaluate(`function() { return window.testAlt }`); err != nil {1235 t.Fatal(err)1236 } else if altKey != true {1237 t.Fatalf("unexpected alt key: %v", altKey)1238 }1239 if ctrlKey, err := page.Evaluate(`function() { return window.testCtrl }`); err != nil {1240 t.Fatal(err)1241 } else if ctrlKey != true {1242 t.Fatalf("unexpected ctrl key: %v", ctrlKey)1243 }1244 if metaKey, err := page.Evaluate(`function() { return window.testMeta }`); err != nil {1245 t.Fatal(err)1246 } else if metaKey != true {1247 t.Fatalf("unexpected meta key: %v", metaKey)1248 }1249 if shiftKey, err := page.Evaluate(`function() { return window.testShift }`); err != nil {1250 t.Fatal(err)1251 } else if shiftKey != true {1252 t.Fatalf("unexpected shift key: %v", shiftKey)1253 }1254}1255// Ensure web page can set content and URL at the same time.1256func TestWebPage_SetContentAndURL(t *testing.T) {1257 // Start process.1258 p := MustOpenNewProcess()1259 defer p.MustClose()1260 // Create & open page.1261 page := p.MustCreateWebPage()1262 defer MustClosePage(page)1263 if err := page.SetContentAndURL(`<html><body>FOO</body></html>`, "http://google.com"); err != nil {1264 t.Fatal(err)1265 }1266 // Verify content & URL.1267 if content, err := page.Content(); err != nil {1268 t.Fatal(err)1269 } else if content != `<html><head></head><body>FOO</body></html>` {1270 t.Fatalf("unexpected content: %s", content)1271 }1272 if u, err := page.URL(); err != nil {1273 t.Fatal(err)1274 } else if u != `http://google.com/` {1275 t.Fatalf("unexpected URL: %s", u)1276 }1277}1278// Ensure web page can call stop().1279func TestWebPage_Stop(t *testing.T) {1280 // Start process.1281 p := MustOpenNewProcess()1282 defer p.MustClose()1283 // Create & open page.1284 page := p.MustCreateWebPage()1285 defer MustClosePage(page)1286 // Call stop and ensure it doesn't blow up.1287 if err := page.Stop(); err != nil {1288 t.Fatal(err)1289 }1290}1291// Ensure web page can switch to the focused frame.1292func TestWebPage_SwitchToFocusedFrame(t *testing.T) {1293 // Mock external HTTP server.1294 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {1295 switch r.URL.Path {1296 case "/":1297 w.Write([]byte(`<html><frameset rows="*,*"><frame name="FRAME1" src="/frame1.html"/><frame name="FRAME2" src="/frame2.html"/></frameset></html>`))1298 case "/frame1.html":1299 w.Write([]byte(`<html><body></body></html>`))1300 case "/frame2.html":1301 w.Write([]byte(`<html><body><input autofocus/></body></html>`))1302 default:1303 http.NotFound(w, r)1304 }1305 }))1306 defer srv.Close()1307 // Start process.1308 p := MustOpenNewProcess()1309 defer p.MustClose()1310 // Create & open page.1311 page := p.MustCreateWebPage()1312 defer MustClosePage(page)1313 if err := page.Open(srv.URL); err != nil {1314 t.Fatal(err)1315 }1316 // Check initial current frame.1317 if other, err := page.FrameName(); err != nil {1318 t.Fatal(err)1319 } else if other != `` {1320 t.Fatalf("unexpected value: %#v", other)1321 }1322 // Switch to focused frame and verify.1323 if err := page.SwitchToFocusedFrame(); err != nil {1324 t.Fatal(err)1325 }1326 if other, err := page.FrameName(); err != nil {1327 t.Fatal(err)1328 } else if other != `FRAME2` {1329 t.Fatalf("unexpected value: %#v", other)1330 }1331}1332// Ensure web page can upload a file to a form field.1333func TestWebPage_UploadFile(t *testing.T) {1334 // Mock external HTTP server.1335 uploadData := make(chan []byte, 0)1336 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {1337 switch r.Method {1338 case "GET":1339 w.Write([]byte(`<html><body><form id="myForm" method="POST" enctype="multipart/form-data"><input type="file" name="myfile"/></form></body></html>`))1340 case "POST":1341 f, _, err := r.FormFile("myfile")1342 if err != nil {1343 t.Fatal(err)1344 }1345 buf, err := ioutil.ReadAll(f)1346 if err != nil {1347 t.Fatal(err)1348 }1349 uploadData <- buf1350 default:1351 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)1352 }1353 }))1354 defer srv.Close()1355 // Start process.1356 p := MustOpenNewProcess()1357 defer p.MustClose()1358 // Create & open page.1359 page := p.MustCreateWebPage()1360 defer MustClosePage(page)1361 if err := page.Open(srv.URL); err != nil {1362 t.Fatal(err)1363 }1364 // Write file to disk.1365 path := filepath.Join(p.Path(), "testfile")1366 if err := ioutil.WriteFile(path, []byte("TESTDATA"), 0600); err != nil {1367 t.Fatal(err)1368 }1369 // Upload to field1370 if err := page.UploadFile("input[name=myfile]", path); err != nil {1371 t.Fatal(err)1372 }1373 // Submit form.1374 if _, err := page.Evaluate(`function() { document.body.querySelector("#myForm").submit() }`); err != nil {1375 t.Fatal(err)1376 }1377 // Wait for upload.1378 buf := <-uploadData1379 if string(buf) != "TESTDATA" {1380 t.Fatalf("unexpected upload data: %s", buf)1381 }1382}1383// Process is a test wrapper for phantomjs.Process.1384type Process struct {1385 *phantomjs.Process1386}1387// NewProcess returns a new, open Process.1388func NewProcess() *Process {1389 return &Process{Process: phantomjs.NewProcess()}1390}1391// MustOpenNewProcess returns a new, open Process. Panic on error.1392func MustOpenNewProcess() *Process {1393 p := NewProcess()1394 if err := p.Open(); err != nil {1395 panic(err)1396 }1397 return p1398}1399// MustClose closes the process. Panic on error.1400func (p *Process) MustClose() {1401 if err := p.Close(); err != nil {1402 panic(err)1403 }1404}1405// MustCreateWebPage creates a web page. Panic on error.1406func (p *Process) MustCreateWebPage() *phantomjs.WebPage {1407 page, err := p.CreateWebPage()1408 if err != nil {1409 panic(err)1410 }1411 return page1412}1413// MustClosePage closes page. Panic on error.1414func MustClosePage(page *phantomjs.WebPage) {1415 if err := page.Close(); err != nil {1416 panic(err)1417 }1418}...
example_test.go
Source:example_test.go
1package chromedp_test2import (3 "bytes"4 "context"5 "fmt"6 "io"7 "io/ioutil"8 "log"9 "net/http"10 "net/http/httptest"11 "os"12 "path/filepath"13 "strings"14 "time"15 "github.com/chromedp/cdproto/cdp"16 "github.com/chromedp/cdproto/dom"17 "github.com/chromedp/cdproto/page"18 "github.com/chromedp/cdproto/runtime"19 "github.com/chromedp/cdproto/target"20 "github.com/chromedp/chromedp"21 "github.com/chromedp/chromedp/device"22)23func writeHTML(content string) http.Handler {24 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {25 w.Header().Set("Content-Type", "text/html")26 io.WriteString(w, strings.TrimSpace(content))27 })28}29func ExampleTitle() {30 ctx, cancel := chromedp.NewContext(context.Background())31 defer cancel()32 ts := httptest.NewServer(writeHTML(`33<head>34 <title>fancy website title</title>35</head>36<body>37 <div id="content"></div>38</body>39 `))40 defer ts.Close()41 var title string42 if err := chromedp.Run(ctx,43 chromedp.Navigate(ts.URL),44 chromedp.Title(&title),45 ); err != nil {46 panic(err)47 }48 fmt.Println(title)49 // Output:50 // fancy website title51}52func ExampleRunResponse() {53 ctx, cancel := chromedp.NewContext(context.Background())54 defer cancel()55 // This server simply shows the URL path as the page title, and contains56 // a link that points to /foo.57 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {58 w.Header().Set("Content-Type", "text/html")59 fmt.Fprintf(w, `60 <head><title>%s</title></head>61 <body><a id="foo" href="/foo">foo</a></body>62 `, r.URL.Path)63 }))64 defer ts.Close()65 // The Navigate action already waits until a page loads, so Title runs66 // once the page is ready.67 var firstTitle string68 if err := chromedp.Run(ctx,69 chromedp.Navigate(ts.URL),70 chromedp.Title(&firstTitle),71 ); err != nil {72 panic(err)73 }74 fmt.Println("first title:", firstTitle)75 // However, actions like Click don't always trigger a page navigation,76 // so they don't wait for a page load directly. Wrapping them with77 // RunResponse does that waiting, and also obtains the HTTP response.78 resp, err := chromedp.RunResponse(ctx, chromedp.Click("#foo", chromedp.ByID))79 if err != nil {80 panic(err)81 }82 fmt.Println("second status code:", resp.Status)83 // Grabbing the title again should work, as the page has finished84 // loading once more.85 var secondTitle string86 if err := chromedp.Run(ctx, chromedp.Title(&secondTitle)); err != nil {87 panic(err)88 }89 fmt.Println("second title:", secondTitle)90 // Finally, it's always possible to wrap Navigate with RunResponse, if91 // one wants the response information for that case too.92 resp, err = chromedp.RunResponse(ctx, chromedp.Navigate(ts.URL+"/bar"))93 if err != nil {94 panic(err)95 }96 fmt.Println("third status code:", resp.Status)97 // Output:98 // first title: /99 // second status code: 200100 // second title: /foo101 // third status code: 200102}103func ExampleExecAllocator() {104 dir, err := ioutil.TempDir("", "chromedp-example")105 if err != nil {106 panic(err)107 }108 defer os.RemoveAll(dir)109 opts := append(chromedp.DefaultExecAllocatorOptions[:],110 chromedp.DisableGPU,111 chromedp.UserDataDir(dir),112 )113 allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)114 defer cancel()115 // also set up a custom logger116 taskCtx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))117 defer cancel()118 // ensure that the browser process is started119 if err := chromedp.Run(taskCtx); err != nil {120 panic(err)121 }122 path := filepath.Join(dir, "DevToolsActivePort")123 bs, err := ioutil.ReadFile(path)124 if err != nil {125 panic(err)126 }127 lines := bytes.Split(bs, []byte("\n"))128 fmt.Printf("DevToolsActivePort has %d lines\n", len(lines))129 // Output:130 // DevToolsActivePort has 2 lines131}132func ExampleNewContext_reuseBrowser() {133 ts := httptest.NewServer(writeHTML(`134<body>135<script>136 // Show the current cookies.137 var p = document.createElement("p")138 p.innerText = document.cookie139 p.setAttribute("id", "cookies")140 document.body.appendChild(p)141 // Override the cookies.142 document.cookie = "foo=bar"143</script>144</body>145 `))146 defer ts.Close()147 // create a new browser148 ctx, cancel := chromedp.NewContext(context.Background())149 defer cancel()150 // start the browser without a timeout151 if err := chromedp.Run(ctx); err != nil {152 panic(err)153 }154 for i := 0; i < 2; i++ {155 // look at the page twice, with a timeout set up; we skip156 // cancels for the sake of brevity157 ctx, _ := context.WithTimeout(ctx, time.Second)158 ctx, _ = chromedp.NewContext(ctx)159 var cookies string160 if err := chromedp.Run(ctx,161 chromedp.Navigate(ts.URL),162 chromedp.Text("#cookies", &cookies),163 ); err != nil {164 panic(err)165 }166 fmt.Printf("Cookies at i=%d: %q\n", i, cookies)167 }168 // Output:169 // Cookies at i=0: ""170 // Cookies at i=1: "foo=bar"171}172func ExampleNewContext_manyTabs() {173 // new browser, first tab174 ctx1, cancel := chromedp.NewContext(context.Background())175 defer cancel()176 // ensure the first tab is created177 if err := chromedp.Run(ctx1); err != nil {178 panic(err)179 }180 // same browser, second tab181 ctx2, _ := chromedp.NewContext(ctx1)182 // ensure the second tab is created183 if err := chromedp.Run(ctx2); err != nil {184 panic(err)185 }186 c1 := chromedp.FromContext(ctx1)187 c2 := chromedp.FromContext(ctx2)188 fmt.Printf("Same browser: %t\n", c1.Browser == c2.Browser)189 fmt.Printf("Same tab: %t\n", c1.Target == c2.Target)190 // Output:191 // Same browser: true192 // Same tab: false193}194func ExampleListenTarget_consoleLog() {195 ctx, cancel := chromedp.NewContext(context.Background())196 defer cancel()197 ts := httptest.NewServer(writeHTML(`198<body>199<script>200 console.log("hello js world")201 console.warn("scary warning", 123)202 null.throwsException203</script>204</body>205 `))206 defer ts.Close()207 gotException := make(chan bool, 1)208 chromedp.ListenTarget(ctx, func(ev interface{}) {209 switch ev := ev.(type) {210 case *runtime.EventConsoleAPICalled:211 fmt.Printf("* console.%s call:\n", ev.Type)212 for _, arg := range ev.Args {213 fmt.Printf("%s - %s\n", arg.Type, arg.Value)214 }215 case *runtime.EventExceptionThrown:216 // Since ts.URL uses a random port, replace it.217 s := ev.ExceptionDetails.Error()218 s = strings.ReplaceAll(s, ts.URL, "<server>")219 fmt.Printf("* %s\n", s)220 gotException <- true221 }222 })223 if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL)); err != nil {224 panic(err)225 }226 <-gotException227 // Output:228 // * console.log call:229 // string - "hello js world"230 // * console.warning call:231 // string - "scary warning"232 // number - 123233 // * exception "Uncaught" (4:6): TypeError: Cannot read property 'throwsException' of null234 // at <server>/:5:7235}236func ExampleWaitNewTarget() {237 ctx, cancel := chromedp.NewContext(context.Background())238 defer cancel()239 mux := http.NewServeMux()240 mux.Handle("/first", writeHTML(`241<input id='newtab' type='button' value='open' onclick='window.open("/second", "_blank");'/>242 `))243 mux.Handle("/second", writeHTML(``))244 ts := httptest.NewServer(mux)245 defer ts.Close()246 // Grab the first spawned tab that isn't blank.247 ch := chromedp.WaitNewTarget(ctx, func(info *target.Info) bool {248 return info.URL != ""249 })250 if err := chromedp.Run(ctx,251 chromedp.Navigate(ts.URL+"/first"),252 chromedp.Click("#newtab", chromedp.ByID),253 ); err != nil {254 panic(err)255 }256 newCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(<-ch))257 defer cancel()258 var urlstr string259 if err := chromedp.Run(newCtx, chromedp.Location(&urlstr)); err != nil {260 panic(err)261 }262 fmt.Println("new tab's path:", strings.TrimPrefix(urlstr, ts.URL))263 // Output:264 // new tab's path: /second265}266func ExampleListenTarget_acceptAlert() {267 ctx, cancel := chromedp.NewContext(context.Background())268 defer cancel()269 mux := http.NewServeMux()270 mux.Handle("/second", writeHTML(``))271 ts := httptest.NewServer(writeHTML(`272<input id='alert' type='button' value='alert' onclick='alert("alert text");'/>273 `))274 defer ts.Close()275 chromedp.ListenTarget(ctx, func(ev interface{}) {276 if ev, ok := ev.(*page.EventJavascriptDialogOpening); ok {277 fmt.Println("closing alert:", ev.Message)278 go func() {279 if err := chromedp.Run(ctx,280 page.HandleJavaScriptDialog(true),281 ); err != nil {282 panic(err)283 }284 }()285 }286 })287 if err := chromedp.Run(ctx,288 chromedp.Navigate(ts.URL),289 chromedp.Click("#alert", chromedp.ByID),290 ); err != nil {291 panic(err)292 }293 // Output:294 // closing alert: alert text295}296func Example_retrieveHTML() {297 ctx, cancel := chromedp.NewContext(context.Background())298 defer cancel()299 ts := httptest.NewServer(writeHTML(`300<body>301<p id="content" onclick="changeText()">Original content.</p>302<script>303function changeText() {304 document.getElementById("content").textContent = "New content!"305}306</script>307</body>308 `))309 defer ts.Close()310 var outerBefore, outerAfter string311 if err := chromedp.Run(ctx,312 chromedp.Navigate(ts.URL),313 chromedp.OuterHTML("#content", &outerBefore),314 chromedp.Click("#content", chromedp.ByID),315 chromedp.OuterHTML("#content", &outerAfter),316 ); err != nil {317 panic(err)318 }319 fmt.Println("OuterHTML before clicking:")320 fmt.Println(outerBefore)321 fmt.Println("OuterHTML after clicking:")322 fmt.Println(outerAfter)323 // Output:324 // OuterHTML before clicking:325 // <p id="content" onclick="changeText()">Original content.</p>326 // OuterHTML after clicking:327 // <p id="content" onclick="changeText()">New content!</p>328}329func ExampleEmulate() {330 ctx, cancel := chromedp.NewContext(context.Background())331 defer cancel()332 var buf []byte333 if err := chromedp.Run(ctx,334 chromedp.Emulate(device.IPhone7),335 chromedp.Navigate(`https://google.com/`),336 chromedp.SendKeys(`input[name=q]`, "what's my user agent?\n"),337 chromedp.WaitVisible(`#rso`, chromedp.ByID),338 chromedp.CaptureScreenshot(&buf),339 ); err != nil {340 panic(err)341 }342 if err := ioutil.WriteFile("google-iphone7.png", buf, 0o644); err != nil {343 panic(err)344 }345}346func ExamplePrintToPDF() {347 ctx, cancel := chromedp.NewContext(context.Background())348 defer cancel()349 var buf []byte350 if err := chromedp.Run(ctx,351 chromedp.Navigate(`https://godoc.org/github.com/chromedp/chromedp`),352 chromedp.ActionFunc(func(ctx context.Context) error {353 var err error354 buf, _, err = page.PrintToPDF().355 WithDisplayHeaderFooter(false).356 WithLandscape(true).357 Do(ctx)358 return err359 }),360 ); err != nil {361 panic(err)362 }363 if err := ioutil.WriteFile("page.pdf", buf, 0o644); err != nil {364 panic(err)365 }366}367func ExampleByJSPath() {368 ctx, cancel := chromedp.NewContext(context.Background())369 defer cancel()370 ts := httptest.NewServer(writeHTML(`371<body>372 <div id="content">cool content</div>373</body>374 `))375 defer ts.Close()376 var ids []cdp.NodeID377 var html string378 if err := chromedp.Run(ctx,379 chromedp.Navigate(ts.URL),380 chromedp.NodeIDs(`document`, &ids, chromedp.ByJSPath),381 chromedp.ActionFunc(func(ctx context.Context) error {382 var err error383 html, err = dom.GetOuterHTML().WithNodeID(ids[0]).Do(ctx)384 return err385 }),386 ); err != nil {387 panic(err)388 }389 fmt.Println("Outer HTML:")390 fmt.Println(html)391 // Output:392 // Outer HTML:393 // <html><head></head><body>394 // <div id="content">cool content</div>395 // </body></html>396}397func ExampleFromNode() {398 ctx, cancel := chromedp.NewContext(context.Background())399 defer cancel()400 ts := httptest.NewServer(writeHTML(`401<body>402 <p class="content">outer content</p>403 <div id="section"><p class="content">inner content</p></div>404</body>405 `))406 defer ts.Close()407 var nodes []*cdp.Node408 if err := chromedp.Run(ctx,409 chromedp.Navigate(ts.URL),410 chromedp.Nodes("#section", &nodes, chromedp.ByQuery),411 ); err != nil {412 panic(err)413 }414 sectionNode := nodes[0]415 var queryRoot, queryFromNode, queryNestedSelector string416 if err := chromedp.Run(ctx,417 // Queries run from the document root by default, so Text will418 // pick the first node it finds.419 chromedp.Text(".content", &queryRoot, chromedp.ByQuery),420 // We can specify a different node to run the query from; in421 // this case, we can tailor the search within #section.422 chromedp.Text(".content", &queryFromNode, chromedp.ByQuery, chromedp.FromNode(sectionNode)),423 // A CSS selector like "#section > .content" achieves the same424 // here, but FromNode allows us to use a node obtained by an425 // entirely separate step, allowing for custom logic.426 chromedp.Text("#section > .content", &queryNestedSelector, chromedp.ByQuery),427 ); err != nil {428 panic(err)429 }430 fmt.Println("Simple query from the document root:", queryRoot)431 fmt.Println("Simple query from the section node:", queryFromNode)432 fmt.Println("Nested query from the document root:", queryNestedSelector)433 // Output:434 // Simple query from the document root: outer content435 // Simple query from the section node: inner content436 // Nested query from the document root: inner content437}438func Example_documentDump() {439 ctx, cancel := chromedp.NewContext(context.Background())440 defer cancel()441 ts := httptest.NewServer(writeHTML(`<!doctype html>442<html>443<body>444 <div id="content">the content</div>445</body>446</html>`))447 defer ts.Close()448 const expr = `(function(d, id, v) {449 var b = d.querySelector('body');450 var el = d.createElement('div');451 el.id = id;452 el.innerText = v;453 b.insertBefore(el, b.childNodes[0]);454 })(document, %q, %q);`455 var nodes []*cdp.Node456 if err := chromedp.Run(ctx,457 chromedp.Navigate(ts.URL),458 chromedp.Nodes(`document`, &nodes, chromedp.ByJSPath),459 chromedp.WaitVisible(`#content`),460 chromedp.ActionFunc(func(ctx context.Context) error {461 s := fmt.Sprintf(expr, "thing", "a new thing!")462 _, exp, err := runtime.Evaluate(s).Do(ctx)463 if err != nil {464 return err465 }466 if exp != nil {467 return exp468 }469 return nil470 }),471 chromedp.WaitVisible(`#thing`),472 ); err != nil {473 panic(err)474 }475 fmt.Println("Document tree:")476 fmt.Print(nodes[0].Dump(" ", " ", false))477 // Output:478 // Document tree:479 // #document <Document>480 // html <DocumentType>481 // html482 // head483 // body484 // div#thing485 // #text "a new thing!"486 // div#content487 // #text "the content"488}...
Defer
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))5 })6 http.ListenAndServe(":8080", nil)7}8import (9func main() {10 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {11 t, err := template.ParseFiles("index.html")12 if err != nil {13 log.Print("template parsing error: ", err)14 }15 err = t.Execute(w, time.Now())16 if err != nil {17 log.Print("template executing error: ", err)18 }19 })20 http.ListenAndServe(":8080", nil)21}22 <p>Current time: {{ . }}</p>23import (24func main() {25 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {26 t, err := template.ParseFiles("index.html")27 if err != nil {28 log.Print("template parsing error: ", err)29 }30 err = t.Execute(w, time.Now())31 if err != nil {32 log.Print("template executing error: ", err)33 }34 })35 http.ListenAndServe(":8080", nil)36}37 <p>Current time: {{ . }}</
Defer
Using AI Code Generation
1if err != nil {2 log.Fatal(err)3}4html.Find(".r").Each(func(i int, s *goquery.Selection) {5 band := s.Find("a").Text()6 title := s.Find("i").Text()7 fmt.Printf("Review %d: %s - %s8})9if err != nil {10 log.Fatal(err)11}12html.Find(".r").Each(func(i int, s *goquery.Selection) {13 band := s.Find("a").Text()14 title := s.Find("i").Text()15 fmt.Printf("Review %d: %s - %s16})17if err != nil {18 log.Fatal(err)19}20html.Find(".r").Each(func(i int, s *goquery.Selection) {21 band := s.Find("a").Text()22 title := s.Find("i").Text()23 fmt.Printf("Review %d: %s - %s24})25if err != nil {26 log.Fatal(err)27}28html.Find(".r").Each(func(i int, s *goquery.Selection) {29 band := s.Find("a").Text()30 title := s.Find("i").Text()31 fmt.Printf("Review %d: %s - %s32})33html, err := goquery.NewDocument("http
Defer
Using AI Code Generation
1func main() {2 html := NewHTML()3 html.Defer()4}5func main() {6 html := NewHTML()7 html.Defer()8}9func main() {10 html := NewHTML()11 html.Defer()12}13func main() {14 html := NewHTML()15 html.Defer()16}17func main() {18 html := NewHTML()19 html.Defer()20}21func main() {22 html := NewHTML()23 html.Defer()24}25func main() {26 html := NewHTML()27 html.Defer()28}29func main() {30 html := NewHTML()31 html.Defer()32}33func main() {34 html := NewHTML()35 html.Defer()36}37func main() {38 html := NewHTML()39 html.Defer()40}41func main() {42 html := NewHTML()43 html.Defer()44}45func main() {46 html := NewHTML()47 html.Defer()48}49func main() {50 html := NewHTML()51 html.Defer()52}53func main() {54 html := NewHTML()55 html.Defer()56}57func main() {58 html := NewHTML()59 html.Defer()60}
Defer
Using AI Code Generation
1import (2func main() {3 fmt.Println(html.EscapeString("This is <b>HTML</b>"))4}5import (6func main() {7 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))8}9import (10func main() {11 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))12}13import (14func main() {15 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))16}17import (18func main() {19 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))20}21import (22func main() {23 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))24}25import (26func main() {27 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))28}29import (30func main() {31 fmt.Println(html.UnescapeString("This is <b>HTML</b>"))32}
Defer
Using AI Code Generation
1func main() {2 f := createFile("/tmp/defer.txt")3 defer closeFile(f)4 writeFile(f)5}6func createFile(p string) *os.File {7 fmt.Println("creating")8 f, err := os.Create(p)9 if err != nil {10 panic(err)11 }12}13func writeFile(f *os.File) {14 fmt.Println("writing")15 fmt.Fprintln(f, "data")16}17func closeFile(f *os.File) {18 fmt.Println("closing")19 f.Close()20}21import "fmt"22func main() {23 fmt.Println("counting")24 for i := 0; i < 10; i++ {25 defer fmt.Println(i)26 }27 fmt.Println("done")28}29import "fmt"30func main() {31 fmt.Println("counting")32 for i := 0; i < 10; i++ {33 defer func() {34 fmt.Println(i)35 }()36 }37 fmt.Println("done")38}
Defer
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 tmpl, err := template.ParseFiles("1.tmpl")6 if err != nil {7 panic(err)8 }9 p := Person{Name: "Naveen R", Age: 50}10 f, err := os.Create("1.html")11 if err != nil {12 panic(err)13 }14 defer f.Close()15 err = tmpl.Execute(f, p)16 if err != nil {17 panic(err)18 }19 fmt.Println("File written successfully")20}
Defer
Using AI Code Generation
1import (2func main() {3 defer fmt.Println("Defer method of html class")4 fmt.Println("Path: 1.go")5 fmt.Println("code to use Defer method of html class")6 fmt.Println("package main")7 fmt.Println("import (")8 fmt.Println(" "fmt")9 fmt.Println(" "html"")10 fmt.Println(" "log"")11 fmt.Println(")")12 fmt.Println("func main() {")13 fmt.Println(" defer fmt.Println(""Defer method of html class"")")14 fmt.Println(" fmt.Println(""Path: 1.go"")")15 fmt.Println(" fmt.Println(""code to use Defer method of html class"")")16 fmt.Println(" fmt.Println(""package main"")")17 fmt.Println(" fmt.Println(""import ("")")18 fmt.Println(" fmt.Println("" ""fmt"")")19 fmt.Println(" fmt.Println("" ""html""")")20 fmt.Println(" fmt.Println("" ""log""""")")21 fmt.Println(" fmt.Println("" "")")22 fmt.Println(" fmt.Println(""func main() {"")")23 fmt.Println(" fmt.Println("" defer fmt.Println(""Defer method of html class"")"")")24 fmt.Println(" fmt.Println("" fmt.Println(""Path: 1.go"")"")")25 fmt.Println(" fmt.Println("" fmt.Println(""code to use Defer method of html class"")"")")26 fmt.Println(" fmt.Println("" fmt.Println(""package main"")"")")27 fmt.Println(" fmt.Println("" fmt.Println(""import ("")"")")28 fmt.Println(" fmt.Println("" fmt.Println("" ""fmt"")"")")29 fmt.Println(" fmt.Println("" fmt.Println("" ""html""")"")")30 fmt.Println(" fmt.Println("" fmt.Println("" ""log""""")"")")31 fmt.Println(" fmt.Println("" fmt.Println("" "")"")")32 fmt.Println(" fmt.Println("" fmt.Println(""func main() {"")"")")33 fmt.Println(" fmt.Println("" fmt.Println("" defer fmt.Println(""Defer method of html class"")"")"")")34 fmt.Println(" fmt.Println("" fmt.Println("" fmt.Println(""Path: 1.go"")"")"")")35 fmt.Println(" fmt.Println("" fmt.Println("" fmt.Println(""code to use Defer method of html class"")"")"")")36 fmt.Println(" fmt.Println("" fmt.Println("" fmt.Println(""package main"")
Defer
Using AI Code Generation
1import (2func main() {3 if len(os.Args) != 2 {4 fmt.Println("Usage: ./1 <string>")5 os.Exit(1)6 }7 fmt.Println(html.EscapeString(os.Args[1]))8}9import (10func main() {11 if len(os.Args) != 2 {12 fmt.Println("Usage: ./2 <string>")13 os.Exit(1)14 }15 fmt.Println(html.UnescapeString(os.Args[1]))16}17import (18func main() {19 if len(os.Args) != 2 {20 fmt.Println("Usage: ./3 <string>")21 os.Exit(1)22 }23 fmt.Println(html.EscapeString(os.Args[1]))24 fmt.Println(html.UnescapeString(os.Args[1]))25}26import (27func main() {28 if len(os.Args) != 2 {29 fmt.Println("Usage: ./4 <string>")30 os.Exit(1)31 }32 fmt.Println(html.EscapeString(os.Args[1]))33 fmt.Println(html.UnescapeString(os.Args[1]))34 fmt.Println(html.EscapeString(os.Args[1]))35 fmt.Println(html.UnescapeString(os.Args[1]))36}37import (38func main() {39 if len(os.Args) != 2 {40 fmt.Println("Usage: ./5 <string>")41 os.Exit(1)42 }43 fmt.Println(html.EscapeString(os.Args[1]))44 fmt.Println(html.UnescapeString(os.Args[1]))45 fmt.Println(html.EscapeString(os.Args[1]))46 fmt.Println(html.UnescapeString(os.Args[1]))47 fmt.Println(html
Defer
Using AI Code Generation
1import (2func main() {3 fmt.Println(html.EscapeString(s))4 fmt.Println(html.UnescapeString(s))5 fmt.Println(html.EscapeString(strings.Repeat(s, 10)))6}
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!!