Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mongo fixtures #227

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
52 changes: 49 additions & 3 deletions README-ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Gonkey протестирует ваши сервисы, используя их

- работает с REST/JSON API
- проверка API сервиса на соответствие OpenAPI-спеке
- заполнение БД сервиса данными из фикстур (поддерживается PostgreSQL, MySQL, Aerospike, Redis)
- заполнение БД сервиса данными из фикстур (поддерживается PostgreSQL, MySQL, Aerospike, Redis, MongoDB)
- моки для имитации внешних сервисов
- можно подключить к проекту как библиотеку и запускать вместе с юнит-тестами
- запись результата тестов в виде отчета [Allure](http://allure.qatools.ru/)
Expand Down Expand Up @@ -35,6 +35,7 @@ Gonkey протестирует ваши сервисы, используя их
- [Выражения](#выражения)
- [Aerospike](#aerospike)
- [Redis](#redis)
- [MongoDB](#mongodb)
- [Моки](#моки)
- [Запуск моков при использовании gonkey как библиотеки](#запуск-моков-при-использовании-gonkey-как-библиотеки)
- [Описание моков в файле с тестом](#описание-моков-в-файле-с-тестом)
Expand All @@ -53,17 +54,18 @@ Gonkey протестирует ваши сервисы, используя их

## Использование консольной утилиты

Для тестирование сервиса, размещенного на удаленном хосте, используйте gonkey как консольную утилиту.
Для тестирования сервиса, размещенного на удаленном хосте, используйте gonkey как консольную утилиту.

`./gonkey -host <...> -tests <...> [-spec <...>] [-db_dsn <...> -fixtures <...>] [-allure] [-v]`

- `-spec <...>` путь к файлу или URL со swagger-спецификацией сервиса
- `-host <...>` хост:порт сервиса
- `-tests <...>` файл или директория с тестами
- `-db-type <...>` - тип базы данных. В данный момент поддерживается PostgreSQL, Aerospike, Redis.
- `-db-type <...>` - тип базы данных. В данный момент поддерживается PostgreSQL, Aerospike, Redis, MongoDB.
- `-db_dsn <...>` dsn для вашей тестовой SQL базы данных (бд будет очищена перед наполнением!), поддерживается только PostgreSQL
- `-aerospike_host <...>` при использовании Aerospike - URL для подключения к нему в формате `host:port/namespace`
- `-redis_url <...>` при использовании Redis - адрес для подключения к Redis, например `redis://user:password@localhost:6789/1?dial_timeout=1&db=1&read_timeout=6s&max_retries=2`
- `-mongo_dsn <...>` при использовании MongoDB - URL для подключения в формате `mongodb://user:password@host:port`
- `-fixtures <...>` директория с вашими фикстурами
- `-allure` генерировать allure-отчет
- `-v` подробный вывод
Expand Down Expand Up @@ -876,6 +878,50 @@ databases:
value: value4
```

### MongoDB

Для того, чтобы подключить MongoDB необходимо:
- Для CLI-версии: использовать флаги `-db-type mongo` и `mongo_dsn { connectionString }`;
- Для Package-версии: при конфигурации раннера установить `DbType: fixtures.Mongo` и пробросить mongo клиент `Mongo: {mongo client}`.

Формат файлов с фикстурами для Mongo:
```yaml
collections:
collection1:
- field1: "value1"
field2: 1
- field1: "value2"
field2: 2
field3: 2.569947773654566
collection2:
- field4: false
field5: null
field1: '"'
- field1: "'"
field5:
- 1
- '2'
```

Если используются разные базы данных:

```yaml
collections:
database1.collection1:
- f1: value1
f2: value2

database2.collection2:
- f1: value3
f2: value4

collection3:
- f1: value5
f2: value6
```

Оператор `eval` не поддерживается.

## Моки

Чтобы для тестов имитировать ответы от внешних сервисов, применяются моки.
Expand Down
49 changes: 47 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Capabilities:

- works with REST/JSON API
- tests service API for compliance with OpenAPI-specs
- seeds the DB with fixtures data (supports PostgreSQL, MySQL, Aerospike, Redis)
- seeds the DB with fixtures data (supports PostgreSQL, MySQL, Aerospike, Redis, MongoDB)
- provides mocks for external services
- can be used as a library and ran together with unit-tests
- stores the results as an [Allure](http://allure.qatools.ru/) report
Expand Down Expand Up @@ -37,6 +37,7 @@ Capabilities:
- [Expressions](#expressions)
- [Aerospike](#aerospike)
- [Redis](#redis)
- [MongoDB](#mongodb)
- [Mocks](#mocks)
- [Running mocks while using gonkey as a library](#running-mocks-while-using-gonkey-as-a-library)
- [Mocks definition in the test file](#mocks-definition-in-the-test-file)
Expand All @@ -62,8 +63,9 @@ To test a service located on a remote host, use gonkey as a console util.
- `-spec <...>` path to a file or URL with the swagger-specs for the service
- `-host <...>` service host:port
- `-tests <...>` test file or directory
- `-db-type <...>` - database type. PostgreSQL, Aerospike, Redis are currently supported.
- `-db-type <...>` - database type. PostgreSQL, Aerospike, Redis, Mongo are currently supported.
- `-aerospike_host <...>` when using Aerospike - connection URL in a form of `host:port/namespace`
- `-mongo_dsn <...>` when using MongoDB - connection URL in a form of `mongodb://user:password@host:port`
- `-redis_url <...>` when using Redis - connection address, for example `redis://user:password@localhost:6789/1?dial_timeout=1&db=1&read_timeout=6s&max_retries=2`
- `-db_dsn <...>` DSN for the test DB (the DB will be cleared before seeding!), supports only PostgreSQL
- `-fixtures <...>` fixtures directory
Expand Down Expand Up @@ -879,6 +881,49 @@ databases:
value: value4
```

### MongoDB

To connect to MongoDB, you need to:
- For the CLI-version: use the flags -db-type mongo and mongo_dsn {connectionString};
- For the Package-version: when configuring the runner, set DbType: fixtures.Mongo and pass the MongoDB client as Mongo: {mongo client}.

The format of fixture files for MongoDB:
```yaml
collections:
collection1:
- field1: "value1"
field2: 1
- field1: "value2"
field2: 2
field3: 2.569947773654566
collection2:
- field4: false
field5: null
field1: '"'
- field1: "'"
field5:
- 1
- '2'
```

If you are using different databases:
```yaml
collections:
database1.collection1:
- f1: value1
f2: value2

database2.collection2:
- f1: value3
f2: value4

collection3:
- f1: value5
f2: value6
```

The `eval` operator is not supported.

## Mocks

In order to imitate responses from external services, use mocks.
Expand Down
13 changes: 13 additions & 0 deletions fixtures/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package fixtures

import (
"database/sql"
"github.com/lamoda/gonkey/fixtures/mongo"
mongoAdapter "github.com/lamoda/gonkey/storage/mongo"
"strings"

_ "github.com/lib/pq"
Expand All @@ -20,18 +22,21 @@ const (
Aerospike
Redis
CustomLoader // using external loader if gonkey used as a library
Mongo
)

const (
PostgresParam = "postgres"
MysqlParam = "mysql"
AerospikeParam = "aerospike"
RedisParam = "redis"
MongoParam = "mongo"
)

type Config struct {
DB *sql.DB
Aerospike *aerospikeClient.Client
Mongo *mongoAdapter.Client
DbType DbType
Location string
Debug bool
Expand Down Expand Up @@ -67,6 +72,12 @@ func NewLoader(cfg *Config) Loader {
location,
cfg.Debug,
)
case Mongo:
loader = mongo.New(
cfg.Mongo,
location,
cfg.Debug,
)
default:
if cfg.FixtureLoader != nil {
return cfg.FixtureLoader
Expand All @@ -87,6 +98,8 @@ func FetchDbType(dbType string) DbType {
return Aerospike
case RedisParam:
return Redis
case MongoParam:
return Mongo
default:
panic("unknown db type param")
}
Expand Down