func main() { reg, router, cxt := cookoo.Cookoo() cxt.Put("VendorDir", VendorDir) routes(reg, cxt) app := cli.NewApp() app.Name = "glide" app.Usage = usage app.Version = version app.Flags = []cli.Flag{ cli.StringFlag{ Name: "yaml, y", Value: "glide.yaml", Usage: "Set a YAML configuration file.", }, cli.BoolFlag{ Name: "quiet, q", Usage: "Quiet (no info or debug messages)", }, } app.CommandNotFound = func(c *cli.Context, command string) { cxt.Put("os.Args", os.Args) cxt.Put("command", command) setupHandler(c, "@plugin", cxt, router) } app.Commands = commands(cxt, router) app.Run(os.Args) }
func TestCommandsNonEmpty(t *testing.T) { _, router, ctx := cookoo.Cookoo() commands := commands(ctx, router) if len(commands) == 0 { t.Fail() } }
func TestReplayHistory(t *testing.T) { reg, router, cxt := cookoo.Cookoo() cxt.AddLogger("out", os.Stdout) medium := NewMedium() cxt.AddDatasource(MediumDS, medium) topic := NewHistoriedTopic("test", 5) medium.Add(topic) topic.Publish([]byte("first")) topic.Publish([]byte("second")) req, _ := http.NewRequest("GET", "https://localhost/v1/t/test", nil) req.Header.Add(XHistoryLength, "4") res := &mockResponseWriter{} cxt.Put("http.Request", req) cxt.Put("http.ResponseWriter", res) reg.Route("test", "Test route"). Does(ReplayHistory, "res").Using("topic").WithDefault("test") err := router.HandleRequest("test", cxt, true) if err != nil { t.Error(err) } last := res.String() if last != "firstsecond" { t.Errorf("Expected 'firstsecond', got '%s'", last) } }
func Example() { _, _, c := cookoo.Cookoo() // Set logging to go to Stdout. c.AddLogger("stdout", os.Stdout) // Set the log level to any of the Log* constants. Level = LogInfo // Functions are named as they are in log/syslog. Err(c, "Failed to do something.") // There are also formatting versions of every log function. Infof(c, "Informational message with %s.", "formatting") // Shorthand for if Level >= LogDebug if Debugging() { Debug(c, "This is a debug message.") } // You can test for any level. if Level >= LogWarning { Warn(c, "And this is a warning.") } Stack(c, "Stack trace from here.") }
func TestShowHelp(t *testing.T) { registry, router, context := cookoo.Cookoo() var out bytes.Buffer registry.Route("test", "Testing help.").Does(ShowHelp, "didShowHelp"). Using("show").WithDefault(true). Using("writer").WithDefault(&out). Using("summary").WithDefault("This is a summary."). Does(Barf, "Fail if help doesn't stop.") e := router.HandleRequest("test", context, false) if e != nil { t.Error("! Unexpected error.") } res := context.Get("didShowHelp", false).(bool) if !res { t.Error("! Expected help to be shown.") } msg := out.String() if !strings.Contains(msg, "SUMMARY\n") { t.Error("! Expected 'summary' as a header.") } if !strings.Contains(msg, "This is a summary.") { t.Error("! Expected 'This is a summary' to be in the output. Got ", msg) } }
func runServer(config *ssh.ServerConfig, c *Circuit, t *testing.T) cookoo.Context { reg, router, cxt := cookoo.Cookoo() cxt.Put(ServerConfig, config) cxt.Put(Address, testingServerAddr) cxt.Put("cookoo.Router", router) reg.AddRoute(cookoo.Route{ Name: "sshPing", Help: "Handles an ssh exec ping.", Does: cookoo.Tasks{ cookoo.Cmd{ Name: "ping", Fn: Ping, Using: []cookoo.Param{ {Name: "request", From: "cxt:request"}, {Name: "channel", From: "cxt:channel"}, }, }, }, }) go func() { if err := Serve(reg, router, c, cxt); err != nil { t.Fatalf("Failed serving with %s", err) } }() return cxt }
// main is an example of a simple Web server written in Cookoo. func main() { // First, we create a new Cookoo app. reg, router, cxt := cookoo.Cookoo() // We declare a route that answers GET requests for the path / // // By default, this will be running on http://localhost:8080/ reg.Route("GET /", "Simple test route."). Does(web.Flush, "out"). Using("content").WithDefault("OH HAI!") // We declare a route that answers GET requests for the path /test // This one uses a basic template. // // By default, this will be running on http://localhost:8080/ // // Because we use `query:you`, try hitting the app on this URL: // http://localhost:8080/test?you=Matt reg.Route("GET /test", "Simple test route."). Does(fmt.Template, "content"). Using("template").WithDefault("Hello {{.you}}"). Using("you").WithDefault("test").From("query:you"). Does(web.Flush, "out"). Using("content").From("cxt:content") // Start the server. web.Serve(reg, router, cxt) }
func TestTimestamp(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test route"). Does(Timestamp, "res") err := router.HandleRequest("test", cxt, true) if err != nil { t.Error(err) } ts := cxt.Get("res", "").(string) if len(ts) == 0 { t.Errorf("Expected timestamp, not empty string.") } tsInt, err := strconv.Atoi(ts) if err != nil { t.Error(err) } if tsInt <= 5 { t.Error("Dude, you're stuck in the '70s.") } }
func TestRunOnce(t *testing.T) { reg, _, _ := cookoo.Cookoo() reg.Route("test", "Test route"). Does(RunOnce, "res"). Using("node").WithDefault("localhost:4001") }
func TestSet(t *testing.T) { reg, router, cxt := cookoo.Cookoo() os.Setenv("SLURM", "COFFEE") reg.Route("test", "Test route"). Does(Set, "res"). Using("HELLO").WithDefault("hello"). Using("EMPTY").WithDefault(nil). Using("FAVORITE_DRINK").WithDefault("$SLURM") if err := router.HandleRequest("test", cxt, true); err != nil { t.Error(err) } expect := map[string]string{ "HELLO": "hello", "EMPTY": "", "FAVORITE_DRINK": "COFFEE", } for k, v := range expect { if v != os.Getenv(k) { t.Errorf("Expected env var %s to be '%s', got '%s'", k, v, os.Getenv(k)) } if cv := cxt.Get(k, "___").(string); cv != v { t.Errorf("Expected context var %s to be '%s', got '%s'", k, v, cv) } } }
func TestTemplate(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test"). Does(Template, "out"). Using("template").WithDefault("{{.Hello}} {{.one}}"). Using("Hello").WithDefault("Hello"). Using("one").WithDefault(1) if err := router.HandleRequest("test", cxt, false); err != nil { t.Errorf("Failed route: %s", err) } if res := cxt.Get("out", "nada"); res != "Hello 1" { t.Errorf("Expected 'Hello 1', got %s", res) } reg.Route("test2", "Test 2"). Does(cookoo.AddToContext, "_").Using("Foo").WithDefault("lambkin"). Does(Template, "out2"). Using("template.Context").WithDefault(true). Using("template").WithDefault("Hello {{.Cxt.Foo}}") if err := router.HandleRequest("test2", cxt, false); err != nil { t.Errorf("Failed route: %s", err) } if res := cxt.Get("out2", "nada"); res != "Hello lambkin" { t.Errorf("Expected 'Hello lambkin', got %s", res) } }
func TestFromYaml(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("t", "Testing"). Does(ParseYamlString, "cfg").Using("yaml").WithDefault(yamlFile) if err := router.HandleRequest("t", cxt, false); err != nil { t.Errorf("Failed to parse YAML: %s", err) } cfg := cxt.Get("cfg", nil).(*Config) if cfg.Name != "fake/testing" { t.Errorf("Expected name to be 'fake/teting', not '%s'", cfg.Name) } if len(cfg.Imports) != 3 { t.Errorf("Expected 3 imports, got %d", len(cfg.Imports)) } imp := cfg.Imports[2] if imp.Name != "github.com/Masterminds/convert" { t.Errorf("Expected the convert package, got %s", imp.Name) } if len(imp.Subpackages) != 3 { t.Errorf("Expected 3 subpackages. got %d", len(imp.Subpackages)) } if imp.Subpackages[0] != "color" { t.Errorf("Expected first subpackage to be 'color', got '%s'", imp.Subpackages[0]) } if len(imp.Os) != 1 { t.Errorf("Expected Os: SOMETHING") } else if imp.Os[0] != "linux" { t.Errorf("Expected Os: linux") } if len(imp.Arch) != 2 { t.Error("Expected two Archs.") } else if imp.Arch[0] != "i386" { t.Errorf("Expected arch 1 to be i386, got %s.", imp.Arch[0]) } else if imp.Arch[1] != "arm" { t.Error("Expected arch 2 to be arm.") } if imp.Repository != "[email protected]:Masterminds/convert.git" { t.Errorf("Got wrong repo") } if imp.Reference != "a9949121a2e2192ca92fa6dddfeaaa4a4412d955" { t.Errorf("Got wrong reference.") } if len(cfg.DevImports) != 1 { t.Errorf("Expected one dev import.") } }
func TestCreateClient(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test route"). Does(CreateClient, "res").Using("url").WithDefault("localhost:4100") if err := router.HandleRequest("test", cxt, true); err != nil { t.Error(err) } // All we really want to know is whether we got a valid client back. _ = cxt.Get("res", nil).(*etcd.Client) }
func TestGet(t *testing.T) { reg, router, cxt := cookoo.Cookoo() drink := "DEIS_DRINK_OF_CHOICE" cookies := "DEIS_FAVORITE_COOKIES" snack := "DEIS_SNACK_TIME" snackVal := fmt.Sprintf("$%s and $%s cookies", drink, cookies) // Set drink, but not cookies. os.Setenv(drink, "coffee") reg.Route("test", "Test route"). Does(Get, "res"). Using(drink).WithDefault("tea"). Using(cookies).WithDefault("chocolate chip"). Does(Get, "res2"). Using(snack).WithDefault(snackVal) err := router.HandleRequest("test", cxt, true) if err != nil { t.Error(err) } // Drink should still be coffee. if coffee := cxt.Get(drink, "").(string); coffee != "coffee" { t.Errorf("A great sin has been committed. Expected coffee, but got '%s'", coffee) } // Env var should be untouched if coffee := os.Getenv(drink); coffee != "coffee" { t.Errorf("Environment was changed from 'coffee' to '%s'", coffee) } // Cookies should have been set to the default if cookies := cxt.Get(cookies, "").(string); cookies != "chocolate chip" { t.Errorf("Expected chocolate chip cookies, but instead, got '%s' :-(", cookies) } // In the environment, cookies should have been set. if cookies := os.Getenv(cookies); cookies != "chocolate chip" { t.Errorf("Expected environment to have chocolate chip cookies, but instead, got '%s'", cookies) } if both := cxt.Get(snack, "").(string); both != "coffee and chocolate chip cookies" { t.Errorf("Expected 'coffee and chocolate chip cookies'. Got '%s'", both) } if both := os.Getenv(snack); both != snackVal { t.Errorf("Expected %s to not be expanded. Got '%s'", snack, both) } }
func TestGetImportsEmptyConfig(t *testing.T) { _, _, c := cookoo.Cookoo() SilenceLogs(c) cfg := new(Config) p := cookoo.NewParamsWithValues(map[string]interface{}{"conf": cfg}) res, it := GetImports(c, p) if it != nil { t.Errorf("Interrupt value non-nil") } bres, ok := res.(bool) if !ok || bres { t.Errorf("Result was non-bool or true: ok=%t bres=%t", ok, bres) } }
func main() { reg, route, c := cookoo.Cookoo() ds, err := backend.NewDS("localhost", "k8e") if err != nil { log.Critf(c, "Shutting down: %s", err) return } defer ds.Close() c.AddDatasource("db", ds) routes(reg) web.Serve(reg, route, c) }
// Run starts the Builder service. // // The Builder service is responsible for setting up the local container // environment and then listening for new builds. The main listening service // is SSH. Builder listens for new Git commands and then sends those on to // Git. // // Run returns on of the Status* status code constants. func Run(cmd string) int { reg, router, ocxt := cookoo.Cookoo() log.SetFlags(0) // Time is captured elsewhere. // We layer the context to add better logging and also synchronize // access so that goroutines don't get into race conditions. cxt := cookoo.SyncContext(ocxt) cxt.Put("cookoo.Router", router) cxt.AddLogger("stdout", os.Stdout) // Build the routes. See routes.go. routes(reg) // Bootstrap the background services. If this fails, we stop. if err := router.HandleRequest("boot", cxt, false); err != nil { clog.Errf(cxt, "Fatal errror on boot: %s", err) return StatusLocalError } // Set up the SSH service. ip := os.Getenv("SSH_HOST_IP") if ip == "" { ip = "0.0.0.0" } port := os.Getenv("SSH_HOST_PORT") if port == "" { port = "2223" } cxt.Put(sshd.Address, ip+":"+port) // Supply route names for handling various internal routing. While this // isn't necessary for Cookoo, it makes it easy for us to mock these // routes in tests. c.f. sshd/server.go cxt.Put("route.sshd.pubkeyAuth", "pubkeyAuth") cxt.Put("route.sshd.sshPing", "sshPing") cxt.Put("route.sshd.sshGitReceive", "sshGitReceive") // Start the SSH service. // TODO: We could refactor Serve to be a command, and then run this as // a route. if err := sshd.Serve(reg, router, cxt); err != nil { clog.Errf(cxt, "SSH server failed: %s", err) return StatusLocalError } return StatusOk }
func TestResolvingSimpleRoute(t *testing.T) { registry, router, context := cookoo.Cookoo() resolver := new(RequestResolver) resolver.Init(registry) router.SetRequestResolver(resolver) registry.Route("test", "A simple test").Does(Nothing, "nada") e := router.HandleRequest("test", context, false) if e != nil { t.Error("! Failed 'test' route.") } }
// TestGetInterpolation is a regression test to make sure that values are // interpolated correctly. func TestGetInterpolation(t *testing.T) { reg, router, cxt := cookoo.Cookoo() os.Setenv("TEST_ENV", "is") reg.Route("test", "Test route"). Does(Get, "res"). Using("TEST_ENV2").WithDefault("de$TEST_ENV") if err := router.HandleRequest("test", cxt, true); err != nil { t.Error(err) } if os.Getenv("TEST_ENV2") != "deis" { t.Errorf("Expected 'deis', got '%s'", os.Getenv("TEST_ENV2")) } }
func TestSleep(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test route"). Does(Sleep, "res").Using("duration").WithDefault(3 * time.Second) start := time.Now() if err := router.HandleRequest("test", cxt, true); err != nil { t.Error(err) } end := time.Now() if end.Sub(start) < 3*time.Second { t.Error("expected elapsed time to be 3 seconds.") } }
func TestSprintf(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test"). Does(Sprintf, "out"). Using("format").WithDefault("%s %d"). Using("0").WithDefault("Hello"). Using("1").WithDefault(1) if err := router.HandleRequest("test", cxt, false); err != nil { t.Errorf("Failed route: %s", err) } if res := cxt.Get("out", "absolutely nothin"); res != "Hello 1" { t.Errorf("Expected 'Hello 1', got %s", res) } }
func TestCreateClient(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test route"). Does(CreateClient, "res").Using("url").WithDefault("http://example.com:4321") if err := router.HandleRequest("test", cxt, true); err != nil { t.Error(err) } if cli := cxt.Get("res", nil); cli == nil { t.Error("Expected a client") } else if _, ok := cli.(*docli.Client); !ok { t.Error("Expected client to be a *docker.Cli") } }
func main() { reg, router, cxt := cookoo.Cookoo() cxt.Put("VendorDir", VendorDir) routes(reg, cxt) app := cli.NewApp() app.Name = "glide" app.Usage = usage app.Version = version app.Flags = []cli.Flag{ cli.StringFlag{ Name: "yaml, y", Value: "glide.yaml", Usage: "Set a YAML configuration file.", }, cli.BoolFlag{ Name: "quiet, q", Usage: "Quiet (no info or debug messages)", }, cli.BoolFlag{ Name: "debug", Usage: "Print Debug messages (verbose)", }, cli.StringFlag{ Name: "home", Value: defaultGlideDir(), Usage: "The location of Glide files", EnvVar: "GLIDE_HOME", }, cli.BoolFlag{ Name: "no-color", Usage: "Turn off colored output for log messages", }, } app.CommandNotFound = func(c *cli.Context, command string) { cxt.Put("os.Args", os.Args) cxt.Put("command", command) setupHandler(c, "@plugin", cxt, router) } app.Commands = commands(cxt, router) app.Run(os.Args) }
func TestMakeDir(t *testing.T) { reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test route"). Does(MakeDir, "res"). Using("client").WithDefault(&stubClient{}). Using("path").WithDefault("/deis/users/foo") err := router.HandleRequest("test", cxt, true) if err != nil { t.Error(err) } if res := cxt.Get("res", nil); res == nil { t.Error("Expected an *etcd.Response, not nil.") } else if tt, ok := res.(*etcd.Response); !ok { t.Errorf("Expected instance of *etcd.Response. Got %T", tt) } }
func standUpServer() error { srv := &http.Server{Addr: hostport} reg, router, cxt := cookoo.Cookoo() buildRegistry(reg, router, cxt) // Our main datasource is the Medium, which manages channels. m := pubsub.NewMedium() cxt.AddDatasource(pubsub.MediumDS, m) cxt.Put("routes", reg.Routes()) http2.ConfigureServer(srv, &http2.Server{}) srv.Handler = web.NewCookooHandler(reg, router, cxt) srv.ListenAndServeTLS("../server/server.crt", "../server/server.key") return nil }
func TestAtoi(t *testing.T) { reg, router, c := cookoo.Cookoo() reg.Route("test", "Test convert.").Does(Atoi, "i").Using("str").From("cxt:a") c.Put("a", "100") e := router.HandleRequest("test", c, false) if e != nil { t.Errorf("! Failed during HandleRequest: %s", e) return } i, ok := c.Has("i") if !ok { t.Error("! Expected to find 'a' in context, but it was missing.") } if i.(int) != 100 { t.Errorf("! Expected '100' to be converted to 100. Got %d", i) } }
func TestParseArgs(t *testing.T) { registry, router, cxt := cookoo.Cookoo() flags := flag.NewFlagSet("test flags", flag.ContinueOnError) flags.String("foo", "binky", "Test foo flag.") flags.Bool("baz", false, "Baz flag") flags.Int("unused", 123, "Unused int flag.") registry.Route("test", "Testing parse arguments."). Does(ParseArgs, "args"). Using("args").WithDefault([]string{"-foo", "bar", "-baz", "arg1"}). Using("flagset").WithDefault(flags) if router.HandleRequest("test", cxt, false) != nil { t.Error("! Request failed.") return } foo := cxt.Get("foo", "").(string) if foo != "bar" { t.Error("Expected 'bar'; got ", foo) return } bazO, ok := cxt.Has("baz") if !ok { t.Error("Expected to find 'baz' in context.") return } baz := bazO.(string) // fmt.Printf("baz is %v", baz) if baz != "true" { t.Error("Expected 'baz' to be true. Got false.") return } unused := cxt.Get("unused", 321).(string) if unused != "123" { t.Error("Expected 'unused' to be int 123. Got ", unused) return } }
func main() { srv := &http.Server{ Addr: ":5500", } reg, router, cxt := cookoo.Cookoo() buildRegistry(reg, router, cxt) // Our main datasource is the Medium, which manages channels. m := pubsub.NewMedium() cxt.AddDatasource(pubsub.MediumDS, m) cxt.Put("routes", reg.Routes()) http2.ConfigureServer(srv, &http2.Server{}) srv.Handler = web.NewCookooHandler(reg, router, cxt) srv.ListenAndServeTLS("server.crt", "server.key") }
func main() { // Build a new Cookoo app. registry, router, context := cookoo.Cookoo() // Fill the registry. registry.AddRoutes( cookoo.Route{ Name: "TEST", Help: "A test route", Does: cookoo.Tasks{ cookoo.Cmd{ Name: "hi", Fn: HelloWorld, }, }, }, ) // Execute the route. router.HandleRequest("TEST", context, false) }
func TestFoo(t *testing.T) { orig := TokenFile defer func() { TokenFile = orig }() TokenFile = "testdata/secret.txt" reg, router, cxt := cookoo.Cookoo() reg.Route("test", "Test route"). Does(GetToken, "res") if err := router.HandleRequest("test", cxt, true); err != nil { t.Error(err) } v := cxt.Get("res", "").(string) if v != "c0ff33" { t.Errorf("Expected c0ff33, got '%s'", v) } }