Ejemplo n.º 1
0
func TestResourceFindPreHookError(t *testing.T) {
	var preHook, postHook, handler bool
	i := NewIndex()
	s := newTestMStorer()
	s.find = func(ctx context.Context, lookup *Lookup, page, perPage int) (*ItemList, error) {
		handler = true
		return nil, errors.New("storer error")
	}
	r := i.Bind("foo", schema.Schema{}, s, DefaultConf)
	r.Use(FindEventHandlerFunc(func(ctx context.Context, lookup *Lookup, page, perPage int) error {
		preHook = true
		return errors.New("pre hook error")
	}))
	r.Use(FoundEventHandlerFunc(func(ctx context.Context, lookup *Lookup, list **ItemList, err *error) {
		postHook = true
		assert.NotNil(t, lookup)
		assert.Nil(t, *list)
		assert.EqualError(t, *err, "pre hook error")
	}))
	ctx := context.Background()
	_, err := r.Find(ctx, NewLookup(), 1, 2)
	assert.EqualError(t, err, "pre hook error")
	assert.True(t, preHook)
	assert.False(t, handler)
	assert.True(t, postHook)
}
Ejemplo n.º 2
0
func TestDurationUnmarshal(t *testing.T) {
	var d Duration
	if assert.NoError(t, d.UnmarshalText([]byte("00:00:00"))) {
		assert.Equal(t, Duration(0), d)
	}
	d = 0
	if assert.NoError(t, d.UnmarshalText([]byte("00:00:02"))) {
		assert.Equal(t, Duration(2*time.Second), d)
	}
	d = 0
	if assert.NoError(t, d.UnmarshalText([]byte("00:02:00"))) {
		assert.Equal(t, Duration(2*time.Minute), d)
	}
	d = 0
	if assert.NoError(t, d.UnmarshalText([]byte("02:00:00"))) {
		assert.Equal(t, Duration(2*time.Hour), d)
	}
	d = 0
	if assert.NoError(t, d.UnmarshalText([]byte("00:00:00.123"))) {
		assert.Equal(t, Duration(123*time.Millisecond), d)
	}
	assert.EqualError(t, d.UnmarshalText([]byte("00:00:60")), "invalid duration: 00:00:60")
	assert.EqualError(t, d.UnmarshalText([]byte("00:60:00")), "invalid duration: 00:60:00")
	assert.EqualError(t, d.UnmarshalText([]byte("00:00:00.-1")), "invalid duration: 00:00:00.-1")
	assert.EqualError(t, d.UnmarshalText([]byte("00:00:00.1000")), "invalid duration: 00:00:00.1000")
	assert.EqualError(t, d.UnmarshalText([]byte("00h01m")), "invalid duration: 00h01m")
}
Ejemplo n.º 3
0
func TestPubSubBubbling(t *testing.T) {
	defer errLogBuf.Reset()
	testPath := "a/b/c"

	m := config.NewManager()

	_, err := m.Subscribe("", nil)
	assert.EqualError(t, err, config.ErrPathEmpty.Error())

	subID, err := m.Subscribe(testPath, &testSubscriber{
		f: func(path string, sg scope.Scope, id int64) error {
			assert.Equal(t, testPath, path)
			if sg == scope.DefaultID {
				assert.Equal(t, int64(0), id)
			} else {
				assert.Equal(t, int64(123), id)
			}
			return nil
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, 1, subID, "The very first subscription ID should be 1")

	assert.NoError(t, m.Write(config.Value(1), config.Path(testPath), config.Scope(scope.WebsiteID, 123)))

	assert.NoError(t, m.Close())
	time.Sleep(time.Millisecond * 10) // wait for goroutine to close

	// send on closed channel
	assert.NoError(t, m.Write(config.Value(1), config.Path(testPath+"Doh"), config.Scope(scope.WebsiteID, 3)))
	assert.EqualError(t, m.Close(), config.ErrPublisherClosed.Error())
}
Ejemplo n.º 4
0
func TestMustNewService(t *testing.T) {
	defer func() {
		if r := recover(); r != nil {
			assert.EqualError(t, r.(error), store.ErrStoreNotFound.Error())
		} else {
			t.Fatal("Expecting a Panic")
		}
	}()
	tests := []struct {
		have    scope.StoreIDer
		wantErr error
	}{
		{scope.MockCode("nilSlices"), store.ErrStoreNotFound},
		{scope.MockID(2), store.ErrStoreNotFound},
		{nil, store.ErrStoreNotFound},
	}
	serviceEmpty := storemock.MustNewService(scope.Option{})
	for _, test := range tests {
		s, err := serviceEmpty.Store(test.have)
		assert.Nil(t, s)
		assert.EqualError(t, test.wantErr, err.Error())
	}
	assert.True(t, serviceStoreSimpleTest.IsCacheEmpty())

}
Ejemplo n.º 5
0
func TestInstanceIDMetadata(t *testing.T) {

	var (
		ns *nilStruct
		ni nilInterface = ns
		i1 *InstanceID
	)

	i1 = &InstanceID{Driver: "vfs"}
	assert.Equal(t, "vfs=", i1.String())
	t.Logf("instanceID=%s", i1)

	assert.EqualError(
		t, i1.MarshalMetadata(nil), ErrIIDMetadataNilData.Error())
	assert.EqualError(
		t, i1.MarshalMetadata(ns), ErrIIDMetadataNilData.Error())
	assert.EqualError(
		t, i1.MarshalMetadata(ni), ErrIIDMetadataNilData.Error())
	assert.NoError(t, i1.MarshalMetadata(newMetadata()))
	assert.Equal(t, expectedI1NoIDString, i1.String())
	t.Logf("instanceID=%s", i1)

	actualMetadata := newMetadataCtor("", "", 0, nil)
	assert.EqualError(
		t, i1.UnmarshalMetadata(nil), ErrIIDMetadataNilDest.Error())
	assert.NoError(t, i1.UnmarshalMetadata(actualMetadata))

	actualBuf, _ := json.Marshal(actualMetadata)
	expectedBuf, _ := json.Marshal(newMetadata())
	assert.Equal(t, string(expectedBuf), string(actualBuf))
}
Ejemplo n.º 6
0
func TestParseInvalidS3Path(t *testing.T) {
	_, _, err := parseS3Path("s3://")
	assert.EqualError(t, err, "Invalid s3 path s3://")

	_, _, err = parseS3Path("s3://ag-ge")
	assert.EqualError(t, err, "Invalid s3 path s3://ag-ge")
}
Ejemplo n.º 7
0
func TestDefaultStoreView(t *testing.T) {
	st, err := testStorage.DefaultStoreView()
	assert.NoError(t, err)
	assert.EqualValues(t, "at", st.Data().Code.String)

	var tst = store.NewStorage(
		store.SetStorageWebsites(
			&store.TableWebsite{WebsiteID: 21, Code: dbr.NullString{NullString: sql.NullString{String: "oz", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "OZ", Valid: true}}, SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: false, Valid: true}}},
		),
		store.SetStorageGroups(
			&store.TableGroup{GroupID: 3, WebsiteID: 2, Name: "Australia", RootCategoryID: 2, DefaultStoreID: 5},
		),
		store.SetStorageStores(
			&store.TableStore{StoreID: 4, Code: dbr.NullString{NullString: sql.NullString{String: "au", Valid: true}}, WebsiteID: 2, GroupID: 3, Name: "Australia", SortOrder: 10, IsActive: true},
			&store.TableStore{StoreID: 6, Code: dbr.NullString{NullString: sql.NullString{String: "nz", Valid: true}}, WebsiteID: 2, GroupID: 3, Name: "Kiwi", SortOrder: 30, IsActive: true},
		),
	)
	dSt, err := tst.DefaultStoreView()
	assert.Nil(t, dSt)
	assert.EqualError(t, store.ErrStoreNotFound, err.Error())

	var tst2 = store.NewStorage(
		store.SetStorageWebsites(
			&store.TableWebsite{WebsiteID: 21, Code: dbr.NullString{NullString: sql.NullString{String: "oz", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "OZ", Valid: true}}, SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}},
		),
		store.SetStorageGroups(
			&store.TableGroup{GroupID: 33, WebsiteID: 2, Name: "Australia", RootCategoryID: 2, DefaultStoreID: 5},
		),
		store.SetStorageStores(),
	)
	dSt2, err := tst2.DefaultStoreView()
	assert.Nil(t, dSt2)
	assert.EqualError(t, store.ErrGroupNotFound, err.Error())
}
Ejemplo n.º 8
0
func TestNewManagerGetRequestStore_ScopeGroup(t *testing.T) {
	testOption := scope.Option{Group: scope.MockID(1)}
	testScope := scope.GroupID

	if haveStore, haveErr := storeManagerRequestStore.GetRequestStore(testOption, testScope); haveErr == nil {
		t.Error("appStore should not be set!")
		t.Fail()
	} else {
		assert.Nil(t, haveStore)
		assert.EqualError(t, store.ErrAppStoreNotSet, haveErr.Error())
	}

	assert.EqualError(t, store.ErrIDNotFoundTableGroupSlice, storeManagerRequestStore.Init(scope.Option{Group: scope.MockID(123)}).Error())
	if err := storeManagerRequestStore.Init(testOption); err != nil {
		t.Error(err)
		t.Fail()
	}
	assert.EqualError(t, store.ErrAppStoreSet, storeManagerRequestStore.Init(testOption).Error())

	if s, err := storeManagerRequestStore.Store(); err == nil {
		assert.EqualValues(t, "at", s.Data.Code.String)
	} else {
		assert.EqualError(t, err, store.ErrStoreNotFound.Error())
		t.Fail()
	}

	if g, err := storeManagerRequestStore.Group(); err == nil {
		assert.EqualValues(t, 1, g.Data.GroupID)
	} else {
		assert.EqualError(t, err, store.ErrStoreNotFound.Error())
		t.Fail()
	}

	// we're testing here against Group ID = 1
	tests := []testNewManagerGetRequestStore{
		{scope.Option{Group: scope.MockID(232)}, "", store.ErrIDNotFoundTableGroupSlice},
		{scope.Option{Store: scope.MockID(232)}, "", store.ErrIDNotFoundTableStoreSlice},
		{scope.Option{}, "", store.ErrUnsupportedScope},
		{scope.Option{Store: scope.MockCode("\U0001f631")}, "", store.ErrIDNotFoundTableStoreSlice},

		{scope.Option{Store: scope.MockID(6)}, "nz", store.ErrStoreChangeNotAllowed},
		{scope.Option{Store: scope.MockCode("ch")}, "", store.ErrStoreNotActive},

		{scope.Option{Store: scope.MockCode("de")}, "de", nil},
		{scope.Option{Store: scope.MockID(2)}, "at", nil},

		{scope.Option{Store: scope.MockID(2)}, "at", nil},
		{scope.Option{Store: scope.MockCode("au")}, "au", store.ErrStoreChangeNotAllowed},
		{scope.Option{Store: scope.MockCode("ch")}, "", store.ErrStoreNotActive},

		{scope.Option{Group: scope.MockCode("ch")}, "", store.ErrIDNotFoundTableGroupSlice},
		{scope.Option{Group: scope.MockID(2)}, "", store.ErrStoreChangeNotAllowed},
		{scope.Option{Group: scope.MockID(1)}, "at", nil},

		{scope.Option{Website: scope.MockCode("xxxx")}, "", store.ErrIDNotFoundTableWebsiteSlice},
		{scope.Option{Website: scope.MockID(2)}, "", store.ErrStoreChangeNotAllowed},
		{scope.Option{Website: scope.MockID(1)}, "at", nil},
	}
	runNewManagerGetRequestStore(t, scope.GroupID, tests)
}
Ejemplo n.º 9
0
func TestInitByRequestGeneral(t *testing.T) {
	errLogBuf.Reset()
	defer errLogBuf.Reset()

	for _, test := range testsInitByRequest {
		if _, haveErr := storeManagerRequestStore.InitByRequest(nil, nil, test.haveScopeType); haveErr != nil {
			assert.EqualError(t, store.ErrAppStoreNotSet, haveErr.Error())
		} else {
			t.Fatal("InitByRequest should return an error if used without running Init() first.")
		}

		if err := storeManagerRequestStore.Init(test.haveSO); err != nil {
			assert.EqualError(t, store.ErrUnsupportedScope, err.Error())
			t.Log("continuing for loop because of expected store.ErrUnsupportedScopeGroup")
			storeManagerRequestStore.ClearCache(true)
			continue
		}

		if s, err := storeManagerRequestStore.Store(); err == nil {
			assert.EqualValues(t, test.wantStoreCode, s.Data.Code.String)
		} else {
			assert.EqualError(t, err, store.ErrStoreNotFound.Error())
			t.Log("continuing for loop because of expected store.ErrStoreNotFound")
			storeManagerRequestStore.ClearCache(true)
			continue
		}
		storeManagerRequestStore.ClearCache(true)
	}
}
Ejemplo n.º 10
0
func TestExecRequestError(t *testing.T) {
	// Initialize
	c := 500

	// Create server
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(c)
	}))
	defer server.Close()

	// Create request set
	reqSet := NewRequestSet()

	// Create requests
	req1 := NewRequest("test1", MethodGet, server.URL)
	reqSet.AddRequest(req1)
	req2 := NewRequest("test2", MethodGet, "test")
	reqSet.AddRequest(req2)

	// Create gozzle
	g := NewGozzle()

	// Execute requests
	respSet := g.Exec(reqSet)

	// Assert
	assert.Len(t, respSet.Names(), 2)
	assert.Equal(t, c, respSet.GetResponse("test1").StatusCode())
	assert.Len(t, respSet.GetResponse("test1").Errors(), 1)
	assert.EqualError(t, respSet.GetResponse("test1").Errors()[0], ErrInvalidStatusCode.Error())
	assert.Len(t, respSet.GetResponse("test2").Errors(), 1)
	assert.EqualError(t, respSet.GetResponse("test2").Errors()[0], "Get test: unsupported protocol scheme \"\"")
}
Ejemplo n.º 11
0
func TestRouteBuildShouldError(t *testing.T) {
	router := DefaultRouter().RouteMap(
		NewRoute().Named("test").For("/people/{id:i}/details/{name}").With("GET", TestController{}.SimpleGet),
	)

	m1 := map[string]interface{}{
		"id":   65,
		"not":  "valid",
		"name": "Joe",
	}

	s1, err1 := router.Get("test").Build(m1)

	assert.EqualError(t, err1, "wrong number of parameters: 3 given, 2 required", "they should match")
	assert.Equal(t, "", s1, "they should match")

	m2 := map[string]interface{}{
		"id":  65,
		"not": "valid",
	}

	s2, err2 := router.Get("test").Build(m2)

	assert.EqualError(t, err2, "parameter not valid: not", "they should match")
	assert.Equal(t, "", s2, "they should match")
}
Ejemplo n.º 12
0
func TestResourceClearPreHookError(t *testing.T) {
	var preHook, postHook, handler bool
	i := NewIndex()
	s := newTestMStorer()
	s.clear = func(ctx context.Context, lookup *Lookup) (int, error) {
		handler = true
		return 0, errors.New("storer error")
	}
	r := i.Bind("foo", schema.Schema{}, s, DefaultConf)
	r.Use(ClearEventHandlerFunc(func(ctx context.Context, lookup *Lookup) error {
		preHook = true
		assert.NotNil(t, lookup)
		return errors.New("pre hook error")
	}))
	r.Use(ClearedEventHandlerFunc(func(ctx context.Context, lookup *Lookup, deleted *int, err *error) {
		postHook = true
		assert.NotNil(t, lookup)
		assert.EqualError(t, *err, "pre hook error")
	}))
	ctx := context.Background()
	_, err := r.Clear(ctx, NewLookup())
	assert.EqualError(t, err, "pre hook error")
	assert.True(t, preHook)
	assert.False(t, handler)
	assert.True(t, postHook)
}
Ejemplo n.º 13
0
func TestResourceDeletePreHookError(t *testing.T) {
	var preHook, postHook, handler bool
	i := NewIndex()
	s := newTestMStorer()
	s.delete = func(ctx context.Context, item *Item) error {
		handler = true
		return errors.New("storer error")
	}
	r := i.Bind("foo", schema.Schema{}, s, DefaultConf)
	r.Use(DeleteEventHandlerFunc(func(ctx context.Context, item *Item) error {
		preHook = true
		assert.Equal(t, &Item{ID: 1}, item)
		return errors.New("pre hook error")
	}))
	r.Use(DeletedEventHandlerFunc(func(ctx context.Context, item *Item, err *error) {
		postHook = true
		assert.Equal(t, &Item{ID: 1}, item)
		assert.EqualError(t, *err, "pre hook error")
	}))
	ctx := context.Background()
	err := r.Delete(ctx, &Item{ID: 1})
	assert.EqualError(t, err, "pre hook error")
	assert.True(t, preHook)
	assert.False(t, handler)
	assert.True(t, postHook)
}
Ejemplo n.º 14
0
func TestResourceInsertError(t *testing.T) {
	var preHook, postHook, handler bool
	i := NewIndex()
	s := newTestMStorer()
	s.insert = func(ctx context.Context, items []*Item) error {
		handler = true
		return errors.New("storer error")
	}
	r := i.Bind("foo", schema.Schema{}, s, DefaultConf)
	r.Use(InsertEventHandlerFunc(func(ctx context.Context, items []*Item) error {
		preHook = true
		assert.Equal(t, []*Item{{ID: 1}}, items)
		return nil
	}))
	r.Use(InsertedEventHandlerFunc(func(ctx context.Context, items []*Item, err *error) {
		postHook = true
		assert.Equal(t, []*Item{{ID: 1}}, items)
		assert.EqualError(t, *err, "storer error")
	}))
	ctx := context.Background()
	err := r.Insert(ctx, []*Item{{ID: 1}})
	assert.EqualError(t, err, "storer error")
	assert.True(t, preHook)
	assert.True(t, handler)
	assert.True(t, postHook)
}
Ejemplo n.º 15
0
func Test_Controller_Error(t *testing.T) {
	err := &Error{"TEST_ERROR", "Test error message"}
	assert.EqualError(t, err, "TEST_ERROR Test error message")

	err = NewError("TEST_ERROR", errors.New("Error message"))
	assert.EqualError(t, err, "TEST_ERROR Error message")
}
Ejemplo n.º 16
0
func TestStoreCodeFromClaimFullToken(t *testing.T) {
	s := store.MustNewStore(
		&store.TableStore{StoreID: 1, Code: dbr.NewNullString("de"), WebsiteID: 1, GroupID: 1, Name: "Germany", SortOrder: 10, IsActive: true},
		&store.TableWebsite{WebsiteID: 1, Code: dbr.NewNullString("admin"), Name: dbr.NewNullString("Admin"), SortOrder: 0, DefaultGroupID: 0, IsDefault: dbr.NewNullBool(false)},
		&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "Default", RootCategoryID: 0, DefaultStoreID: 0},
	)
	token := jwt.New(jwt.SigningMethodHS256)
	s.AddClaim(token.Claims)

	so, err := store.CodeFromClaim(token.Claims)
	assert.NoError(t, err)
	assert.EqualValues(t, "de", so.StoreCode())

	so, err = store.CodeFromClaim(nil)
	assert.EqualError(t, store.ErrStoreNotFound, err.Error())
	assert.Nil(t, so.Website)
	assert.Nil(t, so.Group)
	assert.Nil(t, so.Store)

	token2 := jwt.New(jwt.SigningMethodHS256)
	token2.Claims[store.ParamName] = "Invalid Cod€"
	so, err = store.CodeFromClaim(token2.Claims)
	assert.EqualError(t, store.ErrStoreCodeInvalid, err.Error())
	assert.Nil(t, so.Website)
	assert.Nil(t, so.Group)
	assert.Nil(t, so.Store)
}
Ejemplo n.º 17
0
func TestTableWebsiteSlice(t *testing.T) {
	websites := store.TableWebsiteSlice{
		&store.TableWebsite{WebsiteID: 0, Code: dbr.NewNullString("admin"), Name: dbr.NewNullString("Admin"), SortOrder: 0, DefaultGroupID: 0, IsDefault: dbr.NewNullBool(false)},
		&store.TableWebsite{WebsiteID: 1, Code: dbr.NewNullString("euro"), Name: dbr.NewNullString("Europe"), SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NewNullBool(true)},
		nil,
		&store.TableWebsite{WebsiteID: 2, Code: dbr.NewNullString("oz"), Name: dbr.NewNullString("OZ"), SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NewNullBool(false)},
	}
	assert.True(t, websites.Len() == 4)

	w1, err := websites.FindByWebsiteID(999)
	assert.Nil(t, w1)
	assert.EqualError(t, store.ErrIDNotFoundTableWebsiteSlice, err.Error())

	w2, err := websites.FindByWebsiteID(2)
	assert.NotNil(t, w2)
	assert.NoError(t, err)
	assert.Equal(t, int64(2), w2.WebsiteID)

	w3, err := websites.FindByCode("euro")
	assert.NotNil(t, w3)
	assert.NoError(t, err)
	assert.Equal(t, "euro", w3.Code.String)

	w4, err := websites.FindByCode("corestore")
	assert.Nil(t, w4)
	assert.EqualError(t, store.ErrIDNotFoundTableWebsiteSlice, err.Error())

	wf1 := websites.Filter(func(w *store.TableWebsite) bool {
		return w != nil && w.WebsiteID == 1
	})
	assert.EqualValues(t, "Europe", wf1[0].Name.String)
}
Ejemplo n.º 18
0
func TestStringValidator(t *testing.T) {
	s, err := String{}.Validate("foo")
	assert.NoError(t, err)
	assert.Equal(t, "foo", s)
	s, err = String{MaxLen: 2}.Validate("foo")
	assert.EqualError(t, err, "is longer than 2")
	assert.Nil(t, s)
	s, err = String{MaxLen: 4}.Validate("foo")
	assert.NoError(t, err)
	assert.Equal(t, "foo", s)
	s, err = String{MinLen: 4}.Validate("foo")
	assert.EqualError(t, err, "is shorter than 4")
	assert.Nil(t, s)
	s, err = String{MinLen: 2}.Validate("foo")
	assert.NoError(t, err)
	assert.Equal(t, "foo", s)
	s, err = String{Allowed: []string{"foo", "bar"}}.Validate("foo")
	assert.NoError(t, err)
	assert.Equal(t, "foo", s)
	s, err = String{Allowed: []string{"bar", "baz"}}.Validate("foo")
	assert.EqualError(t, err, "not one of [bar, baz]")
	assert.Nil(t, s)
	v := String{Regexp: "^f.o$"}
	assert.NoError(t, v.Compile())
	s, err = v.Validate("foo")
	assert.NoError(t, err)
	assert.Equal(t, "foo", s)
	v = String{Regexp: "^bar$"}
	assert.NoError(t, v.Compile())
	s, err = v.Validate("foo")
	assert.EqualError(t, err, "does not match ^bar$")
	assert.Nil(t, s)
	v = String{Regexp: "^bar["}
	assert.EqualError(t, v.Compile(), "invalid regexp: error parsing regexp: missing closing ]: `[`")
}
Ejemplo n.º 19
0
func Test_Controller_Set(t *testing.T) {
	repo, controller, mockTCPConn := setupControllerTest(t, 0)
	defer cleanupControllerTest(repo)

	command := []string{"set", "test", "0", "0", "10"}
	fmt.Fprintf(&mockTCPConn.ReadBuffer, "0123567890\r\n")

	err = controller.Set(command)
	assert.NoError(t, err)
	assert.Equal(t, "STORED\r\n", mockTCPConn.WriteBuffer.String())

	mockTCPConn.WriteBuffer.Reset()

	command = []string{"set", "test", "0", "1"}
	fmt.Fprintf(&mockTCPConn.ReadBuffer, "0\r\n")

	err = controller.Set(command)
	assert.EqualError(t, err, "CLIENT_ERROR Invalid command")

	mockTCPConn.WriteBuffer.Reset()

	command = []string{"set", "test", "0", "0", "invalid"}
	fmt.Fprintf(&mockTCPConn.ReadBuffer, "0123567890\r\n")

	err = controller.Set(command)
	assert.EqualError(t, err, "CLIENT_ERROR Invalid <bytes> number")

	mockTCPConn.WriteBuffer.Reset()

	command = []string{"set", "test", "0", "0", "10"}
	fmt.Fprintf(&mockTCPConn.ReadBuffer, "01235678901234567890\r\n")

	err = controller.Set(command)
	assert.Equal(t, "CLIENT_ERROR bad data chunk", err.Error())
}
Ejemplo n.º 20
0
func TestDaemonOffline(t *testing.T) {
	offSend := mail.OfflineSend
	defer func() {
		mail.OfflineSend = offSend
	}()

	mail.OfflineSend = func(from string, to []string, msg io.WriterTo) error {
		var buf bytes.Buffer
		_, err := msg.WriteTo(&buf)
		assert.NoError(t, err)
		assert.Equal(t, "gopher@world", from)
		assert.Equal(t, []string{"apple@cupertino"}, to)
		assert.Contains(t, buf.String(), "phoning home")
		assert.Contains(t, buf.String(), "Subject: Phoning home")
		return nil
	}

	dm, err := mail.NewDaemon()
	dm.Config = configMock
	dm.ScopeID = config.ScopeID(3001)

	assert.NoError(t, err)
	assert.NotNil(t, dm)
	assert.True(t, dm.IsOffline())

	go func() { assert.NoError(t, dm.Worker()) }()
	assert.NoError(t, dm.SendPlain("gopher@world", "apple@cupertino", "Phoning home", "Hey Apple stop phoning home or you become apple puree"))
	assert.NoError(t, dm.Stop())

	assert.EqualError(t, dm.Worker(), mail.ErrMailChannelClosed.Error())
	assert.EqualError(t, dm.Stop(), mail.ErrMailChannelClosed.Error())
	assert.EqualError(t, dm.Send(nil), mail.ErrMailChannelClosed.Error())
	assert.EqualError(t, dm.SendPlain("", "", "", ""), mail.ErrMailChannelClosed.Error())
	assert.EqualError(t, dm.SendHtml("", "", "", ""), mail.ErrMailChannelClosed.Error())
}
Ejemplo n.º 21
0
func Test_parseArgs_not_enough(t *testing.T) {
	_, err := parseArgs([]string{})
	assert.EqualError(t, err, "not enough arguments")

	_, err = parseArgs([]string{"1m"})
	assert.EqualError(t, err, "not enough arguments")
}
Ejemplo n.º 22
0
func TestIDJSONUnmarshalingError(t *testing.T) {
	v := jsonType{}
	err := json.Unmarshal([]byte(`{"ID":"TYjhW2D0huQoQS"}`), &v)
	assert.EqualError(t, err, "invalid ID")
	err = json.Unmarshal([]byte(`{"ID":"TYjhW2D0huQoQS3kdk"}`), &v)
	assert.EqualError(t, err, "invalid ID")
}
Ejemplo n.º 23
0
func TestPubSubBubbling(t *testing.T) {
	defer debugLogBuf.Reset()
	testPath := "a/b/c"

	s := config.NewService()

	_, err := s.Subscribe("", nil)
	assert.EqualError(t, err, config.ErrPathEmpty.Error())

	subID, err := s.Subscribe(testPath, &testSubscriber{
		f: func(path string, sg scope.Scope, id int64) error {
			assert.Equal(t, testPath, path)
			if sg == scope.DefaultID {
				assert.Equal(t, int64(0), id)
			} else {
				assert.Equal(t, int64(123), id)
			}
			return nil
		},
	})
	assert.NoError(t, err)
	assert.Equal(t, 1, subID, "The very first subscription ID should be 1")

	assert.NoError(t, s.Write(config.Value(1), config.Path(testPath), config.Scope(scope.WebsiteID, 123)))
	assert.NoError(t, s.Close())

	// send on closed channel
	assert.NoError(t, s.Write(config.Value(1), config.Path(testPath+"Doh"), config.Scope(scope.WebsiteID, 3)))
	assert.EqualError(t, s.Close(), config.ErrPublisherClosed.Error())
}
Ejemplo n.º 24
0
func TestNewManagerGroupInit(t *testing.T) {

	err := getTestManager(func(ms *mockStorage) {
		ms.g = func() (*store.Group, error) {
			return store.NewGroup(
				&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
				store.SetGroupWebsite(&store.TableWebsite{WebsiteID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "euro", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Europe", Valid: true}}, SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}}),
			), nil
		}
	}).Init(config.ScopeID(1), config.ScopeGroupID)
	assert.EqualError(t, store.ErrGroupDefaultStoreNotFound, err.Error(), "Incorrect DefaultStore for a Group")

	err = getTestManager().Init(config.ScopeID(21), config.ScopeGroupID)
	assert.EqualError(t, store.ErrGroupNotFound, err.Error())

	tm3 := getTestManager(func(ms *mockStorage) {
		ms.g = func() (*store.Group, error) {
			return store.NewGroup(
				&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
				store.SetGroupWebsite(&store.TableWebsite{WebsiteID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "euro", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Europe", Valid: true}}, SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}}),
			).SetStores(store.TableStoreSlice{
				&store.TableStore{StoreID: 2, Code: dbr.NullString{NullString: sql.NullString{String: "at", Valid: true}}, WebsiteID: 1, GroupID: 1, Name: "Österreich", SortOrder: 20, IsActive: true},
			}, nil), nil
		}
	})
	err = tm3.Init(config.ScopeID(1), config.ScopeGroupID)
	assert.NoError(t, err)
	g, err := tm3.Group()
	assert.NoError(t, err)
	assert.NotNil(t, g)
	assert.Equal(t, int64(2), g.Data.DefaultStoreID)
}
Ejemplo n.º 25
0
func TestDefaultStoreView(t *testing.T) {
	st, err := testStorage.DefaultStoreView()
	assert.NoError(t, err)
	assert.EqualValues(t, "at", st.Data.Code.String)

	var tst = store.MustNewStorage(
		store.SetStorageWebsites(
			&store.TableWebsite{WebsiteID: 21, Code: dbr.NewNullString("oz"), Name: dbr.NewNullString("OZ"), SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NewNullBool(false)},
		),
		store.SetStorageGroups(
			&store.TableGroup{GroupID: 3, WebsiteID: 2, Name: "Australia", RootCategoryID: 2, DefaultStoreID: 5},
		),
		store.SetStorageStores(
			&store.TableStore{StoreID: 4, Code: dbr.NewNullString("au"), WebsiteID: 2, GroupID: 3, Name: "Australia", SortOrder: 10, IsActive: true},
			&store.TableStore{StoreID: 6, Code: dbr.NewNullString("nz"), WebsiteID: 2, GroupID: 3, Name: "Kiwi", SortOrder: 30, IsActive: true},
		),
	)
	dSt, err := tst.DefaultStoreView()
	assert.Nil(t, dSt)
	assert.EqualError(t, store.ErrStoreNotFound, err.Error())

	var tst2 = store.MustNewStorage(
		store.SetStorageWebsites(
			&store.TableWebsite{WebsiteID: 21, Code: dbr.NewNullString("oz"), Name: dbr.NewNullString("OZ"), SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NewNullBool(true)},
		),
		store.SetStorageGroups(
			&store.TableGroup{GroupID: 33, WebsiteID: 2, Name: "Australia", RootCategoryID: 2, DefaultStoreID: 5},
		),
		store.SetStorageStores(),
	)
	dSt2, err := tst2.DefaultStoreView()
	assert.Nil(t, dSt2)
	assert.EqualError(t, store.ErrIDNotFoundTableGroupSlice, err.Error())
}
Ejemplo n.º 26
0
func TestTableWebsiteSlice(t *testing.T) {
	websites := store.TableWebsiteSlice{
		&store.TableWebsite{WebsiteID: 0, Code: dbr.NullString{NullString: sql.NullString{String: "admin", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Admin", Valid: true}}, SortOrder: 0, DefaultGroupID: 0, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: false, Valid: true}}},
		&store.TableWebsite{WebsiteID: 1, Code: dbr.NullString{NullString: sql.NullString{String: "euro", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "Europe", Valid: true}}, SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: true, Valid: true}}},
		nil,
		&store.TableWebsite{WebsiteID: 2, Code: dbr.NullString{NullString: sql.NullString{String: "oz", Valid: true}}, Name: dbr.NullString{NullString: sql.NullString{String: "OZ", Valid: true}}, SortOrder: 20, DefaultGroupID: 3, IsDefault: dbr.NullBool{NullBool: sql.NullBool{Bool: false, Valid: true}}},
	}
	assert.True(t, websites.Len() == 4)

	w1, err := websites.FindByID(999)
	assert.Nil(t, w1)
	assert.EqualError(t, store.ErrWebsiteNotFound, err.Error())

	w2, err := websites.FindByID(2)
	assert.NotNil(t, w2)
	assert.NoError(t, err)
	assert.Equal(t, int64(2), w2.WebsiteID)

	w3, err := websites.FindByCode("euro")
	assert.NotNil(t, w3)
	assert.NoError(t, err)
	assert.Equal(t, "euro", w3.Code.String)

	w4, err := websites.FindByCode("corestore")
	assert.Nil(t, w4)
	assert.EqualError(t, store.ErrWebsiteNotFound, err.Error())

	wf1 := websites.Filter(func(w *store.TableWebsite) bool {
		return w.WebsiteID == 1
	})
	assert.EqualValues(t, "Europe", wf1[0].Name.String)
}
Ejemplo n.º 27
0
func TestUpdateRedisMapReferenceRedisErrors(t *testing.T) {
	// should return error if redis does
	redigomock.Clear()
	redigomock.Command("GETSET", "map", "map:1").ExpectError(errors.New("redis error"))
	err := UpdateRedisMapReference(redigomock.NewConn(),
		Params{},
		MapConfig{
			Name:    "map",
			HashKey: "map:1",
		},
	)
	assert.EqualError(t, err, "redis error")

	redigomock.Clear()
	redigomock.Command("GETSET", "map", "map:1").Expect("map:0")
	redigomock.Command("DEL", "map:0").ExpectError(errors.New("redis error"))
	err = UpdateRedisMapReference(redigomock.NewConn(),
		Params{},
		MapConfig{
			Name:    "map",
			HashKey: "map:1",
		},
	)
	assert.EqualError(t, err, "redis error")

}
Ejemplo n.º 28
0
func TestURLCache(t *testing.T) {
	tests := []struct {
		haveType  config.URLType
		url       string
		wantError error
	}{
		{config.URLTypeStatic, "", config.ErrURLEmpty},
		{config.URLTypeWeb, "http://corestore.io/", nil},
		{config.URLTypeStatic, "://corestore.io/", errors.New("parse ://corestore.io/: missing protocol scheme")},
		{config.URLType(254), "https://corestore.io/catalog", errors.New("Unknown Index 254")},
	}
	for i, test := range tests {
		uc := config.NewURLCache()

		if test.wantError != nil {
			pu, err := uc.Set(test.haveType, test.url)
			assert.Nil(t, pu, "Index %d", i)
			assert.EqualError(t, err, test.wantError.Error(), "Index %d", i)
			assert.Nil(t, uc.Get(test.haveType))
			continue
		}

		pu, err := uc.Set(test.haveType, test.url) // pu = parsed URL
		assert.NoError(t, err, "Index %d", i)
		assert.Exactly(t, test.url, pu.String(), "Index %d", i)

		puCache := uc.Get(test.haveType)
		assert.Exactly(t, test.url, puCache.String(), "Index %d", i)

		assert.EqualError(t, uc.Clear(), config.ErrURLCacheCleared.Error())
		assert.Nil(t, uc.Get(test.haveType), "Index %d", i)
	}
}
func TestArrayItemsValidation(t *testing.T) {
	items := spec.NewItems().CollectionOf(stringItems, "").WithMinItems(1).WithMaxItems(5).UniqueValues()
	items.WithEnum("aaa", "bbb", "ccc")
	parent := spec.QueryParam("tags").CollectionOf(items, "")
	path := parent.Name + ".1"
	validator := newItemsValidator(parent.Name, parent.In, items, parent, strfmt.Default)

	// MinItems
	err := validator.Validate(1, []string{})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, minItemsErrorItems(path, validator.in, items), err.Errors[0].Error())
	// MaxItems
	err = validator.Validate(1, []string{"a", "b", "c", "d", "e", "f"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, maxItemsErrorItems(path, validator.in, items), err.Errors[0].Error())
	// UniqueItems
	err = validator.Validate(1, []string{"a", "a"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, duplicatesErrorItems(path, validator.in), err.Errors[0].Error())

	// Enum
	err = validator.Validate(1, []string{"a", "b", "c"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, enumFailItems(path, validator.in, items, []string{"a", "b", "c"}), err.Errors[0].Error())

	// Items
	strItems := spec.NewItems().WithMinLength(3).WithMaxLength(5).WithPattern(`^[a-z]+$`).Typed("string", "")
	items = spec.NewItems().CollectionOf(strItems, "").WithMinItems(1).WithMaxItems(5).UniqueValues()
	validator = newItemsValidator(parent.Name, parent.In, items, parent, strfmt.Default)

	err = validator.Validate(1, []string{"aa", "bbb", "ccc"})
	assert.True(t, err.HasErrors())
	assert.EqualError(t, minLengthErrorItems(path+".0", parent.In, strItems), err.Errors[0].Error())
}
Ejemplo n.º 30
0
func TestResourceMultiGetPreHookError(t *testing.T) {
	var preHook, postHook, handler int
	i := NewIndex()
	s := newTestMStorer()
	s.multiGet = func(ctx context.Context, ids []interface{}) ([]*Item, error) {
		handler++
		return nil, errors.New("storer error")
	}
	r := i.Bind("foo", schema.Schema{}, s, DefaultConf)
	r.Use(GetEventHandlerFunc(func(ctx context.Context, id interface{}) error {
		preHook++
		return errors.New("pre hook error")
	}))
	r.Use(GotEventHandlerFunc(func(ctx context.Context, item **Item, err *error) {
		postHook++
		assert.Nil(t, *item)
		assert.EqualError(t, *err, "pre hook error")
	}))
	ctx := context.Background()
	items, err := r.MultiGet(ctx, []interface{}{1, 1})
	assert.Len(t, items, 0)
	assert.EqualError(t, err, "pre hook error")
	assert.Equal(t, 2, preHook)
	assert.Equal(t, 0, handler)
	assert.Equal(t, 2, postHook)
}