github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/libkb/flock_windows_test.go (about)

     1  // Copyright 2015 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  //go:build windows
     5  // +build windows
     6  
     7  package libkb
     8  
     9  import (
    10  	"os"
    11  	"os/exec"
    12  	"syscall"
    13  	"testing"
    14  )
    15  
    16  func exists(name string) bool {
    17  	_, err := os.Stat(name)
    18  	return !os.IsNotExist(err)
    19  }
    20  
    21  // run runs arg command. It returns error if command could not be run.
    22  // If command did run, the function will return error == nil and
    23  // integer command exit code.
    24  func run(arg ...string) (int, error) {
    25  	err := exec.Command(arg[0], arg[1:]...).Run()
    26  	if err != nil {
    27  		if e2, ok := err.(*exec.ExitError); ok {
    28  			if s, ok := e2.Sys().(syscall.WaitStatus); ok {
    29  				return int(s.ExitCode), nil
    30  			}
    31  		}
    32  		return 0, err
    33  	}
    34  	return 0, nil
    35  }
    36  
    37  func TestLockPIDFile_windows(t *testing.T) {
    38  
    39  	g := MakeThinGlobalContextForTesting(t)
    40  	lpFile := NewLockPIDFile(g, "TestLockPIDWin")
    41  	err := lpFile.Lock()
    42  
    43  	if !exists("TestLockPIDWin") {
    44  		t.Fatalf("LockPIDFile: file creation failed")
    45  	} else if err != nil {
    46  		t.Fatalf("LockPIDFile failed: %v", err)
    47  	} else {
    48  		// External process should be blocked from deleting the file
    49  		run("cmd", "/c", "del", "TestLockPIDWin")
    50  		if !exists("TestLockPIDWin") {
    51  			t.Fatalf("LockPIDFile: expected error deleting locked file")
    52  		}
    53  	}
    54  	lpFile.Close()
    55  
    56  	// External process should be able to delete the file now
    57  	exitcode, err := run("cmd", "/c", "del", "TestLockPIDWin")
    58  	if err != nil || exitcode != 0 || exists("TestLockPIDWin") {
    59  		t.Fatalf("LockPIDFile: exe.Command(del) failed: %v", err)
    60  	}
    61  }