You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
918 B

  1. package user
  2. import (
  3. "os"
  4. "os/exec"
  5. "runtime"
  6. "strings"
  7. "testing"
  8. )
  9. func getWhoamiOutput() (string, error) {
  10. output, err := exec.Command("whoami").Output()
  11. if err != nil {
  12. return "", err
  13. }
  14. return strings.TrimSpace(string(output[:])), nil
  15. }
  16. func TestCurrentUsername(t *testing.T) {
  17. user := CurrentUsername()
  18. if len(user) == 0 {
  19. t.Errorf("expected non-empty user, got: %s", user)
  20. }
  21. // Windows whoami is weird, so just skip remaining tests
  22. if runtime.GOOS == "windows" {
  23. t.Skip("skipped test because of weird whoami on Windows")
  24. }
  25. whoami, err := getWhoamiOutput()
  26. if err != nil {
  27. t.Errorf("failed to run whoami to test current user: %f", err)
  28. }
  29. user = CurrentUsername()
  30. if user != whoami {
  31. t.Errorf("expected %s as user, got: %s", whoami, user)
  32. }
  33. os.Setenv("USER", "spoofed")
  34. user = CurrentUsername()
  35. if user != whoami {
  36. t.Errorf("expected %s as user, got: %s", whoami, user)
  37. }
  38. }