How to use writeFile method of state Package

Best Syzkaller code snippet using state.writeFile

lock_test.go

Source:lock_test.go Github

copy

Full Screen

1// Copyright 2015 The Vanadium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4package lock5import (6 "fmt"7 "io/ioutil"8 "os"9 "path/filepath"10 "testing"11 "v.io/x/lib/gosh"12 "v.io/x/lib/vlog"13 "v.io/x/ref/services/agent/internal/lockutil"14 "v.io/x/ref/test/timekeeper"15)16var goshLevelTryLock = gosh.RegisterFunc("goshLevelTryLock", func(dir string, index int) {17 l := newDirLock(dir, timekeeper.NewManualTime())18 switch outcome := l.tryLock(index).(type) {19 default:20 vlog.Fatalf("Unexpected type %T", outcome)21 case grabbedLock:22 if bool(outcome) {23 fmt.Println("grabbed")24 } else {25 fmt.Println("not grabbed")26 }27 case staleLock:28 fmt.Println("stale")29 case failedLock:30 vlog.Fatalf("Failed: %v", outcome.error)31 }32})33var goshTryLock = gosh.RegisterFunc("goshTryLock", func(dir string) {34 l := newDirLock(dir, timekeeper.NewManualTime())35 grabbed, err := l.TryLock()36 if err != nil {37 vlog.Fatalf("Failed: %v", err)38 }39 fmt.Println(map[bool]string{true: "grabbed", false: "not grabbed"}[grabbed])40})41func setup(t *testing.T) (string, *dirLock) {42 d, err := ioutil.TempDir("", "locktest")43 if err != nil {44 t.Fatalf("Failed to create test dir: %v", err)45 }46 return d, newDirLock(d, timekeeper.NewManualTime())47}48// TestSleep verifies the (internal) sleep method.49func TestSleep(t *testing.T) {50 d, l := setup(t)51 defer os.RemoveAll(d)52 tk := l.timeKeeper.(timekeeper.ManualTime)53 for i := 0; i < 100; i++ {54 sleepDone := make(chan struct{})55 go func() {56 l.sleep()57 close(sleepDone)58 }()59 sleepDuration := <-tk.Requests()60 if sleepDuration < sleepTime-sleepJitter || sleepDuration > sleepTime+sleepJitter {61 t.Fatalf("sleep expected to be %v (+/- %v); got %v instead", sleepTime, sleepJitter, sleepDuration)62 }63 tk.AdvanceTime(sleepDuration)64 <-sleepDone65 }66}67// TestLockFile verifies that the (internal) lockFile method returns a lock file68// path in the right directory.69func TestLockFile(t *testing.T) {70 d, l := setup(t)71 defer os.RemoveAll(d)72 f0 := l.lockFile(0)73 if got := filepath.Dir(f0); got != d {74 t.Fatalf("Expected file %s to be in dir %s", f0, d)75 }76 f1 := l.lockFile(1)77 if got := filepath.Dir(f1); got != d {78 t.Fatalf("Expected file %s to be in dir %s", f1, d)79 }80 if f0 == f1 {81 t.Fatalf("Expected lock files for levels 0 and 1 to differ")82 }83}84func verifyFreeLock(t *testing.T, l *dirLock, index int) {85 lockInfo, err := l.readLockInfo(index)86 if !os.IsNotExist(err) {87 t.Fatalf("readLockInfo should have not found the lockfile, got (%v, %v) instead", string(lockInfo), err)88 }89}90func verifyHeldLock(t *testing.T, l *dirLock, index int) {91 lockInfo, err := l.readLockInfo(index)92 if err != nil {93 t.Fatalf("readLockInfo failed: %v", err)94 }95 if running, err := lockutil.StillHeld(lockInfo); err != nil || !running {96 t.Fatalf("Expected (true, <nil>) got (%t, %v) instead from StillHeld for:\n%v", running, err, string(lockInfo))97 }98}99func verifyStaleLock(t *testing.T, l *dirLock, index int) {100 lockInfo, err := l.readLockInfo(index)101 if err != nil {102 t.Fatalf("readLockInfo failed: %v", err)103 }104 if running, err := lockutil.StillHeld(lockInfo); err != nil || running {105 t.Fatalf("Expected (false, <nil>) got (%t, %v) instead from StillHeld for:\n%v", running, err, string(lockInfo))106 }107}108// TestLevelLock tests the (internal) tryLock, unlock, and poachLock methods.109func TestLevelLock(t *testing.T) {110 d, l := setup(t)111 defer os.RemoveAll(d)112 verifyFreeLock(t, l, 0)113 if outcome := l.tryLock(0).(grabbedLock); !bool(outcome) {114 t.Fatalf("Expected lock was grabbed")115 }116 verifyHeldLock(t, l, 0)117 if outcome := l.tryLock(0).(grabbedLock); bool(outcome) {118 t.Fatalf("Expected lock was not grabbed")119 }120 verifyHeldLock(t, l, 0)121 if err := l.unlock(0); err != nil {122 t.Fatalf("unlock failed: %v", err)123 }124 verifyFreeLock(t, l, 0)125 if outcome := l.tryLock(0).(grabbedLock); !bool(outcome) {126 t.Fatalf("Expected lock was grabbed")127 }128 verifyHeldLock(t, l, 0)129 if err := l.poachLock(0); err != nil {130 t.Fatalf("poachLock failed: %v", err)131 }132 verifyHeldLock(t, l, 0)133 if outcome := l.tryLock(1).(grabbedLock); !bool(outcome) {134 t.Fatalf("Expected lock was grabbed")135 }136 verifyHeldLock(t, l, 0)137 verifyHeldLock(t, l, 1)138}139// TestLevelLockStale tests the (internal) tryLock, poachLock, and unlock140// methods in the face of stale locks created by external processes.141func TestLevelLockStale(t *testing.T) {142 d, l := setup(t)143 defer os.RemoveAll(d)144 sh := gosh.NewShell(t)145 defer sh.Cleanup()146 verifyFreeLock(t, l, 0)147 if out := sh.FuncCmd(goshLevelTryLock, d, 0).Stdout(); out != "grabbed\n" {148 t.Fatalf("Unexpected output: %s", out)149 }150 verifyStaleLock(t, l, 0)151 if _, ok := l.tryLock(0).(staleLock); !ok {152 t.Fatalf("Expected lock to be stale")153 }154 if out := sh.FuncCmd(goshLevelTryLock, d, 0).Stdout(); out != "stale\n" {155 t.Fatalf("Unexpected output: %s", out)156 }157 if err := l.poachLock(0); err != nil {158 t.Fatalf("poachLock failed: %v", err)159 }160 verifyHeldLock(t, l, 0)161 if out := sh.FuncCmd(goshLevelTryLock, d, 0).Stdout(); out != "not grabbed\n" {162 t.Fatalf("Unexpected output: %s", out)163 }164 if err := l.unlock(0); err != nil {165 t.Fatalf("unlock failed: %v", err)166 }167 verifyFreeLock(t, l, 0)168 if out := sh.FuncCmd(goshLevelTryLock, d, 0).Stdout(); out != "grabbed\n" {169 t.Fatalf("Unexpected output: %s", out)170 }171}172// TestLock tests the exported TryLocker and TryLockerSafe methods. This is a173// black-box test (if we ignore the timeKeeper manipulation).174func TestLock(t *testing.T) {175 d, l := setup(t)176 defer os.RemoveAll(d)177 if grabbed, err := l.TryLock(); err != nil || !grabbed {178 t.Fatalf("Expected lock was grabbed, got (%t, %v) instead", grabbed, err)179 }180 if grabbed, err := l.TryLock(); err != nil || grabbed {181 t.Fatalf("Expected lock was not grabbed, got (%t, %v) instead", grabbed, err)182 }183 if err := l.Unlock(); err != nil {184 t.Fatalf("Unlock failed: %v", err)185 }186 if grabbed := l.Must().TryLock(); !grabbed {187 t.Fatalf("Expected lock was grabbed, got %t instead", grabbed)188 }189 if grabbed := l.Must().TryLock(); grabbed {190 t.Fatalf("Expected lock was not grabbed, got %t instead", grabbed)191 }192 l.Must().Unlock()193 if grabbed, err := l.TryLock(); err != nil || !grabbed {194 t.Fatalf("Expected lock was grabbed, got (%t, %v) instead", grabbed, err)195 }196 // Lock is currently held. Attempt to grab the lock in a goroutine.197 // Should only succeed once we release the lock.198 lockDone := make(chan error, 1)199 go func() {200 lockDone <- l.Lock()201 }()202 // Lock should be blocked, and we should see it going to Sleep203 // regularly, waiting for the lock to be released.204 tk := l.timeKeeper.(timekeeper.ManualTime)205 for i := 0; i < 10; i++ {206 select {207 case <-lockDone:208 t.Fatalf("Didn't expect lock to have been grabbed (iteration %d)", i)209 default:210 tk.AdvanceTime(<-tk.Requests())211 }212 }213 if err := l.Unlock(); err != nil {214 t.Fatalf("Unlock failed: %v", err)215 }216 // The lock should now be available for the Lock call to complete.217 if err := <-lockDone; err != nil {218 t.Fatalf("Lock failed: %v", err)219 }220 l.Must().Unlock()221 l.Must().Lock()222 if grabbed := l.Must().TryLock(); grabbed {223 t.Fatalf("Expected lock was not grabbed, got %t instead", grabbed)224 }225}226// TestLockStale tests the exported TryLockerSafe methods in the face of stale227// locks created by external processes. This is a black-box test.228func TestLockStale(t *testing.T) {229 d, l := setup(t)230 defer os.RemoveAll(d)231 sh := gosh.NewShell(t)232 defer sh.Cleanup()233 // Lock gets grabbed by the subprocess (which then exits, rendering the234 // lock stale).235 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "grabbed\n" {236 t.Fatalf("Unexpected output: %s", out)237 }238 // Stale lock gets replaced by the current process.239 if grabbed, err := l.TryLock(); !grabbed || err != nil {240 t.Fatalf("Expected (true, <nil>) got (%t, %v) instead", grabbed, err)241 }242 // Subprocess finds that the lock is legitimately owned by a live243 // process.244 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "not grabbed\n" {245 t.Fatalf("Unexpected output: %s", out)246 }247 if err := l.Unlock(); err != nil {248 t.Fatalf("Unlock failed: %v", err)249 }250 // The lock is available, so the subprocess grabs it.251 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "grabbed\n" {252 t.Fatalf("Unexpected output: %s", out)253 }254 // The lock is stale, so the subprocess grabs it.255 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "grabbed\n" {256 t.Fatalf("Unexpected output: %s", out)257 }258}259func assertNumLockFiles(t *testing.T, d string, num int) {260 files, err := ioutil.ReadDir(d)261 if err != nil {262 t.Fatalf("ReadDir failed: %v", err)263 }264 if nfiles := len(files); nfiles != num {265 t.Fatalf("Expected %d file, found %d", num, nfiles)266 }267}268// TestLockLevelStateChanges verifies the behavior of TryLock when faced with a269// variety of level lock states that may change while TryLock is executing.270func TestLockLevelStateChanges(t *testing.T) {271 d, l := setup(t)272 defer os.RemoveAll(d)273 sh := gosh.NewShell(t)274 defer sh.Cleanup()275 // Test case 1: Start with clean slate. The lock is grabbed by the276 // subprocess.277 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "grabbed\n" {278 t.Fatalf("Unexpected output: %s", out)279 }280 assertNumLockFiles(t, d, 1)281 // Remember the lock info, to be re-used to simulate stale locks further282 // down.283 staleInfo, err := l.readLockInfo(0)284 if err != nil {285 t.Fatalf("readLockInfo failed: %v", err)286 }287 if err := l.Unlock(); err != nil {288 t.Fatalf("Unlock failed: %v", err)289 }290 assertNumLockFiles(t, d, 0)291 // Test case 2: Start with level 0 lock stale. The lock is grabbed by the292 // current process.293 if err := ioutil.WriteFile(l.lockFile(0), staleInfo, os.ModePerm); err != nil {294 t.Fatalf("WriteFile failed: %v", err)295 }296 assertNumLockFiles(t, d, 1)297 if grabbed, err := l.TryLock(); err != nil || !grabbed {298 t.Fatalf("Expected lock was grabbed, got (%t, %v) instead", grabbed, err)299 }300 assertNumLockFiles(t, d, 1)301 // Remember the lock info, to be re-used to simulate actively held locks302 // further down.303 activeInfo, err := l.readLockInfo(0)304 if err != nil {305 t.Fatalf("readLockInfo failed: %v", err)306 }307 // goTryLock runs TryLock in a goroutine and returns a function that can308 // be used to verify the outcome of TryLock. Used in subsequent test309 // cases.310 goTryLock := func() func(bool) {311 doneTryLock := make(chan struct {312 grabbed bool313 err error314 }, 1)315 go func() {316 grabbed, err := l.TryLock()317 doneTryLock <- struct {318 grabbed bool319 err error320 }{grabbed, err}321 }()322 return func(expected bool) {323 if outcome := <-doneTryLock; outcome.err != nil || outcome.grabbed != expected {324 t.Fatalf("TryLock: expected (%t, <nil>), got (%t, %v) instead", expected, outcome.grabbed, outcome.err)325 }326 }327 }328 // Test case 3: Start with stale level 0 lock, actively held level 1329 // lock.330 if err := ioutil.WriteFile(l.lockFile(0), staleInfo, os.ModePerm); err != nil {331 t.Fatalf("WriteFile failed: %v", err)332 }333 if err := ioutil.WriteFile(l.lockFile(1), activeInfo, os.ModePerm); err != nil {334 t.Fatalf("WriteFile failed: %v", err)335 }336 assertNumLockFiles(t, d, 2)337 verifyTryLock := goTryLock()338 tk := l.timeKeeper.(timekeeper.ManualTime)339 // TryLock finds lock 1 held, so it sleeps and retries.340 sleepDuration := <-tk.Requests()341 // Unlock level 1, letting TryLock grab it.342 l.unlock(1)343 tk.AdvanceTime(sleepDuration)344 // TryLock managed to grab level 1 and it then reclaims level 0.345 verifyTryLock(true)346 assertNumLockFiles(t, d, 1)347 // Test case 4: Start with stale lock 0, active lock 1 (which then348 // becomes stale).349 if err := ioutil.WriteFile(l.lockFile(0), staleInfo, os.ModePerm); err != nil {350 t.Fatalf("WriteFile failed: %v", err)351 }352 if err := ioutil.WriteFile(l.lockFile(1), activeInfo, os.ModePerm); err != nil {353 t.Fatalf("WriteFile failed: %v", err)354 }355 assertNumLockFiles(t, d, 2)356 verifyTryLock = goTryLock()357 // TryLock finds lock 1 held, so it sleeps and retries.358 sleepDuration = <-tk.Requests()359 // Change lock 1 to stale. TryLock should then move on to level 2,360 // which it can grab and reclaim level 0.361 if err := ioutil.WriteFile(l.lockFile(1), staleInfo, os.ModePerm); err != nil {362 t.Fatalf("WriteFile failed: %v", err)363 }364 tk.AdvanceTime(sleepDuration)365 verifyTryLock(true)366 assertNumLockFiles(t, d, 1)367 // Test case 5: Start with stale lock 0, stale lock 1, active lock 2368 // (which then becomes unlocked).369 if err := ioutil.WriteFile(l.lockFile(0), staleInfo, os.ModePerm); err != nil {370 t.Fatalf("WriteFile failed: %v", err)371 }372 if err := ioutil.WriteFile(l.lockFile(1), staleInfo, os.ModePerm); err != nil {373 t.Fatalf("WriteFile failed: %v", err)374 }375 if err := ioutil.WriteFile(l.lockFile(2), activeInfo, os.ModePerm); err != nil {376 t.Fatalf("WriteFile failed: %v", err)377 }378 assertNumLockFiles(t, d, 3)379 verifyTryLock = goTryLock()380 // TryLock finds lock 2 held, so it sleeps and retries.381 sleepDuration = <-tk.Requests()382 // Remove lock 2. TryLock should then grab it, and then reclaim level383 // 0.384 l.unlock(2)385 tk.AdvanceTime(sleepDuration)386 verifyTryLock(true)387 assertNumLockFiles(t, d, 1)388 // Test case 6: Start with stale lock 0, stale lock 1, active lock 2389 // (which then becomes unlocked; but lock 0 also changes to active).390 if err := ioutil.WriteFile(l.lockFile(0), staleInfo, os.ModePerm); err != nil {391 t.Fatalf("WriteFile failed: %v", err)392 }393 if err := ioutil.WriteFile(l.lockFile(1), staleInfo, os.ModePerm); err != nil {394 t.Fatalf("WriteFile failed: %v", err)395 }396 if err := ioutil.WriteFile(l.lockFile(2), activeInfo, os.ModePerm); err != nil {397 t.Fatalf("WriteFile failed: %v", err)398 }399 assertNumLockFiles(t, d, 3)400 verifyTryLock = goTryLock()401 // TryLock finds lock 2 held, so it sleeps and retries.402 sleepDuration = <-tk.Requests()403 l.unlock(2)404 // We use the hook to control the execution of TryLock and allow405 // ourselves to manipulate the lock files 'asynchronously'.406 tryLockCalled := make(chan struct{})407 l.tryLockHook = func() { tryLockCalled <- struct{}{} }408 tk.AdvanceTime(sleepDuration)409 <-tryLockCalled // Back to level 0, TryLock finds it stale.410 // Mark lock 0 actively held.411 if err := ioutil.WriteFile(l.lockFile(0), activeInfo, os.ModePerm); err != nil {412 t.Fatalf("WriteFile failed: %v", err)413 }414 <-tryLockCalled // For lock 1.415 <-tryLockCalled // For lock 2.416 // TryLock grabs lock level 2, but finds that lock level 0 has changed,417 // so it sleeps and retries.418 tk.AdvanceTime(<-tk.Requests())419 <-tryLockCalled // Back to level 0.420 // This time, the level 0 lock is found to be actively held.421 verifyTryLock(false)422 assertNumLockFiles(t, d, 2)423 select {424 case <-tk.Requests():425 t.Fatalf("Not expecting any more sleeps")426 default:427 }428 // Test case 7: Start with stale lock 0, stale lock 1, active lock 2429 // (which then becomes unlocked; but lock 0 also changes to unlocked).430 l.tryLockHook = nil431 if err := ioutil.WriteFile(l.lockFile(0), staleInfo, os.ModePerm); err != nil {432 t.Fatalf("WriteFile failed: %v", err)433 }434 if err := ioutil.WriteFile(l.lockFile(1), staleInfo, os.ModePerm); err != nil {435 t.Fatalf("WriteFile failed: %v", err)436 }437 if err := ioutil.WriteFile(l.lockFile(2), activeInfo, os.ModePerm); err != nil {438 t.Fatalf("WriteFile failed: %v", err)439 }440 assertNumLockFiles(t, d, 3)441 verifyTryLock = goTryLock()442 // TryLock finds level 2 lock held, so it sleeps and retries.443 sleepDuration = <-tk.Requests()444 // Unlock level 2.445 l.unlock(2)446 tryLockCalled = make(chan struct{})447 l.tryLockHook = func() { tryLockCalled <- struct{}{} }448 tk.AdvanceTime(sleepDuration)449 <-tryLockCalled // Back to level 0, TryLock finds it stale.450 // Unlock level 0.451 l.unlock(0)452 <-tryLockCalled // For lock 1.453 <-tryLockCalled // For lock 2.454 // TryLock grabs level 2, but finds level 0 has changed (unlocked). It455 // sleeps and retries.456 tk.AdvanceTime(<-tk.Requests())457 <-tryLockCalled // Back to level 0.458 // This time, the level 0 lock is found to be available.459 verifyTryLock(true)460 assertNumLockFiles(t, d, 2)461}462type lockState int463const (464 // Free.465 fr lockState = iota466 // Active (held).467 ac468 // Stale.469 st470)471// TestLockLevelConfigurations verifies the behavior of TryLock when faced with472// a variety of initial lock level states and changes to the states while473// TryLock sleeps.474func TestLockLevelConfigurations(t *testing.T) {475 d, l := setup(t)476 defer os.RemoveAll(d)477 sh := gosh.NewShell(t)478 defer sh.Cleanup()479 // Generate a stale lock info and an active lock info file.480 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "grabbed\n" {481 t.Fatalf("Unexpected output: %s", out)482 }483 staleInfo, err := l.readLockInfo(0)484 if err != nil {485 t.Fatalf("readLockInfo failed: %v", err)486 }487 if err := l.Unlock(); err != nil {488 t.Fatalf("Unlock failed: %v", err)489 }490 if grabbed, err := l.TryLock(); err != nil || !grabbed {491 t.Fatalf("Expected lock was grabbed, got (%t, %v) instead", grabbed, err)492 }493 activeInfo, err := l.readLockInfo(0)494 if err != nil {495 t.Fatalf("readLockInfo failed: %v", err)496 }497 if err := l.Unlock(); err != nil {498 t.Fatalf("Unlock failed: %v", err)499 }500 for i, c := range []struct {501 // locks lists the initial state of the locks, subsequent states502 // of the locks to be set while TryLock sleeps, and the final503 // expected state of the locks.504 locks [][]lockState505 // The expected return value of TryLock.506 outcome bool507 }{508 // No existing locks -> success.509 {[][]lockState{510 []lockState{},511 []lockState{ac},512 }, true},513 // Level 0 held -> can't lock.514 {[][]lockState{515 []lockState{ac},516 []lockState{ac},517 }, false},518 // Level 0 stale -> success.519 {[][]lockState{520 []lockState{st},521 []lockState{ac},522 }, true},523 // Level 0-4 stale -> success.524 {[][]lockState{525 []lockState{st, st, st, st, st},526 []lockState{ac},527 }, true},528 // Scenarios where TryLock sleeps, during which time we alter529 // the lock states.530 {[][]lockState{531 []lockState{st, st, ac, st, st},532 []lockState{st, st, st, st, st},533 []lockState{ac},534 }, true},535 {[][]lockState{536 []lockState{st, st, ac, st, st},537 []lockState{st, st, st, st, st},538 []lockState{ac},539 }, true},540 {[][]lockState{541 []lockState{st, st, ac, st, st},542 []lockState{st, st, st, st, ac},543 []lockState{st, st, st, ac, st},544 []lockState{ac, st, st, ac, st},545 []lockState{ac, st, st, ac, st},546 }, false},547 {[][]lockState{548 []lockState{st, st, ac, st, st, fr, st, ac},549 []lockState{st, st, st, st, st, fr, fr, ac},550 []lockState{ac, fr, fr, fr, fr, fr, fr, ac},551 }, true},552 {[][]lockState{553 []lockState{st, st, ac},554 []lockState{st, st, st, st, st},555 []lockState{ac},556 }, true},557 } {558 setStates := func(states []lockState) {559 // First, remove all lock files.560 files, err := ioutil.ReadDir(d)561 if err != nil {562 t.Fatalf("ReadDir failed: %v", err)563 }564 for _, f := range files {565 os.Remove(filepath.Join(d, f.Name()))566 }567 assertNumLockFiles(t, d, 0)568 // Populate the lock files specified by states.569 for level, state := range states {570 switch state {571 default:572 t.Fatalf("Unexpected state: %v", state)573 case fr:574 case ac:575 if err := ioutil.WriteFile(l.lockFile(level), activeInfo, os.ModePerm); err != nil {576 t.Fatalf("WriteFile failed: %v", err)577 }578 case st:579 if err := ioutil.WriteFile(l.lockFile(level), staleInfo, os.ModePerm); err != nil {580 t.Fatalf("WriteFile failed: %v", err)581 }582 }583 }584 }585 setStates(c.locks[0])586 statesIndex := 1587 // Spin up a goroutine to wake up sleeping locks.588 closeTKLoop := make(chan struct{})589 tkLoopDone := make(chan struct{})590 go func() {591 defer close(tkLoopDone)592 tk := l.timeKeeper.(timekeeper.ManualTime)593 for {594 select {595 case sleepDuration := <-tk.Requests():596 setStates(c.locks[statesIndex])597 statesIndex++598 tk.AdvanceTime(sleepDuration)599 case <-closeTKLoop:600 return601 }602 }603 }()604 if outcome, err := l.TryLock(); err != nil {605 t.Fatalf("case %d: TryLock failed: %v", i, err)606 } else if outcome != c.outcome {607 t.Fatalf("case %d: expected outcome %t, got %t instead", i, c.outcome, outcome)608 }609 close(closeTKLoop)610 <-tkLoopDone611 if statesIndex != len(c.locks)-1 {612 t.Fatalf("case %d: expected to exhaust lock states, but statesIndex is %d", i, statesIndex)613 }614 for level, state := range c.locks[statesIndex] {615 switch state {616 default:617 t.Fatalf("case %d: Unexpected state: %v", i, state)618 case fr:619 verifyFreeLock(t, l, level)620 case ac:621 verifyHeldLock(t, l, level)622 l.unlock(level)623 case st:624 verifyStaleLock(t, l, level)625 l.unlock(level)626 }627 }628 assertNumLockFiles(t, d, 0)629 }630}631// TestStaleLockMany verifies it's ok to have many concurrent lockers trying to632// grab the same stale lock. Only one should succeed at a time. This is a633// black-box test (if we ignore the timeKeeper manipulation).634func TestStaleLockMany(t *testing.T) {635 d, l := setup(t)636 defer os.RemoveAll(d)637 sh := gosh.NewShell(t)638 defer sh.Cleanup()639 // Make a stale lock.640 if out := sh.FuncCmd(goshTryLock, d).Stdout(); out != "grabbed\n" {641 t.Fatalf("Unexpected output: %s", out)642 }643 // Spin up a goroutine to wake up sleeping locks.644 closeTKLoop := make(chan struct{})645 tkLoopDone := make(chan struct{})646 go func() {647 defer close(tkLoopDone)648 tk := l.timeKeeper.(timekeeper.ManualTime)649 for {650 select {651 case sleepDuration := <-tk.Requests():652 tk.AdvanceTime(sleepDuration)653 case <-closeTKLoop:654 return655 }656 }657 }()658 // Bring up a bunch of lockers at the same time, contending over the659 // same stale lock.660 const nLockers = 50661 errors := make(chan error, 2*nLockers)662 for i := 0; i < nLockers; i++ {663 go func() {664 errors <- l.Lock()665 // If more than one locker would be allowed in here,666 // Unlock will return an error for the second attempt at667 // freeing the lock.668 errors <- l.Unlock()669 }()670 }671 for i := 0; i < 2*nLockers; i++ {672 if err := <-errors; err != nil {673 t.Fatalf("Error (%d): %v", i, err)674 }675 }676 close(closeTKLoop)677 <-tkLoopDone678}679func TestMain(m *testing.M) {680 gosh.InitMain()681 os.Exit(m.Run())682}...

Full Screen

Full Screen

git_test.go

Source:git_test.go Github

copy

Full Screen

1package main2import (3 "fmt"4 "github.com/stretchr/testify/assert"5 "github.com/tanin47/git-notes/internal/test_helpers"6 "log"7 "os"8 "testing"9)10func assertState(t *testing.T, path string, expectedState State) {11 gogit := GitCmd{}12 state, err := gogit.GetState(path)13 assert.NoError(t, err)14 log.Printf("State: %v", state)15 assert.Equal(t, expectedState, state)16}17func performUpdate(t *testing.T, path string) {18 gogit := GitCmd{}19 err := gogit.Update(path)20 assert.NoError(t, err)21}22func performSync(t *testing.T, path string) {23 gogit := GitCmd{}24 err := gogit.Sync(path)25 assert.NoError(t, err)26}27func TestParseStatusBranch_NoRemote(t *testing.T) {28 state, err := ParseStatusBranch("## master")29 assert.NoError(t, err)30 assert.Equal(t, Ahead, state)31}32func TestParseStatusBranch_Sync(t *testing.T) {33 state, err := ParseStatusBranch("## master...origin/master")34 assert.NoError(t, err)35 assert.Equal(t, Sync, state)36}37func TestParseStatusBranch_Ahead(t *testing.T) {38 state, err := ParseStatusBranch("## master...origin/master [ahead 1]")39 assert.NoError(t, err)40 assert.Equal(t, Ahead, state)41}42func TestParseStatusBranch_OutOfSync(t *testing.T) {43 state, err := ParseStatusBranch("## master...origin/master [behind 99]")44 assert.NoError(t, err)45 assert.Equal(t, OutOfSync, state)46}47func TestParseStatusBranch_OutOfSync2(t *testing.T) {48 state, err := ParseStatusBranch("## master...origin/master [ahead 8, behind 99]")49 assert.NoError(t, err)50 assert.Equal(t, OutOfSync, state)51}52func TestGoGit_Rename(t *testing.T) {53 repos := test_helpers.SetupRepos()54 defer test_helpers.CleanupRepos(repos)55 test_helpers.WriteFile(t, repos.Local, "test_name", "TestContent")56 assertState(t, repos.Local, Dirty)57 performSync(t, repos.Local)58 assertState(t, repos.Local, Sync)59 assert.NoError(t, os.Rename(fmt.Sprintf("%s/%s", repos.Local, "test_name"), fmt.Sprintf("%s/%s", repos.Local, "TEST_NAME")))60 assertState(t, repos.Local, Dirty)61 performUpdate(t, repos.Local)62 assertState(t, repos.Local, Ahead)63}64func TestGoGit_Copy(t *testing.T) {65 repos := test_helpers.SetupRepos()66 defer test_helpers.CleanupRepos(repos)67 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")68 assertState(t, repos.Local, Dirty)69 performSync(t, repos.Local)70 assertState(t, repos.Local, Sync)71 test_helpers.WriteFile(t, repos.Local, "copied.md", "TestContent")72 assertState(t, repos.Local, Dirty)73 performUpdate(t, repos.Local)74 assertState(t, repos.Local, Ahead)75}76func TestGoGit_Modify(t *testing.T) {77 repos := test_helpers.SetupRepos()78 defer test_helpers.CleanupRepos(repos)79 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")80 assertState(t, repos.Local, Dirty)81 performSync(t, repos.Local)82 assertState(t, repos.Local, Sync)83 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent2")84 assertState(t, repos.Local, Dirty)85 performUpdate(t, repos.Local)86 assertState(t, repos.Local, Ahead)87}88func TestGoGit_Deletion(t *testing.T) {89 repos := test_helpers.SetupRepos()90 defer test_helpers.CleanupRepos(repos)91 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")92 assertState(t, repos.Local, Dirty)93 performSync(t, repos.Local)94 assertState(t, repos.Local, Sync)95 assert.NoError(t, os.Remove(fmt.Sprintf("%s/%s", repos.Local, "test.md")))96 assertState(t, repos.Local, Dirty)97 performUpdate(t, repos.Local)98 assertState(t, repos.Local, Ahead)99}100func TestGoGit_UpdateDirty(t *testing.T) {101 repos := test_helpers.SetupRepos()102 defer test_helpers.CleanupRepos(repos)103 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")104 assertState(t, repos.Local, Dirty)105 performUpdate(t, repos.Local)106 assertState(t, repos.Local, Ahead)107}108func TestGoGit_UpdateAhead(t *testing.T) {109 repos := test_helpers.SetupRepos()110 defer test_helpers.CleanupRepos(repos)111 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")112 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")113 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test")114 assertState(t, repos.Local, Ahead)115 performUpdate(t, repos.Local)116 assertState(t, repos.Local, Sync)117}118func TestGoGit_UpdateSync(t *testing.T) {119 repos := test_helpers.SetupRepos()120 defer test_helpers.CleanupRepos(repos)121 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")122 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")123 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test")124 test_helpers.PerformCmd(t, repos.Local, "git", "push", "origin", "master", "-u")125 assertState(t, repos.Local, Sync)126 performUpdate(t, repos.Local)127 assertState(t, repos.Local, Sync)128}129func TestGoGit_UpdateOutOfSync(t *testing.T) {130 repos := test_helpers.SetupRepos()131 defer test_helpers.CleanupRepos(repos)132 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")133 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")134 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test")135 test_helpers.PerformCmd(t, repos.Local, "git", "push", "origin", "master", "-u")136 makeConflict(t, repos.Remote)137 assertState(t, repos.Local, OutOfSync)138 performUpdate(t, repos.Local)139 assertState(t, repos.Local, Sync)140}141func TestGoGit_UpdateFixConflict(t *testing.T) {142 repos := test_helpers.SetupRepos()143 defer test_helpers.CleanupRepos(repos)144 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")145 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")146 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test local")147 test_helpers.PerformCmd(t, repos.Local, "git", "push", "origin", "master", "-u")148 makeConflict(t, repos.Remote)149 assertState(t, repos.Local, OutOfSync)150 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent2")151 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")152 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test cause conflict")153 assertState(t, repos.Local, OutOfSync)154 performUpdate(t, repos.Local)155 assertState(t, repos.Local, Dirty)156 performUpdate(t, repos.Local)157 assertState(t, repos.Local, Ahead)158 performUpdate(t, repos.Local)159 assertState(t, repos.Local, Sync)160}161func TestGoGit_SyncDirty(t *testing.T) {162 repos := test_helpers.SetupRepos()163 defer test_helpers.CleanupRepos(repos)164 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")165 assertState(t, repos.Local, Dirty)166 performSync(t, repos.Local)167 assertState(t, repos.Local, Sync)168}169func TestGoGit_SyncAhead(t *testing.T) {170 repos := test_helpers.SetupRepos()171 defer test_helpers.CleanupRepos(repos)172 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")173 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")174 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test")175 assertState(t, repos.Local, Ahead)176 performSync(t, repos.Local)177 assertState(t, repos.Local, Sync)178}179func TestGoGit_SyncSync(t *testing.T) {180 repos := test_helpers.SetupRepos()181 defer test_helpers.CleanupRepos(repos)182 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")183 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")184 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test")185 test_helpers.PerformCmd(t, repos.Local, "git", "push", "origin", "master", "-u")186 assertState(t, repos.Local, Sync)187 performSync(t, repos.Local)188 assertState(t, repos.Local, Sync)189}190func TestGoGit_SyncOutOfSync(t *testing.T) {191 repos := test_helpers.SetupRepos()192 defer test_helpers.CleanupRepos(repos)193 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")194 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")195 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test")196 test_helpers.PerformCmd(t, repos.Local, "git", "push", "origin", "master", "-u")197 makeConflict(t, repos.Remote)198 assertState(t, repos.Local, OutOfSync)199 performSync(t, repos.Local)200 assertState(t, repos.Local, Sync)201}202func makeConflict(t *testing.T, remote string) {203 anotherLocal := test_helpers.SetupGitRepo("another_local", false)204 test_helpers.SetupRemote(anotherLocal, remote)205 test_helpers.PerformCmd(t, anotherLocal, "git", "fetch")206 test_helpers.PerformCmd(t, anotherLocal, "git", "checkout", "master")207 test_helpers.WriteFile(t, anotherLocal, "test.md", "Cause conflict")208 test_helpers.PerformCmd(t, anotherLocal, "git", "add", "--all")209 test_helpers.PerformCmd(t, anotherLocal, "git", "commit", "-m", "Test Remote")210 test_helpers.PerformCmd(t, anotherLocal, "git", "push")211}212func TestGoGit_SyncFixConflict(t *testing.T) {213 repos := test_helpers.SetupRepos()214 defer test_helpers.CleanupRepos(repos)215 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent")216 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")217 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test local")218 test_helpers.PerformCmd(t, repos.Local, "git", "push", "origin", "master", "-u")219 makeConflict(t, repos.Remote)220 assertState(t, repos.Local, OutOfSync)221 test_helpers.WriteFile(t, repos.Local, "test.md", "TestContent2")222 test_helpers.PerformCmd(t, repos.Local, "git", "add", "--all")223 test_helpers.PerformCmd(t, repos.Local, "git", "commit", "-m", "Test cause conflict")224 assertState(t, repos.Local, OutOfSync)225 performSync(t, repos.Local)226 assertState(t, repos.Local, Sync)227}...

Full Screen

Full Screen

led.go

Source:led.go Github

copy

Full Screen

1package service2import(3 "os"4 "log"5 "io/ioutil"6 "time"7 "sync/atomic"8 pb "github.com/mame82/P4wnP1_aloa/proto"9)10const (11 LED_TRIGGER_PATH = "/sys/class/leds/led0/trigger"12 LED_BRIGHTNESS_PATH = "/sys/class/leds/led0/brightness"13 LED_TRIGGER_MANUAL = "none"14 LED_ON = "0"15 LED_OFF = "1"16 LED_DELAY_ON = 200 * time.Millisecond17 LED_DELAY_OFF = 200 * time.Millisecond18 LED_DELAY_PAUSE = 500 * time.Millisecond19)20type LedState struct {21 blink_count *uint3222}23/*24var (25 blink_count uint32 = 026)27*/28func NewLed(led_on bool) (ledState *LedState, err error) {29 blinkCount := uint32(0)30 ledState = &LedState{ &blinkCount }31 //set trigger of LED to manual32 log.Println("Setting LED to manual trigger ...")33 ioutil.WriteFile(LED_TRIGGER_PATH, []byte(LED_TRIGGER_MANUAL), os.ModePerm)34 if led_on {35 log.Println("Setting LED to ON ...")36 ioutil.WriteFile(LED_BRIGHTNESS_PATH, []byte(LED_ON), os.ModePerm)37 } else {38 log.Println("Setting LED to OFF ...")39 ioutil.WriteFile(LED_BRIGHTNESS_PATH, []byte(LED_OFF), os.ModePerm)40 }41 go ledState.led_loop() // watcher loop42 ledState.SetLed(GetDefaultLEDSettings()) //set default setting43 return ledState,nil44}45func (leds *LedState) led_loop() {46 47 for {48 for i := uint32(0); i < atomic.LoadUint32(leds.blink_count); i++ {49 ioutil.WriteFile(LED_BRIGHTNESS_PATH, []byte(LED_ON), os.ModePerm)50 time.Sleep(LED_DELAY_ON)51 52 //Don't turn off led if blink_count >= 255 (solid)53 if 255 > atomic.LoadUint32(leds.blink_count) {54 ioutil.WriteFile(LED_BRIGHTNESS_PATH, []byte(LED_OFF), os.ModePerm)55 time.Sleep(LED_DELAY_OFF)56 }57 }58 time.Sleep(LED_DELAY_PAUSE)59 }60}61func (leds *LedState) SetLed(s *pb.LEDSettings) (error) {62 //log.Printf("setLED called with %+v", s)63 64 atomic.StoreUint32(leds.blink_count, s.BlinkCount)65 66 return nil67}68func (leds *LedState) GetLed() (res *pb.LEDSettings, err error) {69 return &pb.LEDSettings{BlinkCount: atomic.LoadUint32(leds.blink_count)}, nil70}...

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2type SimpleChaincode struct {3}4func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) peer.Response {5 return shim.Success(nil)6}7func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) peer.Response {8 function, args := stub.GetFunctionAndParameters()9 if function == "write" {10 return t.write(stub, args)11 } else if function == "read" {12 return t.read(stub, args)13 }14 return shim.Error("Invalid invoke function name. Expecting \"write\" \"read\"")15}16func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) peer.Response {17 fmt.Println("running write()")18 if len(args) != 2 {19 return shim.Error("Incorrect number of arguments. Expecting 2. name of the key and value to set")20 }21 if err != nil {22 return shim.Error(err.Error())23 }24 return shim.Success(nil)25}26func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) peer.Response {27 if len(args) != 1 {28 return shim.Error("Incorrect number of arguments. Expecting name of the key to query")29 }30 if err != nil {31 jsonResp = "{\"Error\":\"Failed to get state for " + key + "\"}"32 return shim.Error(jsonResp)33 } else if valAsbytes == nil {34 jsonResp = "{\"Error\":\"Nil amount for " + key + "\"}"35 return shim.Error(jsonResp)36 }37 return shim.Success(valAsbytes)38}39func main() {40 err := shim.Start(new(S

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 err := shim.Start(new(SimpleChaincode))4 if err != nil {5 fmt.Printf("Error starting Simple chaincode: %s", err)6 }7}8type SimpleChaincode struct {9}10func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {11}12func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {13 if function == "write" {14 return t.write(stub, args)15 }16}17func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {18 fmt.Println("running write()")19 if len(args) != 2 {20 return nil, fmt.Errorf("Incorrect number of arguments. Expecting 2. Got: %d.", len(args))21 }22 if err != nil {23 }24}25import (26func main() {27 err := shim.Start(new(SimpleChaincode))28 if err != nil {29 fmt.Printf("Error starting Simple chaincode: %s", err)30 }31}32type SimpleChaincode struct {33}34func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {35}36func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {37 if function == "read" {38 return t.read(stub, args)39 }40}41func (t *Simple

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2type SimpleChaincode struct {3}4type State struct {5}6func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {7}8func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {9 if function == "write" {10 return t.write(stub, args)11 } else if function == "read" {12 return t.read(stub, args)13 }14}15func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {16 fmt.Println("running write()")17 if len(args) != 2 {18 return nil, fmt.Errorf("Incorrect number of arguments. Expecting 2. Got: %d.", len(args))19 }20 stateAsBytes, err := stub.GetState(name)21 if err != nil {22 jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}"23 return nil, fmt.Errorf(jsonResp)24 } else if stateAsBytes != nil {25 fmt.Println("This state already exists: " + name)26 return nil, fmt.Errorf("This state already exists: " + name)27 }28 state := &State{Name: args[1]}29 stateJSONasBytes, err := json.Marshal(state)30 if err != nil {31 return nil, fmt.Errorf(err.Error())32 }33 err = stub.PutState(name, stateJSONasBytes)34 if err != nil {35 }36}37func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {38 if len(args) != 1 {39 return nil, fmt.Errorf("Incorrect number of arguments. Expecting name of the state to query")40 }41 valAsbytes, err := stub.GetState(name)42 if err != nil {43 jsonResp = "{\"Error\":\"Failed to get state for "

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2type State struct {3}4func (s *State) writeFile() {5 file, err := os.Create("state.txt")6 if err != nil {7 fmt.Println(err)8 }9 defer file.Close()10 fmt.Println("File created successfully")11 fmt.Println("Enter the name of state")12 reader := bufio.NewReader(os.Stdin)13 s.name, _ = reader.ReadString('14 file.WriteString(strings.TrimSpace(s.name))15}16func main() {17 s1.writeFile()18}

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1func main(){2 state := &State{}3 state.writeFile("test.txt", "Hello World")4}5func main(){6 state := &State{}7 state.readFile("test.txt")8}

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 state.writeFile("test.txt", "this is a test")4}5import (6func main() {7 state.readFile("test.txt")8}9import (10func main() {11 state.deleteFile("test.txt")12}13import (14func main() {15 state.appendFile("test.txt", "this is a test")16}17import (18func main() {19 state.createDir("testdir")20}21import (22func main() {23 state.deleteDir("testdir")24}25import (26func main() {27 state.copyFile("test.txt", "test2.txt")28}29import (30func main() {31 state.moveFile("test.txt", "test2.txt")32}33import (34func main() {35 state.renameFile("test.txt", "test2.txt")36}37import (38func main() {

Full Screen

Full Screen

writeFile

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 state.writeFile("hello.txt", "hello world")4}5import (6func main() {7 data := state.readFile("hello.txt")8 fmt.Println(data)9}10import (11func main() {12 state.deleteFile("hello.txt")13}14import (15func main() {16 state.appendFile("hello.txt", "hello world")17}18import (19func main() {20 state.createDirectory("hello")21}22import (23func main() {24 state.deleteDirectory("hello")25}26import (27func main() {28 state.copyFile("hello.txt", "hello_copy.txt")29}30import (31func main() {32 state.moveFile("hello.txt", "hello_copy.txt")33}34import (35func main() {36 state.renameFile("hello.txt", "hello_copy.txt")37}38import (39func 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