예제 #1
0
func TestStringCSV(t *testing.T) {
	t.Parallel()
	wantPath := scope.StrDefault.FQPathInt64(0, "web/cors/exposed_headers")
	b := model.NewStringCSV(
		"web/cors/exposed_headers",
		model.WithConfigStructure(configStructure),
		model.WithSourceByString(
			"Content-Type", "Content Type", "X-CoreStore-ID", "CoreStore Microservice ID",
		),
	)

	assert.NotEmpty(t, b.Options())

	assert.Exactly(t, []string{"Content-Type", "X-CoreStore-ID"}, b.Get(config.NewMockGetter().NewScoped(0, 0, 0)))

	assert.Exactly(t, []string{"Content-Application", "X-Gopher"}, b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: "Content-Application,X-Gopher",
		}),
	).NewScoped(0, 0, 0)))

	mw := &config.MockWrite{}
	b.Source.Merge(source.NewByString("a", "a", "b", "b", "c", "c"))

	assert.NoError(t, b.Write(mw, []string{"a", "b", "c"}, scope.DefaultID, 0))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, "a,b,c", mw.ArgValue.(string))
}
예제 #2
0
func TestIntCSV(t *testing.T) {
	t.Parallel()
	defer debugLogBuf.Reset()
	defer infoLogBuf.Reset()

	b := model.NewIntCSV(
		"web/cors/int_slice",
		model.WithConfigStructure(configStructure),
		model.WithSourceByInt(source.Ints{
			{2014, "Year 2014"},
			{2015, "Year 2015"},
			{2016, "Year 2016"},
			{2017, "Year 2017"},
		}),
	)

	assert.Len(t, b.Options(), 4)

	assert.Exactly(t, []int{2014, 2015, 2016}, b.Get(config.NewMockGetter().NewScoped(0, 0, 4)))
	assert.Exactly(t, "web/cors/int_slice", b.String())

	wantPath := scope.StrStores.FQPathInt64(4, "web/cors/int_slice")
	assert.Exactly(t, []int{}, b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: "3015,3016",
		}),
	).NewScoped(0, 0, 4)))

	assert.Contains(t, debugLogBuf.String(), "The value '3015' cannot be found within the allowed Options")
	assert.Contains(t, debugLogBuf.String(), "The value '3016' cannot be found within the allowed Options")

	assert.Exactly(t, []int{2015, 2017}, b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: "2015,2017",
		}),
	).NewScoped(0, 0, 4)))

	mw := &config.MockWrite{}
	b.Source.Merge(source.NewByInt(source.Ints{
		{2018, "Year 2018"},
	}))
	assert.NoError(t, b.Write(mw, []int{2016, 2017, 2018}, scope.StoreID, 4))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, "2016,2017,2018", mw.ArgValue.(string))

	//t.Log("\n", debugLogBuf.String())

}
예제 #3
0
func TestWithValidateBaseUrl_ActivatedAndShouldNotRedirectWithPOSTRequest(t *testing.T) {

	mockReader := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			scope.StrDefault.FQPathInt64(0, backend.Backend.WebURLRedirectToBase.String()): 301,
		}),
	)

	w := httptest.NewRecorder()
	req, err := http.NewRequest(httputil.MethodGet, "http://corestore.io/catalog/product/view", nil)
	assert.NoError(t, err)

	mw := store.WithValidateBaseURL(mockReader)(finalHandlerWithValidateBaseURL(t))

	err = mw.ServeHTTPContext(context.Background(), w, req)
	assert.EqualError(t, err, store.ErrContextServiceNotFound.Error())

	w = httptest.NewRecorder()
	req, err = http.NewRequest(httputil.MethodPost, "http://corestore.io/catalog/product/view", strings.NewReader(`{ "k1": "v1",  "k2": { "k3": ["va1"]  }}`))
	assert.NoError(t, err)

	err = mw.ServeHTTPContext(context.Background(), w, req)
	assert.NoError(t, err)

}
예제 #4
0
func TestConfigRedirectToBase(t *testing.T) {
	defer debugLogBuf.Reset()
	t.Parallel()

	r := backend.NewConfigRedirectToBase(
		backend.Backend.WebURLRedirectToBase.String(),
		model.WithConfigStructure(backend.ConfigStructure),
	)

	cr := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			backend.Backend.WebURLRedirectToBase.FQPathInt64(scope.StrDefault, 0): 2,
		}),
	)

	code := r.Get(cr.NewScoped(0, 0, 0))
	assert.Exactly(t, 2, code)
	code = r.Get(cr.NewScoped(1, 1, 2))
	assert.Exactly(t, 0, code)

	// that is crap we should return an error
	assert.Contains(t, debugLogBuf.String(), "Scope permission insufficient: Have 'Store'; Want 'Default'")

	mw := new(config.MockWrite)
	assert.EqualError(t, r.Write(mw, 200, scope.DefaultID, 0),
		"Cannot find 200 in list: [{\"Value\":0,\"Label\":\"No\"},{\"Value\":1,\"Label\":\"Yes (302 Found)\"},{\"Value\":302,\"Label\":\"Yes (302 Found)\"},{\"Value\":301,\"Label\":\"Yes (301 Moved Permanently)\"}]\n",
	) // 200 not allowed

}
예제 #5
0
func TestScopedService(t *testing.T) {
	tests := []struct {
		desc                        string
		fqpath                      string
		path                        []string
		websiteID, groupID, storeID int64
		err                         error
	}{
		{
			"Default ScopedGetter should return default scope",
			scope.StrDefault.FQPath("0", "a/b/c"), []string{"a/b/c"}, 0, 0, 0, nil,
		},
		{
			"Website ID 1 ScopedGetter should fall back to default scope",
			scope.StrDefault.FQPath("0", "a/b/c"), []string{"a/b/c"}, 1, 0, 0, nil,
		},
		{
			"Website ID 10 + Group ID 12 ScopedGetter should fall back to website 10 scope",
			scope.StrWebsites.FQPath("10", "a/b/c"), []string{"a/b/c"}, 10, 12, 0, nil,
		},
		{
			"Website ID 10 + Group ID 12 + Store 22 ScopedGetter should fall back to website 10 scope",
			scope.StrWebsites.FQPath("10", "a/b/c"), []string{"a/b/c"}, 10, 12, 22, nil,
		},
		{
			"Website ID 10 + Group ID 12 + Store 22 ScopedGetter should return Store 22 scope",
			scope.StrStores.FQPath("22", "a/b/c"), []string{"a/b/c"}, 10, 12, 22, nil,
		},
		{
			"Website ID 10 + Group ID 12 + Store 42 ScopedGetter should return nothing",
			scope.StrStores.FQPath("22", "a/b/c"), []string{"a/b/c"}, 10, 12, 42, config.ErrKeyNotFound,
		},
		{
			"Path consists of only two elements which is incorrect",
			scope.StrDefault.FQPath("0", "a/b/c"), []string{"a", "b"}, 0, 0, 0, config.ErrPathEmpty,
		},
	}

	vals := []interface{}{"Gopher", true, float64(3.14159), int(2016), time.Now()}

	for vi, val := range vals {
		for _, test := range tests {

			cg := config.NewMockGetter(config.WithMockValues(config.MockPV{
				test.fqpath: val,
			}))

			sg := cg.NewScoped(test.websiteID, test.groupID, test.storeID)

			switch val.(type) {
			case string:
				s, err := sg.String(test.path...)
				testScopedService(t, s, test.desc, err, test.err)
			default:
				t.Fatalf("Unsupported type: %#v in index %d", val, vi)
			}
		}
	}
}
예제 #6
0
func TestContextMustGetter(t *testing.T) {
	mr := config.NewMockGetter()
	ctx := config.WithContextGetter(context.Background(), mr)
	mrHave := config.FromContextGetter(ctx)
	assert.Exactly(t, mr, mrHave)

	ctx = config.WithContextGetter(context.Background(), nil)
	mrHave = config.FromContextGetter(ctx)
	assert.Exactly(t, config.DefaultService, mrHave)
}
예제 #7
0
func TestFloat64(t *testing.T) {
	t.Parallel()
	wantPath := scope.StrWebsites.FQPathInt64(10, "web/cors/float64")
	b := model.NewFloat64("web/cors/float64", model.WithConfigStructure(configStructure))

	assert.Empty(t, b.Options())

	assert.Exactly(t, 2015.1000001, b.Get(config.NewMockGetter().NewScoped(0, 0, 0)))

	assert.Exactly(t, 2016.1000001, b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: 2016.1000001,
		}),
	).NewScoped(10, 0, 0)))

	mw := &config.MockWrite{}
	assert.NoError(t, b.Write(mw, 1.123456789, scope.WebsiteID, 10))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, "1.12345678900000", mw.ArgValue.(string))
}
예제 #8
0
func TestStr(t *testing.T) {
	t.Parallel()
	wantPath := scope.StrDefault.FQPathInt64(0, "web/cors/exposed_headers")
	b := model.NewStr("web/cors/exposed_headers", model.WithConfigStructure(configStructure))

	assert.Empty(t, b.Options())

	assert.Exactly(t, "Content-Type,X-CoreStore-ID", b.Get(config.NewMockGetter().NewScoped(0, 0, 0)))

	assert.Exactly(t, "X-Gopher", b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: "X-Gopher",
		}),
	).NewScoped(0, 0, 0)))

	mw := &config.MockWrite{}
	assert.NoError(t, b.Write(mw, "dude", scope.DefaultID, 0))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, "dude", mw.ArgValue.(string))
}
예제 #9
0
func TestBool(t *testing.T) {
	t.Parallel()
	wantPath := scope.StrWebsites.FQPathInt64(3, "web/cors/allow_credentials")
	b := model.NewBool("web/cors/allow_credentials", model.WithConfigStructure(configStructure), model.WithSource(source.YesNo))

	assert.Exactly(t, source.YesNo, b.Options())
	// because default value in packageConfiguration is "true"
	assert.True(t, b.Get(config.NewMockGetter().NewScoped(0, 0, 0)))

	assert.False(t, b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: 0,
		}),
	).NewScoped(0, 0, 3)))

	mw := &config.MockWrite{}
	assert.EqualError(t, b.Write(mw, true, scope.StoreID, 3), "Scope permission insufficient: Have 'Store'; Want 'Default,Website'")
	assert.NoError(t, b.Write(mw, true, scope.WebsiteID, 3))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, "true", mw.ArgValue.(string))
}
예제 #10
0
func TestContextMustGetterPubSuber(t *testing.T) {
	mr := config.NewMockGetter()
	ctx := config.WithContextGetterPubSuber(context.Background(), mr)
	mrHave, ok := config.FromContextGetterPubSuber(ctx)
	assert.Exactly(t, mr, mrHave)
	assert.True(t, ok)

	ctx = config.WithContextGetterPubSuber(context.Background(), nil)
	mrHave, ok = config.FromContextGetterPubSuber(ctx)
	assert.Nil(t, mrHave)
	assert.False(t, ok)
}
예제 #11
0
func TestBaseURL(t *testing.T) {
	t.Parallel()
	wantPath := scope.StrStores.FQPathInt64(1, "web/unsecure/base_url")
	b := model.NewBaseURL("web/unsecure/base_url", model.WithConfigStructure(configStructure))

	assert.Empty(t, b.Options())

	assert.Exactly(t, "{{base_url}}", b.Get(config.NewMockGetter().NewScoped(0, 0, 1)))

	assert.Exactly(t, "http://cs.io", b.Get(config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: "http://cs.io",
		}),
	).NewScoped(0, 0, 1)))

	mw := &config.MockWrite{}
	assert.NoError(t, b.Write(mw, "dude", scope.StoreID, 1))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, "dude", mw.ArgValue.(string))

}
예제 #12
0
func TestBasePathString(t *testing.T) {
	t.Parallel()
	const path = "web/cors/exposed_headers"
	p1 := NewPath(path, WithConfigStructure(configStructure))
	assert.Exactly(t, path, p1.String())

	wantPath := scope.StrWebsites.FQPathInt64(2, "web/cors/exposed_headers")
	wantWebsiteID := int64(2) // This number 2 is usually stored in core_website/store_website table in column website_id

	mw := new(config.MockWrite)
	assert.NoError(t, p1.Write(mw, 314159, scope.WebsiteID, wantWebsiteID))
	assert.Exactly(t, wantPath, mw.ArgPath)
	assert.Exactly(t, 314159, mw.ArgValue.(int))

	sg := config.NewMockGetter().NewScoped(wantWebsiteID, 0, 0)
	defaultStr, err := p1.lookupString(sg)
	assert.NoError(t, err)
	assert.Exactly(t, "Content-Type,X-CoreStore-ID", defaultStr)

	sg = config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			wantPath: "X-CoreStore-TOKEN",
		}),
	).NewScoped(wantWebsiteID, 0, 0)

	customStr, err := p1.lookupString(sg)
	assert.NoError(t, err)
	assert.Exactly(t, "X-CoreStore-TOKEN", customStr)

	// now change a default value in the packageConfiguration and see it reflects to p1
	f, err := configStructure.FindFieldByPath(path)
	assert.NoError(t, err)
	f.Default = "Content-Size,Y-CoreStore-ID"

	ws, err := p1.lookupString(config.NewMockGetter().NewScoped(wantWebsiteID, 0, 0))
	assert.NoError(t, err)
	assert.Exactly(t, "Content-Size,Y-CoreStore-ID", ws)
}
예제 #13
0
func TestPathGeneralCountryAllowDefault(t *testing.T) {
	t.Parallel()
	defer debugLogBuf.Reset()

	cr := config.NewMockGetter(
		config.WithMockValues(config.MockPV{}),
	)

	haveCountries := directory.Backend.GeneralCountryAllow.Get(cr.NewScoped(1, 1, 1))

	assert.Exactly(t,
		[]string{"AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AX", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BL", "BT", "BO", "BA", "BW", "BV", "BR", "IO", "VG", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CD", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CK", "CR", "HR", "CU", "CY", "CZ", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "GA", "GM", "GE", "DE", "GG", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GN", "GW", "GY", "HT", "HM", "HN", "HK", "HU", "IS", "IM", "IN", "ID", "IR", "IQ", "IE", "IL", "IT", "CI", "JE", "JM", "JP", "JO", "KZ", "KE", "KI", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "ME", "MF", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "FX", "MX", "FM", "MD", "MC", "MN", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "KP", "MP", "NO", "OM", "PK", "PW", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PS", "PT", "PR", "QA", "RE", "RO", "RS", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "GS", "KR", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TL", "TW", "TJ", "TZ", "TH", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "VI", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VA", "VE", "VN", "WF", "EH", "YE", "ZM", "ZW"},
		haveCountries,
	)
}
예제 #14
0
func TestBasePathInScope(t *testing.T) {
	t.Parallel()
	tests := []struct {
		sg      config.ScopedGetter
		p       scope.Perm
		wantErr error
	}{
		{
			config.NewMockGetter().NewScoped(0, 0, 0),
			scope.NewPerm(scope.DefaultID, scope.WebsiteID),
			nil,
		},
		{
			config.NewMockGetter().NewScoped(0, 0, 4),
			scope.NewPerm(scope.StoreID),
			nil,
		},
		{
			config.NewMockGetter().NewScoped(0, 4, 0),
			scope.NewPerm(scope.StoreID),
			errors.New("Scope permission insufficient: Have 'Group'; Want 'Store'"),
		},
	}
	for _, test := range tests {
		p1 := NewPath("a/b/c", WithField(&element.Field{
			Scope: test.p,
		}))
		haveErr := p1.InScope(test.sg)

		if test.wantErr != nil {
			assert.EqualError(t, haveErr, test.wantErr.Error())
		} else {
			assert.NoError(t, haveErr)
		}
	}
}
예제 #15
0
func TestWithValidateBaseUrl_DeactivatedAndShouldNotRedirectWithGETRequest(t *testing.T) {

	mockReader := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			scope.StrDefault.FQPathInt64(0, backend.Backend.WebURLRedirectToBase.String()): 0,
		}),
	)

	// no post request but check deactivated
	w := httptest.NewRecorder()
	req, err := http.NewRequest(httputil.MethodGet, "http://corestore.io/catalog/product/view", nil)
	assert.NoError(t, err)

	err = store.WithValidateBaseURL(mockReader)(finalHandlerWithValidateBaseURL(t)).ServeHTTPContext(context.Background(), w, req)
	assert.NoError(t, err)
}
예제 #16
0
func TestPasswordFromConfig(t *testing.T) {

	cfg := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			scope.StrDefault.FQPathInt64(ctxjwt.PathJWTPassword): `Rump3lst!lzch3n`,
		}),
	)

	jm, err := ctxjwt.NewService(
		ctxjwt.WithPasswordFromConfig(cfg),
	)
	assert.NoError(t, err)

	theToken, _, err := jm.GenerateToken(nil)
	assert.NoError(t, err)
	assert.NotEmpty(t, theToken)

}
예제 #17
0
func TestNewConfigCurrencyGet(t *testing.T) {
	t.Parallel()
	cc := directory.NewConfigCurrency(directory.Backend.CurrencyOptionsBase.String())

	cr := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			directory.Backend.CurrencyOptionsBase.FQPathInt64(scope.StrStores, 1): "EUR",
			directory.Backend.CurrencyOptionsBase.FQPathInt64(scope.StrStores, 2): "WIR", // Special Swiss currency
		}),
	)

	cur, err := cc.Get(cr.NewScoped(1, 1, 1))
	assert.NoError(t, err)
	assert.Exactly(t, directory.MustNewCurrencyISO("EUR"), cur)

	cur, err = cc.Get(cr.NewScoped(1, 1, 2))
	assert.EqualError(t, err, "currency: tag is not a recognized currency")
	assert.Exactly(t, directory.Currency{}, cur)
}
예제 #18
0
func TestPathCountryAllowedCustom(t *testing.T) {
	t.Parallel()
	defer debugLogBuf.Reset()

	previous := directory.Backend.GeneralCountryAllow.Option(model.WithSourceByString(
		"DE", "Germany", "AU", "'Straya", "CH", "Switzerland",
	))
	defer directory.Backend.GeneralCountryAllow.Option(previous)

	cr := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			directory.Backend.GeneralCountryAllow.FQPathInt64(scope.StrStores, 1): "DE,AU,CH,AT",
		}),
	)

	haveCountries := directory.Backend.GeneralCountryAllow.Get(cr.NewScoped(1, 1, 1))

	assert.Exactly(t, []string{"DE", "AU", "CH", "AT"}, haveCountries)
	// todo validation
}
예제 #19
0
func TestScopedServiceScope(t *testing.T) {
	tests := []struct {
		websiteID, groupID, storeID int64
		wantScope                   scope.Scope
		wantID                      int64
	}{
		{0, 0, 0, scope.DefaultID, 0},
		{1, 0, 0, scope.WebsiteID, 1},
		{1, 2, 0, scope.GroupID, 2},
		{1, 2, 3, scope.StoreID, 3},
		{0, 0, 3, scope.StoreID, 3},
		{0, 2, 0, scope.GroupID, 2},
	}
	for i, test := range tests {
		sg := config.NewMockGetter().NewScoped(test.websiteID, test.groupID, test.storeID)
		haveScope, haveID := sg.Scope()
		assert.Exactly(t, test.wantScope, haveScope, "Index %d", i)
		assert.Exactly(t, test.wantID, haveID, "Index %d", i)
	}
}
예제 #20
0
func TestHTTPRateLimitConfig(t *testing.T) {
	cr := config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			config.MockPathScopeDefault(ctxthrottled.PathRateLimitBurst):    0,
			config.MockPathScopeDefault(ctxthrottled.PathRateLimitRequests): 1,
			config.MockPathScopeDefault(ctxthrottled.PathRateLimitDuration): "i",
		}),
	)

	limiter := ctxthrottled.HTTPRateLimit{
		Config: cr,
		VaryBy: &pathGetter{},
	}

	handler := limiter.WithRateLimit(nil, ctxhttp.HandlerFunc(func(_ context.Context, w http.ResponseWriter, _ *http.Request) error {
		w.WriteHeader(200)
		return nil
	}))

	runHTTPTestCases(t, handler, []httpTestCase{
		{"xx", 200, map[string]string{"X-Ratelimit-Limit": "1", "X-Ratelimit-Remaining": "0", "X-Ratelimit-Reset": "60"}},
		{"xx", 429, map[string]string{"X-Ratelimit-Limit": "1", "X-Ratelimit-Remaining": "0", "X-Ratelimit-Reset": "60", "Retry-After": "60"}},
	})
}
예제 #21
0
func init() {
	middlewareConfigReader = config.NewMockGetter(
		config.WithMockValues(config.MockPV{
			scope.StrDefault.FQPathInt64(0, backend.Backend.WebURLRedirectToBase.String()):  1,
			scope.StrStores.FQPathInt64(1, backend.Backend.WebSecureUseInFrontend.String()): true,
			scope.StrStores.FQPathInt64(1, backend.Backend.WebUnsecureBaseURL.String()):     "http://www.corestore.io/",
			scope.StrStores.FQPathInt64(1, backend.Backend.WebSecureBaseURL.String()):       "https://www.corestore.io/",
		}),
	)

	middlewareCtxStoreService = storemock.WithContextMustService(
		scope.Option{},
		func(ms *storemock.Storage) {
			ms.MockStore = func() (*store.Store, error) {
				return store.NewStore(
					&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("euro"), Name: dbr.NewNullString("Europe"), SortOrder: 0, DefaultGroupID: 1, IsDefault: dbr.NewNullBool(true)},
					&store.TableGroup{GroupID: 1, WebsiteID: 1, Name: "DACH Group", RootCategoryID: 2, DefaultStoreID: 2},
					store.WithStoreConfig(middlewareConfigReader),
				)
			}
		},
	)
}
예제 #22
0
func TestStoreBaseURLandPath(t *testing.T) {
	defer debugLogBuf.Reset()

	s, err := store.NewStore(
		&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: 1},
	)
	assert.NoError(t, err)
	if s == nil {
		t.Fail()
	}

	tests := []struct {
		haveR        config.Getter
		haveUT       config.URLType
		haveIsSecure bool
		wantBaseUrl  string
		wantPath     string
	}{
		{
			config.NewMockGetter(config.WithMockString(
				func(path string) (string, error) {

					switch path {
					// scope is here store but config.ScopedGetter must fall back to default
					case backend.Backend.WebSecureBaseURL.FQPathInt64(scope.StrDefault, 0):
						return "https://corestore.io", nil
					case backend.Backend.WebUnsecureBaseURL.FQPathInt64(scope.StrDefault, 0):
						return "http://corestore.io", nil
					}
					return "", config.ErrKeyNotFound
				},
			)),
			config.URLTypeWeb, true, "https://corestore.io/", "/",
		},
		{
			config.NewMockGetter(config.WithMockString(
				func(path string) (string, error) {
					switch path {
					case backend.Backend.WebSecureBaseURL.FQPathInt64(scope.StrDefault, 0):
						return "https://myplatform.io/customer1", nil
					case backend.Backend.WebUnsecureBaseURL.FQPathInt64(scope.StrDefault, 0):
						return "http://myplatform.io/customer1", nil
					}
					return "", config.ErrKeyNotFound
				},
			)),
			config.URLTypeWeb, false, "http://myplatform.io/customer1/", "/customer1/",
		},
		{
			config.NewMockGetter(config.WithMockString(
				func(path string) (string, error) {
					switch path {
					case backend.Backend.WebSecureBaseURL.FQPathInt64(scope.StrDefault, 0):
						return model.PlaceholderBaseURL, nil
					case backend.Backend.WebUnsecureBaseURL.FQPathInt64(scope.StrDefault, 0):
						return model.PlaceholderBaseURL, nil
					case scope.StrDefault.FQPathInt64(0, config.PathCSBaseURL):
						return config.CSBaseURL, nil
					}
					return "", config.ErrKeyNotFound
				},
			)),
			config.URLTypeWeb, false, config.CSBaseURL, "/",
		},
	}

	for i, test := range tests {
		s.ApplyOptions(store.WithStoreConfig(test.haveR))
		assert.NotNil(t, s.Config, "Index %d", i)
		baseURL, err := s.BaseURL(test.haveUT, test.haveIsSecure)
		assert.NoError(t, err)
		assert.EqualValues(t, test.wantBaseUrl, baseURL.String())
		assert.EqualValues(t, test.wantPath, s.Path())

		_, err = s.BaseURL(config.URLTypeAbsent, false)
		assert.EqualError(t, err, config.ErrURLCacheCleared.Error())
	}
	t.Log(debugLogBuf.String()) // bug in config ScopedGetter
}