func TestPub(t *testing.T) {
	config.LoadFromService("testservice")
	s := config.AtPath("configService", "hash").AsString("default")
	if s == "default" {
		t.Fatal("Failed to load config from config service")
	}
	err := Publish("testtopic", []byte("This is my payload"))
	if err != nil {
		t.Error(fmt.Sprintf("Failed to PUB: %v", err))
	}
}
func TestDriverTokenRecovery(t *testing.T) {
	setupOnce.Do(setupTests)

	config.LoadFromService("testservice")

	driverToken := `fYNtPGwtJrSWwhJaGzXEVHspevtgAdbUYToh/6aEJf7ZzpsZl06v63FjA4and1nfQeoU5lrSgwSogCDmK2bcpQ==`
	err := RecoverSession(driverToken)
	if err != nil {
		t.Fatalf("Recover session failed with an error: %v", err)
	}
	if !IsAuth() {
		t.Error("Driver token should have been automatically recovered")
	}
}
func TestInvalidTokenRecovery(t *testing.T) {
	setupOnce.Do(setupTests)

	config.LoadFromService("testservice")

	driverToken := `foobarbaz`
	err := RecoverSession(driverToken)
	if err != nil {
		t.Fatalf("Recover session failed with an error: %v", err)
	}
	if IsAuth() {
		t.Error("Recover session was not expected to recover a user")
	}
}
func TestPub(t *testing.T) {
	config.LoadFromService("testservice")

	val := time.Now().Nanosecond()
	setVal := []byte(string(val))

	if err := Set(&memcache.Item{Key: "foo", Value: setVal}); err != nil {
		t.Fatalf("Failed to Set: %v", err)
	}

	it, err := Get("foo")
	if err != nil {
		t.Fatalf("Failed to Get: %v", err)
	}

	if bytes.Equal(it.Value, setVal) == false {
		t.Errorf("Retrieved doesn't match set")
	}
}
// Init is a local init call that handles setup
func Init() {
	// Parse flags and handle them. No other code should be calling flag.Parse()
	handleFlags()

	if len(Name) == 0 {
		log.Critical("No service name found")
		cleanupLogs()
		os.Exit(1)
	}

	// GO!
	log.Infof("Starting up %v (%v)\n%v\n", Name, Version, banner.PrintS(Name))

	rand.Seed(time.Now().UnixNano())
	tokens = make(map[string]chan bool, 100)

	servicesConfigFile := configDir + "/" + Name + "-seelog.xml"
	if _, err := os.Stat(servicesConfigFile); err == nil {
		loadLogConfig(servicesConfigFile)
	}

	// Try and open the access log file
	if accessLogDir := os.Getenv(accessLogEnv); accessLogDir != "" {
		var err error
		accessLogFilename := filepath.Join(accessLogDir, Name+"-access.log")
		commonLogger, err = os.OpenFile(accessLogFilename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			log.Errorf("[Server] Error opening access log file: %v", err)
			commonLogger = nil
		}
	} else {
		log.Errorf("[Server] No access log env (%v) set", accessLogEnv)
	}

	log.Infof("[Server] Running with %d cores", runtime.GOMAXPROCS(0))
	uuid, _ := uuid.NewV4()
	InstanceID = fmt.Sprintf("server-%s-%s", Name, uuid)

	// Configure key service layer components, loading config from the config service automatically
	config.LoadFromService(Name)
	inst.SetNamespace(Name)
	ssync.SetRegionLockNamespace(Name)

	// Register region leader cleanup function
	RegisterCleanupHandler(ssync.CleanupRegionLeaders)

	// Ping graphite that we have started
	inst.Counter(1.0, "runtime.started", 1)

	// Connect the raven and keep checking its status
	ch := raven.Connect()
	if online := <-ch; !online {
		log.Warn("[Server] Failed to connect the raven on first attempt")
	}
	go monitorRaven(ch)

	// Create a new registry for the endpoints
	reg = newRegistry()

	// Add default middleware
	registerMiddleware(authMiddleware)
	registerMiddleware(tracingMiddleware)
	registerMiddleware(instrumentedMiddleware)
	registerMiddleware(tokenConstrainedMiddleware)
	registerMiddleware(waitGroupMiddleware)
	registerMiddleware(commonLoggerMiddleware(commonLogger))

	// Add default endpoints
	registerEndpoint(&Endpoint{
		Name:             "health",
		Mean:             100,
		Upper95:          200,
		Handler:          healthHandler,
		RequestProtocol:  new(healthproto.Request),
		ResponseProtocol: new(healthproto.Response),
	})
	registerEndpoint(&Endpoint{
		Name:             "stats",
		Mean:             100,
		Upper95:          200,
		Handler:          statsHandler,
		RequestProtocol:  new(statsproto.Request),
		ResponseProtocol: new(statsproto.PlatformStats),
	})
	registerEndpoint(&Endpoint{
		Name:             "loadedconfig",
		Mean:             100,
		Upper95:          200,
		Handler:          loadedConfigHandler,
		RequestProtocol:  new(loadedconfigproto.Request),
		ResponseProtocol: new(loadedconfigproto.Response),
	})
	registerEndpoint(&Endpoint{
		Name:             "jsonschema",
		Mean:             100,
		Upper95:          200,
		Handler:          jsonschemaHandler,
		RequestProtocol:  new(jsonschemaproto.Request),
		ResponseProtocol: new(jsonschemaproto.Response),
		Authoriser:       OpenToTheWorldAuthoriser(),
	})

	// Initialise platform healthchecks
	initHealthChecks()
	initialised = true
}