Skip to content

Commit

Permalink
chore: clean tests usage of endpoints (#158)
Browse files Browse the repository at this point in the history
* chore: clean tests usage of endpoints

Previously, once we hit the feature refresh interval, we saw failed
requests against https://localhost:4242, this update replaces all usages
in these tests with the gocked url instead of a fake localhost address

---------

Co-authored-by: Simon Hornby <[email protected]>
  • Loading branch information
Christopher Kolstad and sighphyre authored Dec 11, 2023
1 parent 6e71cb0 commit 34874e1
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 52 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ jobs:
matrix:
version: [1.13, 1.15, 1.16]
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
name: Checkout code
- uses: actions/checkout@v2
- uses: actions/checkout@v4
name: Checkout client specifications
with:
repository: Unleash/client-specification
ref: refs/tags/v5.1.0
path: testdata/client-specification
- uses: actions/setup-go@v2
- uses: actions/setup-go@v5
name: Setup go
with:
go-version: ${{ matrix.version }}
Expand Down
14 changes: 5 additions & 9 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,11 @@ func NewClient(options ...ConfigOption) (*Client, error) {
}()

if uc.options.url == "" {
return nil, fmt.Errorf("Unleash server URL missing")
return nil, fmt.Errorf("unleash server URL missing")
}

if strings.HasSuffix(uc.options.url, deprecatedSuffix) {
uc.warn(fmt.Errorf("Unleash server URL %s should no longer link directly to /features", uc.options.url))
uc.warn(fmt.Errorf("unleash server URL %s should no longer link directly to /features", uc.options.url))
uc.options.url = strings.TrimSuffix(uc.options.url, deprecatedSuffix)
}

Expand All @@ -148,7 +148,7 @@ func NewClient(options ...ConfigOption) (*Client, error) {
}

if uc.options.appName == "" {
return nil, fmt.Errorf("Unleash client appName missing")
return nil, fmt.Errorf("unleash client appName missing")
}

if uc.options.instanceId == "" {
Expand Down Expand Up @@ -358,7 +358,7 @@ func (uc *Client) isParentDependencySatisfied(feature *api.Feature, context cont

enabledResult := uc.isEnabled(parent.Feature, WithContext(context))
// According to the schema, if the enabled property is absent we assume it's true.
if parent.Enabled == nil || *parent.Enabled == true {
if parent.Enabled == nil || *parent.Enabled {
if parent.Variants != nil && len(*parent.Variants) > 0 && enabledResult.Variant != nil {
return enabledResult.Enabled && contains(*parent.Variants, enabledResult.Variant.Name)
}
Expand All @@ -372,11 +372,7 @@ func (uc *Client) isParentDependencySatisfied(feature *api.Feature, context cont
return dependenciesSatisfied(parent.(api.Dependency))
})

if !allDependenciesSatisfied {
return false
}

return true
return allDependenciesSatisfied
}

// GetVariant queries a variant as the specified feature is enabled.
Expand Down
26 changes: 2 additions & 24 deletions client_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package unleash

import (
"fmt"
"time"

"github.com/Unleash/unleash-client-go/v4/api"
Expand Down Expand Up @@ -35,23 +34,8 @@ func TestClientWithoutListener(t *testing.T) {
)
assert.Nil(err, "client should not return an error")

go func() {
for {
select {
case e := <-client.Errors():
t.Errorf("Unexpected error: %v", e)
return
case w := <-client.Warnings():
t.Errorf("Unexpected warning: %v", w)
return
case <-client.Count():
case <-client.Sent():
}
}
}()
<-client.Registered()
<-client.Ready()
client.Close()
err = client.Close()
assert.Nil(err)
assert.True(gock.IsDone(), "there should be no more mocks")
}

Expand Down Expand Up @@ -635,8 +619,6 @@ func TestClient_WithMultipleSegments(t *testing.T) {
assert.NoError(err)
client.WaitForReady()

fmt.Printf("%v", client.repository.segments)

isEnabled := client.IsEnabled(feature, WithContext(context.Context{
Properties: map[string]string{"custom-id": "custom-ctx", "semver": "3.2.2", "age": "18", "domain": "unleashtest"},
}))
Expand Down Expand Up @@ -752,8 +734,6 @@ func TestClient_VariantShouldRespectConstraint(t *testing.T) {
assert.NoError(err)
client.WaitForReady()

fmt.Printf("%v", client.repository.segments)

variant := client.GetVariant(feature, WithVariantContext(context.Context{
Properties: map[string]string{"custom-id": "custom-ctx", "semver": "3.2.2", "age": "18", "domain": "unleashtest"},
}))
Expand Down Expand Up @@ -869,8 +849,6 @@ func TestClient_VariantShouldFailWhenSegmentConstraintsDontMatch(t *testing.T) {
assert.NoError(err)
client.WaitForReady()

fmt.Printf("%v", client.repository.segments)

variant := client.GetVariant(feature, WithVariantContext(context.Context{
Properties: map[string]string{"custom-id": "custom-ctx", "semver": "3.2.2", "age": "18", "domain": "unleashtest"},
}))
Expand Down
33 changes: 26 additions & 7 deletions example_bootstrap_from_file_test.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,55 @@
package unleash_test

import (
"fmt"
"io/ioutil"
"os"
"testing"
"time"

"github.com/Unleash/unleash-client-go/v4"
"github.com/Unleash/unleash-client-go/v4/context"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)

func Test_bootstrapFromFile(t *testing.T) {
a := assert.New(t)
defer gock.OffAll()
demoReader, err := os.Open("demo_app_toggles.json")
if err != nil {
t.Fail()
}
gock.New("http://foo.com").
Post("/client/register").
Persist().
Reply(200)
// Read the file into a byte slice
featuresReader, err := os.Open("demo_app_toggles.json")
if err != nil {
t.Fail()
}
byteValue, _ := ioutil.ReadAll(featuresReader)
// Convert the byte slice to a string
jsonStr := string(byteValue)

// Use the string as the body of the Gock request
gock.New("http://foo.com").
Get("/client/features").Persist().Reply(200).BodyString(jsonStr)
err = unleash.Initialize(
unleash.WithListener(&unleash.DebugListener{}),
unleash.WithAppName("my-application"),
unleash.WithRefreshInterval(5*time.Second),
unleash.WithMetricsInterval(5*time.Second),
unleash.WithDisableMetrics(true),
unleash.WithStorage(&unleash.BootstrapStorage{Reader: demoReader}),
unleash.WithUrl("https://localhost:4242"),
unleash.WithUrl("http://foo.com"),
)

if err != nil {
t.Fail()
}

enabled := unleash.IsEnabled("DateExample", unleash.WithContext(context.Context{}))
fmt.Printf("feature is enabled? %v\n", enabled)
if enabled == false {
t.Fatalf("Expected feature to be enabled")
}
a.True(enabled)
err = unleash.Close()
a.Nil(err)
}
1 change: 1 addition & 0 deletions internal/strategies/flexible_rollout_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build norace
// +build norace

package strategies
Expand Down
2 changes: 1 addition & 1 deletion metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func TestMetrics_DoPost(t *testing.T) {
WithUrl(mockerServer),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
WithListener(&DebugListener{}),
)

assert.Nil(err, "client should not return an error")
Expand Down
64 changes: 56 additions & 8 deletions unleash_test.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,54 @@
package unleash_test

import (
"fmt"
"io/ioutil"
"os"
"testing"
"time"

"github.com/Unleash/unleash-client-go/v4"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)

func Test_withVariants(t *testing.T) {
a := assert.New(t)
demoReader, err := os.Open("demo_app_toggles.json")
if err != nil {
t.Fail()
}
defer gock.OffAll()
defer demoReader.Close()

gock.New("http://foo.com").
Post("/client/register").
Reply(200)

jsonStr, err := read_demo_app_toggles()
if err != nil {
t.Fail()
}

// Use the string as the body of the Gock request
gock.New("http://foo.com").
Get("/client/features").Reply(200).BodyString(jsonStr)
if err != nil {
t.Fail()
}
err = unleash.Initialize(
unleash.WithListener(&unleash.DebugListener{}),
unleash.WithAppName("my-application"),
unleash.WithRefreshInterval(5*time.Second),
unleash.WithMetricsInterval(5*time.Second),
unleash.WithDisableMetrics(true),
unleash.WithStorage(&unleash.BootstrapStorage{Reader: demoReader}),
unleash.WithUrl("https://localhost:4242"),
unleash.WithUrl("http://foo.com"),
)

if err != nil {
t.Fail()
}

feature := unleash.GetVariant("Demo")
fmt.Printf("feature is %v\n", feature)
if feature.Enabled == false {
t.Fatalf("Expected feature to be enabled")
}
Expand All @@ -38,36 +58,64 @@ func Test_withVariants(t *testing.T) {
if feature.Payload.Value != "35" && feature.Payload.Value != "55" {
t.Fatalf("Expected one of the variant payloads")
}
err = unleash.Close()
a.Nil(err)
}

func read_demo_app_toggles() (string, error) {
demoReader, err := os.Open("demo_app_toggles.json")
if err != nil {
return "", err
}
defer demoReader.Close()
byteValue, _ := ioutil.ReadAll(demoReader)
return string(byteValue), nil
}

func Test_withVariantsAndANonExistingStrategyName(t *testing.T) {
a := assert.New(t)
demoReader, err := os.Open("demo_app_toggles.json")
if err != nil {
t.Fail()
}
defer gock.OffAll()

gock.New("http://foo.com").
Post("/client/register").
Reply(200)
jsonStr, err := read_demo_app_toggles()
if err != nil {
t.Fail()
}

// Use the string as the body of the Gock request
gock.New("http://foo.com").
Get("/client/features").Reply(200).BodyString(jsonStr)
err = unleash.Initialize(
unleash.WithListener(&unleash.DebugListener{}),
unleash.WithAppName("my-application"),
unleash.WithRefreshInterval(5*time.Second),
unleash.WithMetricsInterval(5*time.Second),
unleash.WithRefreshInterval(20*time.Second),
unleash.WithDisableMetrics(true),
unleash.WithStorage(&unleash.BootstrapStorage{Reader: demoReader}),
unleash.WithUrl("https://localhost:4242"),
unleash.WithUrl("http://foo.com"),
)

if err != nil {
t.Fail()
}

feature := unleash.GetVariant("AuditLog")
fmt.Printf("feature is %v\n", feature)
if feature.Enabled == true {
t.Fatalf("Expected feature to be disabled because Environment does not exist as strategy")
}
err = unleash.Close()
a.Nil(err)
}

func Test_IsEnabledWithUninitializedClient(t *testing.T) {
result := unleash.IsEnabled("foo", unleash.WithFallback(true))
if !result {
t.Fatalf("Expected true")
}

}

0 comments on commit 34874e1

Please sign in to comment.