Skip to content
This repository has been archived by the owner on Sep 3, 2024. It is now read-only.

Commit

Permalink
Merge pull request #365 from sbtqa/rest-remove-empties
Browse files Browse the repository at this point in the history
Remove empty objects
  • Loading branch information
clicman authored Nov 29, 2021
2 parents fd13eb2 + 431a338 commit e75c1be
Show file tree
Hide file tree
Showing 12 changed files with 123 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,10 @@
* @return path to template
*/
String template() default "";

/**
* Remove empty objects like "key":{} from template
* @return {@link Boolean}
*/
boolean shouldRemoveEmptyObjects() default false;
}
2 changes: 2 additions & 0 deletions page-factory-doc/src/main/asciidoc/rest-plugin.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ include::rest_build_request.asciidoc[]

include::rest_steps_en.asciidoc[]

include::rest_properties.asciidoc[]

=== SSL
Включить упрощенную схему работы с ssl можно следующим образом:
[source,]
Expand Down
1 change: 1 addition & 0 deletions page-factory-doc/src/main/asciidoc/rest_entries.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* `path` - путь, относительно заданного в `api.baseURI`
* `title` - имя метода для обращения из тестового сценария
* `template` - шаблон запроса
* `shouldRemoveEmptyObjects` - необходимо ли удалять пустые объекты в шаблоне
*__Пример:__*
[source,]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ public class ReplacerEntry extends EndpointEntry {

При этом подстановка в шаблон будет выполнена по соответствию параметра `name` аннотации `@Body` и значения, обозначенного через `${}`

Если необходимо из шаблона удалять пустые объекты вида `"key": { }`, то в конфигурационном файле необходимо указать параметр `api.template.remove.empties = true`

BodyArray используется для параметризации массивов. Элементы массива приводятся к одному типу.
Если надо в строковом типе поставить запятую, то она экранируется обратным слешем в фиче.

Expand Down
38 changes: 38 additions & 0 deletions page-factory-doc/src/main/asciidoc/rest_properties.asciidoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
=== Настройки проекта
[width="100%",options="header,footer"]
|====================
^.^| Параметр ^.^| Описание ^.^| Значение по умолчанию
| api.baseURI
| Базовый урл

Пример: https//localhost:8080
|

| api.endpoint.package
| Путь к Endpoint объектам

Пример: ru.qa.rest
|

| api.template.encoding
| Кодировка шаблона
| UTF-8

| api.ssl.relaxed
| Упрощенная схема работы с ssl

Возможные значения: true или false.
| false

| api.template.remove.optional
| Удалять опциональные параметры, которые после подстановки параметров в шаблон, остались с плейхолдером

Возможные значения: true или false.
| true

| api.template.remove.empties
| Удалять пустые вида "key": { } из шаблона

Возможные значения: true или false.
| false
|====================
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class EndpointEntry implements ApiEndpoint {
private String path;
private final String template;
private final String title;
private final boolean shouldRemoveEmptyObjects;

public EndpointEntry() {
Endpoint endpoint = this.getClass().getAnnotation(Endpoint.class);
Expand All @@ -48,6 +49,7 @@ public EndpointEntry() {
host = endpoint.host();
template = endpoint.template();
title = endpoint.title();
shouldRemoveEmptyObjects = endpoint.shouldRemoveEmptyObjects();

reflection = new EndpointEntryReflection(this);
blankStorage = ApiEnvironment.getBlankStorage();
Expand Down Expand Up @@ -151,10 +153,18 @@ private RequestSpecification buildRequest() {

public String getBody() {
String body = TemplateUtils.loadFromResources(this.getClass(), template, PROPERTIES.getTemplateEncoding());
Map<String, Object> parameters = getParameters();
if(template.endsWith(".json")) {
return PlaceholderUtils.replaceJsonTemplatePlaceholders(this.reflection.getEndpoint(), body, getParameters());
String result = PlaceholderUtils.replaceJsonTemplatePlaceholders(this.reflection.getEndpoint(), body, parameters);
if (PROPERTIES.shouldRemoveOptional()) {
result = PlaceholderUtils.removeOptionals(result, parameters);
}
if (PROPERTIES.shouldRemoveEmptyObjects() || shouldRemoveEmptyObjects) {
result = PlaceholderUtils.removeEmptyObjects(result);
}
return result;
} else {
return PlaceholderUtils.replaceTemplatePlaceholders(this.reflection.getEndpoint(), body, getParameters());
return PlaceholderUtils.replaceTemplatePlaceholders(this.reflection.getEndpoint(), body, parameters);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ public interface ApiConfiguration extends Config {
@DefaultValue("false")
boolean isSslRelaxed();

@Key("api.template.remove.optional")
@DefaultValue("true")
boolean shouldRemoveOptional();

@Key("api.template.remove.empties")
@DefaultValue("false")
boolean shouldRemoveEmptyObjects();

static ApiConfiguration create() {
return Configuration.init(ApiConfiguration.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,15 @@ public static String replaceJsonTemplatePlaceholders(EndpointEntry entry, String

}

return removeOptionals(jsonString, parameters);
return jsonString;
}

private static boolean isFieldExists(EndpointEntry entry, String fieldName) {
return FieldUtils.getAllFieldsList(entry.getClass()).stream()
.anyMatch(field -> field.getName().equals(fieldName));
}

private static String removeOptionals(String jsonString, Map<String, Object> parameters) {
public static String removeOptionals(String jsonString, Map<String, Object> parameters) {
Set<Map.Entry<String, Object>> optionals = parameters.entrySet().stream()
.filter(stringObjectEntry -> stringObjectEntry.getValue() == null)
.collect(Collectors.toSet());
Expand All @@ -109,6 +109,11 @@ private static String removeOptionals(String jsonString, Map<String, Object> par
return jsonString.replaceAll(orphanCommaRegex, "$2");
}

public static String removeEmptyObjects(String jsonString) {
String regex = "\"[\\w]+\"[\\s\\r\\n]*:[\\s\\r\\n]*\\{[\\s\\r\\n]*}[\\s\\r\\n,]*";
return jsonString.replaceAll(regex, "");
}

/**
* Replace placeholder in string on value
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package ru.sbtqa.tag.api.entries.template;

import ru.sbtqa.tag.api.EndpointEntry;
import ru.sbtqa.tag.api.annotation.Body;
import ru.sbtqa.tag.api.annotation.Header;
import ru.sbtqa.tag.api.annotation.Validation;
import ru.sbtqa.tag.pagefactory.Rest;
import ru.sbtqa.tag.pagefactory.annotations.rest.Endpoint;

import static org.hamcrest.Matchers.equalTo;

@Endpoint(method = Rest.POST, path = "client/typed-arrays", title = "empty objects", template = "templates/EmptyObjects.json", shouldRemoveEmptyObjects = true)
public class EmptyObjectsEntry extends EndpointEntry {

@Body(name = "first")
private String first;

@Validation(title = "result")
public void validate() {
String expected = "{ " +
"\"first\" : \"parameter\" }";
getResponse().body("result", equalTo(expected));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ public void validate() {
"}] }";
getResponse().body("result", equalTo(expected));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@ Feature: Test template placeholder replacing
| day1 | null |
| day11 | "null" |
* system returns "works correctly"

@empty-objects
Scenario: Test template placeholder replacing with empty objects
* user sends request for "empty objects" with parameters
| first | parameter |
* system returns "result"
16 changes: 16 additions & 0 deletions plugins/rest-plugin/src/test/resources/templates/EmptyObjects.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"minusOne": {

},
"zero": { },
"first": "${first}",
"second": { },
"third": {



},
"four": {}
, "fifth":{},"sixth":{},"seventh":
{ }
}

0 comments on commit e75c1be

Please sign in to comment.