Skip to content

Commit

Permalink
verify (#10)
Browse files Browse the repository at this point in the history
* Verify()
* Times()
* refactoring
* docs
  • Loading branch information
astrizhachuk authored Aug 10, 2020
1 parent 905d7eb commit bd4d7ee
Show file tree
Hide file tree
Showing 31 changed files with 1,340 additions and 159 deletions.
91 changes: 87 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@

That's all! Mock is created!

## Guidelines

[Getting Started](https://github.com/astrizhachuk/mockserver-client-1c/blob/master/docs/en/GettingStarted.md)

## Dependencies

The project built with:
Expand All @@ -45,3 +41,90 @@ Working with HTTP is implemented using the following libraries:

* [HTTPConnector](https://github.com/vbondarevsky/Connector)
* [HTTPStatusCodes](https://github.com/astrizhachuk/HTTPStatusCodes)

## Getting Started

[Overview](https://www.mock-server.com/mock_server/getting_started.html)

The typical sequence for using MockServer is as follows:

* [Start MockServer](#StartMockServer)
* [Create an instance of the client](#CreateInstance)
* [Setup Expectations](#SetupExpectations)
* Run Your Test Scenarios
* Verify Requests

### Start MockServer<a name="StartMockServer"></a>

[Running MockServer documentation](https://www.mock-server.com/mock_server/running_mock_server.html)

For example, start the MockServer docker container:

```bash
docker run -d --rm -p 1080:1080 --name mockserver-1c-integration mockserver/mockserver -logLevel DEBUG -serverPort 1080
```

Or run docker-compose.yml from root directory of the project:

```bash
docker-compose -f "docker-compose.yml" up -d --build
```

### Create an instance of the client<a name="CreateInstance"></a>

Connect to the default server:

```bash
Mock = DataProcessors.MockServerClient.Create();
```

Connect to the server at the specified host and port:

```bash
Mock = DataProcessors.MockServerClient.Create();
Mock = Mock.Server( "http://server" );
# or
Mock = DataProcessors.MockServerClient.Create();
Mock = Mock.Server( "http://server", "1099" );
```

Connect to the server at the specified host and port with a completely MockServer [reset](https://www.mock-server.com/mock_server/clearing_and_resetting.html):

```bash
Mock = DataProcessors.MockServerClient.Create();
Mock = Mock.Server( "http://server", "1099", True );
```

### Setup Expectations<a name="SetupExpectations"></a>

Setup expectation (and verify requests) consists of two stages: preparing conditions (json) and sending an action (PUT json).

There are two types of methods: **intermediate** (returns self-object) and **terminal** (perform action). Some object's methods as parameters can accept a reference to themselves or a json-format string. Before executing the action, a json will be auto-generated.

Use method chaining style (fluent interface):

```bash
# full json without auto-generating
Mock.Server( "localhost", "1080" )
.When( "{""name"":""value""}" )
.Respond();

# httpRequest property in json-style
Mock.Server( "localhost", "1080" )
.When(
Mock.Request( """name"":""value""" )
)
.Respond();

# combined style
Mock.Server( "localhost", "1080" )
.When(
Mock.Request()
.WithMethod( "GET" )
.WithPath( "some/path" )
)
.Respond(
Mock.Response( """statusCode"": 404" )
);

```
24 changes: 0 additions & 24 deletions docs/en/GettingStarted.md

This file was deleted.

Empty file removed docs/ru/GettingStarted.md
Empty file.
87 changes: 87 additions & 0 deletions docs/ru/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,90 @@

* [HTTPConnector](https://github.com/vbondarevsky/Connector)
* [HTTPStatusCodes](https://github.com/astrizhachuk/HTTPStatusCodes)

## Начало работы

[Руководство пользователя (англ.)](https://www.mock-server.com/mock_server/getting_started.html)

Обычная последовательность действий при работе с MockServer:

* [Запустить MockServer](#StartMockServer)
* [Создать экземпляр клиента](#CreateInstance)
* [Установить ожидаемое поведение](#SetupExpectations)
* Запустить тестовые сценарии
* Проверить запросы

### Запуск MockServer<a name="StartMockServer"></a>

[Документация по запуску MockServer](https://www.mock-server.com/mock_server/running_mock_server.html)

Пример запуска docker-контейнера с MockServer:

```bash
docker run -d --rm -p 1080:1080 --name mockserver-1c-integration mockserver/mockserver -logLevel DEBUG -serverPort 1080
```

Или запуск docker-compose.yml из корня текущего проекта:

```bash
docker-compose -f "docker-compose.yml" up -d --build
```

### Создание экземпляра клиента<a name="CreateInstance"></a>

Подключение к серверу по умолчанию:

```bash
Мок = Обработки.MockServerClient.Создать();
```

Подключение к серверу с некоторым адресом и портом подключения:

```bash
Мок = Обработки.MockServerClient.Создать();
Мок = Мок.Server( "http://server" );
# или
Мок = Обработки.MockServerClient.Создать();
Мок = Мок.Сервер( "http://server", "1099" );
```

Подключение к серверу с некоторым адресом и портом подключения с предварительной [очисткой](https://www.mock-server.com/mock_server/clearing_and_resetting.html) MockServer:

```bash
Мок = Обработки.MockServerClient.Создать();
Мок = Мок.Сервер( "http://server", "1099", Истина );
```

### Установка ожидания поведения<a name="SetupExpectations"></a>

Установка ожидания поведения (и проверка запросов) состоит из двух стадий: подготовка условий (в формате json) и выполнение действия для этих условий (отправка json на сервер).

Для клиента доступны два вида методов: **промежуточные** (возвращающие ссылки на объект клиента) и **терминальные** (выполняющие некоторое действие). некоторые методы принимать в качестве параметров как ссылки на клиент, так и строки в формате json. Перед отправкой действия на сервер предварительно будет сгенерирован json.

Текущая реализация клиента позволяет использовать вызовы методов в виде цепочки действий, завершающихся терминальной операцией (fluent interface):

```bash
# передача готового json без автоматической генерации
Мок.Сервер( "localhost", "1080" )
.Когда( "{""name"":""value""}" )
.Ответить();

# передача свойства httpRequest в json-формате
Мок.Server( "localhost", "1080" )
.Когда(
Мок.Запрос( """name"":""value""" )
)
.Ответить();

# комбинированный вариант
Мок.Сервер( "localhost", "1080" )
.Когда(
Мок.Запрос()
.Метод( "GET" )
.Путь( "some/path" )
)
.Ответить(
Мок.Ответ( """statusCode"": 404" )
);

```
37 changes: 36 additions & 1 deletion mockserver-client.Tests/features/all/Tests_CallWrapperRu.feature
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,39 @@ Scenario: WithReasonPhrase
@OnServer
Scenario: Respond
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.Respond(Context());' |
| 'Tests_CallWrapperRu.Respond(Context());' |

@OnServer
Scenario: Times
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.Times(Context());' |

@OnServer
Scenario: AtLeast
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.AtLeast(Context());' |

@OnServer
Scenario: AtMost
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.AtMost(Context());' |

@OnServer
Scenario: Exactly
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.Exactly(Context());' |

@OnServer
Scenario: Once
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.Once(Context());' |

@OnServer
Scenario: Between
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.Between(Context());' |

@OnServer
Scenario: Verify
And I execute 1C:Enterprise script at server
| 'Tests_CallWrapperRu.Verify(Context());' |
17 changes: 16 additions & 1 deletion mockserver-client.Tests/features/all/Tests_Integration.feature
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ Scenario: MockServerDockerUp
And I execute 1C:Enterprise script at server
| 'Tests_Integration.MockServerDockerUp(Context());' |

@OnServer
Scenario: ExpectationFail
And I execute 1C:Enterprise script at server
| 'Tests_Integration.ExpectationFail(Context());' |

@OnServer
Scenario: MatchRequestByPath
And I execute 1C:Enterprise script at server
Expand All @@ -26,4 +31,14 @@ Scenario: MatchRequestByQueryParameterWithRegexValue
@OnServer
Scenario: LiteralResponseWithStatusCodeAndReasonPhrase
And I execute 1C:Enterprise script at server
| 'Tests_Integration.LiteralResponseWithStatusCodeAndReasonPhrase(Context());' |
| 'Tests_Integration.LiteralResponseWithStatusCodeAndReasonPhrase(Context());' |

@OnServer
Scenario: VerifyRequestsReceivedAtLeastTwice
And I execute 1C:Enterprise script at server
| 'Tests_Integration.VerifyRequestsReceivedAtLeastTwice(Context());' |

@OnServer
Scenario: VerifyRequestsReceivedAtLeastTwiceFail
And I execute 1C:Enterprise script at server
| 'Tests_Integration.VerifyRequestsReceivedAtLeastTwiceFail(Context());' |
29 changes: 29 additions & 0 deletions mockserver-client.Tests/features/all/Tests_Times.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# language: en

@tree
@classname=ModuleExceptionPath

Feature: mockserver-client.Tests.Tests_Times
As Developer
I want the returns value to be equal to expected value
That I can guarantee the execution of the method

@OnServer
Scenario: TimesUndefinedConstructor
And I execute 1C:Enterprise script at server
| 'Tests_Times.TimesUndefinedConstructor(Context());' |

@OnServer
Scenario: TimesReInitWrongConstructor
And I execute 1C:Enterprise script at server
| 'Tests_Times.TimesReInitWrongConstructor(Context());' |

@OnServer
Scenario: TimesRequestExists
And I execute 1C:Enterprise script at server
| 'Tests_Times.TimesRequestExists(Context());' |

@OnServer
Scenario: TimesStringJson
And I execute 1C:Enterprise script at server
| 'Tests_Times.TimesStringJson(Context());' |
34 changes: 34 additions & 0 deletions mockserver-client.Tests/features/all/Tests_TimesMethods.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# language: en

@tree
@classname=ModuleExceptionPath

Feature: mockserver-client.Tests.Tests_TimesMethods
As Developer
I want the returns value to be equal to expected value
That I can guarantee the execution of the method

@OnServer
Scenario: AtLeast
And I execute 1C:Enterprise script at server
| 'Tests_TimesMethods.AtLeast(Context());' |

@OnServer
Scenario: AtMost
And I execute 1C:Enterprise script at server
| 'Tests_TimesMethods.AtMost(Context());' |

@OnServer
Scenario: Exactly
And I execute 1C:Enterprise script at server
| 'Tests_TimesMethods.Exactly(Context());' |

@OnServer
Scenario: Once
And I execute 1C:Enterprise script at server
| 'Tests_TimesMethods.Once(Context());' |

@OnServer
Scenario: Between
And I execute 1C:Enterprise script at server
| 'Tests_TimesMethods.Between(Context());' |
Loading

0 comments on commit bd4d7ee

Please sign in to comment.