Ejemplo n.º 1
0
func prepareTestContainer(t *testing.T, s logical.Storage, b logical.Backend) (cid dockertest.ContainerID, retURI string) {
	if os.Getenv("MONGODB_URI") != "" {
		return "", os.Getenv("MONGODB_URI")
	}

	// Without this the checks for whether the container has started seem to
	// never actually pass. There's really no reason to expose the test
	// containers, so don't.
	dockertest.BindDockerToLocalhost = "yep"

	testImagePull.Do(func() {
		dockertest.Pull(dockertest.MongoDBImageName)
	})

	cid, connErr := dockertest.ConnectToMongoDB(60, 500*time.Millisecond, func(connURI string) bool {
		connURI = "mongodb://" + connURI
		// This will cause a validation to run
		resp, err := b.HandleRequest(&logical.Request{
			Storage:   s,
			Operation: logical.UpdateOperation,
			Path:      "config/connection",
			Data: map[string]interface{}{
				"uri": connURI,
			},
		})
		if err != nil || (resp != nil && resp.IsError()) {
			// It's likely not up and running yet, so return false and try again
			return false
		}
		if resp == nil {
			t.Fatal("expected warning")
		}

		retURI = connURI
		return true
	})

	if connErr != nil {
		t.Fatalf("could not connect to database: %v", connErr)
	}

	return
}
Ejemplo n.º 2
0
func TestMain(m *testing.M) {
	// We are in testing - notify the program
	// so that it is not confused if some other commad line
	// arguments come in - for example when test is started with `go test -v ./...`
	// which is what Travis does
	os.Setenv("TEST_ENV", "1")

	var db *mgo.Session
	c, err := dockertest.ConnectToMongoDB(15, time.Millisecond*500, func(url string) bool {
		// This callback function checks if the image's process is responsive.
		// Sometimes, docker images are booted but the process (in this case MongoDB) is still doing maintenance
		// before being fully responsive which might cause issues like "TCP Connection reset by peer".
		var err error
		db, err = mgo.Dial(url)
		if err != nil {
			return false
		}

		// Sometimes, dialing the database is not enough because the port is already open but the process is not responsive.
		// Most database conenctors implement a ping function which can be used to test if the process is responsive.
		// Alternatively, you could execute a query to see if an error occurs or not.
		return db.Ping() == nil
	})
	if err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	}

	// Set-up DB
	mfdb.SetMainSession(db)
	mfdb.SetMainDb("mainflux_test")

	// Run tests
	result := m.Run()

	// Close database connection.
	db.Close()

	// Clean up image.
	c.KillRemove()

	// Exit tests.
	os.Exit(result)
}