github.com/joey-fossa/fossa-cli@v0.7.34-0.20190708193710-569f1e8679f0/buildtools/okbuck/okbuck_test.go (about)

     1  package okbuck_test
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  
    10  	"github.com/fossas/fossa-cli/buildtools/okbuck"
    11  	"github.com/fossas/fossa-cli/pkg"
    12  )
    13  
    14  func TestOkBuck(t *testing.T) {
    15  	temp := MockOkBuck("testdata/buckw-targets", "")
    16  	testGraph, err := temp.Deps("")
    17  	assert.NoError(t, err)
    18  	assertImport(t, testGraph.Direct, "dep:one")
    19  	assertImport(t, testGraph.Direct, "dep:two")
    20  
    21  	dep2, err := findPackage(testGraph.Transitive, "dep:two")
    22  	assert.NoError(t, err)
    23  	assert.Empty(t, dep2.Imports)
    24  }
    25  
    26  func TestOkBuckClassPath(t *testing.T) {
    27  	temp := MockOkBuck("testdata/buckw-targets", "testdata/buckw-classpath")
    28  	testGraph, err := temp.Deps("classpath")
    29  	assert.NoError(t, err)
    30  	assertImport(t, testGraph.Direct, "dep:one")
    31  	assertImport(t, testGraph.Direct, "dep:three")
    32  
    33  	dep3, err := findPackage(testGraph.Transitive, "dep:three")
    34  	assert.NoError(t, err)
    35  	assert.Empty(t, dep3.Imports)
    36  }
    37  
    38  func MockOkBuck(file string, classpath string) okbuck.OkBuck {
    39  	return okbuck.Setup{
    40  		Target: "test",
    41  		Cmd: func(args ...string) (string, error) {
    42  			switch args[0] {
    43  			case "targets":
    44  				return testFile(file)
    45  			case "audit":
    46  				return testFile(classpath)
    47  			default:
    48  				return testFile(file)
    49  			}
    50  		},
    51  	}
    52  }
    53  
    54  func testFile(file string) (string, error) {
    55  	contents, err := ioutil.ReadFile(file)
    56  	if err != nil {
    57  		return "", err
    58  	}
    59  	return string(contents), nil
    60  }
    61  
    62  func findPackage(packages map[pkg.ID]pkg.Package, name string) (pkg.Package, error) {
    63  	for id := range packages {
    64  		if id.Name == name {
    65  			return packages[id], nil
    66  		}
    67  	}
    68  	return pkg.Package{}, fmt.Errorf("Package %s not found", name)
    69  }
    70  
    71  func assertImport(t *testing.T, imports pkg.Imports, name string) {
    72  	for _, importedProj := range imports {
    73  		if importedProj.Resolved.Name == name {
    74  			return
    75  		}
    76  	}
    77  	assert.Fail(t, "missing "+name)
    78  }