Best K6 code snippet using log.readKey
input_test.go
Source:input_test.go
1package zzterm2import (3 "bytes"4 "encoding/json"5 "errors"6 "io/ioutil"7 "log"8 "os"9 "strings"10 "testing"11)12func TestInput_ReadKey_Multiple(t *testing.T) {13 invalidRuneKey := Key('\x01')14 cases := []struct {15 in string16 keys []Key17 bytes []string18 }{19 {"", nil, nil},20 {"a", []Key{Key('a')}, []string{"a"}},21 {"ab", []Key{Key('a'), Key('b')}, []string{"a", "b"}},22 {"\xff", []Key{invalidRuneKey}, []string{"\xff"}},23 {"\xffa", []Key{invalidRuneKey, Key('a')}, []string{"\xff", "a"}},24 {"ð¿\x1b[abc", []Key{Key('ð¿'), keyFromTypeMod(KeyESCSeq, ModNone)}, []string{"ð¿", "\x1b[abc"}},25 }26 input := NewInput(WithMouse(), WithFocus())27 for _, c := range cases {28 t.Run(c.in, func(t *testing.T) {29 r := strings.NewReader(c.in)30 for i, wantk := range c.keys {31 wantb := c.bytes[i]32 got, err := input.ReadKey(r)33 if wantk == invalidRuneKey {34 if err.Error() != "invalid rune" {35 t.Fatalf("[%d]: want invalid rune, got %v", i, err)36 }37 wantk = Key(0)38 } else if err != nil {39 t.Fatalf("[%d]: want %s, got error %v", i, wantk, err)40 }41 if got.Type() != wantk.Type() {42 t.Fatalf("[%d]: want key type %s, got %s", i, wantk.Type(), got.Type())43 }44 if gotb := string(input.Bytes()); gotb != wantb {45 t.Fatalf("[%d]: want bytes %q, got %q", i, wantb, gotb)46 }47 }48 // after the loop, must return a "timeout" error (via EOF)49 got, err := input.ReadKey(r)50 if !errors.Is(err, ErrTimeout) {51 t.Fatalf("after loop: want ErrTimeout, got %v (key %v)", err, got)52 }53 if !os.IsTimeout(err) {54 t.Fatal("after loop: want ErrTimeout to be identified as such with os.IsTimeout")55 }56 })57 }58}59func TestInput_ReadKey_BustBuffer(t *testing.T) {60 // this '⬼ ' character is 3 bytes in utf-8, so it ends up crossing61 // over the buffer size (which is an even number). This tests that62 // ReadKey properly tries a Read to get more bytes when it only63 // has an invalid rune to work with.64 want, wantn := "\xE2\xAC\xBC", 10065 r := strings.NewReader(strings.Repeat(want, wantn))66 input := NewInput()67 var count int68 for {69 key, err := input.ReadKey(r)70 if errors.Is(err, ErrTimeout) {71 break72 }73 if err != nil {74 t.Fatal(err)75 }76 count++77 if got := string(input.Bytes()); got != want {78 t.Fatalf("[%d]: got bytes %q", count, got)79 }80 if key.Type() != KeyRune || key.Rune() != '⬼' {81 t.Fatalf("[%d]: unexpected key %v", count, key)82 }83 }84 if count != 100 {85 t.Fatalf("want %d keys, got %d", wantn, count)86 }87}88type testcase struct {89 in string90 r rune91 typ KeyType92 m Mod93}94func TestInput_ReadKey_DefaultTinfo(t *testing.T) {95 cases := []testcase{96 {"a", 'a', KeyRune, ModNone},97 {"B", 'B', KeyRune, ModNone},98 {"1", '1', KeyRune, ModNone},99 {"\x00", -1, KeyNUL, ModNone},100 {"\x01", -1, KeySOH, ModNone},101 {"\n", -1, KeyLF, ModNone},102 {"â¢", 'â¢', KeyRune, ModNone},103 {"ðª", 'ðª', KeyRune, ModNone},104 {"ð¤¡", 'ð¤¡', KeyRune, ModNone},105 {"ð°§", 'ð°§', KeyRune, ModNone},106 {"âº", 'âº', KeyRune, ModNone},107 {"\u007f", -1, KeyDEL, ModNone},108 {"\x1b[A", -1, KeyUp, ModNone},109 {"\x1b[3~", -1, KeyDelete, ModNone},110 {"\x1b[1;2D", -1, KeyLeft, ModShift},111 {"\x1b[1;2C", -1, KeyRight, ModShift},112 }113 input := NewInput()114 for _, c := range cases {115 runTestcase(t, c, input)116 }117}118func TestInput_ReadKey_VT100Tinfo(t *testing.T) {119 b, err := ioutil.ReadFile("testdata/vt100.json")120 if err != nil {121 t.Fatal(err)122 }123 var m map[string]string124 if err := json.Unmarshal(b, &m); err != nil {125 t.Fatal(err)126 }127 cases := []testcase{128 {"a", 'a', KeyRune, ModNone},129 {"B", 'B', KeyRune, ModNone},130 {"1", '1', KeyRune, ModNone},131 {"\x00", -1, KeyNUL, ModNone},132 {"\x01", -1, KeySOH, ModNone},133 {"\n", -1, KeyLF, ModNone},134 {"â¢", 'â¢', KeyRune, ModNone},135 {"ðª", 'ðª', KeyRune, ModNone},136 {"ð¤¡", 'ð¤¡', KeyRune, ModNone},137 {"ð°§", 'ð°§', KeyRune, ModNone},138 {"âº", 'âº', KeyRune, ModNone},139 {"\u007f", -1, KeyDEL, ModNone},140 {"\x1bOA", -1, KeyUp, ModNone},141 {"\x1bOP", -1, KeyF1, ModNone},142 {"\x1bOD", -1, KeyLeft, ModNone},143 }144 input := NewInput(WithESCSeq(FromTerminfo(m)))145 for _, c := range cases {146 runTestcase(t, c, input)147 }148}149func TestInput_ReadKey_Focus(t *testing.T) {150 input := NewInput(WithFocus())151 in := "\x1b[I"152 k, err := input.ReadKey(strings.NewReader(in))153 if err != nil {154 log.Fatal(err)155 }156 if k.Type() != KeyFocusIn || k.Mod() != ModNone {157 t.Errorf("invalid modifier flags or key type: %s", k)158 }159 in = "\x1b[O"160 k, err = input.ReadKey(strings.NewReader(in))161 if err != nil {162 log.Fatal(err)163 }164 if k.Type() != KeyFocusOut || k.Mod() != ModNone {165 t.Errorf("invalid modifier flags or key type: %s", k)166 }167 // without focus decoding168 input = NewInput()169 in = "\x1b[O"170 k, err = input.ReadKey(strings.NewReader(in))171 if err != nil {172 log.Fatal(err)173 }174 if k.Type() != KeyESCSeq || k.Mod() != ModNone {175 t.Errorf("invalid modifier flags or key type: %s", k)176 }177 in = "\x1b[I"178 k, err = input.ReadKey(strings.NewReader(in))179 if err != nil {180 log.Fatal(err)181 }182 if k.Type() != KeyESCSeq || k.Mod() != ModNone {183 t.Errorf("invalid modifier flags or key type: %s", k)184 }185}186func TestInput_ReadKey_Mouse(t *testing.T) {187 cases := []struct {188 in string189 m Mod190 btn int191 pressed bool192 x, y int193 }{194 {"\x1b[<35;1;1M", ModNone, 0, true, 1, 1},195 {"\x1b[<0;21;13m", ModNone, 1, false, 21, 13},196 {"\x1b[<6;123;542M", ModShift, 3, true, 123, 542},197 {"\x1b[<70;1;1m", ModShift, 6, false, 1, 1},198 {"\x1b[<157;65536;65536m", ModShift | ModMeta | ModCtrl, 9, false, 65535, 65535},199 // all button IDs200 {"\x1b[<0;1;1m", ModNone, 1, false, 1, 1},201 {"\x1b[<1;1;1m", ModNone, 2, false, 1, 1},202 {"\x1b[<2;1;1m", ModNone, 3, false, 1, 1},203 {"\x1b[<3;1;1m", ModNone, 0, false, 1, 1}, // AFAICT, this should never happen (no button should be value 35)204 {"\x1b[<64;1;1m", ModNone, 4, false, 1, 1},205 {"\x1b[<65;1;1m", ModNone, 5, false, 1, 1},206 {"\x1b[<66;1;1m", ModNone, 6, false, 1, 1},207 {"\x1b[<67;1;1m", ModNone, 7, false, 1, 1},208 {"\x1b[<128;1;1m", ModNone, 8, false, 1, 1},209 {"\x1b[<129;1;1m", ModNone, 9, false, 1, 1},210 {"\x1b[<130;1;1m", ModNone, 10, false, 1, 1},211 {"\x1b[<131;1;1m", ModNone, 11, false, 1, 1},212 {"\x1b[<132;1;1m", ModShift, 8, false, 1, 1},213 }214 input := NewInput(WithMouse())215 for _, c := range cases {216 t.Run(c.in, func(t *testing.T) {217 k, err := input.ReadKey(strings.NewReader(c.in))218 if err != nil {219 t.Fatal(err)220 }221 if k.Type() != KeyMouse {222 t.Fatalf("want key type %d, got %d", KeyMouse, k.Type())223 }224 if k.Mod() != c.m {225 t.Fatalf("want modifier flags %04b, got %04b", c.m, k.Mod())226 }227 mouse := input.Mouse()228 if mouse.ButtonID() != c.btn {229 t.Errorf("want button %d, got %d", c.btn, mouse.ButtonID())230 }231 if mouse.ButtonPressed() != c.pressed {232 t.Errorf("want pressed %t, got %t", c.pressed, mouse.ButtonPressed())233 }234 if x, y := mouse.Coords(); x != c.x || y != c.y {235 t.Errorf("want %d, %d, got %d, %d", c.x, c.y, x, y)236 }237 })238 }239}240func TestInput_ReadKey_Bytes(t *testing.T) {241 input := NewInput(WithESCSeq(make(map[string]string)))242 // before any read, Bytes returns nil243 b := input.Bytes()244 if b != nil {245 t.Fatalf("want nil bytes, got %x", b)246 }247 in := "\x1baBc"248 k, err := input.ReadKey(strings.NewReader(in))249 if err != nil {250 t.Fatal(err)251 }252 if k.Type() != KeyESCSeq || k.Mod() != ModNone {253 t.Fatalf("want escape sequence, got %s", k)254 }255 // bytes return the same bytes256 b = input.Bytes()257 if !bytes.Equal([]byte(in), b) {258 t.Fatalf("want %x, got %x", []byte(in), b)259 }260 // appending to the returned bytes does not impact the internal buffer261 bb, err := ioutil.ReadFile("testdata/vt100.json")262 if err != nil {263 t.Fatal(err)264 }265 oriLen, oriCap := len(input.buf), cap(input.buf)266 _ = append(b, bb...)267 if len(input.buf) != oriLen {268 t.Errorf("appending to returned bytes impacted internal buffer: len %d => %d", oriLen, len(input.buf))269 }270 if cap(input.buf) != oriCap {271 t.Errorf("appending to returned bytes impacted internal buffer: cap %d => %d", oriCap, cap(input.buf))272 }273}274func runTestcase(t *testing.T, c testcase, input *Input) {275 t.Helper()276 t.Run(c.in, func(t *testing.T) {277 k, err := input.ReadKey(strings.NewReader(c.in))278 if err != nil {279 t.Fatal(err)280 }281 if k.Rune() != c.r {282 t.Errorf("want rune %c (%[1]U), got %c (%[2]U)", c.r, k.Rune())283 }284 if k.Type() != c.typ {285 t.Errorf("want key type %d, got %d", c.typ, k.Type())286 }287 if k.Mod() != c.m {288 t.Errorf("want modifier flags %04b, got %04b", c.m, k.Mod())289 }290 })291}292var BenchmarkKey Key293func BenchmarkInput_ReadKey(b *testing.B) {294 cases := []string{295 "a", "B", "1", "\x00", "ø", "ðª", "å¹³",296 "\x1b[B", "\x1b[1;2C", "\x1b[I", "\x1b[<35;1;2M",297 }298 for _, c := range cases {299 input := NewInput(WithFocus(), WithMouse())300 b.Run(c, func(b *testing.B) {301 r := strings.NewReader(c)302 b.ResetTimer()303 for i := 0; i < b.N; i++ {304 k, err := input.ReadKey(r)305 if err != nil {306 b.Fatal(err)307 }308 BenchmarkKey = k309 r.Reset(c)310 }311 })312 }313}314var BenchmarkBytes []byte315func BenchmarkInput_ReadKey_Bytes(b *testing.B) {316 input := NewInput(WithESCSeq(make(map[string]string)))317 data := "\x1baBc"318 r := strings.NewReader(data)319 b.ResetTimer()320 for i := 0; i < b.N; i++ {321 k, err := input.ReadKey(r)322 if err != nil {323 b.Fatal(err)324 }325 BenchmarkKey = k326 BenchmarkBytes = input.Bytes()327 r.Reset(data)328 }329}330var BenchmarkMouseEvent MouseEvent331func BenchmarkInput_ReadKey_Mouse(b *testing.B) {332 input := NewInput(WithMouse())333 data := "\x1b[<6;123;542M"334 r := strings.NewReader(data)335 b.ResetTimer()336 for i := 0; i < b.N; i++ {337 k, err := input.ReadKey(r)338 if err != nil {339 b.Fatal(err)340 }341 BenchmarkKey = k342 BenchmarkMouseEvent = input.Mouse()343 r.Reset(data)344 }345}346func BenchmarkInput_ReadKey_Multiple(b *testing.B) {347 input := NewInput(WithMouse())348 data := "a⬼\x1b[<6;123;542M"349 r := strings.NewReader(data)350 b.ResetTimer()351 for i := 0; i < b.N; i++ {352 var count int353 for j := 0; j < 3; j++ {354 if _, err := input.ReadKey(r); err != nil {355 b.Fatal(err)356 }357 count++358 }359 if count != 3 {360 b.Fatalf("want 3 keys, got %d", count)361 }362 r.Reset(data)363 }364}365func BenchmarkInput_ReadKey_Timeout(b *testing.B) {366 input := NewInput()367 data := "⬼"368 r := strings.NewReader(data)369 b.ResetTimer()370 for i := 0; i < b.N; i++ {371 var count int372 for j := 0; j < 2; j++ {373 if _, err := input.ReadKey(r); err != nil {374 if err == ErrTimeout {375 break376 }377 b.Fatal(err)378 }379 count++380 }381 if count != 1 {382 b.Fatalf("want 1 key, got %d", count)383 }384 r.Reset(data)385 }386}...
server.go
Source:server.go
...9 "net"10)11type Server struct {12}13func (s *Server) readKey(r *bufio.Reader) (string, error) {14 kLen, err := util.ReadLen(r)15 if err != nil {16 return "", err17 }18 k := make([]byte, kLen)19 _, err = io.ReadFull(r, k)20 if err != nil {21 return "", err22 }23 return string(k), nil24}25func (s *Server) readAll(r *bufio.Reader) (string, []byte, error) {26 kLen, err := util.ReadLen(r)27 if err != nil {28 return "", nil, err29 }30 vLen, err := util.ReadLen(r)31 if err != nil {32 return "", nil, err33 }34 key := make([]byte, kLen)35 _, err = io.ReadFull(r, key)36 if err != nil {37 return "", nil, err38 }39 value := make([]byte, vLen)40 _, err = io.ReadFull(r, value)41 if err != nil {42 return "", nil, err43 }44 return string(key[:]), value, nil45}46func (s *Server) get(conn net.Conn, r *bufio.Reader) error {47 key, err := s.readKey(r)48 if err != nil {49 return err50 }51 value, err := db.Get(key)52 log.Info("get key=%s", key)53 return util.SendData(value, nil, conn)54}55func (s *Server) set(conn net.Conn, r *bufio.Reader) error {56 key, value, err := s.readAll(r)57 if err != nil {58 return err59 }60 log.Info("set key=%s", key)61 err = db.Set(key, value)62 return util.SendData([]byte(key), err, conn)63}64func (s *Server) del(conn net.Conn, r *bufio.Reader) error {65 key, err := s.readKey(r)66 if err != nil {67 return err68 }69 log.Info("del key=%s", key)70 err = db.Del(key)71 if err != nil {72 log.Error("del err:=%v", err)73 }74 return util.SendData([]byte(key), err, conn)75}76func (s *Server) prefix(conn net.Conn, r *bufio.Reader) error {77 key, err := s.readKey(r)78 if err != nil {79 return err80 }81 value, _ := db.Iterator(key)82 ctx, err := json.Marshal(value)83 if err != nil {84 log.Error("prefix error:", err)85 }86 return util.SendData(ctx, err, conn)87}88func (s *Server) prefixOnlyKey(conn net.Conn, r *bufio.Reader) error {89 key, err := s.readKey(r)90 if err != nil {91 return err92 }93 value, _ := db.IteratorOnlyKey(key)94 ctx, err := json.Marshal(value)95 if err != nil {96 log.Error("prefix error:", err)97 }98 return util.SendData(ctx, err, conn)99}100func (s *Server) closedb(conn net.Conn, r *bufio.Reader) error {101 db.CloseDB()102 _, err := s.readKey(r)103 if err != nil {104 return err105 }106 var data []byte107 err = db.CloseDB()108 if err != nil {109 data = append(data, 0)110 } else {111 data = append(data, 1)112 }113 log.Info("closing db")114 return util.SendData(data, nil, conn)115}116func (s *Server) opendb(conn net.Conn, r *bufio.Reader) error {117 key, err := s.readKey(r)118 if err != nil {119 return err120 }121 var data []byte122 //db.CloseDB()123 db = dbserver.NewDB(key) // db æ¯ä¸ªå
¨å±åé124 if err != nil {125 data = append(data, 0)126 } else {127 data = append(data, 1)128 }129 log.Info("opening db")130 if state, err := db.State(""); err == nil {131 log.Info(state)...
main.go
Source:main.go
...49 return nil, errors.New("failed to decode certificate")50 }51 return x509.ParseCertificate(block.Bytes)52}53func readKey(keyFileName string) []byte {54 // read key file55 keyFile, err := os.ReadFile(keyFileName)56 check(err)57 log.Println(string(keyFile))58 // decrypt key file59 key, err := decryptKey(keyFile, "mypassword")60 check(err)61 log.Println(string(key))62 return key63}64func readCert(certFileName string) []byte {65 // read cert file66 certFile, err := os.ReadFile(certFileName)67 check(err)68 log.Println(string(certFile))69 certInfo, err := loadCertificateByte(certFile)70 check(err)71 if certInfo.NotAfter.Unix() < time.Now().Unix() {72 log.Println("invalid certificate")73 }74 return certFile75}76func testPKCS1Nocrypt() {77 log.Println("********** testPKCS1Nocrypt **********")78 key := readKey("pkcs1-nocrypt.key")79 cert := readCert("pkcs1-nocrypt.crt")80 _, err := tls.X509KeyPair(cert, key)81 check(err)82}83func testPKCS8Nocrypt() {84 log.Println("********** testPKCS8Nocrypt **********")85 key := readKey("pkcs8-nocrypt.key")86 cert := readCert("pkcs8-nocrypt.crt")87 _, err := tls.X509KeyPair(cert, key)88 check(err)89}90func testPKCS1Crypt() {91 log.Println("********** testPKCS1Crypt **********")92 key := readKey("pkcs1-crypt.key")93 cert := readCert("pkcs1-crypt.crt")94 _, err := tls.X509KeyPair(cert, key)95 check(err)96}97func testPKCS8Crypt() {98 log.Println("********** testPKCS8Crypt **********")99 key := readKey("pkcs8-crypt.key")100 cert := readCert("pkcs8-crypt.crt")101 _, err := tls.X509KeyPair(cert, key)102 check(err)103}104func main() {105 testPKCS1Nocrypt()106 testPKCS8Nocrypt()107 testPKCS1Crypt()108 testPKCS8Crypt()109}...
readKey
Using AI Code Generation
1import (2func main() {3 key = log.ReadKey()4 fmt.Println(key)5}6import (7func main() {8 key = log.ReadKey()9 fmt.Println(key)10}11func ReadKey() string {12 fmt.Scanln(&key)13}14import (15func main() {16 key = log.ReadKey()17 fmt.Println(key)18}19import (20func main() {21 key = log.ReadKey()22 fmt.Println(key)23}24import (25func main() {26 key = log.ReadKey()27 fmt.Println(key)28}29import (30func main() {31 key = log.ReadKey()32 fmt.Println(key)33}34import (35func main() {36 key = log.ReadKey()37 fmt.Println(key)38}39import (40func main() {41 key = log.ReadKey()42 fmt.Println(key)43}44import (45func main() {46 key = log.ReadKey()47 fmt.Println(key)48}49import (50func main() {51 key = log.ReadKey()
readKey
Using AI Code Generation
1import "fmt"2import "log"3func main() {4 log.SetPrefix("myapp: ")5 log.SetFlags(0)6 log.Print("message")7 log.SetFlags(log.Lshortfile)8 log.Print("message")9 log.SetFlags(log.Lshortfile | log.Lmicroseconds)10 log.Print("message")11 log.SetFlags(log.LstdFlags | log.Lshortfile)12 log.Print("message")13 log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)14 log.Print("message")15 log.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds | log.Llongfile)16 log.Print("message")17}
readKey
Using AI Code Generation
1import (2func main() {3log.Println("Enter the key to be searched")4reader := bufio.NewReader(os.Stdin)5key, _ := reader.ReadString('6key = key[:len(key)-1]7log.Println("Key entered is ", key)8log.Println("Searching for key")9if log.readKey(key) {10log.Println("Key found")11} else {12log.Println("Key not found")13}14}15import (16func readKey(key string) bool {17file, err := os.Open("data.txt")18if err != nil {19fmt.Println("File not found")20}21defer file.Close()22byteValue, _ := ioutil.ReadAll(file)23lines := strings.Split(string(byteValue), "24for _, line := range lines {25if line == key {26}27}28}29}30import (31func readKey(key string) bool {32file, err := os.Open("data.txt")33if err != nil {34fmt.Println("File not found")35}36defer file.Close()37byteValue, _ := ioutil.ReadAll(file)38lines := strings.Split(string(byteValue), "39for _, line := range lines {40if line == key {41}42}43}44}45import (46func readKey(key string) bool {47file, err := os.Open("data.txt")48if err != nil {49fmt.Println("File not found")50}51defer file.Close()52byteValue, _ := ioutil.ReadAll(file)53lines := strings.Split(string(byteValue), "54for _, line := range lines {55if line == key {56}57}58}59}60import (
readKey
Using AI Code Generation
1import (2func main() {3 log.ReadKey()4 fmt.Println("Program terminated")5}6import (7func main() {8 log.ReadKey()9 fmt.Println("Program terminated")10}11import (12func main() {13 log.ReadKey()14 fmt.Println("Program terminated")15}16import (17func main() {18 log.ReadKey()19 fmt.Println("Program terminated")20}21import (22func main() {23 log.ReadKey()24 fmt.Println("Program terminated")25}26import (27func main() {28 log.ReadKey()29 fmt.Println("Program terminated")30}31import (32func main() {33 log.ReadKey()34 fmt.Println("Program terminated")35}36import (37func main() {38 log.ReadKey()39 fmt.Println("Program terminated")40}41import (42func main() {43 log.ReadKey()44 fmt.Println("Program terminated")45}46import (47func main() {48 log.ReadKey()49 fmt.Println("Program terminated")50}51import (52func main()
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!!