github.com/go-maxhub/gremlins@v1.0.1-0.20231227222204-b03a6a1e3e09/core/gomodule/gomodule_test.go (about) 1 /* 2 * Copyright 2022 The Gremlins Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package gomodule_test 18 19 import ( 20 "os" 21 "path/filepath" 22 "testing" 23 24 "github.com/go-maxhub/gremlins/core/gomodule" 25 ) 26 27 func TestDetectsModule(t *testing.T) { 28 t.Run("does not return error if it can retrieve module", func(t *testing.T) { 29 const modName = "example.com" 30 rootDir := t.TempDir() 31 pkgDir := "pkgDir" 32 absPkgDir := filepath.Join(rootDir, pkgDir) 33 _ = os.MkdirAll(absPkgDir, 0600) 34 goMod := filepath.Join(rootDir, "go.mod") 35 err := os.WriteFile(goMod, []byte("module "+modName), 0600) 36 if err != nil { 37 t.Fatal(err) 38 } 39 40 mod, err := gomodule.Init(absPkgDir) 41 if err != nil { 42 t.Fatal(err) 43 } 44 45 if mod.Name != modName { 46 t.Errorf("expected Go module to be %q, got %q", modName, mod.Name) 47 } 48 if mod.Root != rootDir { 49 t.Errorf("expected Go root to be %q, got %q", rootDir, mod.Root) 50 } 51 if mod.CallingDir != pkgDir { 52 t.Errorf("expected Go package dir to be %q, got %q", pkgDir, mod.CallingDir) 53 } 54 }) 55 56 t.Run("returns error if go.mod is invalid", func(t *testing.T) { 57 path := t.TempDir() 58 goMod := path + "/go.mod" 59 err := os.WriteFile(goMod, []byte(""), 0600) 60 if err != nil { 61 t.Fatal(err) 62 } 63 64 _, err = gomodule.Init(path) 65 if err == nil { 66 t.Errorf("expected an error") 67 } 68 }) 69 70 t.Run("returns error if it cannot find module", func(t *testing.T) { 71 _, err := gomodule.Init(t.TempDir()) 72 if err == nil { 73 t.Errorf("expected an error") 74 } 75 }) 76 77 t.Run("returns error if path is empty", func(t *testing.T) { 78 _, err := gomodule.Init("") 79 if err == nil { 80 t.Errorf("expected an error") 81 } 82 }) 83 }