Best K6 code snippet using html.ClassList
html-script-results.go
Source:html-script-results.go
1// 2019 Daniel Oaks <daniel@danieloaks.net>2// released under the MIT license3package lib4import (5 "encoding/json"6 "fmt"7 "sort"8 "strings"9)10const (11 htmlTemplate = `<html>12<head>13<title>%[1]s - IRC Foundation Test Framework</title>14<meta charset="utf-8">15<style>16:root {17 --sans-font-family: Trebuchet MS, Lucida Grande, Lucida Sans Unicode, Lucida Sans, Tahoma, sans-serif;18 --mono-font-family: monaco, Consolas, Lucida Console, monospace;19 --side-indent: 0.65em;20 --content-indent: 0.3em;21}22html {23 box-sizing: border-box;24}25*, *:before, *:after {26 box-sizing: inherit;27}28html {29 margin: 0;30 padding: 0;31 min-height: 100%%;32}33body {34 font-family: var(--sans-font-family);35 display: flex;36 flex-direction: column;37 min-height: 100%%;38 margin: 0;39 padding: 0;40}41header {42 flex: 0 0 content;43 padding: 0 var(--side-indent);44 display: flex;45 flex-direction: column;46}47.content {48 flex: 1 1 auto;49 background: #d4e3ed;50 min-height: 100%%;51 min-width: 100%%;52 display: flex;53 flex-direction: column;54}55footer {56 flex: 0 0 content;57 display: flex;58 padding: 0.3em var(--side-indent);59}60.tab-bar {61 display: flex;62 width: 100%%;63 padding: 0 1.5em 0 var(--content-indent);64 flex: 0 0 content;65 top: -1px;66 position: sticky;67 background: #fff;68}69.tabs {70 flex: 1 1 auto;71 display: flex;72}73.tab {74 padding: 0.3em 0.6em;75 border-top: 1px solid #ddf;76 border-right: 1px solid #ddf;77}78.tab:hover, .tab.active {79 background: #eef;80}81.tab:first-child {82 border-left: 1px solid #ddf;83}84.tab-options {85 flex: 0 0 content;86}87.tab-content {88 flex: 1 1 auto;89 padding: 0;90}91.tab-content .section:nth-child(2n) {92 background: #eee;93}94.options {95 display: flex;96}97.section {98 display: flex;99}100.lines {101 flex: 1 1 auto;102 font-size: 1.3em;103}104pre {105 margin: 0;106 white-space: pre-wrap;107}108pre.c {109 font-weight: bold;110}111pre.err {112 font-weight: bold;113 color: #822;114}115%[5]s116a {117 color: #217de4;118 font-style: italic;119 text-decoration: none;120}121h1 {122 font-size: 3em;123 color: #243847;124 padding: 0.5em 0;125 margin: 0;126}127.desc {128 display: block;129 color: #455e6e;130 margin-top: -0.8em;131 font-size: 1.05em;132 padding-bottom: 1.7em;133}134</style>135</head>136<body>137<header>138 <h1>%[1]s</h1>139 <span class="desc">%[2]s</span>140</header>141<div class="content">142 <div class="tab-bar">143 <div class="tabs">144%[3]s145 </div>146 <div class="options">147 <a id="sanitised-toggle" class="tab emoji" href="#" title="Toggle Sanitised/Raw">ð¨</a>148 </div>149 </div>150 <div class="tab-content">151 <div class="section">152 <div class="lines active">153<pre>154Content here155</pre>156 </div>157 <div class="collapse-button">158 </div>159 </div>160 </div>161</div>162<footer>163 <a href="https://github.com/irccom/script-runner">IRC Foundation's script-runner</a>164</footer>165<script>166var serverInfo = %[4]s;167var server = serverInfo['default-server']168var sanitised = true169// print default server to console170console.log('default server is', serverInfo['default-server'])171// setup listeners for ircd buttons172var ircdButtons = document.querySelectorAll('[data-tab-button]')173for (var i = 0, len = ircdButtons.length; i < len; i++) {174 ircdButtons[i].addEventListener('click', (event) => {175 event.preventDefault()176 // console.log('btn ' + event.currentTarget.dataset.serverid)177 server = event.currentTarget.dataset.serverid178 showLogFor(server, sanitised)179 })180}181// setup listener for sanitised toggle182var sanitisedToggle = document.getElementById('sanitised-toggle')183sanitisedToggle.addEventListener('click', (event) => {184 event.preventDefault()185 sanitised = !sanitised186 showLogFor(server, sanitised)187 sanitisedToggle.classList.toggle('active')188})189sanitisedToggle.classList.add('active')190function showLogFor(ircd, sanitised) {191 console.log('showing log for', ircd)192 // 'press' button in the gui193 var ircdButtons = document.querySelectorAll('[data-tab-button]')194 for (var i = 0, len = ircdButtons.length; i < len; i++) {195 if (ircdButtons[i].dataset.serverid == ircd) {196 ircdButtons[i].classList.add('active')197 } else {198 ircdButtons[i].classList.remove('active')199 }200 }201 // construct and populate lines content202 var lines = document.createElement("div");203 lines.classList.add('lines')204 var logs205 if (sanitised) {206 logs = serverInfo["server-logs"][ircd]["sanitised"]207 } else {208 logs = serverInfo["server-logs"][ircd]["raw"]209 }210 for (var i = 0, len = logs.length; i < len; i++) {211 var raw = logs[i]212 // console.log(raw['c'], raw['s'], raw['l']);213 var content = ''214 if (0 < raw['e'].length) {215 content = raw['e']216 } else {217 content = raw['c'] + ' '218 if (raw['s'] == 'c') {219 content += ' ->'220 } else {221 content += '<- '222 }223 content += ' ' + raw['l']224 }225 var line = document.createElement("pre")226 line.classList.add('c-' + raw['c'])227 if (0 < raw['e'].length) {228 line.classList.add('err')229 } else {230 line.classList.add(raw['s'])231 }232 line.innerText = content233 lines.appendChild(line)234 }235 // replace it236 var linesElements = document.querySelectorAll('.lines.active')237 for (var i = 0, len = linesElements.length; i < len; i++) {238 var parent = linesElements[i].parentElement239 // out with the old240 linesElements[i].classList.remove('active')241 parent.removeChild(linesElements[i])242 // in with the new243 lines.classList.add('active')244 parent.appendChild(lines)245 }246}247showLogFor(server, sanitised);248</script>249</body>250</html>`251 tabText = `<a class="tab" href="" data-tab-button data-serverid="%[1]s">%[2]s</a>`252 cssPreTemplate = `pre.c-%[1]s {253 padding: 2px 0 2px calc(%[2]dch + var(--content-indent));254 text-indent: -%[2]dch;255 background: hsl(%[3]d, 90%%, 90%%);256}257`258)259type htmlJSONBlob struct {260 DefaultServer string `json:"default-server"`261 ServerNames map[string]string `json:"server-names"`262 ServerLogs map[string]serverBlob `json:"server-logs"`263}264type serverBlob struct {265 Raw []lineBlob `json:"raw"`266 Sanitised []lineBlob `json:"sanitised"`267}268type lineBlob struct {269 Client string `json:"c"`270 SentBy string `json:"s"`271 Line string `json:"l"`272 Error string `json:"e"`273}274// HTMLFromResults takes a set of results and outputs an HTML representation of those results.275func HTMLFromResults(script *Script, serverConfigs map[string]ServerConfig, scriptResults map[string]*ScriptResults) string {276 // sorted ID list277 var sortedIDs []string278 for id := range serverConfigs {279 sortedIDs = append(sortedIDs, id)280 }281 sort.Strings(sortedIDs)282 // tab buttons283 var tabs string284 for _, id := range sortedIDs {285 tabs += fmt.Sprintf(tabText, id, serverConfigs[id].DisplayName)286 }287 // css288 var css string289 hue := 150290 for id := range script.Clients {291 // + 5 for ' <- ' or similar292 css += fmt.Sprintf(cssPreTemplate, id, len(id)+5, hue)293 hue += 40294 }295 // construct JSON blob used by the page296 blob := htmlJSONBlob{297 DefaultServer: sortedIDs[0],298 ServerNames: make(map[string]string),299 ServerLogs: make(map[string]serverBlob),300 }301 for id, info := range serverConfigs {302 blob.ServerNames[id] = info.DisplayName303 }304 for id, sr := range scriptResults {305 var sBlob serverBlob306 var actionIndex int307 for _, srl := range sr.Lines {308 switch srl.Type {309 case ResultIRCMessage:310 // raw line311 lineRaw := lineBlob{312 Client: srl.Client,313 SentBy: "s",314 Line: strings.TrimSuffix(srl.RawLine, "\r\n"),315 }316 sBlob.Raw = append(sBlob.Raw, lineRaw)317 // sanitised line318 sanitisedLine := srl.RawLine319 for orig, new := range serverConfigs[id].SanitisedReplacements {320 sanitisedLine = strings.Replace(sanitisedLine, orig, new, -1)321 }322 lineSanitised := lineBlob{323 Client: srl.Client,324 SentBy: "s",325 Line: strings.TrimSuffix(sanitisedLine, "\r\n"),326 }327 sBlob.Sanitised = append(sBlob.Sanitised, lineSanitised)328 case ResultActionSync:329 thisAction := script.Actions[actionIndex]330 if thisAction.LineToSend != "" {331 // sent line always stays the same332 line := lineBlob{333 Client: thisAction.Client,334 SentBy: "c",335 Line: strings.TrimSuffix(thisAction.LineToSend, "\r\n"),336 }337 sBlob.Raw = append(sBlob.Raw, line)338 sBlob.Sanitised = append(sBlob.Sanitised, line)339 }340 actionIndex++341 case ResultDisconnected:342 line := lineBlob{343 Client: srl.Client,344 Error: fmt.Sprintf("%s was disconnected unexpectedly", srl.Client),345 }346 sBlob.Raw = append(sBlob.Raw, line)347 sBlob.Sanitised = append(sBlob.Sanitised, line)348 case ResultDisconnectedExpected:349 line := lineBlob{350 Client: srl.Client,351 Error: fmt.Sprintf("%s was disconnected", srl.Client),352 }353 sBlob.Raw = append(sBlob.Raw, line)354 sBlob.Sanitised = append(sBlob.Sanitised, line)355 }356 }357 blob.ServerLogs[id] = sBlob358 }359 // marshall json blob360 blobBytes, err := json.Marshal(blob)361 blobString := "{'error': 1}"362 if err == nil {363 blobString = string(blobBytes)364 }365 // assemble template366 return fmt.Sprintf(htmlTemplate, script.Name, script.ShortDescription, tabs, blobString, css)367}...
dom.go
Source:dom.go
...8 "github.com/yosssi/gohtml"9)10type Op string11const (12 ClassList Op = "classlist"13 Dataset Op = "dataset"14 SetAttributes Op = "setAttributes"15 RemoveAttributes Op = "removeAttributes"16 Morph Op = "morph"17 Reload Op = "reload"18 AddClass Op = "addClass"19 RemoveClass Op = "removeClass"20 SetValue Op = "setValue"21 SetInnerHTML Op = "setInnerHTML"22)23type Operation struct {24 Op Op `json:"op"`25 Selector string `json:"selector"`26 Value interface{} `json:"value"`27}28func (m *Operation) Bytes() []byte {29 b, err := json.Marshal(m)30 if err != nil {31 log.Printf("error marshalling dom %v\n", err)32 return nil33 }34 return b35}36type DOM interface {37 SetDataset(selector string, data M)38 SetAttributes(selector string, data M)39 SetValue(selector string, value interface{})40 SetInnerHTML(selector string, value interface{})41 RemoveAttributes(selector string, data []string)42 ToggleClassList(selector string, classList map[string]bool)43 AddClass(selector, class string)44 RemoveClass(selector, class string)45 Morph(selector, template string, data M)46 Reload()47}48type dom struct {49 rootTemplate *template.Template50 store Store51 temporaryKeys []string52 topic string53 wc *websocketController54}55func (d *dom) SetAttributes(selector string, data M) {56 m := &Operation{57 Op: SetAttributes,58 Selector: selector,59 Value: data,60 }61 d.wc.message(d.topic, m.Bytes())62 d.setStore(data)63}64func (d *dom) RemoveAttributes(selector string, data []string) {65 m := &Operation{66 Op: RemoveAttributes,67 Selector: selector,68 Value: data,69 }70 d.wc.message(d.topic, m.Bytes())71}72func (d *dom) SetDataset(selector string, data M) {73 dataset := make(map[string]interface{})74 for k, v := range data {75 k = strings.TrimPrefix(k, "data-")76 dataset[kebabToCamelCase(k)] = v77 }78 m := &Operation{79 Op: Dataset,80 Selector: selector,81 Value: dataset,82 }83 d.wc.message(d.topic, m.Bytes())84 d.setStore(data)85}86func (d *dom) ToggleClassList(selector string, boolData map[string]bool) {87 classList := make(map[string]interface{})88 for k, v := range boolData {89 classList[k] = v90 }91 m := &Operation{92 Op: ClassList,93 Selector: selector,94 Value: classList,95 }96 d.wc.message(d.topic, m.Bytes())97 // update inmemStore98 data := make(map[string]interface{})99 for k, v := range boolData {100 data[k] = v101 }102 d.setStore(data)103}104func (d *dom) AddClass(selector, class string) {105 m := &Operation{106 Op: AddClass,...
ClassList
Using AI Code Generation
1import (2func main() {3 doc, err := html.Parse(os.Stdin)4 if err != nil {5 fmt.Fprintf(os.Stderr, "findlinks1: %v6 os.Exit(1)7 }8 for _, link := range visit(nil, doc) {9 fmt.Println(link)10 }11}12func visit(links []string, n *html.Node) []string {13 if n.Type == html.ElementNode && n.Data == "a" {14 for _, a := range n.Attr {15 if a.Key == "href" {16 links = append(links, a.Val)17 }18 }19 }20 for c := n.FirstChild; c != nil; c = c.NextSibling {21 links = visit(links, c)22 }23}
ClassList
Using AI Code Generation
1import (2func main() {3 for _, url := range os.Args[1:] {4 resp, err := http.Get(url)5 if err != nil {6 fmt.Fprintf(os.Stderr, "fetch: %v\n", err)7 os.Exit(1)8 }9 doc, err := html.Parse(resp.Body)10 resp.Body.Close()11 if err != nil {12 fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)13 os.Exit(1)14 }15 for _, link := range visit(nil, doc) {16 fmt.Println(link)17 }18 }19}20func visit(links []string, n *html.Node) []string {21 if n.Type == html.ElementNode && n.Data == "a" {22 for _, a := range n.Attr {23 if a.Key == "href" {24 links = append(links, a.Val)25 }26 }27 }28 for c := n.FirstChild; c != nil; c = c.NextSibling {29 links = visit(links, c)30 }31}32import (33func main() {34 for _, url := range os.Args[1:] {35 resp, err := http.Get(url)36 if err != nil {37 fmt.Fprintf(os.Stderr, "fetch: %v\n", err)38 os.Exit(1)39 }40 doc, err := html.Parse(resp.Body)41 resp.Body.Close()42 if err != nil {43 fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err)44 os.Exit(1)45 }46 for _, link := range visit(nil, doc) {47 fmt.Println(link)48 }49 }50}51func visit(links []string, n *html.Node) []string {52 if n.Type == html.ElementNode && n.Data == "a" {53 for _, a := range n.Attr {54 if a.Key == "href" {55 links = append(links, a.Val)56 }57 }58 }59 for c := n.FirstChild; c != nil; c = c.NextSibling {
ClassList
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer resp.Body.Close()7 doc, err := html.Parse(resp.Body)8 if err != nil {9 log.Fatal(err)10 }11 forEachNode(doc, startElement, endElement)12}13func forEachNode(n *html.Node, pre, post func(n *html.Node)) {14 if pre != nil {15 pre(n)16 }17 for c := n.FirstChild; c != nil; c = c.NextSibling {18 forEachNode(c, pre, post)19 }20 if post != nil {21 post(n)22 }23}24func startElement(n *html.Node) {25 if n.Type == html.ElementNode {26 fmt.Println(n.Data)27 }28}29func endElement(n *html.Node) {30 if n.Type == html.ElementNode {31 fmt.Println(n.Data)32 }33}34func ClassList(n *html.Node) []string {35 if n.Type == html.ElementNode {36 for _, a := range n.Attr {37 if a.Key == "class" {38 return strings.Fields(a.Val)39 }40 }41 }42}
ClassList
Using AI Code Generation
1import (2func main() {3 z := html.NewTokenizer(resp.Body)4 for {5 tt := z.Next()6 switch {7 t := z.Token()8 if isAnchor {9 for _, a := range t.Attr {10 if a.Key == "href" {11 fmt.Printf("link: %q12 }13 }14 }15 }16 }17}
ClassList
Using AI Code Generation
1import (2func ClassList(n *html.Node) []string {3 for _, a := range n.Attr {4 if a.Key == "class" {5 classes = strings.Fields(a.Val)6 }7 }8}9func main() {10 if err != nil {11 fmt.Println(err)12 }13 defer resp.Body.Close()14 doc, err := html.Parse(resp.Body)15 if err != nil {16 fmt.Println(err)17 }18 for _, class := range ClassList(doc) {19 fmt.Println(class)20 }21}
ClassList
Using AI Code Generation
1import (2func main() {3 start := time.Now()4 ch := make(chan string)5 for _, url := range os.Args[1:] {6 }7 for range os.Args[1:] {8 }9 fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())10}11func fetch(url string, ch chan<- string) {12 start := time.Now()13 resp, err := http.Get(url)14 if err != nil {15 }16 n, err := html.Parse(resp.Body)17 if err != nil {18 ch <- fmt.Sprintf("while reading %s: %v", url, err)19 }20 for _, link := range visit(nil, n) {21 if strings.Contains(link, "class") {22 ClassList = append(ClassList, link)23 }24 }25 ch <- fmt.Sprintf("%.2fs %7d %s", time.Since(start).Seconds(), len(ClassList), url)26}27func visit(links []string, n *html.Node) []string {28 if n.Type == html.ElementNode {29 links = append(links, n.Data)30 }31 for c := n.FirstChild; c != nil; c = c.NextSibling {32 links = visit(links, c)33 }34}
ClassList
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer resp.Body.Close()7 doc, err := html.Parse(resp.Body)8 if err != nil {9 log.Fatal(err)10 }11 for _, link := range visit(nil, doc) {12 fmt.Println(link)13 }14}15func visit(links []string, n *html.Node) []string {16 if n.Type == html.ElementNode && n.Data == "a" {17 for _, a := range n.Attr {18 if a.Key == "href" {19 links = append(links, a.Val)20 }21 }22 }23 for c := n.FirstChild; c != nil; c = c.NextSibling {24 links = visit(links, c)25 }26}
ClassList
Using AI Code Generation
1import (2func main() {3 doc, _ := html.Parse(strings.NewReader(s))4 classes := ClassList(doc)5 fmt.Println(classes)6}7func ClassList(n *html.Node) []string {8 if n.Type == html.ElementNode {9 for _, a := range n.Attr {10 if a.Key == "class" {11 return strings.Fields(a.Val)12 }13 }14 }15}
ClassList
Using AI Code Generation
1import (2func ClassList(n *html.Node) []string {3 for _, a := range n.Attr {4 if a.Key == "class" {5 classes = append(classes, a.Val)6 }7 }8}9func main() {10 if err != nil {11 fmt.Printf("Error: %v", err)12 }13 defer resp.Body.Close()14 doc, err := html.Parse(resp.Body)15 if err != nil {16 fmt.Printf("Error: %v", err)17 }18 forEachNode(doc, startElement, endElement)19}20func forEachNode(n *html.Node, pre, post func(n *html.Node)) {21 if pre != nil {22 pre(n)23 }24 for c := n.FirstChild; c != nil; c = c.NextSibling {25 forEachNode(c, pre, post)26 }27 if post != nil {28 post(n)29 }30}31func startElement(n *html.Node) {32 if n.Type == html.ElementNode {33 fmt.Printf("%s ", n.Data)34 if len(ClassList(n)) > 0 {35 fmt.Printf("%s ", ClassList(n))36 }37 }38}39func endElement(n *html.Node) {40 if n.Type == html.ElementNode {41 fmt.Printf("end of %s ", n.Data)42 if len(ClassList(n)) > 0 {
ClassList
Using AI Code Generation
1import (2func ClassList(n *html.Node) []string {3 if n.Type == html.ElementNode {4 for _, a := range n.Attr {5 if a.Key == "class" {6 list = append(list, a.Val)7 }8 }9 }10 for c := n.FirstChild; c != nil; c = c.NextSibling {11 list = append(list, ClassList(c)...)12 }13}14func main() {15 htmlFile, err := ioutil.ReadFile("index.html")16 if err != nil {17 fmt.Println(err)18 }19 n, err := html.Parse(strings.NewReader(string(htmlFile)))20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println(ClassList(n))24}
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!!