github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/apiv3/testutil/server.go (about)

     1  package testutil
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"net/http/httptest"
     7  
     8  	"github.com/codegangsta/negroni"
     9  	"github.com/evergreen-ci/evergreen"
    10  	"github.com/evergreen-ci/evergreen/apiv3/route"
    11  	"github.com/evergreen-ci/evergreen/apiv3/servicecontext"
    12  	"github.com/evergreen-ci/evergreen/db"
    13  	"github.com/gorilla/mux"
    14  	"github.com/mongodb/grip"
    15  )
    16  
    17  const (
    18  	testServerPort = 9191
    19  )
    20  
    21  // NewTestServerFromSettings takes an evergreen.Settings and creates a database backed
    22  // REST v2 test server. It automatically starts the server on port 9191.
    23  func NewTestServerFromSettings(settings *evergreen.Settings) (*httptest.Server, error) {
    24  	db.SetGlobalSessionProvider(db.SessionFactoryFromConfig(settings))
    25  	sc := &servicecontext.DBServiceContext{}
    26  
    27  	sc.SetPrefix(evergreen.RestRoutePrefix)
    28  	sc.SetSuperUsers(settings.SuperUsers)
    29  
    30  	return NewTestServerFromServiceContext(testServerPort, sc)
    31  }
    32  
    33  // NewTestServerFromServiceContext takes in a port and already constructed ServiceContext
    34  // and creates an REST v2 API server. This is very useful when testing, especially when
    35  // mocking out sections of the ServiceContext to make sure request occur as expected.
    36  func NewTestServerFromServiceContext(port int, sc servicecontext.ServiceContext) (*httptest.Server, error) {
    37  	root := mux.NewRouter()
    38  	route.GetHandler(root, sc)
    39  	n := negroni.New()
    40  	n.UseHandler(root)
    41  
    42  	server := httptest.NewUnstartedServer(n)
    43  	addr := fmt.Sprintf(":%d", port)
    44  	l, err := net.Listen("tcp", addr)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	sc.SetURL(fmt.Sprintf("http://localhost:%d", port))
    49  	server.Listener = l
    50  	server.Start()
    51  
    52  	grip.Infoln("started server:", sc.GetURL())
    53  
    54  	return server, nil
    55  }