func (delegate *TestClientDelegate) Initialize(ctx application.Context) { log.Printf("TestClientDelegate.Initialize...") // Set the necessary flags using the mojo args. args := ctx.Args() mojoFlag = flag.NewFlagSet(args[0], flag.ExitOnError) mojoRun := mojoFlag.String("test.run", "", "") mojoBench := mojoFlag.String("test.bench", "", "") endpointFlag = mojoFlag.String("endpoint", "", "") v23TcpAddr := mojoFlag.String("v23.tcp.address", "", "") mojoFlag.Parse(args[1:]) flag.Set("test.run", *mojoRun) flag.Set("test.bench", *mojoBench) flag.Set("v23.tcp.address", *v23TcpAddr) tests := []func(*testing.T, application.Context){ TestSimple, TestMultiArgs, TestReuseProxy, TestNoOutArgs, } benchmarks := []func(*testing.B, application.Context){ BenchmarkSimpleRpc, } matchAllTests := func(pat, str string) (bool, error) { return true, nil } exitCode := testing.MainStart(matchAllTests, convertTests(tests, ctx), convertBenchmarks(benchmarks, ctx), nil).Run() if exitCode == 0 { fmt.Printf("%s\n", expected.SuccessMessage) } else { fmt.Printf("%s\n", expected.FailureMessage) } ctx.Close() os.Exit(exitCode) }
func Init() error { Program = filepath.Base(os.Args[0]) if !isPidInitialize() { if "windows" == runtime.GOOS { flag.Set("pid_file", Program+".pid") } else { flag.Set("pid_file", "/var/run/"+Program+".pid") } } if "." == RootDir { RootDir = abs(filepath.Dir(os.Args[0])) dirs := []string{abs(filepath.Dir(os.Args[0])), filepath.Join(abs(filepath.Dir(os.Args[0])), "..")} for _, s := range dirs { if DirExists(filepath.Join(s, "conf")) { RootDir = s break } } } else { RootDir = abs(RootDir) } if !DirExists(RootDir) { return errors.New("root directory '" + RootDir + "' is not exist.") } else { log.Println("root directory is '" + RootDir + "'.") } e := os.Chdir(RootDir) if nil != e { log.Println("change current dir to \""+RootDir+"\",", e) } return nil }
func main() { mrand.Seed(time.Now().UnixNano()) errors := []error{ flag.Set("logtostderr", "true"), flag.Set("logcolor", "true"), } for _, err := range errors { if err != nil { panic(err) } } lg.SetSrcHighlight("alkasir/cmd", "alkasir/pkg") lg.CopyStandardLogTo("info") flag.Parse() flagenv.Prefix = "ALKASIR_" flagenv.Parse() err := commandHandler(flag.Args()) if err != nil { if err == errCommandNotFound { fmt.Println("") fmt.Println("Command index:") fmt.Println("") rootCommand.PrintHelp("alkasir-admin", 0) fmt.Println("") os.Exit(1) } lg.Fatal(err) os.Exit(1) } }
// NewVtctlPipe creates a new VtctlPipe based on the given topo server. func NewVtctlPipe(t *testing.T, ts topo.Server) *VtctlPipe { // Register all vtctl commands servenvInitialized.Do(func() { // make sure we use the right protocol flag.Set("vtctl_client_protocol", "grpc") // Enable all query groups flag.Set("enable_queries", "true") servenv.FireRunHooks() }) // Listen on a random port listener, err := net.Listen("tcp", ":0") if err != nil { t.Fatalf("Cannot listen: %v", err) } // Create a gRPC server and listen on the port server := grpc.NewServer() grpcvtctlserver.StartServer(server, ts) go server.Serve(listener) // Create a VtctlClient gRPC client to talk to the fake server client, err := vtctlclient.New(listener.Addr().String(), 30*time.Second) if err != nil { t.Fatalf("Cannot create client: %v", err) } return &VtctlPipe{ listener: listener, client: client, t: t, } }
func init() { sdk := env.URL(nil) if sdk != "" { flag.Set("sdk", sdk) flag.Set("vm-path", "docker-appliance") flag.Set("cluster", os.Getenv("GOVC_CLUSTER")) } // fake up a docker-host for pprof collection u := url.URL{Scheme: "http", Host: "127.0.0.1:6060"} go func() { log.Println(http.ListenAndServe(u.Host, nil)) }() transport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } insecureClient = &http.Client{Transport: transport} flag.Set("docker-host", u.Host) config.hostCertFile = "fixtures/vicadmin_test_cert.pem" config.hostKeyFile = "fixtures/vicadmin_test_pkey.pem" cert, cerr := ioutil.ReadFile(config.hostCertFile) key, kerr := ioutil.ReadFile(config.hostKeyFile) if kerr != nil || cerr != nil { panic("unable to load test certificate") } vchConfig.HostCertificate = &vchconfig.RawCertificate{ Cert: cert, Key: key, } }
func main() { role := flag.String("role", "master", "Escort role") flag.Set("alsologtostderr", "true") flag.Set("v", "5") flag.Parse() if role == nil || len(*role) == 0 { Usage() return } glog.Infoln(*role) switch *role { case "master": // 主服务 server.Work() case "slave": // 备份服务 client.Work() default: Usage() } }
// ExampleFlightGetBadID tests giving a non integer as ID value, with null output func ExampleFlightGetBadID() { _ = flag.Set("id", "i") _ = flag.Set("startID", "") _ = flag.Set("max", "") runFlightGet(CmdFlightGet, []string{}) // Output: }
func Start(port string, onStart func()) { // Logging init flag.Set("log_dir", utils.GetRuntimeDir(config.GetString("log_dir"))) flag.Set("alsologtostderr", "true") flag.Parse() defer glog.Flush() m := martini.Classic() m.Use(render.Renderer(render.Options{ Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8". Delims: render.Delims{"${", "}"}, Directory: utils.GetRuntimeDir("resources/views"), })) m.Use(martini.Static(utils.GetRuntimeDir("public"))) controller.MappingController(m) http.Handle("/rpc", rpc.GetServer()) http.Handle("/", m) if db.IsConnected() { defer db.Close() } onStart() for _, fn := range methods { go fn() } http.ListenAndServe(":"+port, nil) }
func (s *MainSuite) TestGenApi(c *C) { flag.Set("pkg", "github.com/hypermusk/hypermusk/tests/api") flag.Set("lang", "objc") flag.Set("outdir", "tests") flag.Set("impl", "github.com/hypermusk/hypermusk/tests/apiimpl") genApi() }
// ExampleFlightGetByID uses the mock flight implementation to query data and // verify flight-get works. First, a specific id is passed. Second, a start id // is passed. func ExampleFlightGetByID() { plugin.Register("mockflightgetbyid", &mock.Mock{ GetFlightByIDF: func(id int) (flight.Flight, error) { f := flight.Flight{ Header: flight.Header{ Date: time.Date(2015, 1, 10, 0, 0, 0, 0, time.UTC), Pilot: "MOCK PILOT 1", GliderType: "MOCK GLIDER 1", GliderID: "MOCK ID 1", }, Sources: map[string]flight.Source{ "netcoupe": flight.Source{ Name: "MOCK NAME 1", Category: "MOCK CATEGORY 1", Club: "MOCK CLUB 1", Region: "MOCK REGION 1", Country: "MOCK COUNTRY 1", Distance: 100.01, Points: 100.02, }, }, } return f, nil }, }, ) config.Set(config.Config{Global: config.Global{Flighter: "mockflightgetbyid"}}) _ = flag.Set("id", "1") _ = flag.Set("startID", "") _ = flag.Set("max", "") runFlightGet(CmdFlightGet, []string{}) // Output: // 10/01/2015,MOCK PILOT 1,MOCK GLIDER 1,MOCK ID 1 // netcoupe,MOCK NAME 1,MOCK CATEGORY 1,MOCK CLUB 1,MOCK COUNTRY 1,MOCK REGION 1,100.01,100.02 }
func init() { if os.Getenv("DATABASE_URL") != "" { flag.Set("driver", "postgres") flag.Set("dbsource", os.Getenv("DATABASE_URL")) log.Println("Using PostgreSQL") } else { log.Println("Using SQLite3") } db, err := gorm.Open(*driver, *dbsource) if err != nil { panic(err) } db.LogMode(false) // Here database and tables are created in case they do not exist yet. // If database or tables do exist, nothing will happen to the original ones. db.CreateTable(&User{}) db.CreateTable(&Post{}) db.AutoMigrate(&User{}, &Post{}) connection.SQL = db.DB() connection.Gorm = db }
func main() { defer glog.Flush() flag.Set("logtostderr", "true") flag.Set("v", "2") flag.Parse() // Add actions sources for _, source := range strings.Split(sources, ",") { core.Source(source) } // Executor ex := executor.New(tests) // API http.Handle("/watch", api.WatchHandler{Executor: ex}) http.Handle("/execute", api.ExecuteHandler{Executor: ex}) http.Handle("/status/poll", api.PollHandler{Executor: ex}) http.Handle("/status", api.StatusHandler{Executor: ex}) http.Handle("/latest", api.LatestHandler{Executor: ex}) // Dashboard http.Handle("/", http.FileServer(http.Dir(dashboard))) if watch { go ex.Watch() } // Start listening glog.Infof("Listening on address %s\n", listenaddr) glog.Fatal(http.ListenAndServe(listenaddr, nil)) }
// TestNewRestartableResultReader tests the correct error handling e.g. // if the connection to a tablet fails due to a canceled context. func TestNewRestartableResultReader(t *testing.T) { wantErr := errors.New("restartable_result_reader_test.go: context canceled") tabletconn.RegisterDialer("fake_dialer", func(tablet *topodatapb.Tablet, timeout time.Duration) (tabletconn.TabletConn, error) { return nil, wantErr }) protocol := flag.CommandLine.Lookup("tablet_protocol").Value.String() flag.Set("tablet_protocol", "fake_dialer") // Restore the previous flag value after the test. defer flag.Set("tablet_protocol", protocol) // Create dependencies e.g. a "singleTabletProvider" instance. ts := zktestserver.New(t, []string{"cell1"}) wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient()) alias := &topodatapb.TabletAlias{ Cell: "cell1", Uid: 1, } tablet := &topodatapb.Tablet{ Keyspace: "ks1", Shard: "-80", Alias: alias, } ctx := context.Background() if err := ts.CreateTablet(ctx, tablet); err != nil { t.Fatalf("CreateTablet failed: %v", err) } tp := newSingleTabletProvider(ctx, ts, alias) _, err := NewRestartableResultReader(ctx, wr.Logger(), tp, nil /* td */, chunk{}, false) if err == nil || !strings.Contains(err.Error(), wantErr.Error()) { t.Fatalf("NewRestartableResultReader() should have failed because the context is canceled: %v", err) } }
func loadConfig() { var cfgPath string cfgPath = os.Getenv("HOME") if cfgPath != "" { cfgPath = cfgPath + "/.config" err := verifyOrCreateDirectory(cfgPath) if err != nil { panic(err) } cfgPath = cfgPath + "/magopie-cui" } if cfgPath != "" { file, err := os.Open(cfgPath) if err != nil { // Couldn't load config even though one was specified return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { tstString := scanner.Text() if strings.HasPrefix(tstString, "server=") { prts := strings.Split(tstString, "=") if len(prts) > 1 { flag.Set("http", prts[1]) } } else if strings.HasPrefix(tstString, "key=") { prts := strings.Split(tstString, "=") if len(prts) > 1 { flag.Set("key", prts[1]) } } } } }
// ExampleFlightGetFromID queries using flight-get. First no max is given, so all records // starting at 'startID' are returned. Second, a max is given so the number of results is limited. func ExampleFlightGetFromID() { plugin.Register("mockflightgetfromid", &mock.Mock{ GetFlightFromIDF: func(startID int, max int) ([]flight.Flight, error) { flights := []flight.Flight{ flight.Flight{ Header: flight.Header{ Date: time.Date(2015, 1, 10, 0, 0, 0, 0, time.UTC), Pilot: "MOCK PILOT 1", GliderType: "MOCK GLIDER 1", GliderID: "MOCK ID 1", }, Sources: map[string]flight.Source{ "netcoupe": flight.Source{ Name: "MOCK NAME 1", Category: "MOCK CATEGORY 1", Club: "MOCK CLUB 1", Region: "MOCK REGION 1", Country: "MOCK COUNTRY 1", Distance: 101.01, Points: 101.02, }, }, }, flight.Flight{ Header: flight.Header{ Date: time.Date(2015, 1, 11, 0, 0, 0, 0, time.UTC), Pilot: "MOCK PILOT 2", GliderType: "MOCK GLIDER 2", GliderID: "MOCK ID 2", }, Sources: map[string]flight.Source{ "netcoupe": flight.Source{ Name: "MOCK NAME 2", Category: "MOCK CATEGORY 2", Club: "MOCK CLUB 2", Region: "MOCK REGION 2", Country: "MOCK COUNTRY 2", Distance: 102.01, Points: 102.02, }, }, }, } if max > 0 { flights = flights[0:max] } return flights, nil }, }, ) config.Set(config.Config{Global: config.Global{Flighter: "mockflightgetfromid"}}) _ = flag.Set("startID", "1") _ = flag.Set("max", "") runFlightGet(CmdFlightGet, []string{}) _ = flag.Set("max", "1") runFlightGet(CmdFlightGet, []string{}) // Output: // 10/01/2015,MOCK PILOT 1,MOCK GLIDER 1,MOCK ID 1 // netcoupe,MOCK NAME 1,MOCK CATEGORY 1,MOCK CLUB 1,MOCK COUNTRY 1,MOCK REGION 1,101.01,101.02 // 11/01/2015,MOCK PILOT 2,MOCK GLIDER 2,MOCK ID 2 // netcoupe,MOCK NAME 2,MOCK CATEGORY 2,MOCK CLUB 2,MOCK COUNTRY 2,MOCK REGION 2,102.01,102.02 // 10/01/2015,MOCK PILOT 1,MOCK GLIDER 1,MOCK ID 1 // netcoupe,MOCK NAME 1,MOCK CATEGORY 1,MOCK CLUB 1,MOCK COUNTRY 1,MOCK REGION 1,101.01,101.02 }
func main() { flag.Parse() args := flag.Args() // check environment variables if *host == "localhost:27017" { if env := os.Getenv("GODMHOST"); env != "" { flag.Set("host", env) } } if *database == "test" { if env := os.Getenv("GODMDB"); env != "" { flag.Set("db", env) } } db := &Db{*host, *database} if len(args) == 0 { helpFunc(db, nil, args) os.Exit(1) } cmdName, args := args[0], args[1:] if cmd := findCommand(cmdName); cmd != nil { cmd.Run(db, args) } else { log.Fatal("Unknown command. 'help' for usage.") } }
// InitLogs initializes logs the way we want for SkyRing. func InitLogs(logConf conf.SkyringLogging) { flag.Parse() flag.Set("logtostderr", strconv.FormatBool(logConf.Logtostderr)) flag.Set("log_dir", logConf.Log_dir) flag.Set("v", strconv.Itoa(logConf.V)) // The default glog flush interval is 30 seconds, which is frighteningly long. go Forever(glog.Flush, 5*time.Second) }
func init() { /* **To configure glog */ flag.Set("logtostderr", "true") flag.Set("log_dir", ".") flag.Set("V", "3") flag.Parse() }
func test_storage_init() (err error) { runtime.GOMAXPROCS(runtime.NumCPU()) flag.Set("alsologtostderr", "true") flag.Set("v", "2") flag.Parse() storageApp = &Backend{ ShmMagic: 0x80386, ShmKey: 0x6020, ShmSize: 1 << 28, // 256m Storage: Storage{ Type: "rrdlite", }, } testDirs = make([]string, MAX_HD_NUMBER) for i := 0; i < MAX_HD_NUMBER; i++ { testDirs[i] = fmt.Sprintf("%s/hdd%d/test", testDir, i+1) os.RemoveAll(testDirs[i]) os.MkdirAll(testDirs[i], 0755) } err = storageCheckHds(testDirs) if err != nil { glog.Fatalf(MODULE_NAME+"rrdtool.Start error, bad data dir %v\n", err) } storageApp.storageIoTaskCh = make([]chan *ioTask, MAX_HD_NUMBER) for i := 0; i < MAX_HD_NUMBER; i++ { storageApp.storageIoTaskCh[i] = make(chan *ioTask, 320) go storageApp.ioWorker(storageApp.storageIoTaskCh[i]) } storageApp.cacheInit() if err := storageApp.cacheReset(); err != nil { fmt.Println(err) } storageApp.timeStart() now = time.Now().Unix() storageApp.ts = now for i := 0; i < MAX_HD_NUMBER; i++ { item := newRrdItem2(i, now) for j := 0; j < benchSize; j++ { es[i][j], err = storageApp.rrdToEntry(item) if err != nil { glog.Infof("benchmarkAdd %s\n", err) return err } es[i][j].setName(fmt.Sprintf("key_%d_%d", i, j)) es[i][j].setHashkey(es[i][j].csum()) } } return nil }
func main() { flag.Set("test.bench", "Large") flag.Set("test.v", "true") testing.Main(func(pat, str string) (bool, error) { return true, nil }, []testing.InternalTest{{"TestLargeMapGC", TestLargeMapGC}}, []testing.InternalBenchmark{{"BenchmarkLargeMapGC", BenchmarkLargeMapGC}}, []testing.InternalExample{}) }
func glogFlags(c *cli.Context) error { v := c.Int("v") if v < 0 { flag.Set("logtostderr", "false") } else if v > 0 { flag.Set("v", fmt.Sprintf("%d", v)) } return nil }
func Test_load3(t *testing.T) { flag.Set("h", "192.168.1.3") flag.Set("u", "Chemasmas") load() impresion() if *host == "127.0.0.1" { t.Fail() } }
func initGlog() { checkDir(*logDir) if *logToStderr { flag.Set("alsologtostderr", "true") } flag.Set("v", *vLevel) flag.Set("log_dir", *logDir) }
func main() { server_mode := flag.Bool("server", false, "server mode (vs. client mode") port := flag.String("port", ":1111", "port to listen or dial to") flag.Parse() if !strings.Contains(*port, ":") { // make sure it looks like a port flag.Set("port", ":"+*port) } if !*server_mode && strings.HasPrefix(*port, ":") { // the client should point to a server address flag.Set("port", "localhost"+*port) } if *server_mode { // // the server // log.Println("listening on port", *port) l, err := muxado.Listen("tcp", *port) if err != nil { log.Fatal("server listen", err) } for { sess, err := l.Accept() if err != nil { log.Fatal("listen accept", err) } go handleSession(sess, "server") go client(sess, "server", nil) } } else { // // the client // sess, err := muxado.Dial("tcp", *port) if err != nil { log.Fatal(err) } defer sess.Close() var wg sync.WaitGroup for _, v := range []string{"1", "2", "3"} { wg.Add(1) go handleSession(sess, "client") go client(sess, "client "+v, &wg) } wg.Wait() } }
func Test_load4(t *testing.T) { flag.Set("h", "192.168.1.4") flag.Set("u", "Chemasmas") flag.Set("p", "GopherGala") load() impresion() if *host == "127.0.0.1" { t.Fail() } }
func main() { log.Println(runtime.Version()) flag.Set("test.bench", "foo") flag.Set("test.v", "true") testing.Main(func(pat, str string) (bool, error) { return true, nil }, []testing.InternalTest{{"TestSlice", TestSlice}, {"TestSliceByte", TestSliceByte}}, []testing.InternalBenchmark{}, []testing.InternalExample{}) }
func main() { log.Println(runtime.Version()) flag.Set("test.bench", "foo") flag.Set("test.v", "true") testing.Main(func(pat, str string) (bool, error) { return true, nil }, []testing.InternalTest{}, []testing.InternalBenchmark{{"BenchmarkFreelist", BenchmarkFreelist}, {"BenchmarkFreelist2", BenchmarkFreelist2}}, []testing.InternalExample{}) }
func init() { flag.Set("v", "1") flag.Set("stderrthreshold", "ERROR") utils.IsTesting = true utils.LoadConfig("../../config/config.json") _s = NewStore() _conn, _ = setupConnectionPGX(utils.Cfg.StorageSettings) }
// Test handler for SIGHUP func TestReloadSignal(t *testing.T) { oldConfig := getSignalTestConfig() flag.Set("config", `invalid`) if badConfig := reloadConfig(oldConfig); badConfig != nil { t.Errorf("Invalid configuration did not return nil") } flag.Set("config", `{ "consul": "newconsul:8500" }`) if newConfig := reloadConfig(oldConfig); newConfig.Consul != "newconsul:8500" { t.Errorf("Configuration was not reloaded.") } }
func TestWaypointGetBadAfter(t *testing.T) { plugin.Register("mockwaypointbadafter", &mock.Mock{ GetWaypointF: func(regions []string, updatedSince time.Time) ([]waypoint.Waypoint, error) { return nil, nil }, }, ) config.Set(config.Config{Global: config.Global{Waypointer: "mockwaypointbadafter"}}) flag.Set("after", "22-00-11") flag.Set("region", "") runWaypointGet(CmdWaypointGet, []string{}) }