github.com/leowmjw/otto@v0.2.1-0.20160126165905-6400716cf085/otto/testing_core.go (about)

     1  package otto
     2  
     3  import (
     4  	"io/ioutil"
     5  	"path/filepath"
     6  
     7  	"github.com/hashicorp/otto/app"
     8  	"github.com/hashicorp/otto/directory"
     9  	"github.com/hashicorp/otto/ui"
    10  )
    11  
    12  // TestAppTuple is a basic app tuple that can be used for testing and
    13  // has all fields set to "test".
    14  var TestAppTuple = app.Tuple{"test", "test", "test"}
    15  
    16  // TestCoreOpts is a specialized struct that is used to create a Core,
    17  // focused on the most common usage for tests.
    18  type TestCoreOpts struct {
    19  	// Path is the path to an Appfile to compile
    20  	Path string
    21  
    22  	// App to register with the TestAppTuple as a fixed result
    23  	App app.App
    24  }
    25  
    26  // TestCore returns a *Core for testing. If TestCoreOpts is nil then
    27  // this is equivalent to creating a core with TestCoreConfig set.
    28  func TestCore(t TestT, config *TestCoreOpts) *Core {
    29  	// Get the base config because we'll need this anyways
    30  	coreConfig := TestCoreConfig(t)
    31  
    32  	// If a config is set, then use that to do things
    33  	if config != nil {
    34  		if config.Path != "" {
    35  			coreConfig.Appfile = TestAppfile(t, config.Path)
    36  		}
    37  
    38  		if config.App != nil {
    39  			coreConfig.Apps[TestAppTuple] = func() (app.App, error) {
    40  				return config.App, nil
    41  			}
    42  		}
    43  	}
    44  
    45  	// Create the core!
    46  	core, err := NewCore(coreConfig)
    47  	if err != nil {
    48  		t.Fatal("error creating core: ", err)
    49  	}
    50  
    51  	return core
    52  }
    53  
    54  // TestCoreConfig returns a CoreConfig that can be used for testing.
    55  func TestCoreConfig(t TestT) *CoreConfig {
    56  	// Temporary directory for data
    57  	td, err := ioutil.TempDir("", "otto")
    58  	if err != nil {
    59  		t.Fatal("err: ", err)
    60  	}
    61  
    62  	// Basic config
    63  	config := &CoreConfig{
    64  		DataDir:    filepath.Join(td, "data"),
    65  		LocalDir:   filepath.Join(td, "local"),
    66  		CompileDir: filepath.Join(td, "compile"),
    67  		Directory:  &directory.BoltBackend{Dir: filepath.Join(td, "directory")},
    68  		Ui:         &ui.Logged{Ui: new(ui.Mock)},
    69  	}
    70  
    71  	// Add some default mock implementations. These can be overwritten easily
    72  	TestInfra(t, "test", config)
    73  	TestApp(t, TestAppTuple, config)
    74  
    75  	return config
    76  }