github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/user/user_test.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package user
     7  
     8  import (
     9  	"os"
    10  	"os/exec"
    11  	"runtime"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  func getWhoamiOutput() (string, error) {
    17  	output, err := exec.Command("whoami").Output()
    18  	if err != nil {
    19  		return "", err
    20  	}
    21  	return strings.TrimSpace(string(output)), nil
    22  }
    23  
    24  func TestCurrentUsername(t *testing.T) {
    25  	user := CurrentUsername()
    26  	if len(user) == 0 {
    27  		t.Errorf("expected non-empty user, got: %s", user)
    28  	}
    29  	// Windows whoami is weird, so just skip remaining tests
    30  	if runtime.GOOS == "windows" {
    31  		t.Skip("skipped test because of weird whoami on Windows")
    32  	}
    33  	whoami, err := getWhoamiOutput()
    34  	if err != nil {
    35  		t.Errorf("failed to run whoami to test current user: %f", err)
    36  	}
    37  	user = CurrentUsername()
    38  	if user != whoami {
    39  		t.Errorf("expected %s as user, got: %s", whoami, user)
    40  	}
    41  	os.Setenv("USER", "spoofed")
    42  	user = CurrentUsername()
    43  	if user != whoami {
    44  		t.Errorf("expected %s as user, got: %s", whoami, user)
    45  	}
    46  }