Skip to content

Commit

Permalink
Merge pull request #201 from Alexey19/register_mocks_as_env
Browse files Browse the repository at this point in the history
New: register mock address as environment variables
  • Loading branch information
fetinin committed Sep 6, 2023
2 parents 28c0f94 + 105b66c commit 933e759
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README-ru.md
Expand Up @@ -930,6 +930,8 @@ runner.RunWithTesting(t, &runner.RunWithTestingParams{
})
```

Дополнительно библиотека регистрирует специальные переменные окружения `GONKEY_MOCK_<ИМЯ_MOCK>`, которые содержат адрес и порт соответствующего мок-сервера. Эти переменные окружения вы можете использовать при написании тестов.

### Описание моков в файле с тестом

Каждый тест перед запуском сообщает мок-серверу конфигурацию, которая определяет, что мок-сервер ответит на тот или иной запрос. Эта конфигурация задается в YAML-файле с тестом в секции `mocks`.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -933,6 +933,8 @@ runner.RunWithTesting(t, &runner.RunWithTestingParams{
})
```

Additionally, the library registers special environment variables `GONKEY_MOCK_<MOCK_NAME>`, which contain the address and port of the corresponding mock server. You can use these environment variables when writing tests.

### Mocks definition in the test file

Each test communicates a configuration to the mock-server before running. This configuration defines the responses for specific requests in the mock-server. The configuration is defined in a YAML-file with test in the `mocks` section.
Expand Down
8 changes: 8 additions & 0 deletions mocks/mocks.go
Expand Up @@ -90,3 +90,11 @@ func (m *Mocks) EndRunningContext() []error {
}
return errors
}

func (m *Mocks) GetNames() []string {
names := []string{}
for n := range m.mocks {
names = append(names, n)
}
return names
}
11 changes: 11 additions & 0 deletions runner/runner_testing.go
Expand Up @@ -3,9 +3,11 @@ package runner
import (
"database/sql"
"errors"
"fmt"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"

"github.com/aerospike/aerospike-client-go/v5"
Expand Down Expand Up @@ -46,12 +48,21 @@ type RunWithTestingParams struct {
FixtureLoader fixtures.Loader
}

func registerMocksEnvironment(m *mocks.Mocks) {
names := m.GetNames()
for _, n := range names {
varName := fmt.Sprintf("GONKEY_MOCK_%s", strings.ToUpper(n))
os.Setenv(varName, m.Service(n).ServerAddr())
}
}

// RunWithTesting is a helper function the wraps the common Run and provides simple way
// to configure Gonkey by filling the params structure.
func RunWithTesting(t *testing.T, params *RunWithTestingParams) {
var mocksLoader *mocks.Loader
if params.Mocks != nil {
mocksLoader = mocks.NewLoader(params.Mocks)
registerMocksEnvironment(params.Mocks)
}

if params.EnvFilePath != "" {
Expand Down

0 comments on commit 933e759

Please sign in to comment.