github.com/apptainer/singularity@v3.1.1+incompatible/pkg/util/unix/socket_test.go (about) 1 // Copyright (c) 2019, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package unix 7 8 import ( 9 "math/rand" 10 "os" 11 "path/filepath" 12 "testing" 13 "time" 14 15 "github.com/sylabs/singularity/internal/pkg/test" 16 ) 17 18 func init() { 19 rand.Seed(time.Now().UnixNano()) 20 } 21 22 var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") 23 24 func randSeq(n int) string { 25 b := make([]rune, n) 26 for i := range b { 27 b[i] = letters[rand.Intn(len(letters))] 28 } 29 return string(b) 30 } 31 32 func TestCreateSocket(t *testing.T) { 33 test.DropPrivilege(t) 34 defer test.ResetPrivilege(t) 35 36 paths := []string{ 37 filepath.Join(os.TempDir(), randSeq(10), "socket"), // short path 38 filepath.Join(os.TempDir(), randSeq(100), "socket"), // long path 39 } 40 41 for _, path := range paths { 42 syncCh := make(chan bool, 1) 43 44 dir := filepath.Dir(path) 45 os.Mkdir(dir, 0700) 46 47 defer os.RemoveAll(dir) 48 49 // create socket and returns listener 50 ln, err := CreateSocket(path) 51 if err != nil { 52 t.Fatal(err) 53 } 54 55 // accept connection and test if received data are correct 56 go func() { 57 buf := make([]byte, 4) 58 59 conn, err := ln.Accept() 60 if err != nil { 61 t.Error(err) 62 } 63 n, err := conn.Read(buf) 64 if err != nil { 65 t.Error(err) 66 } 67 if n != 4 { 68 t.Error() 69 } 70 if string(buf) != "send" { 71 t.Errorf("unexpected data returned: %s", string(buf)) 72 } 73 syncCh <- true 74 }() 75 76 // open / write / close to socket path 77 if err := WriteSocket(path, []byte("send")); err != nil { 78 t.Error(err) 79 } 80 81 <-syncCh 82 83 // close socket implies to delete file automatically 84 os.Chdir(dir) 85 ln.Close() 86 87 // socket file is deleted by net package at close 88 if err := os.Remove(path); err == nil { 89 t.Errorf("unexpected success during socket removal") 90 } 91 } 92 }