github.com/apptainer/singularity@v3.1.1+incompatible/pkg/client/library/search_test.go (about) 1 // Copyright (c) 2018, 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 client 7 8 import ( 9 "bytes" 10 "io" 11 "log" 12 "net/http" 13 "os" 14 "testing" 15 ) 16 17 const ( 18 testSearchOutput = `Found 1 users for 'test' 19 library://test-user 20 21 Found 1 collections for 'test' 22 library://test-user/test-collection 23 24 Found 1 containers for 'test' 25 library://test-user/test-collection/test-container 26 Tags: latest test-tag 27 28 ` 29 30 testSearchOutputEmpty = `No users found for 'test' 31 32 No collections found for 'test' 33 34 No containers found for 'test' 35 36 ` 37 ) 38 39 func Test_SearchLibrary(t *testing.T) { 40 m := mockService{ 41 t: t, 42 code: http.StatusOK, 43 body: JSONResponse{Data: testSearch, Error: JSONError{}}, 44 httpPath: "/v1/search", 45 } 46 47 m.Run() 48 defer m.Stop() 49 50 err := SearchLibrary("a", m.baseURI, "") 51 if err == nil { 52 t.Errorf("Search of 1 character shouldn't be submitted") 53 } 54 err = SearchLibrary("ab", m.baseURI, "") 55 if err == nil { 56 t.Errorf("Search of 2 characters shouldn't be submitted") 57 } 58 59 old := os.Stdout 60 r, w, _ := os.Pipe() 61 os.Stdout = w 62 63 err = SearchLibrary("test", m.baseURI, "") 64 65 outC := make(chan string) 66 go func() { 67 var buf bytes.Buffer 68 io.Copy(&buf, r) 69 outC <- buf.String() 70 }() 71 72 w.Close() 73 os.Stdout = old 74 out := <-outC 75 76 if err != nil { 77 t.Errorf("Search of test should succeed") 78 } 79 log.SetOutput(os.Stderr) 80 81 if out != testSearchOutput { 82 t.Errorf("Output of search not as expected") 83 t.Errorf("=== EXPECTED ===") 84 t.Errorf(testSearchOutput) 85 t.Errorf("=== ACTUAL ===") 86 t.Errorf(out) 87 } 88 } 89 90 func Test_SearchLibraryEmpty(t *testing.T) { 91 m := mockService{ 92 t: t, 93 code: http.StatusOK, 94 body: JSONResponse{Data: SearchResults{}, Error: JSONError{}}, 95 httpPath: "/v1/search", 96 } 97 98 m.Run() 99 defer m.Stop() 100 101 old := os.Stdout 102 r, w, _ := os.Pipe() 103 os.Stdout = w 104 105 err := SearchLibrary("test", m.baseURI, "") 106 107 outC := make(chan string) 108 go func() { 109 var buf bytes.Buffer 110 io.Copy(&buf, r) 111 outC <- buf.String() 112 }() 113 114 w.Close() 115 os.Stdout = old 116 out := <-outC 117 118 if err != nil { 119 t.Errorf("Search of test should succeed") 120 } 121 log.SetOutput(os.Stderr) 122 123 if out != testSearchOutputEmpty { 124 t.Errorf("Output of search not as expected") 125 t.Errorf("=== EXPECTED ===") 126 t.Errorf(testSearchOutputEmpty) 127 t.Errorf("=== ACTUAL ===") 128 t.Errorf(out) 129 } 130 }