How to use Write method of got Package

Best Got code snippet using got.Write

writesched_priority_test.go

Source:writesched_priority_test.go Github

copy

Full Screen

...7 "fmt"8 "sort"9 "testing"10)11func defaultPriorityWriteScheduler() *priorityWriteScheduler {12 return NewPriorityWriteScheduler(nil).(*priorityWriteScheduler)13}14func checkPriorityWellFormed(ws *priorityWriteScheduler) error {15 for id, n := range ws.nodes {16 if id != n.id {17 return fmt.Errorf("bad ws.nodes: ws.nodes[%d] = %d", id, n.id)18 }19 if n.parent == nil {20 if n.next != nil || n.prev != nil {21 return fmt.Errorf("bad node %d: nil parent but prev/next not nil", id)22 }23 continue24 }25 found := false26 for k := n.parent.kids; k != nil; k = k.next {27 if k.id == id {28 found = true29 break30 }31 }32 if !found {33 return fmt.Errorf("bad node %d: not found in parent %d kids list", id, n.parent.id)34 }35 }36 return nil37}38func fmtTree(ws *priorityWriteScheduler, fmtNode func(*priorityNode) string) string {39 var ids []int40 for _, n := range ws.nodes {41 ids = append(ids, int(n.id))42 }43 sort.Ints(ids)44 var buf bytes.Buffer45 for _, id := range ids {46 if buf.Len() != 0 {47 buf.WriteString(" ")48 }49 if id == 0 {50 buf.WriteString(fmtNode(&ws.root))51 } else {52 buf.WriteString(fmtNode(ws.nodes[uint32(id)]))53 }54 }55 return buf.String()56}57func fmtNodeParentSkipRoot(n *priorityNode) string {58 switch {59 case n.id == 0:60 return ""61 case n.parent == nil:62 return fmt.Sprintf("%d{parent:nil}", n.id)63 default:64 return fmt.Sprintf("%d{parent:%d}", n.id, n.parent.id)65 }66}67func fmtNodeWeightParentSkipRoot(n *priorityNode) string {68 switch {69 case n.id == 0:70 return ""71 case n.parent == nil:72 return fmt.Sprintf("%d{weight:%d,parent:nil}", n.id, n.weight)73 default:74 return fmt.Sprintf("%d{weight:%d,parent:%d}", n.id, n.weight, n.parent.id)75 }76}77func TestPriorityTwoStreams(t *testing.T) {78 ws := defaultPriorityWriteScheduler()79 ws.OpenStream(1, OpenStreamOptions{})80 ws.OpenStream(2, OpenStreamOptions{})81 want := "1{weight:15,parent:0} 2{weight:15,parent:0}"82 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {83 t.Errorf("After open\ngot %q\nwant %q", got, want)84 }85 // Move 1's parent to 2.86 ws.AdjustStream(1, PriorityParam{87 StreamDep: 2,88 Weight: 32,89 Exclusive: false,90 })91 want = "1{weight:32,parent:2} 2{weight:15,parent:0}"92 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {93 t.Errorf("After adjust\ngot %q\nwant %q", got, want)94 }95 if err := checkPriorityWellFormed(ws); err != nil {96 t.Error(err)97 }98}99func TestPriorityAdjustExclusiveZero(t *testing.T) {100 // 1, 2, and 3 are all children of the 0 stream.101 // Exclusive reprioritization to any of the streams should bring102 // the rest of the streams under the reprioritized stream.103 ws := defaultPriorityWriteScheduler()104 ws.OpenStream(1, OpenStreamOptions{})105 ws.OpenStream(2, OpenStreamOptions{})106 ws.OpenStream(3, OpenStreamOptions{})107 want := "1{weight:15,parent:0} 2{weight:15,parent:0} 3{weight:15,parent:0}"108 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {109 t.Errorf("After open\ngot %q\nwant %q", got, want)110 }111 ws.AdjustStream(2, PriorityParam{112 StreamDep: 0,113 Weight: 20,114 Exclusive: true,115 })116 want = "1{weight:15,parent:2} 2{weight:20,parent:0} 3{weight:15,parent:2}"117 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {118 t.Errorf("After adjust\ngot %q\nwant %q", got, want)119 }120 if err := checkPriorityWellFormed(ws); err != nil {121 t.Error(err)122 }123}124func TestPriorityAdjustOwnParent(t *testing.T) {125 // Assigning a node as its own parent should have no effect.126 ws := defaultPriorityWriteScheduler()127 ws.OpenStream(1, OpenStreamOptions{})128 ws.OpenStream(2, OpenStreamOptions{})129 ws.AdjustStream(2, PriorityParam{130 StreamDep: 2,131 Weight: 20,132 Exclusive: true,133 })134 want := "1{weight:15,parent:0} 2{weight:15,parent:0}"135 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {136 t.Errorf("After adjust\ngot %q\nwant %q", got, want)137 }138 if err := checkPriorityWellFormed(ws); err != nil {139 t.Error(err)140 }141}142func TestPriorityClosedStreams(t *testing.T) {143 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxClosedNodesInTree: 2}).(*priorityWriteScheduler)144 ws.OpenStream(1, OpenStreamOptions{})145 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})146 ws.OpenStream(3, OpenStreamOptions{PusherID: 2})147 ws.OpenStream(4, OpenStreamOptions{PusherID: 3})148 // Close the first three streams. We lose 1, but keep 2 and 3.149 ws.CloseStream(1)150 ws.CloseStream(2)151 ws.CloseStream(3)152 want := "2{weight:15,parent:0} 3{weight:15,parent:2} 4{weight:15,parent:3}"153 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {154 t.Errorf("After close\ngot %q\nwant %q", got, want)155 }156 if err := checkPriorityWellFormed(ws); err != nil {157 t.Error(err)158 }159 // Adding a stream as an exclusive child of 1 gives it default160 // priorities, since 1 is gone.161 ws.OpenStream(5, OpenStreamOptions{})162 ws.AdjustStream(5, PriorityParam{StreamDep: 1, Weight: 15, Exclusive: true})163 // Adding a stream as an exclusive child of 2 should work, since 2 is not gone.164 ws.OpenStream(6, OpenStreamOptions{})165 ws.AdjustStream(6, PriorityParam{StreamDep: 2, Weight: 15, Exclusive: true})166 want = "2{weight:15,parent:0} 3{weight:15,parent:6} 4{weight:15,parent:3} 5{weight:15,parent:0} 6{weight:15,parent:2}"167 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {168 t.Errorf("After add streams\ngot %q\nwant %q", got, want)169 }170 if err := checkPriorityWellFormed(ws); err != nil {171 t.Error(err)172 }173}174func TestPriorityClosedStreamsDisabled(t *testing.T) {175 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler)176 ws.OpenStream(1, OpenStreamOptions{})177 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})178 ws.OpenStream(3, OpenStreamOptions{PusherID: 2})179 // Close the first two streams. We keep only 3.180 ws.CloseStream(1)181 ws.CloseStream(2)182 want := "3{weight:15,parent:0}"183 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {184 t.Errorf("After close\ngot %q\nwant %q", got, want)185 }186 if err := checkPriorityWellFormed(ws); err != nil {187 t.Error(err)188 }189}190func TestPriorityIdleStreams(t *testing.T) {191 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxIdleNodesInTree: 2}).(*priorityWriteScheduler)192 ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle193 ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle194 ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle195 ws.OpenStream(4, OpenStreamOptions{})196 ws.OpenStream(5, OpenStreamOptions{})197 ws.OpenStream(6, OpenStreamOptions{})198 ws.AdjustStream(4, PriorityParam{StreamDep: 1, Weight: 15})199 ws.AdjustStream(5, PriorityParam{StreamDep: 2, Weight: 15})200 ws.AdjustStream(6, PriorityParam{StreamDep: 3, Weight: 15})201 want := "2{weight:15,parent:0} 3{weight:20,parent:2} 4{weight:15,parent:0} 5{weight:15,parent:2} 6{weight:15,parent:3}"202 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {203 t.Errorf("After open\ngot %q\nwant %q", got, want)204 }205 if err := checkPriorityWellFormed(ws); err != nil {206 t.Error(err)207 }208}209func TestPriorityIdleStreamsDisabled(t *testing.T) {210 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler)211 ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle212 ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle213 ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle214 ws.OpenStream(4, OpenStreamOptions{})215 want := "4{weight:15,parent:0}"216 if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want {217 t.Errorf("After open\ngot %q\nwant %q", got, want)218 }219 if err := checkPriorityWellFormed(ws); err != nil {220 t.Error(err)221 }222}223func TestPrioritySection531NonExclusive(t *testing.T) {224 // Example from RFC 7540 Section 5.3.1.225 // A,B,C,D = 1,2,3,4226 ws := defaultPriorityWriteScheduler()227 ws.OpenStream(1, OpenStreamOptions{})228 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})229 ws.OpenStream(3, OpenStreamOptions{PusherID: 1})230 ws.OpenStream(4, OpenStreamOptions{})231 ws.AdjustStream(4, PriorityParam{232 StreamDep: 1,233 Weight: 15,234 Exclusive: false,235 })236 want := "1{parent:0} 2{parent:1} 3{parent:1} 4{parent:1}"237 if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want {238 t.Errorf("After adjust\ngot %q\nwant %q", got, want)239 }240 if err := checkPriorityWellFormed(ws); err != nil {241 t.Error(err)242 }243}244func TestPrioritySection531Exclusive(t *testing.T) {245 // Example from RFC 7540 Section 5.3.1.246 // A,B,C,D = 1,2,3,4247 ws := defaultPriorityWriteScheduler()248 ws.OpenStream(1, OpenStreamOptions{})249 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})250 ws.OpenStream(3, OpenStreamOptions{PusherID: 1})251 ws.OpenStream(4, OpenStreamOptions{})252 ws.AdjustStream(4, PriorityParam{253 StreamDep: 1,254 Weight: 15,255 Exclusive: true,256 })257 want := "1{parent:0} 2{parent:4} 3{parent:4} 4{parent:1}"258 if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want {259 t.Errorf("After adjust\ngot %q\nwant %q", got, want)260 }261 if err := checkPriorityWellFormed(ws); err != nil {262 t.Error(err)263 }264}265func makeSection533Tree() *priorityWriteScheduler {266 // Initial tree from RFC 7540 Section 5.3.3.267 // A,B,C,D,E,F = 1,2,3,4,5,6268 ws := defaultPriorityWriteScheduler()269 ws.OpenStream(1, OpenStreamOptions{})270 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})271 ws.OpenStream(3, OpenStreamOptions{PusherID: 1})272 ws.OpenStream(4, OpenStreamOptions{PusherID: 3})273 ws.OpenStream(5, OpenStreamOptions{PusherID: 3})274 ws.OpenStream(6, OpenStreamOptions{PusherID: 4})275 return ws276}277func TestPrioritySection533NonExclusive(t *testing.T) {278 // Example from RFC 7540 Section 5.3.3.279 // A,B,C,D,E,F = 1,2,3,4,5,6280 ws := defaultPriorityWriteScheduler()281 ws.OpenStream(1, OpenStreamOptions{})282 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})283 ws.OpenStream(3, OpenStreamOptions{PusherID: 1})284 ws.OpenStream(4, OpenStreamOptions{PusherID: 3})285 ws.OpenStream(5, OpenStreamOptions{PusherID: 3})286 ws.OpenStream(6, OpenStreamOptions{PusherID: 4})287 ws.AdjustStream(1, PriorityParam{288 StreamDep: 4,289 Weight: 15,290 Exclusive: false,291 })292 want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:4}"293 if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want {294 t.Errorf("After adjust\ngot %q\nwant %q", got, want)295 }296 if err := checkPriorityWellFormed(ws); err != nil {297 t.Error(err)298 }299}300func TestPrioritySection533Exclusive(t *testing.T) {301 // Example from RFC 7540 Section 5.3.3.302 // A,B,C,D,E,F = 1,2,3,4,5,6303 ws := defaultPriorityWriteScheduler()304 ws.OpenStream(1, OpenStreamOptions{})305 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})306 ws.OpenStream(3, OpenStreamOptions{PusherID: 1})307 ws.OpenStream(4, OpenStreamOptions{PusherID: 3})308 ws.OpenStream(5, OpenStreamOptions{PusherID: 3})309 ws.OpenStream(6, OpenStreamOptions{PusherID: 4})310 ws.AdjustStream(1, PriorityParam{311 StreamDep: 4,312 Weight: 15,313 Exclusive: true,314 })315 want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:1}"316 if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want {317 t.Errorf("After adjust\ngot %q\nwant %q", got, want)318 }319 if err := checkPriorityWellFormed(ws); err != nil {320 t.Error(err)321 }322}323func checkPopAll(ws WriteScheduler, order []uint32) error {324 for k, id := range order {325 wr, ok := ws.Pop()326 if !ok {327 return fmt.Errorf("Pop[%d]: got ok=false, want %d (order=%v)", k, id, order)328 }329 if got := wr.StreamID(); got != id {330 return fmt.Errorf("Pop[%d]: got %v, want %d (order=%v)", k, got, id, order)331 }332 }333 wr, ok := ws.Pop()334 if ok {335 return fmt.Errorf("Pop[%d]: got %v, want ok=false (order=%v)", len(order), wr.StreamID(), order)336 }337 return nil338}339func TestPriorityPopFrom533Tree(t *testing.T) {340 ws := makeSection533Tree()341 ws.Push(makeWriteHeadersRequest(3 /*C*/))342 ws.Push(makeWriteNonStreamRequest())343 ws.Push(makeWriteHeadersRequest(5 /*E*/))344 ws.Push(makeWriteHeadersRequest(1 /*A*/))345 t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot))346 if err := checkPopAll(ws, []uint32{0 /*NonStream*/, 1, 3, 5}); err != nil {347 t.Error(err)348 }349}350func TestPriorityPopFromLinearTree(t *testing.T) {351 ws := defaultPriorityWriteScheduler()352 ws.OpenStream(1, OpenStreamOptions{})353 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})354 ws.OpenStream(3, OpenStreamOptions{PusherID: 2})355 ws.OpenStream(4, OpenStreamOptions{PusherID: 3})356 ws.Push(makeWriteHeadersRequest(3))357 ws.Push(makeWriteHeadersRequest(4))358 ws.Push(makeWriteHeadersRequest(1))359 ws.Push(makeWriteHeadersRequest(2))360 ws.Push(makeWriteNonStreamRequest())361 ws.Push(makeWriteNonStreamRequest())362 t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot))363 if err := checkPopAll(ws, []uint32{0, 0 /*NonStreams*/, 1, 2, 3, 4}); err != nil {364 t.Error(err)365 }366}367func TestPriorityFlowControl(t *testing.T) {368 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: false})369 ws.OpenStream(1, OpenStreamOptions{})370 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})371 sc := &serverConn{maxFrameSize: 16}372 st1 := &stream{id: 1, sc: sc}373 st2 := &stream{id: 2, sc: sc}374 ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 16), false}, st1, nil})375 ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 16), false}, st2, nil})376 ws.AdjustStream(2, PriorityParam{StreamDep: 1})377 // No flow-control bytes available.378 if wr, ok := ws.Pop(); ok {379 t.Fatalf("Pop(limited by flow control)=%v,true, want false", wr)380 }381 // Add enough flow-control bytes to write st2 in two Pop calls.382 // Should write data from st2 even though it's lower priority than st1.383 for i := 1; i <= 2; i++ {384 st2.flow.add(8)385 wr, ok := ws.Pop()386 if !ok {387 t.Fatalf("Pop(%d)=false, want true", i)388 }389 if got, want := wr.DataSize(), 8; got != want {390 t.Fatalf("Pop(%d)=%d bytes, want %d bytes", i, got, want)391 }392 }393}394func TestPriorityThrottleOutOfOrderWrites(t *testing.T) {395 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: true})396 ws.OpenStream(1, OpenStreamOptions{})397 ws.OpenStream(2, OpenStreamOptions{PusherID: 1})398 sc := &serverConn{maxFrameSize: 4096}399 st1 := &stream{id: 1, sc: sc}400 st2 := &stream{id: 2, sc: sc}401 st1.flow.add(4096)402 st2.flow.add(4096)403 ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 4096), false}, st2, nil})404 ws.AdjustStream(2, PriorityParam{StreamDep: 1})405 // We have enough flow-control bytes to write st2 in a single Pop call.406 // However, due to out-of-order write throttling, the first call should407 // only write 1KB.408 wr, ok := ws.Pop()409 if !ok {410 t.Fatalf("Pop(st2.first)=false, want true")411 }412 if got, want := wr.StreamID(), uint32(2); got != want {413 t.Fatalf("Pop(st2.first)=stream %d, want stream %d", got, want)414 }415 if got, want := wr.DataSize(), 1024; got != want {416 t.Fatalf("Pop(st2.first)=%d bytes, want %d bytes", got, want)417 }418 // Now add data on st1. This should take precedence.419 ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 4096), false}, st1, nil})420 wr, ok = ws.Pop()421 if !ok {422 t.Fatalf("Pop(st1)=false, want true")423 }424 if got, want := wr.StreamID(), uint32(1); got != want {425 t.Fatalf("Pop(st1)=stream %d, want stream %d", got, want)426 }427 if got, want := wr.DataSize(), 4096; got != want {428 t.Fatalf("Pop(st1)=%d bytes, want %d bytes", got, want)429 }430 // Should go back to writing 1KB from st2.431 wr, ok = ws.Pop()432 if !ok {433 t.Fatalf("Pop(st2.last)=false, want true")434 }435 if got, want := wr.StreamID(), uint32(2); got != want {436 t.Fatalf("Pop(st2.last)=stream %d, want stream %d", got, want)437 }438 if got, want := wr.DataSize(), 1024; got != want {439 t.Fatalf("Pop(st2.last)=%d bytes, want %d bytes", got, want)440 }441}442func TestPriorityWeights(t *testing.T) {443 ws := defaultPriorityWriteScheduler()444 ws.OpenStream(1, OpenStreamOptions{})445 ws.OpenStream(2, OpenStreamOptions{})446 sc := &serverConn{maxFrameSize: 8}447 st1 := &stream{id: 1, sc: sc}448 st2 := &stream{id: 2, sc: sc}449 st1.flow.add(40)450 st2.flow.add(40)451 ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 40), false}, st1, nil})452 ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 40), false}, st2, nil})453 ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 34})454 ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 9})455 // st1 gets 3.5x the bandwidth of st2 (3.5 = (34+1)/(9+1)).456 // The maximum frame size is 8 bytes. The write sequence should be:457 // st1, total bytes so far is (st1=8, st=0)458 // st2, total bytes so far is (st1=8, st=8)459 // st1, total bytes so far is (st1=16, st=8)460 // st1, total bytes so far is (st1=24, st=8) // 3x bandwidth461 // st1, total bytes so far is (st1=32, st=8) // 4x bandwidth462 // st2, total bytes so far is (st1=32, st=16) // 2x bandwidth463 // st1, total bytes so far is (st1=40, st=16)464 // st2, total bytes so far is (st1=40, st=24)465 // st2, total bytes so far is (st1=40, st=32)466 // st2, total bytes so far is (st1=40, st=40)467 if err := checkPopAll(ws, []uint32{1, 2, 1, 1, 1, 2, 1, 2, 2, 2}); err != nil {468 t.Error(err)469 }470}471func TestPriorityRstStreamOnNonOpenStreams(t *testing.T) {472 ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{473 MaxClosedNodesInTree: 0,474 MaxIdleNodesInTree: 0,475 })476 ws.OpenStream(1, OpenStreamOptions{})477 ws.CloseStream(1)478 ws.Push(FrameWriteRequest{write: streamError(1, ErrCodeProtocol)})479 ws.Push(FrameWriteRequest{write: streamError(2, ErrCodeProtocol)})480 if err := checkPopAll(ws, []uint32{1, 2}); err != nil {481 t.Error(err)482 }483}...

Full Screen

Full Screen

builder_test.go

Source:builder_test.go Github

copy

Full Screen

...24}25func TestBuilder(t *testing.T) {26 var b Builder27 check(t, &b, "")28 n, err := b.WriteString("hello")29 if err != nil || n != 5 {30 t.Errorf("WriteString: got %d,%s; want 5,nil", n, err)31 }32 check(t, &b, "hello")33 if err = b.WriteByte(' '); err != nil {34 t.Errorf("WriteByte: %s", err)35 }36 check(t, &b, "hello ")37 n, err = b.WriteString("world")38 if err != nil || n != 5 {39 t.Errorf("WriteString: got %d,%s; want 5,nil", n, err)40 }41 check(t, &b, "hello world")42}43func TestBuilderString(t *testing.T) {44 var b Builder45 b.WriteString("alpha")46 check(t, &b, "alpha")47 s1 := b.String()48 b.WriteString("beta")49 check(t, &b, "alphabeta")50 s2 := b.String()51 b.WriteString("gamma")52 check(t, &b, "alphabetagamma")53 s3 := b.String()54 // Check that subsequent operations didn't change the returned strings.55 if want := "alpha"; s1 != want {56 t.Errorf("first String result is now %q; want %q", s1, want)57 }58 if want := "alphabeta"; s2 != want {59 t.Errorf("second String result is now %q; want %q", s2, want)60 }61 if want := "alphabetagamma"; s3 != want {62 t.Errorf("third String result is now %q; want %q", s3, want)63 }64}65func TestBuilderReset(t *testing.T) {66 var b Builder67 check(t, &b, "")68 b.WriteString("aaa")69 s := b.String()70 check(t, &b, "aaa")71 b.Reset()72 check(t, &b, "")73 // Ensure that writing after Reset doesn't alter74 // previously returned strings.75 b.WriteString("bbb")76 check(t, &b, "bbb")77 if want := "aaa"; s != want {78 t.Errorf("previous String result changed after Reset: got %q; want %q", s, want)79 }80}81func TestBuilderGrow(t *testing.T) {82 if runtime.Compiler == "gccgo" {83 t.Skip("skip for gccgo until escape analysis improves")84 }85 for _, growLen := range []int{0, 100, 1000, 10000, 100000} {86 p := bytes.Repeat([]byte{'a'}, growLen)87 allocs := testing.AllocsPerRun(100, func() {88 var b Builder89 b.Grow(growLen) // should be only alloc, when growLen > 090 if b.Cap() < growLen {91 t.Fatalf("growLen=%d: Cap() is lower than growLen", growLen)92 }93 b.Write(p)94 if b.String() != string(p) {95 t.Fatalf("growLen=%d: bad data written after Grow", growLen)96 }97 })98 wantAllocs := 199 if growLen == 0 {100 wantAllocs = 0101 }102 if g, w := int(allocs), wantAllocs; g != w {103 t.Errorf("growLen=%d: got %d allocs during Write; want %v", growLen, g, w)104 }105 }106}107func TestBuilderWrite2(t *testing.T) {108 const s0 = "hello 世界"109 for _, tt := range []struct {110 name string111 fn func(b *Builder) (int, error)112 n int113 want string114 }{115 {116 "Write",117 func(b *Builder) (int, error) { return b.Write([]byte(s0)) },118 len(s0),119 s0,120 },121 {122 "WriteRune",123 func(b *Builder) (int, error) { return b.WriteRune('a') },124 1,125 "a",126 },127 {128 "WriteRuneWide",129 func(b *Builder) (int, error) { return b.WriteRune('世') },130 3,131 "世",132 },133 {134 "WriteString",135 func(b *Builder) (int, error) { return b.WriteString(s0) },136 len(s0),137 s0,138 },139 } {140 t.Run(tt.name, func(t *testing.T) {141 var b Builder142 n, err := tt.fn(&b)143 if err != nil {144 t.Fatalf("first call: got %s", err)145 }146 if n != tt.n {147 t.Errorf("first call: got n=%d; want %d", n, tt.n)148 }149 check(t, &b, tt.want)150 n, err = tt.fn(&b)151 if err != nil {152 t.Fatalf("second call: got %s", err)153 }154 if n != tt.n {155 t.Errorf("second call: got n=%d; want %d", n, tt.n)156 }157 check(t, &b, tt.want+tt.want)158 })159 }160}161func TestBuilderWriteByte(t *testing.T) {162 var b Builder163 if err := b.WriteByte('a'); err != nil {164 t.Error(err)165 }166 if err := b.WriteByte(0); err != nil {167 t.Error(err)168 }169 check(t, &b, "a\x00")170}171func TestBuilderAllocs(t *testing.T) {172 if runtime.Compiler == "gccgo" {173 t.Skip("skip for gccgo until escape analysis improves")174 }175 var b Builder176 const msg = "hello"177 b.Grow(len(msg) * 2) // because AllocsPerRun does an extra "warm-up" iteration178 var s string179 allocs := int(testing.AllocsPerRun(1, func() {180 b.WriteString("hello")181 s = b.String()182 }))183 if want := msg + msg; s != want {184 t.Errorf("String: got %#q; want %#q", s, want)185 }186 if allocs > 0 {187 t.Fatalf("got %d alloc(s); want 0", allocs)188 }189 // Issue 23382; verify that copyCheck doesn't force the190 // Builder to escape and be heap allocated.191 n := testing.AllocsPerRun(10000, func() {192 var b Builder193 b.Grow(5)194 b.WriteString("abcde")195 _ = b.String()196 })197 if n != 1 {198 t.Errorf("Builder allocs = %v; want 1", n)199 }200}201func TestBuilderCopyPanic(t *testing.T) {202 tests := []struct {203 name string204 fn func()205 wantPanic bool206 }{207 {208 name: "String",209 wantPanic: false,210 fn: func() {211 var a Builder212 a.WriteByte('x')213 b := a214 _ = b.String() // appease vet215 },216 },217 {218 name: "Len",219 wantPanic: false,220 fn: func() {221 var a Builder222 a.WriteByte('x')223 b := a224 b.Len()225 },226 },227 {228 name: "Cap",229 wantPanic: false,230 fn: func() {231 var a Builder232 a.WriteByte('x')233 b := a234 b.Cap()235 },236 },237 {238 name: "Reset",239 wantPanic: false,240 fn: func() {241 var a Builder242 a.WriteByte('x')243 b := a244 b.Reset()245 b.WriteByte('y')246 },247 },248 {249 name: "Write",250 wantPanic: true,251 fn: func() {252 var a Builder253 a.Write([]byte("x"))254 b := a255 b.Write([]byte("y"))256 },257 },258 {259 name: "WriteByte",260 wantPanic: true,261 fn: func() {262 var a Builder263 a.WriteByte('x')264 b := a265 b.WriteByte('y')266 },267 },268 {269 name: "WriteString",270 wantPanic: true,271 fn: func() {272 var a Builder273 a.WriteString("x")274 b := a275 b.WriteString("y")276 },277 },278 {279 name: "WriteRune",280 wantPanic: true,281 fn: func() {282 var a Builder283 a.WriteRune('x')284 b := a285 b.WriteRune('y')286 },287 },288 {289 name: "Grow",290 wantPanic: true,291 fn: func() {292 var a Builder293 a.Grow(1)294 b := a295 b.Grow(2)296 },297 },298 }299 for _, tt := range tests {300 didPanic := make(chan bool)301 go func() {302 defer func() { didPanic <- recover() != nil }()303 tt.fn()304 }()305 if got := <-didPanic; got != tt.wantPanic {306 t.Errorf("%s: panicked = %v; want %v", tt.name, got, tt.wantPanic)307 }308 }309}310var someBytes = []byte("some bytes sdljlk jsklj3lkjlk djlkjw")311var sinkS string312func benchmarkBuilder(b *testing.B, f func(b *testing.B, numWrite int, grow bool)) {313 b.Run("1Write_NoGrow", func(b *testing.B) {314 b.ReportAllocs()315 f(b, 1, false)316 })317 b.Run("3Write_NoGrow", func(b *testing.B) {318 b.ReportAllocs()319 f(b, 3, false)320 })321 b.Run("3Write_Grow", func(b *testing.B) {322 b.ReportAllocs()323 f(b, 3, true)324 })325}326func BenchmarkBuildString_Builder(b *testing.B) {327 benchmarkBuilder(b, func(b *testing.B, numWrite int, grow bool) {328 for i := 0; i < b.N; i++ {329 var buf Builder330 if grow {331 buf.Grow(len(someBytes) * numWrite)332 }333 for i := 0; i < numWrite; i++ {334 buf.Write(someBytes)335 }336 sinkS = buf.String()337 }338 })339}340func BenchmarkBuildString_ByteBuffer(b *testing.B) {341 benchmarkBuilder(b, func(b *testing.B, numWrite int, grow bool) {342 for i := 0; i < b.N; i++ {343 var buf bytes.Buffer344 if grow {345 buf.Grow(len(someBytes) * numWrite)346 }347 for i := 0; i < numWrite; i++ {348 buf.Write(someBytes)349 }350 sinkS = buf.String()351 }352 })353}...

Full Screen

Full Screen

timer_test.go

Source:timer_test.go Github

copy

Full Screen

...29 defer sumTimer.ObserveDuration()30 defer gaugeTimer.ObserveDuration()31 }()32 m := &dto.Metric{}33 his.Write(m)34 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {35 t.Errorf("want %d observations for histogram, got %d", want, got)36 }37 m.Reset()38 sum.Write(m)39 if want, got := uint64(1), m.GetSummary().GetSampleCount(); want != got {40 t.Errorf("want %d observations for summary, got %d", want, got)41 }42 m.Reset()43 gauge.Write(m)44 if got := m.GetGauge().GetValue(); got <= 0 {45 t.Errorf("want value > 0 for gauge, got %f", got)46 }47}48func TestTimerEmpty(t *testing.T) {49 emptyTimer := NewTimer(nil)50 emptyTimer.ObserveDuration()51 // Do nothing, just demonstrate it works without panic.52}53func TestTimerConditionalTiming(t *testing.T) {54 var (55 his = NewHistogram(HistogramOpts{56 Name: "test_histogram",57 })58 timeMe = true59 m = &dto.Metric{}60 )61 timedFunc := func() {62 timer := NewTimer(ObserverFunc(func(v float64) {63 if timeMe {64 his.Observe(v)65 }66 }))67 defer timer.ObserveDuration()68 }69 timedFunc() // This will time.70 his.Write(m)71 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {72 t.Errorf("want %d observations for histogram, got %d", want, got)73 }74 timeMe = false75 timedFunc() // This will not time again.76 m.Reset()77 his.Write(m)78 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {79 t.Errorf("want %d observations for histogram, got %d", want, got)80 }81}82func TestTimerByOutcome(t *testing.T) {83 var (84 his = NewHistogramVec(85 HistogramOpts{Name: "test_histogram"},86 []string{"outcome"},87 )88 outcome = "foo"89 m = &dto.Metric{}90 )91 timedFunc := func() {92 timer := NewTimer(ObserverFunc(func(v float64) {93 his.WithLabelValues(outcome).Observe(v)94 }))95 defer timer.ObserveDuration()96 if outcome == "foo" {97 outcome = "bar"98 return99 }100 outcome = "foo"101 }102 timedFunc()103 his.WithLabelValues("foo").(Histogram).Write(m)104 if want, got := uint64(0), m.GetHistogram().GetSampleCount(); want != got {105 t.Errorf("want %d observations for 'foo' histogram, got %d", want, got)106 }107 m.Reset()108 his.WithLabelValues("bar").(Histogram).Write(m)109 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {110 t.Errorf("want %d observations for 'bar' histogram, got %d", want, got)111 }112 timedFunc()113 m.Reset()114 his.WithLabelValues("foo").(Histogram).Write(m)115 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {116 t.Errorf("want %d observations for 'foo' histogram, got %d", want, got)117 }118 m.Reset()119 his.WithLabelValues("bar").(Histogram).Write(m)120 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {121 t.Errorf("want %d observations for 'bar' histogram, got %d", want, got)122 }123 timedFunc()124 m.Reset()125 his.WithLabelValues("foo").(Histogram).Write(m)126 if want, got := uint64(1), m.GetHistogram().GetSampleCount(); want != got {127 t.Errorf("want %d observations for 'foo' histogram, got %d", want, got)128 }129 m.Reset()130 his.WithLabelValues("bar").(Histogram).Write(m)131 if want, got := uint64(2), m.GetHistogram().GetSampleCount(); want != got {132 t.Errorf("want %d observations for 'bar' histogram, got %d", want, got)133 }134}...

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 file, err := os.OpenFile("test.txt", os.O_CREATE|os.O_WRONLY, 0666)4 if err != nil {5 fmt.Println(err)6 }7 defer file.Close()8 file.WriteString("Hello world!")9}10import (11func main() {12 file, err := os.OpenFile("test.txt", os.O_RDONLY, 0666)13 if err != nil {14 fmt.Println(err)15 }16 defer file.Close()17 buf := make([]byte, 1024)18 n, _ := file.Read(buf)19 fmt.Println(string(buf[:n]))20}21func (f *File) WriteString(s string) (n int, err error)22func (f *File) Read(b []byte) (n int, err error)23func (f *File) ReadAt(b []byte, off int64) (n int, err error)24func (f *File) ReadDir(n int) ([]os.FileInfo, error)25func (f *File) ReadFrom(r io.Reader) (n int64, err error)26func (f *File) ReadAtLeast(b []byte, off int64, min int) (n int, err error)27func (f *File) ReadFull(b []byte) (n int, err error)28func (f *File) Seek(offset int64, whence int) (ret int64, err error)29func (f *File) Sync() error30func (f *File) Truncate(size int64) error31func (f *File) Write(b []byte) (n int, err error)32func (f *File) WriteAt(b []byte, off int64) (n int, err error)33func (f *File) WriteString(s string) (n int, err error)34func (f *File) WriteTo(w io.Writer) (n int64, err error)35func (f *File) Close() error36func (f *File) Chdir() error37func (f *File)

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1func main() {2 got := got.Got{}3 got.Write("Hello World")4}5func main() {6 got := got.Got{}7 got.Write("Hello World")8}9func main() {10 got := got.Got{}11 got.Write("Hello World")12}13func main() {14 got := got.Got{}15 got.Write("Hello World")16}17func main() {18 got := got.Got{}19 got.Write("Hello World")20}21func main() {22 got := got.Got{}23 got.Write("Hello World")24}25func main() {26 got := got.Got{}27 got.Write("Hello World")28}29func main() {30 got := got.Got{}31 got.Write("Hello World")32}33func main() {34 got := got.Got{}35 got.Write("Hello World")36}37func main() {38 got := got.Got{}39 got.Write("Hello World")40}41func main() {42 got := got.Got{}43 got.Write("Hello World")44}45func main() {46 got := got.Got{}47 got.Write("Hello World")48}49func main() {50 got := got.Got{}51 got.Write("Hello World")52}53func main() {54 got := got.Got{}55 got.Write("Hello World")56}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 g := got.NewGot()4 g.Write("Hello World")5}6import (7func main() {8 g := got.NewGot()9 fmt.Println(g.Read())10}11import (12func main() {13 g := got.NewGot()14 g.Write("Hello World")15 fmt.Println(g.Read())16}17import (18func main() {19 g := got.NewGot()20 g.Write("Hello World")21 g.Write("Hello World")22 fmt.Println(g.Read())23 fmt.Println(g.Read())24}25import (26func main() {27 g := got.NewGot()28 g.Write("Hello World")29 g.Write("Hello World")30 g.Write("Hello World")31 fmt.Println(g.Read())32 fmt.Println(g.Read())33 fmt.Println(g.Read())34}35import (36func main() {37 g := got.NewGot()38 g.Write("Hello World")39 g.Write("Hello

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Print("Enter your name: ")4 fmt.Scanln(&name)5 fmt.Println("Hello", name)6}7import (8func main() {9 fmt.Print("Enter your name: ")10 fmt.Scanln(&name)11 fmt.Println("Hello", name)12}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 w.Write([]byte("Hello, world!"))4}5import "fmt"6func main() {7 b := make([]byte, 1024)8 r.Read(b)9}10type got struct {}11func (g *got) Write(b []byte) (int, error) {12 fmt.Println(string(b))13 return len(b), nil14}15func (g *got) Read(b []byte) (int, error) {16 fmt.Println(string(b))17 return len(b), nil18}19import "fmt"20import "github.com/yourname/yourproject/got"21func main() {22 w.Write([]byte("Hello, world!"))23}24import "fmt"25import "github.com/yourname/yourproject/got"26func main() {27 b := make([]byte, 1024)28 r.Read(b)29}30import (

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 g := got.NewGot()4 g.Write("hello")5 fmt.Println(g)6}7type Got struct {8}9func NewGot() *Got {10 return &Got{}11}12func (g *Got) Write(s string) {13}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3got:=new(Write)4got.Write("Hello, World!")5}6import "fmt"7type Write struct{}8func (w Write) Write(s string) {9fmt.Println(s)10}11func main() {12got:=new(Write)13got.Write("Hello, World!")14}15import "fmt"16type Write struct{}17func (w Write) Write(s string) {18fmt.Println(s)19}20func (w Write) Write(s1 string, s2 string) {21fmt.Println(s1, s2)22}23func main() {24got:=new(Write)25got.Write("Hello, World!")26got.Write("Hello", "World!")27}28import "fmt"29type Write struct{}30func (w Write) Write(s string) {31fmt.Println(s)32}33func (w Write) Write(s1 string, s2 string) {34fmt.Println(s1, s2)35}36func main() {37got:=new(Write)38got.Write("Hello, World!")39got.Write("Hello", "World!")40}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 file, err := os.Open("C:\\Users\\Karan\\Desktop\\1.txt")5 if err != nil {6 fmt.Println(err)7 }8 io.Copy(got, file)9 fmt.Println(got)10 fmt.Println(got.Read())11}12import (13func main() {14 fmt.Println("Hello World")15 file, err := os.Open("C:\\Users\\Karan\\Desktop\\1.txt")16 if err != nil {17 fmt.Println(err)18 }19 io.Copy(got, file)20 fmt.Println(got)21 fmt.Println(got.Read())22}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 got := got.New()4 got.Write("Hello, World!")5}6import (7func main() {8 got := got.New()9 fmt.Println(got.Read())10}11import (12func main() {13 got := got.New()14 got.Use()15}16import (17func main() {18 got := got.New()19 got.Write("Hello, World!")20}21import (22func main() {23 got := got.New()24 fmt.Println(got.Read())25}26import (27func main() {28 got := got.New()29 got.Use()30}31import (32func main() {33 got := got.New()34 got.Write("Hello, World!")35}36import (37func main() {38 got := got.New()39 fmt.Println(got.Read())40}41import (42func main() {

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful