launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/environs/tools/build_test.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package tools_test
     5  
     6  import (
     7  	"fmt"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  
    12  	gc "launchpad.net/gocheck"
    13  
    14  	"launchpad.net/juju-core/environs/tools"
    15  	"launchpad.net/juju-core/testing/testbase"
    16  )
    17  
    18  type buildSuite struct {
    19  	testbase.LoggingSuite
    20  	restore  func()
    21  	cwd      string
    22  	filePath string
    23  }
    24  
    25  var _ = gc.Suite(&buildSuite{})
    26  
    27  func (b *buildSuite) SetUpTest(c *gc.C) {
    28  	b.LoggingSuite.SetUpTest(c)
    29  
    30  	dir1 := c.MkDir()
    31  	dir2 := c.MkDir()
    32  
    33  	c.Log(dir1)
    34  	c.Log(dir2)
    35  
    36  	path := os.Getenv("PATH")
    37  	os.Setenv("PATH", fmt.Sprintf("%s:%s:%s", dir1, dir2, path))
    38  
    39  	// Make an executable file called "juju-test" in dir2.
    40  	b.filePath = filepath.Join(dir2, "juju-test")
    41  	err := ioutil.WriteFile(
    42  		b.filePath,
    43  		[]byte("doesn't matter, we don't execute it"),
    44  		0755)
    45  	c.Assert(err, gc.IsNil)
    46  
    47  	cwd, err := os.Getwd()
    48  	c.Assert(err, gc.IsNil)
    49  
    50  	b.cwd = c.MkDir()
    51  	err = os.Chdir(b.cwd)
    52  	c.Assert(err, gc.IsNil)
    53  
    54  	b.restore = func() {
    55  		os.Setenv("PATH", path)
    56  		os.Chdir(cwd)
    57  	}
    58  }
    59  
    60  func (b *buildSuite) TearDownTest(c *gc.C) {
    61  	b.restore()
    62  	b.LoggingSuite.TearDownTest(c)
    63  }
    64  
    65  func (b *buildSuite) TestFindExecutable(c *gc.C) {
    66  
    67  	for _, test := range []struct {
    68  		execFile   string
    69  		expected   string
    70  		errorMatch string
    71  	}{{
    72  		execFile: "/some/absolute/path",
    73  		expected: "/some/absolute/path",
    74  	}, {
    75  		execFile: "./foo",
    76  		expected: filepath.Join(b.cwd, "foo"),
    77  	}, {
    78  		execFile: "juju-test",
    79  		expected: b.filePath,
    80  	}, {
    81  		execFile:   "non-existent-exec-file",
    82  		errorMatch: `could not find "non-existent-exec-file" in the path`,
    83  	}} {
    84  		result, err := tools.FindExecutable(test.execFile)
    85  		if test.errorMatch == "" {
    86  			c.Assert(err, gc.IsNil)
    87  			c.Assert(result, gc.Equals, test.expected)
    88  		} else {
    89  			c.Assert(err, gc.ErrorMatches, test.errorMatch)
    90  			c.Assert(result, gc.Equals, "")
    91  		}
    92  	}
    93  }