github.com/joomcode/cue@v0.4.4-0.20221111115225-539fe3512047/cue/load/import_test.go (about)

     1  // Copyright 2018 The CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package load
    16  
    17  import (
    18  	"os"
    19  	"reflect"
    20  	"testing"
    21  
    22  	"github.com/joomcode/cue/cue/build"
    23  	"github.com/joomcode/cue/cue/token"
    24  )
    25  
    26  const testdata = "./testdata/"
    27  
    28  func getInst(pkg, cwd string) (*build.Instance, error) {
    29  	c, _ := (&Config{Dir: cwd}).complete()
    30  	l := loader{cfg: c}
    31  	inst := c.newRelInstance(token.NoPos, pkg, c.Package)
    32  	p := l.importPkg(token.NoPos, inst)[0]
    33  	return p, p.Err
    34  }
    35  
    36  func TestEmptyImport(t *testing.T) {
    37  	p, err := getInst("", "")
    38  	if err == nil {
    39  		t.Fatal(`Import("") returned nil error.`)
    40  	}
    41  	if p == nil {
    42  		t.Fatal(`Import("") returned nil package.`)
    43  	}
    44  	if p.DisplayPath != "" {
    45  		t.Fatalf("DisplayPath=%q, want %q.", p.DisplayPath, "")
    46  	}
    47  }
    48  
    49  func TestEmptyFolderImport(t *testing.T) {
    50  	_, err := getInst(".", testdata+"empty")
    51  	if _, ok := err.(*NoFilesError); !ok {
    52  		t.Fatal(`Import("testdata/empty") did not return NoCUEError.`)
    53  	}
    54  }
    55  
    56  func TestMultiplePackageImport(t *testing.T) {
    57  	_, err := getInst(".", testdata+"multi")
    58  	mpe, ok := err.(*MultiplePackageError)
    59  	if !ok {
    60  		t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`)
    61  	}
    62  	mpe.Dir = ""
    63  	want := &MultiplePackageError{
    64  		Packages: []string{"main", "test_package"},
    65  		Files:    []string{"file.cue", "file_appengine.cue"},
    66  	}
    67  	if !reflect.DeepEqual(mpe, want) {
    68  		t.Errorf("got %#v; want %#v", mpe, want)
    69  	}
    70  }
    71  
    72  func TestLocalDirectory(t *testing.T) {
    73  	cwd, err := os.Getwd()
    74  	if err != nil {
    75  		t.Fatal(err)
    76  	}
    77  
    78  	p, err := getInst(".", cwd)
    79  	if err != nil {
    80  		t.Fatal(err)
    81  	}
    82  
    83  	if p.DisplayPath != "." {
    84  		t.Fatalf("DisplayPath=%q, want %q", p.DisplayPath, ".")
    85  	}
    86  }