blob: e968692828e4ea11dc2648d70fe7509297175567 [file] [edit]
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package netutil
import (
"os"
"strings"
"testing"
_ "github.com/bazelbuild/rsclient/internal/pkg/testsetup"
)
func TestNewShortTempDir(t *testing.T) {
td, err := NewShortTempDir("test-*")
if err != nil {
t.Fatalf("NewShortTempDir failed: %v", err)
}
// Verify path exists.
if info, err := os.Stat(td.Path); err != nil {
t.Errorf("Stat(%q) failed: %v", td.Path, err)
} else if !info.IsDir() {
t.Errorf("%q is not a directory", td.Path)
}
path := td.Path
// Verify cleanup.
if err := td.Close(); err != nil {
t.Errorf("Close failed: %v", err)
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Errorf("directory %q still exists after Close", path)
}
// Verify idempotency.
if err := td.Close(); err != nil {
t.Errorf("second Close failed: %v", err)
}
}
func TestNewShortTempDir_Shortness(t *testing.T) {
td, err := NewShortTempDir("short-*")
if err != nil {
t.Fatalf("NewShortTempDir failed: %v", err)
}
defer td.Close()
// If we are on Linux, we expect /tmp to be used if writable.
// We can't guarantee this in all environments, but we can verify
// that the path length is within reasonable limits.
if len(td.Path) > 100 {
t.Errorf("temp dir path is suspiciously long (%d chars): %s", len(td.Path), td.Path)
}
// On most systems where /tmp is writable, it should be the prefix.
if _, err := os.Stat("/tmp"); err == nil {
if !strings.HasPrefix(td.Path, "/tmp") {
t.Logf("Warning: /tmp exists but was not used as prefix for %s. This might be intentional in some environments.", td.Path)
}
}
}