Ejemplo n.º 1
0
func TestInterface(t *testing.T) {
	assert.Implements(t, (*loadbalancer.LoadBalancer)(nil), new(vulcan))
	assert.Implements(t, (*loadbalancer.Frontend)(nil), new(frontend))
	assert.Implements(t, (*loadbalancer.Backend)(nil), new(backend))
	assert.Implements(t, (*loadbalancer.Server)(nil), new(server))
	assert.Implements(t, (*loadbalancer.Middleware)(nil), new(middleware))
}
Ejemplo n.º 2
0
func TestTextRendererFactory_TestInterface(t *testing.T) {
	var inter *TextRendererFactory

	assert.Implements(t, inter, new(MarkdownTextRendererFactory))
	assert.Implements(t, inter, new(EscapeCodeRendererFactory))
	assert.Implements(t, inter, new(PlainRendererFactory))
}
Ejemplo n.º 3
0
func TestJSONStoreImplements(t *testing.T) {
	t.Parallel()

	j := new(JSONStore)
	assert.Implements(t, (*Storage)(nil), j)
	assert.Implements(t, (*TaskStore)(nil), j)
	assert.Implements(t, (*MetaStore)(nil), j)
	assert.Implements(t, (*MetaTaskStore)(nil), j)
}
Ejemplo n.º 4
0
func TestInboundsOrderIsMaintained(t *testing.T) {
	dispatcher := basicDispatcher(t)

	// Order must be maintained
	assert.Implements(t,
		(*tch.Inbound)(nil), dispatcher.Inbounds()[0], "first inbound must be TChannel")
	assert.Implements(t,
		(*http.Inbound)(nil), dispatcher.Inbounds()[1], "second inbound must be HTTP")
}
Ejemplo n.º 5
0
// TestGetMeRequest tests
func TestGetMeRequest(t *testing.T) {
	assert := assert.New(t)

	assert.Implements((*Parameter)(nil), new(GetMeRequest))
	assert.Implements((*RequestParameter)(nil), new(GetMeRequest))

	var p GetMeRequest
	p = GetMeRequest{}
	_ = p

}
Ejemplo n.º 6
0
func TestParserDiffStates(t *testing.T) {
	ps := testParseAll(
		t, "tpdifs01", "--time=37", "-nn", "-xplay", "-t", "47", "effie")

	testOpt := (*Option)(nil)
	testStrArr := []string{}

	psArgs := ps.Last()
	assert.NotNil(t, psArgs)
	assert.NotNil(t, psArgs.Value())
	assert.IsType(t, testStrArr, psArgs.Value())
	assert.Len(t, psArgs.Value(), 1)
	assert.Equal(t, "effie", psArgs.Value().([]string)[0])

	psT0 := ps.First()
	assert.NotNil(t, psT0)
	assert.NotNil(t, psT0.Value())
	assert.Implements(t, testOpt, psT0.Value())
	o := psT0.Value().(Option)
	assert.EqualValues(t, 't', o.Opt())
	assert.Equal(t, "37", o.Value())

	psN0, _ := psT0.Next()
	assert.NotNil(t, psN0)
	assert.NotNil(t, psN0.Value())
	assert.Implements(t, testOpt, psN0.Value())
	o = psN0.Value().(Option)
	assert.EqualValues(t, 'n', o.Opt())

	psN1, _ := psN0.Next()
	assert.NotNil(t, psN1)
	assert.NotNil(t, psN1.Value())
	assert.Implements(t, testOpt, psN1.Value())
	o = psN1.Value().(Option)
	assert.EqualValues(t, 'n', o.Opt())

	psX0, _ := psN1.Next()
	assert.NotNil(t, psX0)
	assert.NotNil(t, psX0.Value())
	assert.Implements(t, testOpt, psX0.Value())
	o = psX0.Value().(Option)
	assert.EqualValues(t, 'x', o.Opt())
	assert.Equal(t, "play", o.Value())

	psT1, _ := psX0.Next()
	assert.NotNil(t, psT1)
	assert.NotNil(t, psT1.Value())
	assert.Implements(t, testOpt, psT1.Value())
	o = psT1.Value().(Option)
	assert.EqualValues(t, 't', o.Opt())
	assert.Equal(t, "47", o.Value())
}
Ejemplo n.º 7
0
func TestAvgReducer(t *testing.T) {
	reducer := &Avg{[]string{"foo", "bar"}}
	assert.Implements(t, (*Reducer)(nil), reducer)

	// Prepare import channel
	input := make(chan *Entry, 2)
	input <- NewEntry(Fields{
		"uri": "/asd/fgh",
		"foo": "123",
		"bar": "234",
		"baz": "345",
	})
	input <- NewEntry(Fields{
		"uri": "/zxc/vbn",
		"foo": "456",
		"bar": "567",
		"baz": "678",
	})
	close(input)
	output := make(chan *Entry, 1) // Make it buffered to avoid deadlock
	reducer.Reduce(input, output)

	result, ok := <-output
	assert.True(t, ok)
	value, err := result.FloatField("foo")
	assert.NoError(t, err)
	assert.Equal(t, value, (123.0+456)/2.0)
	value, err = result.FloatField("bar")
	assert.NoError(t, err)
	assert.Equal(t, value, (234.0+567.0)/2.0)
	_, err = result.Field("buz")
	assert.Error(t, err)
}
Ejemplo n.º 8
0
func TestCreateAndCloseLogger(t *testing.T) {
	tf, err := ioutil.TempFile("", "")
	require.Nil(t, err)

	c := &Config{
		Logger: struct {
			Output, Formatter, Level string
			LogFile                  string `mapstructure:"log_file"`
		}{
			Output:    "both",
			Formatter: "json",
			Level:     "info",
			LogFile:   tf.Name(),
		},
	}

	l, err := NewLogger(c)
	require.Nil(t, err)

	assert.Equal(t, c, l.config)
	assert.Equal(t, tf.Name(), l.file.Name())
	assert.Implements(t, (*io.Writer)(nil), l.Out)
	assert.IsType(t, new(log.JSONFormatter), l.Formatter)
	assert.Equal(t, log.InfoLevel, l.Level)

	_, err = l.file.Stat()
	assert.Nil(t, err)

	l.Close()

	_, err = l.file.Stat()
	assert.NotNil(t, err)
}
Ejemplo n.º 9
0
func TestWatchError(t *testing.T) {
	t.Parallel()
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		flusher, ok := w.(http.Flusher)
		require.True(t, ok, "streaming unsupported")

		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		flusher.Flush()
	}))

	var (
		notifications = make(chan Event)
		fb            = New(server.URL)
	)
	defer server.Close()

	if err := fb.Watch(notifications); err != nil {
		t.Fatal(err)
	}

	go server.Close()
	event, ok := <-notifications
	require.True(t, ok, "notifications closed")
	assert.Equal(t, EventTypeError, event.Type, "event type doesn't match")
	assert.Empty(t, event.Path, "event path is not empty")
	assert.NotNil(t, event.Data, "event data is nil")
	assert.Implements(t, new(error), event.Data)
}
Ejemplo n.º 10
0
func TestThenFuncNil(t *testing.T) {
	assert := assert.New(t)
	assert.NotPanics(func() {
		final := New().ThenFunc(nil)
		assert.Implements((*http.Handler)(nil), final)
	})
}
Ejemplo n.º 11
0
func TestNewStorm(t *testing.T) {
	db, err := Open("")

	assert.Error(t, err)
	assert.Nil(t, db)

	dir, err := ioutil.TempDir(os.TempDir(), "storm")
	assert.NoError(t, err)
	defer os.RemoveAll(dir)

	file := filepath.Join(dir, "storm.db")
	db, err = Open(file)
	defer db.Close()

	assert.Implements(t, (*Node)(nil), db)

	assert.NoError(t, err)
	assert.Equal(t, file, db.Path)
	assert.NotNil(t, db.Bolt)
	assert.Equal(t, defaultCodec, db.Codec())

	var v string
	err = db.Get(dbinfo, "version", &v)
	assert.NoError(t, err)
	assert.Equal(t, Version, v)
}
Ejemplo n.º 12
0
// TestFoundationRequest runs
func TestFoundationRequest(t *testing.T) {
	assert := assert.New(t)

	var ctx Context = NewContext(gintest.SharedContext())
	o := ctx.Request()
	assert.NotNil(o)
	assert.Implements((*Request)(nil), o)
	assert.NotPanics(func() {
		orgReq := (ctx.(*FoundationContext)).opt.Request
		clnReq := o.Clone()
		assert.NotEqual(fmt.Sprintf("%p", orgReq), fmt.Sprintf("%p", clnReq), "Shouldn't be equal.")
		assert.Equal(orgReq, clnReq, "Should be the same contained object")
		assert.False(o.RequestedAt().IsZero())
		assert.Equal([]byte(""), o.Body())
		assert.Equal([]byte(""), o.Body())
		assert.Equal("/", o.URL().String())
		assert.Equal("GET", o.Method())
		assert.Equal(url.Values{}, o.Query())

		ipAddr := o.ClientIP()
		assert.True(strings.HasPrefix(ipAddr, "127.0.0.1") || strings.HasPrefix(ipAddr, "[::1]"))
		assert.Equal("Go-http-client/1.1", o.UserAgent())
		assert.Equal("", o.Header("foobar"), "Doesn't exist a value of the key")
		assert.Equal(o.UserAgent(), o.Header("User-Agent"), "Doesn't exist a value of the key")

		// X-Forwarded-For
		(ctx.(*FoundationContext)).opt.Request.Header.Set("X-Forwarded-For", "10.0.0.1")
		assert.True(strings.HasPrefix(o.ClientIP(), "10.0.0.1"))

		// X-Real-Ip
		(ctx.(*FoundationContext)).opt.Request.Header.Set("X-Real-Ip", "10.0.0.2")
		assert.True(strings.HasPrefix(o.ClientIP(), "10.0.0.2"))
	})
}
Ejemplo n.º 13
0
// TestEngine runs
func TestEngine(t *testing.T) {
	assert := assert.New(t)

	var engine *Engine
	assert.Nil(engine)

	engine = New()
	assert.NotNil(engine)

	engine = Default()
	assert.NotNil(engine)

	Middlewares = []Middleware{
		RecoveryMiddleware(),
		RecoveryMiddleware(),
	}
	engine = Default()
	assert.NotNil(engine)

	assert.NotNil(engine.Static("", ""))
	assert.Panics(func() {
		engine.LoadHTMLGlob("", "")
	})

	handler := func(c *gin.Context) {}
	assert.NotNil(engine.Group("/test", handler))
	assert.Implements((*IRoutes)(nil), engine.POST("/test/post", handler))
	assert.Panics(func() {
		// panic: path segment '/' conflicts with existing wildcard '/*filepath' in path '/'
		engine.GET("/test/get", handler)
	})
	assert.Implements((*IRoutes)(nil), engine.DELETE("/test/delete", handler))
	assert.Implements((*IRoutes)(nil), engine.PATCH("/test/patch", handler))
	assert.Implements((*IRoutes)(nil), engine.PUT("/test/put", handler))

	go func() {
		assert.NoError(engine.Run(":8123"))
	}()
	go func() {
		// Because: no such file or directory
		assert.Error(engine.RunTLS(":8133", "cert", "key"))
	}()
	go func() {
		assert.NoError(engine.RunUnix("/tmp/unix.sock"))
	}()
	time.Sleep(100 * time.Millisecond)
}
Ejemplo n.º 14
0
// TestFoundationResponse runs
func TestFoundationResponse(t *testing.T) {
	assert := assert.New(t)

	var ctx Context = NewContext(gintest.SharedContext())
	o := ctx.Response()
	assert.NotNil(o)
	assert.Implements((*Response)(nil), o)
}
Ejemplo n.º 15
0
func TestThenFuncNoMiddleware(t *testing.T) {
	assert := assert.New(t)
	assert.NotPanics(func() {
		chain := New()
		final := chain.ThenFunc(handlerOne)
		assert.Implements((*http.Handler)(nil), final)
	})
}
Ejemplo n.º 16
0
// TestPaginationRequest tests
func TestPaginationRequest(t *testing.T) {
	assert := assert.New(t)

	assert.Implements((*PaginationParameter)(nil), new(PaginationRequest))
	var paging PaginationRequest
	assert.Error(paging.Validate())
	assert.NoError(DefaultPaginationRequest.Validate())
}
Ejemplo n.º 17
0
// TestFoundationSession runs
func TestFoundationSession(t *testing.T) {
	assert := assert.New(t)

	var ctx Context = NewContext(gintest.SharedContext())
	o := ctx.Session()
	assert.NotNil(o)
	assert.Implements((*Session)(nil), o)
}
Ejemplo n.º 18
0
func TestEtcdBackend(t *testing.T) {
	s, er := NewEtcdStore([]string{"bad:/url"}, 5*time.Second)
	assert.Error(t, err, "EtcdStore")
	s, er = NewEtcdStore([]string{"http://127.0.0.1:2379"}, 2*time.Second)
	assert.NoError(t, er, "EtcdStore")
	assert.Implements(t, (*Store)(nil), new(EtcdStore), "EtcdStore")
	testImplementation(t, s)
}
Ejemplo n.º 19
0
func TestImplementations(t *testing.T) {
	es := []interface{}{
		new(DataCenterCapabilities),
		new(Server),
		new(Credentials),
		new(Status),
	}
	for _, e := range es {
		assert.Implements(t, (*Entity)(nil), e)
	}

	ses := []interface{}{
		new(Server),
		new(PublicIPAddress),
	}
	for _, se := range ses {
		assert.Implements(t, (*SavableEntity)(nil), se)
	}
}
Ejemplo n.º 20
0
// TestFoundationOperation runs
func TestFoundationOperation(t *testing.T) {
	assert := assert.New(t)

	var ctx Context = NewContext(gintest.SharedContext())
	o := ctx.Operation()
	assert.NotNil(o)
	assert.Implements((*Operation)(nil), o)
	assert.NotPanics(func() {
		o.Next()
	})
}
Ejemplo n.º 21
0
// TestFoundationRender runs
func TestFoundationRender(t *testing.T) {
	assert := assert.New(t)

	var ctx Context = NewContext(gintest.SharedContext())
	o := ctx.Render()
	assert.NotNil(o)
	assert.Implements((*Render)(nil), o)
	assert.NotPanics(func() {
		o.JSON(200, map[string]string{"foo": "bar"})
		o.HTML(200, "index", map[string]string{"foo": "bar"})
	})
}
Ejemplo n.º 22
0
func TestDatetimeReduce(t *testing.T) {
	filter := &Datetime{
		Field:  "timestamp",
		Format: time.RFC3339,
		Start:  time.Date(2015, time.February, 2, 2, 2, 2, 0, time.UTC),
		End:    time.Date(2015, time.May, 5, 5, 5, 5, 0, time.UTC),
	}
	assert.Implements(t, (*Reducer)(nil), filter)

	// Prepare input channel
	input := make(chan *Entry, 5)
	input <- NewEntry(Fields{
		"timestamp": "2015-01-01T01:01:01Z",
		"foo":       "12",
	})
	input <- NewEntry(Fields{
		"timestamp": "2015-02-02T02:02:02Z",
		"foo":       "34",
	})
	input <- NewEntry(Fields{
		"timestamp": "2015-03-03T03:03:03Z",
		"foo":       "56",
	})
	input <- NewEntry(Fields{
		"timestamp": "2015-04-04T04:04:04Z",
		"foo":       "78",
	})
	input <- NewEntry(Fields{
		"timestamp": "2015-05-05T05:05:05Z",
		"foo":       "90",
	})
	close(input)

	output := make(chan *Entry, 5) // Make it buffered to avoid deadlock
	filter.Reduce(input, output)

	expected := []string{
		"'timestamp'=2015-02-02T02:02:02Z;'foo'=34",
		"'timestamp'=2015-03-03T03:03:03Z;'foo'=56",
		"'timestamp'=2015-04-04T04:04:04Z;'foo'=78",
	}
	results := []string{}

	for result := range output {
		results = append(
			results,
			result.FieldsHash([]string{"timestamp", "foo"}),
		)
	}
	assert.Equal(t, results, expected)
}
Ejemplo n.º 23
0
func TestHandlerFunc(t *testing.T) {
	assert := assert.New(t)
	assert.NotPanics(func() {
		ctx := context.Background()
		r, _ := http.NewRequest("GET", "http://github.com/", nil)
		w := httptest.NewRecorder()

		handler := HandlerFunc(handlerOne)
		assert.Implements((*Handler)(nil), handler)

		handler.ServeHTTP(ctx, w, r)
		assert.Equal(w.Code, 200)
		assert.Equal(w.Body.String(), "h1\n")
	})
}
Ejemplo n.º 24
0
func (suite *DialectTestSuite) TestDefaultDialect() {
	assert.Implements(suite.T(), (*Compiler)(nil), suite.def.GetCompiler())
	assert.Equal(suite.T(), false, suite.def.SupportsUnsigned())
	assert.Equal(suite.T(), "test", suite.def.Escape("test"))
	assert.Equal(suite.T(), false, suite.def.Escaping())
	suite.def.SetEscaping(true)
	assert.Equal(suite.T(), true, suite.def.Escaping())
	assert.Equal(suite.T(), "`test`", suite.def.Escape("test"))
	assert.Equal(suite.T(), []string{"`test`"}, suite.def.EscapeAll([]string{"test"}))
	assert.Equal(suite.T(), "", suite.def.Driver())

	autoincCol := Column("id", Int()).PrimaryKey().AutoIncrement()
	assert.Equal(suite.T(),
		"INT PRIMARY KEY AUTO INCREMENT",
		suite.def.AutoIncrement(&autoincCol))

}
Ejemplo n.º 25
0
func TestParserCountAndIndex(t *testing.T) {

	payloads := []*testParserCountAndIndexData{
		&testParserCountAndIndexData{
			Argv:    []string{"--time=37", "-nn", "effie"},
			Count:   2,
			Indices: []int{1, 2},
		},
		&testParserCountAndIndexData{
			Argv:    []string{"-n", "-nnn", "--time=37", "effie"},
			Count:   4,
			Indices: []int{0, 1, 2, 3},
		},
		&testParserCountAndIndexData{
			Argv:    []string{"--name", "--time=37", "effie", "-nnn", "--name"},
			Count:   5,
			Indices: []int{0, 2, 3, 4, 5},
		},
		&testParserCountAndIndexData{
			Argv:    []string{"effie", "-nnn", "-nnnt", "37"},
			Count:   6,
			Indices: []int{0, 1, 2, 3, 4, 5},
		},
	}

	testOpt := (*Option)(nil)
	pp := 0

	for x, td := range payloads {
		assert.Equal(t, td.Count, len(td.Indices), "td.Count == len(td.Indices)")
		argv := []string{fmt.Sprintf("tpctidx0%d", x)}
		argv = append(argv, td.Argv...)
		ps := testParseAll(t, argv...)
		fps := ps.LookupOpt('n')
		assert.Equal(t, td.Count, len(fps), "Count")
		for y, fpsi := range fps {
			assert.Implements(t, testOpt, fpsi.Value())
			o := fpsi.Value().(Option)
			assert.Equal(t, td.Indices[y], fpsi.Index(), "ParserState.Index")
			assert.Equal(t, y, o.Index(), "Option.Index")
		}
		pp++
	}

	assert.Equal(t, 4, pp)
}
Ejemplo n.º 26
0
func TestReadAllReducer(t *testing.T) {
	reducer := new(ReadAll)
	assert.Implements(t, (*Reducer)(nil), reducer)

	// Prepare import channel
	input := make(chan *Entry, 1)
	entry := NewEmptyEntry()
	input <- entry
	close(input)

	output := make(chan *Entry, 1) // Make it buffered to avoid deadlock
	reducer.Reduce(input, output)

	// ReadAll reducer writes input channel to the output
	result, ok := <-output
	assert.True(t, ok)
	assert.Equal(t, result, entry)
}
Ejemplo n.º 27
0
func TestCountReducer(t *testing.T) {
	reducer := new(Count)
	assert.Implements(t, (*Reducer)(nil), reducer)

	// Prepare import channel
	input := make(chan *Entry, 2)
	input <- NewEmptyEntry()
	input <- NewEmptyEntry()
	close(input)

	output := make(chan *Entry, 1) // Make it buffered to avoid deadlock
	reducer.Reduce(input, output)

	result, ok := <-output
	assert.True(t, ok)
	count, err := result.Field("count")
	assert.NoError(t, err)
	assert.Equal(t, count, "2")
}
Ejemplo n.º 28
0
func TestDatetimeFilter(t *testing.T) {
	filter := &Datetime{
		Field:  "timestamp",
		Format: time.RFC3339,
		Start:  time.Date(2015, time.February, 2, 2, 2, 2, 0, time.UTC),
		End:    time.Date(2015, time.May, 5, 5, 5, 5, 0, time.UTC),
	}
	assert.Implements(t, (*Filter)(nil), filter)

	entry := NewEntry(Fields{
		"timestamp": "2015-01-01T01:01:01Z",
	})
	assert.Nil(t, filter.Filter(entry))

	entry = NewEntry(Fields{
		"timestamp": "2015-02-02T02:02:02Z",
	})
	assert.Equal(t, filter.Filter(entry), entry)
}
Ejemplo n.º 29
0
func TestDatetimeFilterEnd(t *testing.T) {
	// filter contains upper border only
	filter := &Datetime{
		Field:  "timestamp",
		Format: time.RFC3339,
		End:    time.Date(2015, time.May, 5, 5, 5, 5, 0, time.UTC),
	}
	assert.Implements(t, (*Filter)(nil), filter)

	entry := NewEntry(Fields{
		"timestamp": "2015-01-01T01:01:01Z",
	})
	assert.Equal(t, filter.Filter(entry), entry)

	entry = NewEntry(Fields{
		"timestamp": "2015-05-05T05:05:05Z",
	})
	assert.Nil(t, filter.Filter(entry))
}
Ejemplo n.º 30
0
// TestFoundationContext runs
func TestFoundationContext(t *testing.T) {
	assert := assert.New(t)

	assert.Implements((*Context)(nil), new(FoundationContext))
	var ctx Context = NewContext(gintest.SharedContext())
	{
		tm, ok := ctx.Deadline()
		assert.True(tm.IsZero())
		assert.False(ok)
	}
	{
		assert.Nil(ctx.Done())
	}
	{
		assert.Nil(ctx.Err())
	}
	{
		assert.Nil(ctx.Value(""))
	}
}