Compare commits

...

34 Commits

Author SHA1 Message Date
Travis CI User
909e95685e [maven-release-plugin][skip ci] prepare release v1.112 2022-08-15 13:29:39 +00:00
krdabrowski
91e7b0d66f ACS-3353: POST support for "other fields" (#231)
Fix for equals method.
2022-08-15 14:25:15 +01:00
Travis CI User
cc40cf05a9 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-12 12:03:07 +00:00
Travis CI User
4629c20b51 [maven-release-plugin][skip ci] prepare release v1.111 2022-08-12 12:03:05 +00:00
krdabrowski
ee88946b1c ACS-3353: POST support for "other fields" (#230)
ACS-3353: POST support for "other fields"
- adding method `isEqualTo()` allowing assertion of whole model with different model.
2022-08-12 13:58:46 +02:00
Travis CI User
b1faf15806 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-12 09:33:07 +00:00
Travis CI User
367ad20fb7 [maven-release-plugin][skip ci] prepare release v1.110 2022-08-12 09:33:05 +00:00
Tom Page
80e770f2da ACS-3358 Support isShared in rules API. (#229)
* ACS-3358 Automatically include any unused RestWrapper parameters in the request.

* ACS-3358 Remove unnecessary calls to RestWrapper.getParameters() from rules methods.

* ACS-3358 Move request logging to point of use.

* ACS-3358 Support isShared in rules API.
2022-08-12 10:28:33 +01:00
Tom Page
e8cf525792 ACS-3358 Automatically include extra params. (#228)
* ACS-3358 Automatically include any unused RestWrapper parameters in the request.

* ACS-3358 Remove unnecessary calls to RestWrapper.getParameters() from rules methods.

* ACS-3358 Move request logging to point of use.
2022-08-12 10:28:02 +01:00
Travis CI User
a594341bb5 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-11 09:05:46 +00:00
Travis CI User
058e8d6302 [maven-release-plugin][skip ci] prepare release v1.109 2022-08-11 09:05:44 +00:00
Tom Page
91fcbb0b59 ACS-3358 We no longer need to explicitly give the "?". (#227) 2022-08-11 10:01:17 +01:00
Travis CI User
830898c605 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-10 14:52:23 +00:00
Travis CI User
d214040bc8 [maven-release-plugin][skip ci] prepare release v1.108 2022-08-10 14:52:21 +00:00
Tom Page
1b071cb555 ACS-3358 Refactor ModelRequest to cope with more parameters than tokens in the URL. (#224)
For example we can now pass include parameters without having to update the URL to have a "?" in the test code.
2022-08-10 15:47:46 +01:00
Travis CI User
37e04ee2fc [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-10 10:45:05 +00:00
Travis CI User
10f32aa74c [maven-release-plugin][skip ci] prepare release v1.107 2022-08-10 10:45:03 +00:00
Tom Page
bea386ddc8 ACS-3358 Support specifying include. (#223)
* ACS-3358 Better support when specifying includes.

* ACS-3358 Add unit tests for RestWrapper.withParams().

* ACS-3358 Refactor RestWrapper.withParams().

* ACS-3358 Add unit tests for ModelRequest.
2022-08-10 11:40:45 +01:00
Travis CI User
2449d1d8f3 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-10 10:02:03 +00:00
Travis CI User
3883fd22e3 [maven-release-plugin][skip ci] prepare release v1.106 2022-08-10 10:02:01 +00:00
Tom Page
183ac4c7cd ACS-3358 Remove demo tests. (#222)
These were only intended to demonstrate how to use the TAS library.

Also make tests run against all branches.
2022-08-10 10:58:00 +01:00
Travis CI User
fa1b8d46dd [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-10 08:45:04 +00:00
Travis CI User
df35137d12 [maven-release-plugin][skip ci] prepare release v1.105 2022-08-10 08:45:02 +00:00
Damian Ujma
1d1b454978 ACS-3351 Upgrade to Java 17 (#219) 2022-08-10 10:36:45 +02:00
Travis CI User
deaee78d09 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-09 12:09:27 +00:00
Travis CI User
9e3c144a7d [maven-release-plugin][skip ci] prepare release v1.104 2022-08-09 12:09:24 +00:00
Tom Page
d0b100a88b ACS-3361 Support for inclusionType. (#221) 2022-08-09 13:05:51 +01:00
Travis CI User
9d807242ee [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-09 11:21:44 +00:00
Travis CI User
5f2b5fe9af [maven-release-plugin][skip ci] prepare release v1.103 2022-08-09 11:21:43 +00:00
Marcin Strankowski
7edee67997 Move all versions under the rest-assured.version, update it to 5.1.1 (#220) 2022-08-09 13:17:55 +02:00
Travis CI User
5f151aaa96 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-08 14:20:54 +00:00
Travis CI User
dcf25d89d0 [maven-release-plugin][skip ci] prepare release v1.102 2022-08-08 14:20:51 +00:00
Tom Page
7d5aafecb5 ACS-3362 Add owningFolder field to rule set. (#218)
* ACS-3362 Add owningFolder field to rule set.

* ACS-3362 Allow passing include param.
2022-08-08 15:17:29 +01:00
Travis CI User
1d8f1bd8a2 [maven-release-plugin][skip ci] prepare for next development iteration 2022-08-05 13:58:04 +00:00
24 changed files with 818 additions and 624 deletions

View File

@@ -2,18 +2,12 @@ dist: focal
sudo: required
language: java
jdk:
- openjdk11
- openjdk17
cache:
directories:
- $HOME/.m2/repository
branches:
only:
- master
install: travis_retry mvn install -DskipTests=true -B -V
stages:
- test
- release
@@ -22,7 +16,7 @@ jobs:
include:
- stage: test
name: "Build and test"
script: travis_retry mvn test -Dtest=ModelAssertionTest
script: travis_retry mvn -B -V -ntp test
- stage: release
name: "Push to Nexus"
if: fork = false AND branch = master AND type != pull_request AND commit_message !~ /\[no-release\]/
@@ -33,5 +27,5 @@ jobs:
- git checkout -B "${TRAVIS_BRANCH}"
# Add email to link commits to user
- git config user.email "${GIT_EMAIL}"
# Skip building of release commits
- mvn --batch-mode -DscmCommentPrefix="[maven-release-plugin][skip ci] " -Dusername="${GIT_USERNAME}" -Dpassword="${GIT_PASSWORD}" -DskipTests -Darguments=-DskipTests release:clean release:prepare release:perform
# Make release
- mvn --batch-mode -ntp -DscmCommentPrefix="[maven-release-plugin][skip ci] " -Dusername="${GIT_USERNAME}" -Dpassword="${GIT_PASSWORD}" -Darguments=-DskipTests release:clean release:prepare release:perform

View File

@@ -4,7 +4,7 @@
<groupId>org.alfresco.tas</groupId>
<artifactId>restapi</artifactId>
<name>alfresco-tas-restapi</name>
<version>1.101</version>
<version>1.112</version>
<parent>
<groupId>org.alfresco</groupId>
<artifactId>alfresco-super-pom</artifactId>
@@ -29,11 +29,8 @@
<maven.build.sourceVersion>11</maven.build.sourceVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<tas.utility.version>3.0.49</tas.utility.version>
<rest-assured.version>3.3.0</rest-assured.version>
<rest-assured.version>5.1.1</rest-assured.version>
<httpclient-osgi-version>4.5.6</httpclient-osgi-version>
<json-path.version>3.3.0</json-path.version>
<xml-path.version>3.3.0</xml-path.version>
<json-schema-validator.version>3.3.0</json-schema-validator.version>
<jackson-databind.version>2.13.3</jackson-databind.version>
<maven-release.version>2.5.3</maven-release.version>
<org.glassfish.version>1.1.4</org.glassfish.version>
@@ -70,7 +67,7 @@
<connection>scm:git:https://github.com/Alfresco/alfresco-tas-restapi.git</connection>
<developerConnection>scm:git:https://github.com/Alfresco/alfresco-tas-restapi.git</developerConnection>
<url>https://github.com/Alfresco/alfresco-tas-restapi</url>
<tag>v1.101</tag>
<tag>v1.112</tag>
</scm>
<issueManagement>
@@ -264,7 +261,7 @@
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${json-path.version}</version>
<version>${rest-assured.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-lang3</artifactId>
@@ -276,7 +273,7 @@
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>${xml-path.version}</version>
<version>${rest-assured.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-lang3</artifactId>
@@ -288,7 +285,7 @@
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${json-schema-validator.version}</version>
<version>${rest-assured.version}</version>
</dependency>
<dependency>
@@ -350,8 +347,14 @@
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-json</artifactId>
<version>3.0.12</version>
</dependency>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<reporting>

View File

@@ -27,16 +27,21 @@ package org.alfresco.rest.core;
import static org.alfresco.utility.report.log.Step.STEP;
import org.springframework.http.HttpMethod;
import java.util.MissingFormatArgumentException;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import io.restassured.RestAssured;
import org.springframework.http.HttpMethod;
/**
* @author Paul Brodner
*/
public class RestRequest
{
private String body = "";
private static final String TOKEN_REGEX = "\\{.*?}";
private String body;
private HttpMethod httpMethod;
private String path;
private Object[] pathParams;
@@ -44,10 +49,7 @@ public class RestRequest
private RestRequest(HttpMethod httpMethod, String path, String... pathParams)
{
setHttpMethod(httpMethod);
setPath(path);
setPathParams(pathParams);
STEP(toString());
this(httpMethod, "", path, pathParams);
}
private RestRequest(HttpMethod httpMethod, String body, String path, String... pathParams)
@@ -56,7 +58,8 @@ public class RestRequest
setPath(path);
setPathParams(pathParams);
setBody(body);
STEP(toString());
// Validate that the supplied path and pathParams are compatible.
constructPath();
}
/**
@@ -114,6 +117,7 @@ public class RestRequest
public void setPath(String path)
{
this.path = path;
addQueryParamsIfNeeded();
}
public Object[] getPathParams()
@@ -124,6 +128,32 @@ public class RestRequest
public void setPathParams(Object[] pathParams)
{
this.pathParams = pathParams;
addQueryParamsIfNeeded();
}
/**
* Add query parameters to the path if needed.
* <p>
* e.g. For a path of "api/{fruit}" and params ["apple", "size=10", "colour=red"] then this will
* update the path to be "api/{fruit}?{param0}&{param1}" so that the tokens will be populated by
* RestAssured to make "api/apple?size=10&colour=red".
*/
private void addQueryParamsIfNeeded()
{
// Don't do anything if the path or path params haven't been set yet.
if (path == null || path.length() == 0 || pathParams == null)
{
return;
}
int groupCount = (int) Pattern.compile(TOKEN_REGEX).matcher(path).results().count();
if (pathParams.length > groupCount)
{
// Add the remaining parameters to the URL query.
String queryParams = IntStream.range(0, pathParams.length - groupCount)
.mapToObj(index -> "{parameter" + index + "}")
.collect(Collectors.joining("&"));
path += (path.contains("?") ? "&" : "?") + queryParams;
}
}
public String getContentType()
@@ -136,6 +166,10 @@ public class RestRequest
this.contentType = contentType;
}
/**
* {@inheritDoc}
* @throws MissingFormatArgumentException If there are not enough pathParams for the path.
*/
@Override
public String toString()
{
@@ -144,19 +178,13 @@ public class RestRequest
.append(getHttpMethod())
.append(" ")
.append(RestAssured.baseURI)
.append(":")
.append("://")
.append(RestAssured.port)
.append("/")
.append(RestAssured.basePath)
.append("/");
String getPathFormatted = getPath();
if(getPath().contains("{"))
{
getPathFormatted = getPath().replaceAll("\\{.*?}", "%s");
getPathFormatted = String.format(getPathFormatted, getPathParams());
}
sb.append(getPathFormatted);
sb.append(constructPath());
if(!getBody().isEmpty())
{
@@ -168,4 +196,21 @@ public class RestRequest
return sb.toString();
}
/**
* Populate the path with the pathParams.
*
* @return The path with tokens replaced with values.
* @throws MissingFormatArgumentException If there are not enough pathParams for the path.
*/
private String constructPath()
{
String getPathFormatted = getPath();
if(getPath().contains("{"))
{
getPathFormatted = getPath().replaceAll(TOKEN_REGEX, "%s");
getPathFormatted = String.format(getPathFormatted, getPathParams());
}
return getPathFormatted;
}
}

View File

@@ -39,6 +39,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.xml.parsers.DocumentBuilder;
@@ -76,6 +77,7 @@ import org.alfresco.utility.dsl.DSLWrapper;
import org.alfresco.utility.model.StatusModel;
import org.alfresco.utility.model.TestModel;
import org.alfresco.utility.model.UserModel;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.xml.serialize.OutputFormat;
@@ -619,7 +621,16 @@ public class RestWrapper extends DSLWrapper<RestWrapper>
*/
protected Response sendRequest(RestRequest restRequest)
{
Response returnedResponse = null;
// If there are unused parameters then include them in the request.
String parameters = getParameters();
if (parameters != null && !parameters.isEmpty())
{
restRequest.setPathParams(ArrayUtils.addAll(restRequest.getPathParams(), parameters));
}
STEP(restRequest.toString());
Response returnedResponse;
switch (restRequest.getHttpMethod())
{
case GET:
@@ -628,7 +639,6 @@ public class RestWrapper extends DSLWrapper<RestWrapper>
case DELETE:
returnedResponse = onRequest().delete(restRequest.getPath(), restRequest.getPathParams()).andReturn();
break;
case HEAD:
returnedResponse = onRequest().head(restRequest.getPath(), restRequest.getPathParams()).andReturn();
break;
@@ -866,6 +876,8 @@ public class RestWrapper extends DSLWrapper<RestWrapper>
}
/**
* Get and clear the stored parameters.
*
* @return parameters that you could pass on the request ?param=value
*/
public String getParameters()
@@ -906,26 +918,17 @@ public class RestWrapper extends DSLWrapper<RestWrapper>
}
/**
* Send key=value parameters
* All of them will be automatically passed to url.
* Example: "maxItems=10000"
*
* @param parameters
* @return
* Send key=value parameters.
* <p>
* Note that this will replace any existing parameters.
*
* @param parameters A list of URL query parameters - e.g. "maxItems=10000"
* @return The RestWrapper
*/
public RestWrapper withParams(String... parameters)
{
StringBuilder paramsUrl = new StringBuilder();
String delimiter = (parameters.length > 1 ? "&" : "");
for (int i = 0; i < parameters.length; i++)
{
paramsUrl.append(parameters[i]);
if (i < parameters.length - 1)
paramsUrl.append(delimiter);
}
setParameters(paramsUrl.toString());
String paramsStr = Arrays.stream(parameters).collect(Collectors.joining("&"));
setParameters(paramsStr);
return this;
}

View File

@@ -33,14 +33,16 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.restassured.path.json.JsonPath;
import org.alfresco.utility.exception.TestConfigurationException;
import org.alfresco.utility.model.TestModel;
import org.testng.Assert;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.path.json.JsonPath;
/**
* Assertion on Rest Model
* Just pass your rest model as constructor
@@ -57,7 +59,7 @@ public class ModelAssertion<T>
Assert.fail(String.format("Field {%s} was not found in returned response.",fieldNameToBeRetuned));
}
}
private Object model;
private final Object model;
public ModelAssertion(Object model)
{
@@ -66,10 +68,11 @@ public class ModelAssertion<T>
/**
* Use this DSL for asserting particular fields of your model if your model
* is like this (basic POJO) public class Person extends
* ModelAssertion<Person> { private String id = "1234"; you can use assert
* the id of this person as:
* Person p = new Person(); p.assertField("id").is("1234")
* is like this (basic POJO)
* public class Person extends ModelAssertion<Person>
* { private String id = "1234"; }
* you can use assert the id of this person as:
* Person p = new Person(); p.assertThat().field("id").is("1234")
*
* @param fieldName
* @return
@@ -120,6 +123,24 @@ public class ModelAssertion<T>
return new AssertionItemVerbs(model, actualSize);
}
/**
* Use this method for asserting whole model with different model object. Method allows to ignore particular fields during the comparison.
*
* WARNING: For proper work model should implement {@code toString()} and {@code equals()} methods.
*
* @param expected - expected model.
* @param ignoreFields - fields which should be ignored during assertion.
* @return model.
*/
@SuppressWarnings("unchecked")
public T isEqualTo(T expected, String... ignoreFields)
{
T modelCopy = createCopyIgnoringFields((T) model, ignoreFields);
T expectedCopy = createCopyIgnoringFields(expected, ignoreFields);
Assert.assertEquals(modelCopy, expectedCopy, String.format("Compared objects of type: %s are not equal!", model.getClass()));
return (T) model;
}
/**
* Get all fields declared from all classes hierarchy
*
@@ -144,6 +165,18 @@ public class ModelAssertion<T>
return fields;
}
@SuppressWarnings("unchecked")
private T createCopyIgnoringFields(T model, String... ignoreFields)
{
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(gson.toJson(model), JsonObject.class);
for (String ignoreField : ignoreFields)
{
jsonObject.remove(ignoreField);
}
return gson.fromJson(gson.toJson(jsonObject), (Class<? extends T>) model.getClass());
}
/**
* DSL assertion on Rest Model fields
*

View File

@@ -25,7 +25,7 @@
*/
package org.alfresco.rest.model;
import java.util.List;
import java.util.Objects;
import org.alfresco.rest.core.IRestModel;
import org.alfresco.rest.core.assertion.ModelAssertion;
@@ -85,6 +85,29 @@ public class RestActionBodyExecTemplateModel extends TestModel implements IRestM
public void setParams(Object params)
{
this.params = params;
}
}
@Override
public String toString()
{
return "RestActionBodyExecTemplateModel{" + "actionDefinitionId='" + actionDefinitionId + '\'' + ", params=" + params + '}';
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RestActionBodyExecTemplateModel that = (RestActionBodyExecTemplateModel) o;
return Objects.equals(actionDefinitionId, that.actionDefinitionId) && Objects.equals(params, that.params);
}
@Override
public int hashCode()
{
return Objects.hash(actionDefinitionId, params);
}
}

View File

@@ -26,6 +26,7 @@
package org.alfresco.rest.model;
import java.util.List;
import java.util.Objects;
import org.alfresco.rest.core.IRestModel;
import org.alfresco.rest.core.assertion.ModelAssertion;
@@ -120,6 +121,31 @@ public class RestCompositeConditionDefinitionModel extends TestModel implements
public void setSimpleConditions(List<RestSimpleConditionDefinitionModel> simpleConditions)
{
this.simpleConditions = simpleConditions;
}
}
@Override
public String toString()
{
return "RestCompositeConditionDefinitionModel{" + "inverted=" + inverted + ", booleanMode='" + booleanMode + '\'' + ", compositeConditions=" + compositeConditions
+ ", simpleConditions=" + simpleConditions + '}';
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RestCompositeConditionDefinitionModel that = (RestCompositeConditionDefinitionModel) o;
return inverted == that.inverted && Objects.equals(booleanMode, that.booleanMode) && Objects.equals(compositeConditions, that.compositeConditions) && Objects.equals(
simpleConditions, that.simpleConditions);
}
@Override
public int hashCode()
{
return Objects.hash(inverted, booleanMode, compositeConditions, simpleConditions);
}
}

View File

@@ -26,6 +26,7 @@
package org.alfresco.rest.model;
import java.util.List;
import java.util.Objects;
import org.alfresco.rest.core.IRestModel;
import org.alfresco.rest.core.assertion.ModelAssertion;
@@ -98,12 +99,10 @@ public class RestRuleModel extends TestModel implements IRestModel<RestRuleModel
*/
private String errorScript;
/**
Whether the rule has been shared with more than one folder
*/
/** True if the rule set is linked to, or if the rule is inheritable and the rule set is inherited by a folder with inheriting enabled. */
@JsonProperty
private Boolean isShared;
@JsonProperty(required = true)
private boolean shared;
/**
The set of triggers that cause the rule to be activated.
* inbound - The rule should be activated when an item enters the folder
@@ -200,14 +199,14 @@ If the field is omitted then the rule will apply to all nodes.
this.errorScript = errorScript;
}
public boolean getShared()
public Boolean getIsShared()
{
return this.shared;
return this.isShared;
}
public void setShared(boolean shared)
public void setIsShared(Boolean shared)
{
this.shared = shared;
this.isShared = shared;
}
public List<String> getTriggers()
@@ -238,6 +237,34 @@ If the field is omitted then the rule will apply to all nodes.
public void setActions(List<RestActionBodyExecTemplateModel> actions)
{
this.actions = actions;
}
}
@Override
public String toString()
{
return "RestRuleModel{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", enabled=" + enabled + ", cascade=" + cascade
+ ", asynchronous=" + asynchronous + ", errorScript='" + errorScript + '\'' + ", isShared=" + isShared + ", triggers=" + triggers + ", conditions=" + conditions
+ ", actions=" + actions + '}';
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RestRuleModel ruleModel = (RestRuleModel) o;
return enabled == ruleModel.enabled && cascade == ruleModel.cascade && asynchronous == ruleModel.asynchronous && Objects.equals(id, ruleModel.id) && Objects.equals(
name, ruleModel.name) && Objects.equals(description, ruleModel.description) && Objects.equals(errorScript, ruleModel.errorScript) && Objects.equals(
isShared, ruleModel.isShared) && Objects.equals(triggers, ruleModel.triggers) && Objects.equals(conditions, ruleModel.conditions) && Objects.equals(
actions, ruleModel.actions);
}
@Override
public int hashCode()
{
return Objects.hash(id, name, description, enabled, cascade, asynchronous, errorScript, isShared, triggers, conditions, actions);
}
}

View File

@@ -64,6 +64,10 @@ public class RestRuleSetModel extends TestModel implements IRestModel<RestRuleSe
*/
@JsonProperty (required = true)
private String id;
/** The node id of the folder that owns this rule set */
private String owningFolder;
/** The reason why the rule set is included for the folder. */
private String inclusionType;
public String getId()
{
@@ -74,4 +78,24 @@ public class RestRuleSetModel extends TestModel implements IRestModel<RestRuleSe
{
this.id = id;
}
public String getOwningFolder()
{
return owningFolder;
}
public void setOwningFolder(String owningFolder)
{
this.owningFolder = owningFolder;
}
public String getInclusionType()
{
return inclusionType;
}
public void setInclusionType(String inclusionType)
{
this.inclusionType = inclusionType;
}
}

View File

@@ -25,7 +25,7 @@
*/
package org.alfresco.rest.model;
import java.util.List;
import java.util.Objects;
import org.alfresco.rest.core.IRestModel;
import org.alfresco.rest.core.assertion.ModelAssertion;
@@ -128,6 +128,29 @@ Where a property is multivalued then the condition is true if it is satisfied by
public void setParameter(String parameter)
{
this.parameter = parameter;
}
}
@Override
public String toString()
{
return "RestSimpleConditionDefinitionModel{" + "field='" + field + '\'' + ", comparator='" + comparator + '\'' + ", parameter='" + parameter + '\'' + '}';
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RestSimpleConditionDefinitionModel that = (RestSimpleConditionDefinitionModel) o;
return Objects.equals(field, that.field) && Objects.equals(comparator, that.comparator) && Objects.equals(parameter, that.parameter);
}
@Override
public int hashCode()
{
return Objects.hash(field, comparator, parameter);
}
}

View File

@@ -25,6 +25,9 @@
*/
package org.alfresco.rest.requests;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.alfresco.rest.core.RestWrapper;
public abstract class ModelRequest<Request>
@@ -43,10 +46,26 @@ public abstract class ModelRequest<Request>
return (Request) this;
}
@SuppressWarnings("unchecked")
/**
* Use "include=path" in the URL query.
* <p>
* Nb. Replaces any existing parameters.
*/
public Request includePath()
{
restWrapper.withParams("include=path");
return include("path");
}
/**
* Specify fields to include in the response.
* <p>
* Nb. Replaces any existing parameters.
*/
@SuppressWarnings ("unchecked")
public Request include(String... includes)
{
String includeString = Arrays.stream(includes).collect(Collectors.joining(","));
restWrapper.withParams("include=" + includeString);
return (Request) this;
}
}

View File

@@ -26,13 +26,37 @@
package org.alfresco.rest.requests;
import javax.json.JsonArrayBuilder;
import java.io.File;
import java.io.IOException;
import io.restassured.http.ContentType;
import org.alfresco.rest.core.JsonBodyGenerator;
import org.alfresco.rest.core.RestRequest;
import org.alfresco.rest.core.RestResponse;
import org.alfresco.rest.core.RestWrapper;
import org.alfresco.rest.exception.JsonToModelConversionException;
import org.alfresco.rest.model.*;
import org.alfresco.rest.model.RestActionDefinitionModelsCollection;
import org.alfresco.rest.model.RestCommentModel;
import org.alfresco.rest.model.RestCommentModelsCollection;
import org.alfresco.rest.model.RestNodeAssocTargetModel;
import org.alfresco.rest.model.RestNodeAssociationModel;
import org.alfresco.rest.model.RestNodeAssociationModelCollection;
import org.alfresco.rest.model.RestNodeBodyModel;
import org.alfresco.rest.model.RestNodeBodyMoveCopyModel;
import org.alfresco.rest.model.RestNodeChildAssocModelCollection;
import org.alfresco.rest.model.RestNodeModel;
import org.alfresco.rest.model.RestNodeModelsCollection;
import org.alfresco.rest.model.RestRatingModel;
import org.alfresco.rest.model.RestRatingModelsCollection;
import org.alfresco.rest.model.RestRenditionInfoModel;
import org.alfresco.rest.model.RestRenditionInfoModelCollection;
import org.alfresco.rest.model.RestRuleSetModel;
import org.alfresco.rest.model.RestRuleSetModelsCollection;
import org.alfresco.rest.model.RestTagModel;
import org.alfresco.rest.model.RestTagModelsCollection;
import org.alfresco.rest.model.RestVersionModel;
import org.alfresco.rest.model.RestVersionModelsCollection;
import org.alfresco.rest.model.body.RestNodeLockBodyModel;
import org.alfresco.rest.model.builder.NodesBuilder;
import org.alfresco.utility.Utility;
@@ -41,16 +65,15 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.testng.reporters.Files;
import javax.json.JsonArrayBuilder;
import java.io.File;
import java.io.IOException;
/**
* Declares all Rest API under the /nodes path
*
*/
public class Node extends ModelRequest<Node>
{
private static final String RULE_SETS_URI = "nodes/{nodeId}/rule-sets";
private static final String RULE_SET_BY_ID = RULE_SETS_URI + "/{ruleSetId}";
private RepoTestModel repoModel;
public Node(RestWrapper restWrapper)
@@ -995,7 +1018,8 @@ public class Node extends ModelRequest<Node>
*/
public RestRuleSetModelsCollection getListOfRuleSets()
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, "nodes/{nodeId}/rule-sets", repoModel.getNodeRef());
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, RULE_SETS_URI,
repoModel.getNodeRef());
return restWrapper.processModels(RestRuleSetModelsCollection.class, request);
}
@@ -1007,7 +1031,8 @@ public class Node extends ModelRequest<Node>
*/
public RestRuleSetModel getRuleSet(String ruleSetId)
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, "nodes/{nodeId}/rule-sets/{ruleSetId}", repoModel.getNodeRef(), ruleSetId);
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, RULE_SET_BY_ID,
repoModel.getNodeRef(), ruleSetId);
return restWrapper.processModel(RestRuleSetModel.class, request);
}
@@ -1018,7 +1043,8 @@ public class Node extends ModelRequest<Node>
*/
public RestRuleSetModel getDefaultRuleSet()
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, "nodes/{nodeId}/rule-sets/{ruleSetId}", repoModel.getNodeRef(), "-default-");
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, RULE_SET_BY_ID,
repoModel.getNodeRef(), "-default-");
return restWrapper.processModel(RestRuleSetModel.class, request);
}
}

View File

@@ -54,7 +54,6 @@ public class Sync extends ModelRequest<RestPrivateAPI>
RestSyncNodeSubscriptionModel subscription;
String requestSyncURL = "subscribers/{deviceSubscriptionId}/subscriptions/{nodeSubscriptionId}/sync";
String syncSetURL = requestSyncURL + "/{syncId}";
String params = "?{parameters}";
public Sync(RestSyncNodeSubscriptionModel subscription, RestWrapper restWrapper)
{
@@ -82,7 +81,7 @@ public class Sync extends ModelRequest<RestPrivateAPI>
String postBody = JsonBodyGenerator.defineJSON().add("changes", array.build()).add("clientVersion", clientVersion).build().toString();
RestRequest request = RestRequest.requestWithBody(HttpMethod.POST, postBody, requestSyncURL + params, this.subscriber, nodeSubscriptionModel.getId(),
RestRequest request = RestRequest.requestWithBody(HttpMethod.POST, postBody, requestSyncURL, this.subscriber, nodeSubscriptionModel.getId(),
restWrapper.getParameters());
// This step is necessary for this request. Without it, empty json response is returned
@@ -94,7 +93,7 @@ public class Sync extends ModelRequest<RestPrivateAPI>
public RestWrapper endSync(RestSyncNodeSubscriptionModel nodeSubscriptionModel, RestSyncSetRequestModel sync)
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.DELETE, syncSetURL + params, this.subscriber, nodeSubscriptionModel.getId(),
RestRequest request = RestRequest.simpleRequest(HttpMethod.DELETE, syncSetURL, this.subscriber, nodeSubscriptionModel.getId(),
sync.getSyncId(), restWrapper.getParameters());
restWrapper.processEmptyModel(request);
@@ -111,7 +110,7 @@ public class Sync extends ModelRequest<RestPrivateAPI>
*/
public RestSyncSetGetModel getSync(RestSyncNodeSubscriptionModel nodeSubscriptionModel, RestSyncSetRequestModel sync)
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, syncSetURL + params, this.subscriber, nodeSubscriptionModel.getId(), sync.getSyncId(),
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, syncSetURL, this.subscriber, nodeSubscriptionModel.getId(), sync.getSyncId(),
restWrapper.getParameters());
RestSyncSetGetModel model = restWrapper.processModelWithoutEntryObject(RestSyncSetGetModel.class, request);

View File

@@ -0,0 +1,129 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.core;
import static org.alfresco.rest.core.RestRequest.requestWithBody;
import static org.alfresco.rest.core.RestRequest.simpleRequest;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
import static org.testng.Assert.assertEquals;
import java.util.MissingFormatArgumentException;
import io.restassured.RestAssured;
import org.testng.annotations.Test;
/** Unit tests for {@link RestRequest}. */
public class RestRequestTest
{
@Test
public void testSimpleRequest_emptyPathAndParams()
{
RestRequest restRequest = simpleRequest(GET, "");
assertEquals(restRequest.getPath(), "", "Unexpected path");
}
@Test
public void testSimpleRequest_pathWithEqualParamsAndGroups()
{
RestRequest restRequest = simpleRequest(GET, "nodes/{nodeId}", "nodeId");
assertEquals(restRequest.getPath(), "nodes/{nodeId}", "Unexpected path");
}
@Test
public void testSimpleRequest_pathWithMoreParamsThanGroups()
{
RestRequest restRequest = simpleRequest(GET, "nodes/{nodeId}", "nodeId", "key1=value1", "key2=value2");
assertEquals(restRequest.getPath(), "nodes/{nodeId}?{parameter0}&{parameter1}", "Unexpected path");
}
@Test(expectedExceptions = MissingFormatArgumentException.class)
public void testSimpleRequest_pathWithFewerParamsThanGroups()
{
simpleRequest(GET, "nodes/{nodeId}");
}
@Test
public void testSetPath()
{
RestRequest restRequest = simpleRequest(GET, "nodes/{nodeId}", "nodeId");
restRequest.setPath("nodes");
assertEquals(restRequest.getPath(), "nodes?{parameter0}", "Unexpected path");
}
@Test
public void testSetPathParams()
{
RestRequest restRequest = simpleRequest(GET, "nodes/{nodeId}", "nodeId");
Object[] pathParams = {"nodeId", "key=value"};
restRequest.setPathParams(pathParams);
assertEquals(restRequest.getPath(), "nodes/{nodeId}?{parameter0}", "Unexpected path");
}
@Test
public void testRequestWithBody_pathWithEqualParamsAndGroups()
{
RestRequest restRequest = requestWithBody(POST, "BODY", "nodes/{nodeId}", "nodeId");
assertEquals(restRequest.getPath(), "nodes/{nodeId}", "Unexpected path");
}
@Test
public void testRequestWithBody_pathWithMoreParamsThanGroups()
{
RestRequest restRequest = requestWithBody(GET, "BODY", "nodes/{nodeId}", "nodeId", "key1=value1", "key2=value2");
assertEquals(restRequest.getPath(), "nodes/{nodeId}?{parameter0}&{parameter1}", "Unexpected path");
}
@Test (expectedExceptions = MissingFormatArgumentException.class)
public void testRequestWithBody_pathWithFewerParamsThanGroups()
{
requestWithBody(POST, "BODY", "nodes/{nodeId}");
}
@Test
public void testToString()
{
RestAssured.baseURI = "BASE";
RestAssured.port = 1234;
RestAssured.basePath = "BASE_PATH";
RestRequest restRequest = requestWithBody(GET, "BODY", "nodes/{nodeId}", "nodeId", "key1=value1", "key2=value2");
String expected = "Request: GET BASE://1234/BASE_PATH/nodes/nodeId?key1=value1&key2=value2\nbody:BODY\n";
assertEquals(restRequest.toString(), expected, "Unexpected toString representation");
RestAssured.reset();
}
}

View File

@@ -0,0 +1,77 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.core;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/** Unit tests for {@link RestWrapper}. */
public class RestWrapperTest
{
private RestWrapper restWrapper;
@BeforeMethod
public void setUp()
{
restWrapper = new RestWrapper();
}
@Test
public void testWithParams_noParams()
{
restWrapper.withParams();
assertEquals(restWrapper.getParameters(), "", "Expected empty parameters");
}
@Test
public void testWithParams_singleParam()
{
restWrapper.withParams("param=value");
assertEquals(restWrapper.getParameters(), "param=value", "Unexpected parameter string");
}
@Test
public void testWithParams_multipleParams()
{
restWrapper.withParams("param1=value1", "param2=value2");
assertEquals(restWrapper.getParameters(), "param1=value1&param2=value2", "Unexpected parameter string");
}
@Test
public void testWithParams_lastValueWins()
{
// The first call should be overwritten by the second.
restWrapper.withParams("param1=value1");
restWrapper.withParams("param2=value2");
assertEquals(restWrapper.getParameters(), "param2=value2", "Unexpected parameter string");
}
}

View File

@@ -1,128 +0,0 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.demo;
import org.alfresco.dataprep.CMISUtil.DocumentType;
import org.alfresco.dataprep.SiteService.Visibility;
import org.alfresco.rest.RestTest;
import org.alfresco.rest.exception.JsonToModelConversionException;
import org.alfresco.utility.constants.UserRole;
import org.alfresco.utility.exception.DataPreparationException;
import org.alfresco.utility.model.FileModel;
import org.alfresco.utility.model.FolderModel;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.UserModel;
import org.springframework.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class RestDemoTests extends RestTest
{
private UserModel userModel;
private SiteModel siteModel;
@BeforeClass(alwaysRun=true)
public void dataPreparation() throws DataPreparationException
{
userModel = dataUser.getAdminUser();
siteModel = dataSite.usingUser(userModel).createPublicRandomSite();
restClient.authenticateUser(userModel);
}
/**
* Data preparation create site with custom details <br/>
* Perform GET sites call using admin user<br/>
* Check that created site is included in response <br/>
* Perform GET site call, validate that site title, description and visibility are correct <br/>
*
* @throws JsonToModelConversionException
*/
@Test(groups = { "demo" })
public void adminRetrievesCorrectSiteDetails() throws JsonToModelConversionException
{
restClient.withCoreAPI().getSites().assertThat()
.entriesListContains("id", siteModel.getId());
restClient.withCoreAPI().usingSite(siteModel).getSite()
.assertThat().field("id").isNotNull()
.assertThat().field("description").is(siteModel.getDescription())
.assertThat().field("title").is(siteModel.getTitle())
.assertThat().field("visibility").is(Visibility.PUBLIC);
}
/**
* Data preparation create site and document on server <br/>
* POST one comment to file using admin user <br/>
* Perform GET comments, check the new one is listed <br/>
* Update existing comment using PUT call, check that comment content is updated <br/>
*/
//Opened DESKTOPAPP-475 for fixing the failing test
// @Test(groups = { "demo" })
public void adminCanPostAndUpdateComments()
{
FileModel fileModel = dataContent.usingUser(userModel)
.usingResource(FolderModel.getSharedFolderModel())
.createContent(DocumentType.TEXT_PLAIN);
// add new comment
restClient.withCoreAPI().usingResource(fileModel).addComment("This is a new comment");
restClient.withCoreAPI().usingResource(fileModel).getNodeComments()
.assertThat().entriesListIsNotEmpty().and()
.entriesListContains("content", "This is a new comment");
}
/**
* Data preparation create site and a new user <br/>
* As admin, add user as Consumer to site as a new site member using POST call <br/>
* Update site member role to Manager using PUT call <br/>
* Delete site member using DELETE call <br/>
*
* @throws DataPreparationException
* @throws JsonToModelConversionException
*/
@Test(groups = { "demo" })
public void adminCanAddAndUpdateSiteMemberDetails()
{
UserModel testUser = dataUser.createRandomTestUser("testUser");
testUser.setUserRole(UserRole.SiteConsumer);
// add user as Consumer to site
restClient.withCoreAPI().usingSite(siteModel).addPerson(testUser);
restClient.withCoreAPI().usingSite(siteModel).getSiteMembers().assertThat().entriesListContains("id", testUser.getUsername())
.when().getSiteMember(testUser.getUsername())
.assertSiteMemberHasRole(UserRole.SiteConsumer);
// update site member to Manager
testUser.setUserRole(UserRole.SiteCollaborator);
restClient.withCoreAPI().usingSite(siteModel).updateSiteMember(testUser);
restClient.withCoreAPI().usingSite(siteModel).getSiteMembers().and()
.entriesListContains("id", testUser.getUsername())
.when().getSiteMember(testUser.getUsername())
.assertSiteMemberHasRole(UserRole.SiteCollaborator);
restClient.withCoreAPI().usingSite(siteModel).deleteSiteMember(testUser);
restClient.assertStatusCodeIs(HttpStatus.NO_CONTENT);
}
}

View File

@@ -1,81 +0,0 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.demo;
import org.alfresco.dataprep.CMISUtil.DocumentType;
import org.alfresco.rest.RestTest;
import org.alfresco.rest.exception.JsonToModelConversionException;
import org.alfresco.rest.model.RestCommentModel;
import org.alfresco.utility.model.FileModel;
import org.alfresco.utility.model.FolderModel;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.UserModel;
import org.springframework.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SampleCommentsTests extends RestTest
{
private UserModel userModel;
private FolderModel folderModel;
private SiteModel siteModel;
private FileModel document;
@BeforeClass(alwaysRun=true)
public void dataPreparation()
{
userModel = dataUser.getAdminUser();
siteModel = dataSite.usingUser(userModel).createPublicRandomSite();
folderModel = dataContent.usingUser(userModel).usingSite(siteModel).createFolder();
restClient.authenticateUser(userModel);
document = dataContent.usingUser(userModel).usingResource(folderModel).createContent(DocumentType.TEXT_PLAIN);
}
@Test(groups = { "demo" })
public void admiShouldAddComment() throws JsonToModelConversionException
{
restClient.withCoreAPI().usingResource(document).addComment("This is a new comment");
restClient.assertStatusCodeIs(HttpStatus.CREATED);
}
@Test(groups = { "demo" })
public void admiShouldRetrieveComments()
{
restClient.withCoreAPI().usingResource(document).getNodeComments();
restClient.assertStatusCodeIs(HttpStatus.OK);
}
@Test(groups = { "demo" })
public void adminShouldUpdateComment() throws JsonToModelConversionException
{
RestCommentModel commentModel = restClient.withCoreAPI().usingResource(document).addComment("This is a new comment");
restClient.withCoreAPI().usingResource(document).updateComment(commentModel, "This is the updated comment with Collaborator user")
.assertThat().field("content").is("This is the updated comment with Collaborator user");
}
}

View File

@@ -1,57 +0,0 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.demo;
import org.alfresco.rest.RestTest;
import org.alfresco.utility.exception.DataPreparationException;
import org.alfresco.utility.model.UserModel;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SamplePeopleTests extends RestTest
{
private UserModel userModel;
private UserModel adminUser;
@BeforeClass(alwaysRun=true)
public void dataPreparation() throws DataPreparationException
{
userModel = dataUser.createUser(RandomStringUtils.randomAlphanumeric(20));
adminUser = dataUser.getAdminUser();
restClient.authenticateUser(adminUser);
}
@Test(groups = { "demo" })
public void adminShouldRetrievePerson()
{
restClient.withCoreAPI().usingUser(userModel).getPerson().assertThat().field("id").isNotEmpty();
restClient.assertStatusCodeIs(HttpStatus.OK);
}
}

View File

@@ -1,104 +0,0 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.demo;
import org.alfresco.rest.RestTest;
import org.alfresco.rest.exception.JsonToModelConversionException;
import org.alfresco.utility.constants.UserRole;
import org.alfresco.utility.exception.DataPreparationException;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.UserModel;
import org.springframework.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SampleSitesTests extends RestTest
{
private UserModel userModel;
private SiteModel siteModel;
@BeforeClass(alwaysRun=true)
public void dataPreparation() throws DataPreparationException
{
userModel = dataUser.getAdminUser();
restClient.authenticateUser(userModel);
siteModel = dataSite.usingUser(userModel).createPublicRandomSite();
}
@Test(groups = { "demo" })
public void adminShouldGetSiteDetails() throws JsonToModelConversionException, Exception
{
restClient.withCoreAPI().usingSite(siteModel).getSite()
.assertThat().field("id").isNotNull();
}
@Test(groups = { "demo" })
public void adminShouldGetSites() throws JsonToModelConversionException, Exception
{
restClient.withCoreAPI().usingSite(siteModel).getSite();
restClient.assertStatusCodeIs(HttpStatus.OK);
}
@Test(groups = { "demo" })
public void adminShouldAccessSites() throws JsonToModelConversionException, Exception
{
restClient.withCoreAPI().getSites().assertThat().entriesListIsNotEmpty();
restClient.assertStatusCodeIs(HttpStatus.OK);
}
@Test(groups = { "demo" })
public void adminShouldAccessResponsePagination() throws JsonToModelConversionException, Exception
{
restClient.withCoreAPI().getSites().assertThat().paginationExist();
}
@Test(groups = { "demo" })
public void adminShouldAddNewSiteMember() throws JsonToModelConversionException, DataPreparationException, Exception
{
UserModel testUser = dataUser.createRandomTestUser("testUser");
testUser.setUserRole(UserRole.SiteConsumer);
restClient.withCoreAPI().usingSite(siteModel).addPerson(testUser);
restClient.assertStatusCodeIs(HttpStatus.CREATED);
}
@Test(groups = { "demo" })
public void adminShouldGetSiteFromSitesList() throws JsonToModelConversionException, Exception
{
restClient.withCoreAPI().getSites().assertThat().entriesListContains("id", siteModel.getId());
}
@Test(groups = { "demo" })
public void adminShouldAccessSiteDetails() throws JsonToModelConversionException, Exception
{
restClient.withCoreAPI().usingSite(siteModel).getSite()
.assertThat().field("id").isNotNull()
.and().field("description").is(siteModel.getDescription())
.and().field("title").is(siteModel.getTitle())
.and().field("visibility").is(siteModel.getVisibility());
}
}

View File

@@ -1,77 +0,0 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.demo.workshop;
import org.alfresco.rest.RestTest;
import org.alfresco.utility.constants.UserRole;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.UserModel;
import org.testng.annotations.Test;
public class RestApiDemoTests extends RestTest
{
/*
* Test steps:
* 1. create a user
* 2. create a site
* 3. create a second user
* 4. add the second user to site with a user role
* 5. call rest api call " GET sites/{siteId}/members" with first user authenticated
* Expected: the response contains the user added as a member to the site
*/
@Test(groups = { "demo" })
public void verifyGetSiteMembersRestApiCall()
{
UserModel user = dataUser.createRandomTestUser();
SiteModel site = dataSite.usingUser(user).createPublicRandomSite();
UserModel member = dataUser.createRandomTestUser();
dataUser.usingUser(user).addUserToSite(member, site, UserRole.SiteCollaborator);
//add here code for step 5
}
/*
* Test steps:
* 1. create a user
* 2. create a site
* 3. create a second user
* 4. add the second user to site with a user role
* 5. call rest api call " GET sites/{siteId}/members/{personId}" with first user authenticated
* Expected: the response contains the user added as a member to the site
*/
@Test(groups = { "demo" })
public void verifyGetASiteMemberApiCall()
{
UserModel user = dataUser.createRandomTestUser();
SiteModel site = dataSite.usingUser(user).createPublicRandomSite();
UserModel member = dataUser.createRandomTestUser();
dataUser.usingUser(user).addUserToSite(member, site, UserRole.SiteCollaborator);
//add here code for step 5
}
}

View File

@@ -1,63 +0,0 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.demo.workshop;
import org.alfresco.rest.RestTest;
import org.testng.annotations.Test;
/**
*
* Demo workshop for RestAPI test
*
*/
public class RestApiWorkshopTests extends RestTest
{
@Test(groups = { "demo" })
public void verifyGetSitesRestApiCall()
{
// creating a random user in repository
// create a new random site using your UserModel from above
// using "siteApi", call get "/sites" Rest API and verify created site is present
// verify status is OK
}
@Test(groups = { "demo" })
public void verifyGetASiteRestApiCall()
{
// creating a random user in repository
// create a new random site using your UserModel from above
// using "siteApi", call get "/sites/{siteId}" Rest API
// using "siteApi", verify created site is present
// verify status is OK
}
}

View File

@@ -25,32 +25,36 @@
*/
package org.alfresco.rest.model;
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.rest.core.IRestModel;
import org.alfresco.rest.core.assertion.ModelAssertion;
import org.alfresco.rest.model.RestPersonModel;
import org.junit.Ignore;
import org.testng.annotations.Test;
import static com.google.common.collect.Sets.newHashSet;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import org.alfresco.rest.core.IRestModel;
import org.alfresco.rest.core.assertion.ModelAssertion;
import org.testng.annotations.Test;
public class ModelAssertionTest {
private static final String DEFAULT_ID = "1234";
private static final String DEFAULT_NAME = "test";
@Test(groups = "unit")
public void iCanAssertExistingProperty() {
Person p = new Person();
Person p = new Person(DEFAULT_ID);
p.assertThat().field("id").is("1234");
}
@Test(groups = "unit")
public void iCanAssertExistingPropertyNegative() {
Person p = new Person();
Person p = new Person(DEFAULT_ID);
p.assertThat().field("id").isNot("12342");
RestPersonModel rp = new RestPersonModel();
@@ -66,7 +70,7 @@ public class ModelAssertionTest {
@Test(groups = "unit")
public void iCanTakeTheValueOfFieldsThatDoesntHaveGetters() {
Person p = new Person();
Person p = new Person(DEFAULT_ID, DEFAULT_NAME);
p.assertThat().field("name").is("test");
@@ -74,7 +78,7 @@ public class ModelAssertionTest {
@Test(groups = "unit")
public void iCanAssertStringIsEmpty() {
Person p = new Person();
Person p = new Person(DEFAULT_ID);
// Check no exception when field is empty.
p.assertThat().field("nickname").isEmpty();
@@ -89,7 +93,7 @@ public class ModelAssertionTest {
@Test(groups = "unit")
public void iCanAssertStringIsNotEmpty() {
Person p = new Person();
Person p = new Person(DEFAULT_ID);
// Check no exception when field is not empty.
p.assertThat().field("id").isNotEmpty();
@@ -169,10 +173,108 @@ public class ModelAssertionTest {
p.assertThat().field("age").isNotEmpty();
}
public class Person implements IRestModel<Person> {
private String id = "1234";
private String name = "test";
public String getName() { return name;}
@Test(groups = "unit")
public void testIsEqualTo_noDifferencesNonIgnoredFields()
{
Person person = new Person(DEFAULT_ID, DEFAULT_NAME);
Person otherPerson = new Person(DEFAULT_ID, DEFAULT_NAME);
person.assertThat().isEqualTo(otherPerson);
}
@Test(groups = "unit")
public void testIsEqualTo_differentNameIgnoreName()
{
Person person = new Person(DEFAULT_ID);
Person otherPerson = new Person(DEFAULT_ID, DEFAULT_NAME);
person.assertThat().isEqualTo(otherPerson, "name");
}
@Test(groups = "unit")
public void testIsEqualTo_differentIdAndNameIgnoreIdAndName()
{
Person person = new Person();
Person otherPerson = new Person(DEFAULT_ID, DEFAULT_NAME);
person.assertThat().isEqualTo(otherPerson, "id", "name");
}
@Test(groups = "unit")
public void testIsEqualTo_differentNameNonIgnoredFields()
{
Person person = new Person(DEFAULT_ID, DEFAULT_NAME);
Person otherPerson = new Person(DEFAULT_ID, "otherName");
try {
person.assertThat().isEqualTo(otherPerson);
fail("Expected exception to be raised.");
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("are not equal"), "Expected exception to be about a not equal objects.");
}
}
@Test(groups = "unit")
public void testIsEqualTo_differentIdNonIgnoredFields()
{
Person person = new Person();
Person otherPerson = new Person(DEFAULT_ID);
try {
person.assertThat().isEqualTo(otherPerson);
fail("Expected exception to be raised.");
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("are not equal"), "Expected exception to be about a not equal objects.");
}
}
@Test(groups = "unit")
public void testIsEqualTo_differentIdAndNameIgnoreName()
{
Person person = new Person();
Person otherPerson = new Person(DEFAULT_ID, DEFAULT_NAME);
try {
person.assertThat().isEqualTo(otherPerson, "name");
fail("Expected exception to be raised.");
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("are not equal"), "Expected exception to be about a not equal objects.");
}
}
@Test(groups = "unit")
public void testIsEqualTo_differentNicknameIgnoreIdAndName()
{
Person person = new Person();
Person otherPerson = new Person();
otherPerson.setNickname("Shaggy");
try {
person.assertThat().isEqualTo(otherPerson, "id", "name");
fail("Expected exception to be raised.");
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("are not equal"), "Expected exception to be about a not equal objects.");
}
}
@Test(groups = "unit")
public void testIsEqualTo_differentPreviousNamesIgnoreId()
{
Person person = new Person();
Person otherPerson = new Person();
otherPerson.setPreviousNames(List.of("Paul"));
try {
person.assertThat().isEqualTo(otherPerson, "id");
fail("Expected exception to be raised.");
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("are not equal"), "Expected exception to be about a not equal objects.");
}
}
public static class Person implements IRestModel<Person> {
private String id;
private String name;
private String nickname = "";
private int age = 42;
private Set<String> legs = newHashSet("left", "right");
@@ -180,16 +282,44 @@ public class ModelAssertionTest {
private Map<String, String> clothing = ImmutableMap.of("head", "hat");
private Map<String, String> carrying = Collections.emptyMap();
public Person()
{
}
public Person(String id)
{
this.id = id;
}
public Person(String id, String name)
{
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() { return name;}
public void setName(String name)
{
this.name = name;
}
public String getNickname() { return nickname; }
public void setNickname(String nickname)
{
this.nickname = nickname;
}
public int getAge() { return age; }
public Set<String> getLegs() { return legs; }
public List<String> getPreviousNames() { return previousNames; }
public void setPreviousNames(List<String> previousNames)
{
this.previousNames = previousNames;
}
public Map<String, String> getClothing() { return clothing; }
public Map<String, String> getCarrying() { return carrying; }
@@ -208,6 +338,30 @@ public class ModelAssertionTest {
// TODO Auto-generated method stub
return null;
}
}
@Override
public String toString()
{
return "Person{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", nickname='" + nickname + '\'' + ", age=" + age + ", legs=" + legs + ", previousNames="
+ previousNames + ", clothing=" + clothing + ", carrying=" + carrying + '}';
}
@Override
public boolean equals(Object o)
{
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person person = (Person) o;
return age == person.age && Objects.equals(id, person.id) && Objects.equals(name, person.name) && Objects.equals(nickname, person.nickname) && Objects.equals(
legs, person.legs) && Objects.equals(previousNames, person.previousNames) && Objects.equals(clothing, person.clothing) && Objects.equals(carrying, person.carrying);
}
@Override
public int hashCode()
{
return Objects.hash(id, name, nickname, age, legs, previousNames, clothing, carrying);
}
}
}

View File

@@ -0,0 +1,99 @@
/*-
* #%L
* alfresco-tas-restapi
* %%
* Copyright (C) 2005 - 2022 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.rest.requests;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.MockitoAnnotations.openMocks;
import org.alfresco.rest.core.RestWrapper;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/** Unit tests for {@link ModelRequest}. */
public class ModelRequestTest
{
/** Abstract class, so test with mock passing through to real methods. */
@InjectMocks
private ModelRequest<Object> modelRequest = mock(ModelRequest.class, CALLS_REAL_METHODS);
@Mock
private RestWrapper restWrapperMock;
@BeforeMethod
public void setUp()
{
openMocks(this);
}
@Test
public void testInclude_empty()
{
modelRequest.include();
then(restWrapperMock).should().withParams("include=");
then(restWrapperMock).shouldHaveNoMoreInteractions();
}
@Test
public void testInclude_singleInclude()
{
modelRequest.include("field1");
then(restWrapperMock).should().withParams("include=field1");
then(restWrapperMock).shouldHaveNoMoreInteractions();
}
@Test
public void testInclude_multipleIncludes()
{
modelRequest.include("field1", "field2", "field3");
then(restWrapperMock).should().withParams("include=field1,field2,field3");
then(restWrapperMock).shouldHaveNoMoreInteractions();
}
@Test
public void testIncludePath()
{
modelRequest.includePath();
then(restWrapperMock).should().withParams("include=path");
then(restWrapperMock).shouldHaveNoMoreInteractions();
}
@Test
public void testUsingParams()
{
modelRequest.usingParams("param1=value1", "param2=value2");
then(restWrapperMock).should().withParams("param1=value1", "param2=value2");
then(restWrapperMock).shouldHaveNoMoreInteractions();
}
}