Exemple #1
0
func TestProvideWithFields(t *testing.T) {
	var g inject.Graph
	a := &TypeAnswerStruct{}
	err := g.Provide(&inject.Object{Value: a, Fields: map[string]*inject.Object{}})
	ensure.NotNil(t, err)
	ensure.DeepEqual(t, err.Error(), "fields were specified on object *inject_test.TypeAnswerStruct when it was provided")
}
Exemple #2
0
func Start(port int, fileLocation string) {

	var router routers.Router
	var graph inject.Graph

	// Create database
	db := data.NewJsonDB(fileLocation)

	// Setup DI
	if err := graph.Provide(
		&inject.Object{Value: db},
		&inject.Object{Value: repositories.NewCharacterRepository()},
		&inject.Object{Value: &router}); err != nil {
		log.Fatalf("Error providing dependencies: ", err.Error())
	}

	if err := graph.Populate(); err != nil {
		log.Fatalf("Error populating dependencies: ", err.Error())
	}

	n := negroni.Classic()
	n.UseHandler(router.NewRouter())

	err := http.ListenAndServe(fmt.Sprintf(":%v", port), n)

	if err != nil {
		panic("Error: " + err.Error())
	}
}
Exemple #3
0
// NewApp constructs an new App instance from the provided config.
func NewApp(config config.Config, migrateFlag bool) (app *App, err error) {
	var g inject.Graph

	var driver db.Driver
	switch config.Database.Type {
	case "mysql":
		driver = &mysql.Driver{}
	case "postgres":
		driver = &postgres.Driver{}
	default:
		return nil, fmt.Errorf("%s database has no driver", config.Database.Type)
	}

	err = driver.Init(config.Database.URL)
	if err != nil {
		return
	}

	entityManager := db.NewEntityManager(driver)
	repository := db.NewRepository(driver)

	if migrateFlag {
		var migrationsApplied int
		migrationsApplied, err = driver.MigrateUp("compliance")
		if err != nil {
			return
		}

		log.Info("Applied migrations: ", migrationsApplied)
		os.Exit(0)
		return
	}

	requestHandler := handlers.RequestHandler{}

	err = g.Provide(
		&inject.Object{Value: &requestHandler},
		&inject.Object{Value: &config},
		&inject.Object{Value: &entityManager},
		&inject.Object{Value: &repository},
		&inject.Object{Value: &crypto.SignerVerifier{}},
		&inject.Object{Value: &stellartoml.Resolver{}},
		&inject.Object{Value: &federation.Resolver{}},
		&inject.Object{Value: &http.Client{}},
	)

	if err != nil {
		log.Fatal("Injector: ", err)
	}

	if err := g.Populate(); err != nil {
		log.Fatal("Injector: ", err)
	}

	app = &App{
		config:         config,
		requestHandler: requestHandler,
	}
	return
}
Exemple #4
0
func TestInjectLogging() {
	g := inject.Graph{
		Logger: &logger{
			Expected: []string{
				"provided *main.TypeForLoggingCreated named name_for_logging",
				"provided *main.TypeForLogging",
				"provided embedded *main.TypeForLoggingEmbedded",
				"created *main.TypeForLoggingCreated",
				"assigned newly created *main.TypeForLoggingCreated to field TypeForLoggingCreated in *main.TypeForLogging",
				"assigned existing *main.TypeForLoggingCreated to field TypeForLoggingCreated in *main.TypeForLoggingEmbedded",
				"assigned *main.TypeForLoggingCreated named name_for_logging to field TypeForLoggingCreatedNamed in *main.TypeForLoggingEmbedded",
				"made map for field Map in *main.TypeForLoggingEmbedded",
				"assigned existing *main.TypeForLoggingCreated to interface field TypeForLoggingInterface in *main.TypeForLoggingEmbedded",
			},
		},
	}
	var v TypeForLogging

	err := g.Provide(
		&inject.Object{Value: &TypeForLoggingCreated{}, Name: "name_for_logging"},
		&inject.Object{Value: &v},
	)
	if err != nil {
		fmt.Println(err)
	}
	if err := g.Populate(); err != nil {
		fmt.Println(err)
	}
}
Exemple #5
0
func initiateTests() {
	var router routers.Router
	var graph inject.Graph

	setupTestData()

	db := data.NewJsonDB("../data/testing/testingDB.json")

	if err := graph.Provide(
		&inject.Object{Value: db},
		&inject.Object{Value: repositories.NewCharacterRepository()},
		&inject.Object{Value: &router}); err != nil {
		log.Fatalf("Error providing dependencies: ", err.Error())
	}

	if err := graph.Populate(); err != nil {
		log.Fatalf("Error populating dependencies: ", err.Error())
	}

	n := negroni.Classic()

	n.UseHandler(router.NewRouter())

	ts = httptest.NewServer(n)
}
Exemple #6
0
func StartMyApp(port int, dbName string) {

	var env Env.Env
	var g inject.Graph

	db, e := Data.NewDB(dbName)

	log.Println(e)

	err := g.Provide(
		&inject.Object{Value: &env},
		&inject.Object{Value: db},
	)

	if err != nil {
		log.Fatalf("Error providing dependencies: ", err.Error())
	}

	if err := g.Populate(); err != nil {
		log.Fatalf("Error providing dependencies: ", err.Error())
	}

	routes := Api.Routes(env)

	routes.Run(fmt.Sprintf(":%v", port))
}
Exemple #7
0
func TestProvideNonPointer() {
	var g inject.Graph
	var i *int
	err := g.Provide(&inject.Object{Value: i})

	fmt.Println(err)

}
Exemple #8
0
func ProvideWithFields() {
	var g inject.Graph
	a := &TypeAnswerStruct{}
	err := g.Provide(&inject.Object{Value: a, Fields: map[string]*inject.Object{}})

	fmt.Println(err)
	//ensure.NotNil(glog.Fatal, err)
	//ensure.DeepEqual(fmt, err.Error(), "fields were specified on object *inject_test.TypeAnswerStruct when it was provided")
}
Exemple #9
0
func TestProvideTwoOfTheSame() {
	var g inject.Graph
	a := TypeAnswerStruct{}
	err := g.Provide(&inject.Object{Value: &a})
	fmt.Println(err)

	err = g.Provide(&inject.Object{Value: &a})
	fmt.Println(err)

}
Exemple #10
0
func TestInjectNamedTwoSatisfyInterface() {
	var g inject.Graph
	var v TypeInjectNamedTwoSatisfyInterface
	if err := g.Provide(&inject.Object{Name: "foo", Value: &v}); err != nil {
		fmt.Println(err)
	}

	err := g.Populate()
	fmt.Println(err)
}
Exemple #11
0
func TestObjectString(t *testing.T) {
	var g inject.Graph
	a := &TypeNestedStruct{}
	if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil {
		t.Fatal(err)
	}

	var c TypeForObjectString
	if err := g.Provide(&inject.Object{Value: &c}); err != nil {
		t.Fatal(err)
	}

	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}

	var actual []string
	for _, o := range g.Objects() {
		actual = append(actual, fmt.Sprint(o))
	}

	ensure.SameElements(t, actual, []string{
		"*inject_test.TypeForObjectString",
		"*inject_test.TypeNestedStruct",
		"*inject_test.TypeNestedStruct named foo",
		"*inject_test.TypeAnswerStruct",
	})
}
Exemple #12
0
func TestTwoNamedInstances(t *testing.T) {
	var g inject.Graph
	a := &TypeAnswerStruct{}
	b := &TypeAnswerStruct{}
	if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil {
		t.Fatal(err)
	}

	if err := g.Provide(&inject.Object{Value: b, Name: "bar"}); err != nil {
		t.Fatal(err)
	}

	var c struct {
		A *TypeAnswerStruct `inject:"foo"`
		B *TypeAnswerStruct `inject:"bar"`
	}
	if err := g.Provide(&inject.Object{Value: &c}); err != nil {
		t.Fatal(err)
	}

	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}

	if c.A != a {
		t.Fatal("did not find expected c.A")
	}
	if c.B != b {
		t.Fatal("did not find expected c.B")
	}
}
Exemple #13
0
func main() {
	// command line flags
	confFile := flag.String("conf", "emerald.conf", "location of config-file")
	flag.Parse()
	conf := core.LoadConfiguration(*confFile)

	var app core.EmeraldApp
	mongoService := mongo.NewService(&conf)
	ircClient := irc.NewClient()

	var g inject.Graph
	err := g.Provide(
		&inject.Object{Value: &conf},
		&inject.Object{Value: &app},
		&inject.Object{Value: mongoService},
		&inject.Object{Value: ircClient},
	)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	if err := g.Populate(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	//setup gin
	gin.SetMode(gin.ReleaseMode)
	router := gin.New()

	//Middlewares
	// router.Use(gin.Logger())
	router.Use(gin.Recovery())

	//static files
	router.Static("/assets", "./assets")
	router.StaticFile("/", "./assets/index.html")

	//register all controllers
	app.AddControllers(router)

	//Start all jobs
	app.StartJobs()

	// Listen and server on 0.0.0.0:8080
	addr := fmt.Sprintf(":%d", conf.Port)
	log.Printf("Emerald started port %v\n", addr)
	fmt.Printf("Emerald started port %v\n", addr)
	err = router.Run(addr)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Exemple #14
0
func TestObjectString() {
	var g inject.Graph

	a := &TypeNestedStruct{}
	if err := g.Provide(&inject.Object{Value: a, Name: "foo"}); err != nil {
		fmt.Println(err)
	}

	var c TypeForObjectString
	if err := g.Provide(&inject.Object{Value: &c}); err != nil {
		fmt.Println(err)
	}

	if err := g.Populate(); err != nil {
		fmt.Println(err)
	}

	a.A.answer = 100
	fmt.Printf("c.A.A = %#v, c.B.A = %#v\n", c.A.A, c.B.A)

	var actual []string
	for _, o := range g.Objects() {

		fmt.Printf("%#v\n", o)
		actual = append(actual, fmt.Sprint(o))
	}

	//fmt.Printf("%#v \n", actual)

}
Exemple #15
0
func TestProvideTwoWithTheSameName() {
	var g inject.Graph
	const name = "foo"
	a := TypeAnswerStruct{}
	err := g.Provide(&inject.Object{Value: &a, Name: name})
	fmt.Println(err)

	err = g.Provide(&inject.Object{Value: &a, Name: name})
	fmt.Println(err)

}
Exemple #16
0
func Injector(params ...interface{}) (err error) {
	var g inject.Graph
	for _, v := range params {
		if err = g.Provide(&inject.Object{Value: v}); err != nil {
			return
		}
	}
	if err = g.Populate(); err != nil {
		return
	}
	return
}
Exemple #17
0
func TestProvideNonPointerStruct(t *testing.T) {
	var g inject.Graph
	var i *int
	err := g.Provide(&inject.Object{Value: i})
	if err == nil {
		t.Fatal("expected error")
	}

	const msg = "expected unnamed object value to be a pointer to a struct but got type *int with value <nil>"
	if err.Error() != msg {
		t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error())
	}
}
Exemple #18
0
func TestForSameNameButDifferentPackage(t *testing.T) {
	var g inject.Graph
	err := g.Provide(
		&inject.Object{Value: &injecttesta.Foo{}},
		&inject.Object{Value: &injecttestb.Foo{}},
	)
	if err != nil {
		t.Fatal(err)
	}
	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}
}
Exemple #19
0
func TestCompleteNamedProvides(t *testing.T) {
	var g inject.Graph
	var v struct {
		A *TypeAnswerStruct `inject:""`
	}
	if err := g.Provide(&inject.Object{Value: &v, Complete: true, Name: "foo"}); err != nil {
		t.Fatal(err)
	}

	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}
	if v.A != nil {
		t.Fatal("v.A was not nil")
	}
}
Exemple #20
0
//Map map objects
func (p *Engine) Map(inj *inject.Graph) error {

	enc, err := NewAesHmacEncryptor(Secret(120, 32), Secret(210, 32))
	if err != nil {
		return err
	}

	return inj.Provide(
		&inject.Object{Value: enc},
		&inject.Object{Value: Secret(320, 32), Name: "jwt.key"},
		&inject.Object{Value: crypto.SigningMethodHS512, Name: "jwt.method"},
		&inject.Object{Value: "cache", Name: "cache.prefix"},
		&inject.Object{Value: "ga2", Name: "oauth2.google.state"},
	)

}
Exemple #21
0
func TestInjectNamedTwoSatisfyInterface(t *testing.T) {
	var g inject.Graph
	var v TypeInjectNamedTwoSatisfyInterface
	if err := g.Provide(&inject.Object{Name: "foo", Value: &v}); err != nil {
		t.Fatal(err)
	}

	err := g.Populate()
	if err == nil {
		t.Fatal("was expecting error")
	}

	const msg = "found two assignable values for field Answerable in type *inject_test.TypeInjectNamedTwoSatisfyInterface. one type *inject_test.TypeAnswerStruct with value &{0 0} and another type *inject_test.TypeNestedStruct with value <*inject_test.TypeNestedStruct Value>"
	if err.Error() != msg {
		t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error())
	}
}
Exemple #22
0
func TestInjectNamedOnPrivateInterfaceField(t *testing.T) {
	var g inject.Graph
	var v TypeWithInjectNamedOnPrivateInterfaceField
	if err := g.Provide(&inject.Object{Name: "foo", Value: &v}); err != nil {
		t.Fatal(err)
	}

	err := g.Populate()
	if err == nil {
		t.Fatal("was expecting error")
	}

	const msg = "inject requested on unexported field a in type *inject_test.TypeWithInjectNamedOnPrivateInterfaceField"
	if err.Error() != msg {
		t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error())
	}
}
Exemple #23
0
func newHarnessInternal(url string, s stopper, t testing.TB) *Harness {
	replicaSet := ReplicaSet{
		Addrs:                   url,
		PortStart:               2000,
		PortEnd:                 3000,
		MaxConnections:          5,
		MinIdleConnections:      5,
		ServerIdleTimeout:       5 * time.Minute,
		ServerClosePoolSize:     5,
		ClientIdleTimeout:       5 * time.Minute,
		MaxPerClientConnections: 250,
		GetLastErrorTimeout:     5 * time.Minute,
		MessageTimeout:          time.Minute,
	}
	log := tLogger{TB: t}
	var graph inject.Graph
	err := graph.Provide(
		&inject.Object{Value: &log},
		&inject.Object{Value: &replicaSet},
		&inject.Object{Value: &stats.HookClient{}},
	)
	ensure.Nil(t, err)
	ensure.Nil(t, graph.Populate())
	objects := graph.Objects()
	ensure.Nil(t, startstop.Start(objects, &log))
	return &Harness{
		T:          t,
		Stopper:    s,
		ReplicaSet: &replicaSet,
		Graph:      &graph,
		Log:        &log,
	}
}
Exemple #24
0
func (p FBInjectInstanceInitializer) Initialize(instance interface{}, typeName string) (interface{}, error) {

	var g inject.Graph

	if err := g.Provide(&inject.Object{Value: instance}); err != nil {
		return nil, err
	}

	if entry := p.initializers[typeName]; entry != nil {
		for _, v := range entry.dependencies {
			resolved, e1 := godi.Resolve(v)
			if e1 != nil {
				return nil, e1
			}
			obj := inject.Object{Value: resolved}
			e2 := g.Provide(&obj)
			if e2 != nil {
				return nil, e2
			}
		}
	}

	// construct the instance.
	//
	if e3 := g.Populate(); e3 != nil {
		return nil, e3
	}
	return instance, nil
}
Exemple #25
0
func TestProvideTwoOfTheSame(t *testing.T) {
	var g inject.Graph
	a := TypeAnswerStruct{}
	err := g.Provide(&inject.Object{Value: &a})
	if err != nil {
		t.Fatal(err)
	}

	err = g.Provide(&inject.Object{Value: &a})
	if err == nil {
		t.Fatal("expected error")
	}

	const msg = "provided two unnamed instances of type *github.com/facebookgo/inject_test.TypeAnswerStruct"
	if err.Error() != msg {
		t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error())
	}
}
Exemple #26
0
func TestCompleteProvides() {
	var g inject.Graph
	var v struct {
		A *TypeAnswerStruct `inject:""`
		i int
	}

	if err := g.Provide(&inject.Object{Value: &v, Complete: true, Name: "foo"}); err != nil {
		fmt.Println(err)
	}

	if err := g.Populate(); err != nil {
		fmt.Println(err)
	}

	fmt.Println(v)

}
Exemple #27
0
func main() {
	dconf := distconf.New([]distconf.Reader{distconf.Env()})

	var graph inject.Graph
	var server app.Server

	if err := graph.Provide(
		&inject.Object{
			Value: &timekeeper.RealTime{},
		},
		&inject.Object{
			Value: log.DefaultLogger,
		},
		&inject.Object{
			Value: http.NewServeMux(),
		},
		&inject.Object{
			Value: &app.StrictCheck{
				Username: "******",
				Password: "******",
			},
		},
		&inject.Object{
			Value: dconf,
		},
		&inject.Object{
			Value: &server,
		},
	); err != nil {
		panic(err)
	}
	if err := graph.Populate(); err != nil {
		panic(err)
	}

	logger := server.Logger
	logger.Log("Setting up")
	if err := server.Setup(); err != nil {
		logger.Log("Cannot setup!")
		panic(err)
	}
	err := server.Start(context.Background())
	fmt.Println(err)
}
Exemple #28
0
func TestProvideTwoWithTheSameName(t *testing.T) {
	var g inject.Graph
	const name = "foo"
	a := TypeAnswerStruct{}
	err := g.Provide(&inject.Object{Value: &a, Name: name})
	if err != nil {
		t.Fatal(err)
	}

	err = g.Provide(&inject.Object{Value: &a, Name: name})
	if err == nil {
		t.Fatal("expected error")
	}

	const msg = "provided two instances named foo"
	if err.Error() != msg {
		t.Fatalf("expected:\n%s\nactual:\n%s", msg, err.Error())
	}
}
Exemple #29
0
func main() {
	// Typically an application will have exactly one object graph, and
	// you will create it and use it within a main function:
	var g inject.Graph

	// We provide our graph two "seed" objects, one our empty
	// HomePlanetRenderApp instance which we're hoping to get filled out,
	// and second our DefaultTransport to satisfiy our HTTPTransport
	// dependency. We have to provide the DefaultTransport because the
	// dependency is defined in terms of the http.RoundTripper interface,
	// and since it is an interface the library cannot create an instance
	// for it. Instead it will use the given DefaultTransport to satisfy
	// the dependency since it implements the interface:
	var a HomePlanetRenderApp
	err := g.Provide(
		&inject.Object{Value: &a},
		&inject.Object{Value: http.DefaultTransport},
	)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// Here the Populate call is creating instances of NameAPI &
	// PlanetAPI, and setting the HTTPTransport on both to the
	// http.DefaultTransport provided above:
	if err := g.Populate(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// There is a shorthand API for the simple case which combines the
	// three calls above is available as inject.Populate:
	//
	//   inject.Populate(&a, http.DefaultTransport)
	//
	// The above API shows the underlying API which also allows the use of
	// named instances for more complex scenarios.

	fmt.Println(a.Render(42))

	// Output: Spock is from the planet Vulcan.
}
Exemple #30
0
func TestForNamedWithUnnamed(t *testing.T) {
	var g inject.Graph
	var v TypeForNamedWithUnnamed

	err := g.Provide(
		&inject.Object{Value: &v, Name: "foo"},
	)
	if err != nil {
		t.Fatal(err)
	}
	if err := g.Populate(); err != nil {
		t.Fatal(err)
	}
	if v.TypeForNamedWithUnnamedDepFirst == nil {
		t.Fatal("expected TypeForNamedWithUnnamedDepFirst to be populated")
	}
	if v.TypeForNamedWithUnnamedDepFirst.TypeForNamedWithUnnamedDepSecond == nil {
		t.Fatal("expected TypeForNamedWithUnnamedDepSecond to be populated")
	}
}