github.com/sirkon/goproxy@v1.4.8/internal/cache/default_unix_test.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build !windows,!darwin,!plan9
     6  
     7  package cache
     8  
     9  import (
    10  	"os"
    11  	"strings"
    12  	"testing"
    13  )
    14  
    15  func TestDefaultDir(t *testing.T) {
    16  	goCacheDir := "/tmp/test-go-cache"
    17  	xdgCacheDir := "/tmp/test-xdg-cache"
    18  	homeDir := "/tmp/test-home"
    19  
    20  	// undo env changes when finished
    21  	defer func(GOCACHE, XDG_CACHE_HOME, HOME string) {
    22  		os.Setenv("GOCACHE", GOCACHE)
    23  		os.Setenv("XDG_CACHE_HOME", XDG_CACHE_HOME)
    24  		os.Setenv("HOME", HOME)
    25  	}(os.Getenv("GOCACHE"), os.Getenv("XDG_CACHE_HOME"), os.Getenv("HOME"))
    26  
    27  	os.Setenv("GOCACHE", goCacheDir)
    28  	os.Setenv("XDG_CACHE_HOME", xdgCacheDir)
    29  	os.Setenv("HOME", homeDir)
    30  
    31  	dir, showWarnings := defaultDir()
    32  	if dir != goCacheDir {
    33  		t.Errorf("Cache DefaultDir %q should be $GOCACHE %q", dir, goCacheDir)
    34  	}
    35  	if !showWarnings {
    36  		t.Error("Warnings should be shown when $GOCACHE is set")
    37  	}
    38  
    39  	os.Unsetenv("GOCACHE")
    40  	dir, showWarnings = defaultDir()
    41  	if !strings.HasPrefix(dir, xdgCacheDir+"/") {
    42  		t.Errorf("Cache DefaultDir %q should be under $XDG_CACHE_HOME %q when $GOCACHE is unset", dir, xdgCacheDir)
    43  	}
    44  	if !showWarnings {
    45  		t.Error("Warnings should be shown when $XDG_CACHE_HOME is set")
    46  	}
    47  
    48  	os.Unsetenv("XDG_CACHE_HOME")
    49  	dir, showWarnings = defaultDir()
    50  	if !strings.HasPrefix(dir, homeDir+"/.cache/") {
    51  		t.Errorf("Cache DefaultDir %q should be under $HOME/.cache %q when $GOCACHE and $XDG_CACHE_HOME are unset", dir, homeDir+"/.cache")
    52  	}
    53  	if !showWarnings {
    54  		t.Error("Warnings should be shown when $HOME is not /")
    55  	}
    56  
    57  	os.Unsetenv("HOME")
    58  	if dir, _ := defaultDir(); dir != "off" {
    59  		t.Error("Cache not disabled when $GOCACHE, $XDG_CACHE_HOME, and $HOME are unset")
    60  	}
    61  
    62  	os.Setenv("HOME", "/")
    63  	if _, showWarnings := defaultDir(); showWarnings {
    64  		// https://golang.org/issue/26280
    65  		t.Error("Cache initalization warnings should be squelched when $GOCACHE and $XDG_CACHE_HOME are unset and $HOME is /")
    66  	}
    67  }