Cleanup acceptance tests (#6195)

This commit is contained in:
Phil Davis
2023-05-02 17:25:56 +05:45
committed by GitHub
parent 332593d8bb
commit 9b9d88e7d6
24 changed files with 398 additions and 1021 deletions

View File

@@ -34,10 +34,7 @@ use Behat\Behat\Context\Context;
* AppConfiguration trait
*/
class AppConfigurationContext implements Context {
/**
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @When /^the administrator sets parameter "([^"]*)" of app "([^"]*)" to ((?:'[^']*')|(?:"[^"]*"))$/

View File

@@ -29,25 +29,10 @@ use TestHelpers\SetupHelper;
* Authentication functions
*/
class AuthContext implements Context {
/**
* @var string
*/
private $clientToken;
/**
* @var string
*/
private $appToken;
/**
* @var array
*/
private $appTokens;
/**
* @var FeatureContext
*/
private $featureContext;
private string $clientToken;
private string $appToken;
private array $appTokens;
private FeatureContext $featureContext;
/**
* get the client token that was last generated
@@ -156,15 +141,15 @@ class AuthContext implements Context {
* @throws Exception
*/
public function verifyStatusCode(string $ocsCode, string $httpCode, string $endPoint):void {
if ($ocsCode !== null) {
if ($ocsCode !== '') {
$this->featureContext->ocsContext->theOCSStatusCodeShouldBe(
$ocsCode,
$message = "Got unexpected OCS code while sending request to endpoint " . $endPoint
"Got unexpected OCS code while sending request to endpoint " . $endPoint
);
}
$this->featureContext->theHTTPStatusCodeShouldBe(
$httpCode,
$message = "Got unexpected HTTP code while sending request to endpoint " . $endPoint
"Got unexpected HTTP code while sending request to endpoint " . $endPoint
);
}
@@ -173,11 +158,11 @@ class AuthContext implements Context {
*
* @param string $method
* @param ?string $body
* @param string $ofUser
* @param string|null $ofUser
* @param TableNode $table
*
* @return void
* @throws Exception
* @throws JsonException
*/
public function userRequestsEndpointsWithBodyAndNoAuthThenStatusCodeAboutUser(string $method, ?string $body, ?string $ofUser, TableNode $table):void {
$ofUser = \strtolower($this->featureContext->getActualUsername($ofUser));

View File

@@ -24,7 +24,6 @@
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\TableNode;
use PHPUnit\Framework\Assert;
require_once 'bootstrap.php';
@@ -33,11 +32,7 @@ require_once 'bootstrap.php';
* Capabilities context.
*/
class CapabilitiesContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @Then the major-minor-micro version data in the response should match the version string
@@ -106,7 +101,7 @@ class CapabilitiesContext implements Context {
Assert::assertEquals(
$value === "EMPTY" ? '' : $value,
$actualValue,
"Expected {$pathToElement} capability of files sharing app to be {$value}, but got {$actualValue}"
"Expected $pathToElement capability of files sharing app to be $value, but got $actualValue"
);
}

View File

@@ -30,11 +30,7 @@ require_once 'bootstrap.php';
* Checksum functions
*/
class ChecksumContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @When user :user uploads file :source to :destination with checksum :checksum using the WebDAV API
@@ -60,8 +56,7 @@ class ChecksumContext implements Context {
'PUT',
$destination,
['OC-Checksum' => $checksum],
$file,
"files"
$file
);
$this->featureContext->setResponse($response);
}
@@ -113,8 +108,7 @@ class ChecksumContext implements Context {
'PUT',
$destination,
['OC-Checksum' => $checksum],
$content,
"files"
$content
);
$this->featureContext->setResponse($response);
}
@@ -267,7 +261,7 @@ class ChecksumContext implements Context {
Assert::assertEquals(
$expectedChecksum,
$actualChecksum,
"Expected: webDav checksum should be {$expectedChecksum} but got {$actualChecksum}"
"Expected: webDav checksum should be $expectedChecksum but got $actualChecksum"
);
}
@@ -321,7 +315,7 @@ class ChecksumContext implements Context {
Assert::assertEquals(
$expectedChecksum,
$headerChecksum,
"Expected: header checksum should match {$expectedChecksum} but got {$headerChecksum}"
"Expected: header checksum should match $expectedChecksum but got $headerChecksum"
);
}
@@ -361,7 +355,7 @@ class ChecksumContext implements Context {
Assert::assertEquals(
$expectedStatus,
$status,
"Expected status to be {$expectedStatus} but got {$status}"
"Expected status to be $expectedStatus but got $status"
);
}
@@ -408,8 +402,7 @@ class ChecksumContext implements Context {
'PUT',
$file,
['OC-Checksum' => $expectedChecksum, 'OC-Chunked' => '1'],
$data,
"files"
$data
);
$this->featureContext->setResponse($response);
}

View File

@@ -32,17 +32,8 @@ require_once 'bootstrap.php';
* context containing favorites related API steps
*/
class FavoritesContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
/**
*
* @var WebDavPropertiesContext
*/
private $webDavPropertiesContext;
private FeatureContext $featureContext;
private WebDavPropertiesContext $webDavPropertiesContext;
/**
* @param string$user
@@ -117,8 +108,8 @@ class FavoritesContext implements Context {
}
/**
* @param $user
* @param $path
* @param string $user
* @param string $path
*
* @return void
*/
@@ -171,7 +162,7 @@ class FavoritesContext implements Context {
TableNode $expectedElements
):void {
$user = $this->featureContext->getActualUsername($user);
$this->userListsFavorites($user, null);
$this->userListsFavorites($user);
$this->featureContext->propfindResultShouldContainEntries(
$shouldOrNot,
$expectedElements,

View File

@@ -54,34 +54,14 @@ class FeatureContext extends BehatVariablesContext {
use WebDav;
/**
* @var int Unix timestamp seconds
* Unix timestamp seconds
*/
private $scenarioStartTime;
/**
* @var string
*/
private $adminUsername = '';
/**
* @var string
*/
private $adminPassword = '';
/**
* @var string
*/
private $adminDisplayName = '';
/**
* @var string
*/
private $adminEmailAddress = '';
/**
* @var string
*/
private $originalAdminPassword = '';
private int $scenarioStartTime;
private string $adminUsername = '';
private string $adminPassword = '';
private string $adminDisplayName = '';
private string $adminEmailAddress = '';
private string $originalAdminPassword = '';
/**
* An array of values of replacement values of user attributes.
@@ -89,240 +69,111 @@ class FeatureContext extends BehatVariablesContext {
* run-time values are maintained and referenced in the $createdUsers array.
*
* Key is the username, value is an array of user attributes
*
* @var array|null
*/
private $userReplacements = null;
/**
* @var string
*/
private $regularUserPassword = '';
/**
* @var string
*/
private $alt1UserPassword = '';
/**
* @var string
*/
private $alt2UserPassword = '';
/**
* @var string
*/
private $alt3UserPassword = '';
/**
* @var string
*/
private $alt4UserPassword = '';
private ?array $userReplacements = null;
private string $regularUserPassword = '';
private string $alt1UserPassword = '';
private string $alt2UserPassword = '';
private string $alt3UserPassword = '';
private string $alt4UserPassword = '';
/**
* The password to use in tests that create a sub-admin user
*
* @var string
*/
private $subAdminPassword = '';
private string $subAdminPassword = '';
/**
* The password to use in tests that create another admin user
*
* @var string
*/
private $alternateAdminPassword = '';
private string $alternateAdminPassword = '';
/**
* The password to use in tests that create public link shares
*
* @var string
*/
private $publicLinkSharePassword = '';
private string $publicLinkSharePassword = '';
private string $ocPath = '';
/**
* @var string
* Location of the root folder of ownCloud on the local server under test
*/
private $ocPath = '';
/**
* @var string location of the root folder of ownCloud on the local server under test
*/
private $localServerRoot = null;
/**
* @var string
*/
private $currentUser = '';
/**
* @var string
*/
private $currentServer = '';
private ?string $localServerRoot = null;
private string $currentUser = '';
private string $currentServer = '';
/**
* The base URL of the current server under test,
* without any terminating slash
* e.g. http://localhost:8080
*
* @var string
*/
private $baseUrl = '';
private string $baseUrl = '';
/**
* The base URL of the local server under test,
* without any terminating slash
* e.g. http://localhost:8080
*
* @var string
*/
private $localBaseUrl = '';
private string $localBaseUrl = '';
/**
* The base URL of the remote (federated) server under test,
* without any terminating slash
* e.g. http://localhost:8180
*
* @var string
*/
private $remoteBaseUrl = '';
private string $remoteBaseUrl = '';
/**
* The suite name, feature name and scenario line number.
* Example: apiComments/createComments.feature:24
*
* @var string
*/
private $scenarioString = '';
private string $scenarioString = '';
/**
* A full unique reference to the step that is currently executing.
* Example: apiComments/createComments.feature:24-28
* That is line 28, in the scenario at line 24, in the createComments feature
* in the apiComments suite.
*
* @var string
*/
private $stepLineRef = '';
private string $stepLineRef = '';
private bool $sendStepLineRef = false;
private bool $sendStepLineRefHasBeenChecked = false;
/**
* @var bool|null
*/
private $sendStepLineRef = null;
/**
*
*
* @var boolean true if TEST_SERVER_FED_URL is defined
*/
private $federatedServerExists = false;
/**
* @var int
*/
private $ocsApiVersion = 1;
/**
* @var ResponseInterface
*/
private $response = null;
/**
* @var string
*/
private $responseUser = "";
/**
* @var string
*/
private $responseBodyContent = null;
/**
* @var array
*/
private $userResponseBodyContents = [];
/**
* @var array
*/
public $emailRecipients = [];
/**
* @var CookieJar
*/
private $cookieJar;
/**
* @var string
*/
private $requestToken;
/**
* @var array
*/
private $storageIds = [];
/**
* @var array
*/
private $createdFiles = [];
private bool $federatedServerExists = false;
private int $ocsApiVersion = 1;
private ?ResponseInterface $response = null;
private string $responseUser = '';
private ?string $responseBodyContent = null;
private array $userResponseBodyContents = [];
public array $emailRecipients = [];
private CookieJar $cookieJar;
private string $requestToken;
private array $storageIds = [];
private array $createdFiles = [];
/**
* The local source IP address from which to initiate API actions.
* Defaults to system-selected address matching IP address family and scope.
*
* @var string|null
*/
private $sourceIpAddress = null;
private $guzzleClientHeaders = [];
/**
*
* @var OCSContext
*/
public $ocsContext;
/**
*
* @var AuthContext
*/
public $authContext;
/**
*
* @var GraphContext
*/
public $graphContext;
/**
*
* @var AppConfigurationContext
*/
public $appConfigurationContext;
/**
* @var array
*/
private $initialTrustedServer;
private ?string $sourceIpAddress = null;
private array $guzzleClientHeaders = [];
public OCSContext $ocsContext;
public AuthContext $authContext;
public GraphContext $graphContext;
public AppConfigurationContext $appConfigurationContext;
private array $initialTrustedServer;
/**
* The codes are stored as strings, even though they are numbers
*
* @var array last http status codes
*/
private $lastHttpStatusCodesArray = [];
/**
* @var array last ocs status codes
*/
private $lastOCSStatusCodesArray = [];
private array $lastHttpStatusCodesArray = [];
private array $lastOCSStatusCodesArray = [];
/**
* @var bool
*
* this is set true for db conversion tests
*/
private $dbConversion = false;
private bool $dbConversion = false;
/**
* @param bool $value
@@ -340,10 +191,7 @@ class FeatureContext extends BehatVariablesContext {
return $this->dbConversion;
}
/**
* @var string
*/
private $oCSelector;
private string $oCSelector;
/**
* @param string $selector
@@ -402,7 +250,7 @@ class FeatureContext extends BehatVariablesContext {
* @return void
*/
public function pushToLastOcsCodesArray(string $ocsStatusCode): void {
array_push($this->lastOCSStatusCodesArray, $ocsStatusCode);
$this->lastOCSStatusCodesArray[] = $ocsStatusCode;
}
/**
@@ -438,54 +286,21 @@ class FeatureContext extends BehatVariablesContext {
}
}
/*
* @var Ldap
*/
private $ldap;
/**
* @var string
*/
private $ldapBaseDN;
/**
* @var string
*/
private $ldapHost;
/**
* @var int
*/
private $ldapPort;
/**
* @var string
*/
private $ldapAdminUser;
/**
* @var string
*/
private $ldapAdminPassword = "";
/**
* @var string
*/
private $ldapUsersOU;
/**
* @var string
*/
private $ldapGroupsOU;
/**
* @var string
*/
private $ldapGroupSchema;
/**
* @var bool
*/
private $skipImportLdif;
/**
* @var array
*/
private $toDeleteDNs = [];
private $ldapCreatedUsers = [];
private $ldapCreatedGroups = [];
private $toDeleteLdapConfigs = [];
private $oldLdapConfig = [];
private Ldap $ldap;
private string $ldapBaseDN;
private string $ldapHost;
private int $ldapPort;
private string $ldapAdminUser;
private string $ldapAdminPassword = "";
private string $ldapUsersOU;
private string $ldapGroupsOU;
private string $ldapGroupSchema;
private bool $skipImportLdif;
private array $toDeleteDNs = [];
private array $ldapCreatedUsers = [];
private array $ldapCreatedGroups = [];
private array $toDeleteLdapConfigs = [];
private array $oldLdapConfig = [];
/**
* @return Ldap
@@ -590,8 +405,9 @@ class FeatureContext extends BehatVariablesContext {
* @return bool
*/
public function sendScenarioLineReferencesInXRequestId(): ?bool {
if ($this->sendStepLineRef === null) {
if ($this->sendStepLineRefHasBeenChecked === false) {
$this->sendStepLineRef = (\getenv("SEND_SCENARIO_LINE_REFERENCES") === "true");
$this->sendStepLineRefHasBeenChecked = true;
}
return $this->sendStepLineRef;
}
@@ -4032,15 +3848,12 @@ class FeatureContext extends BehatVariablesContext {
$this->getAdminPassword(),
$userName
);
if ($response) {
$data = \json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
if (isset($data["id"])) {
return $data["id"];
} else {
throw new Exception(__METHOD__ . " accounts-list is empty");
}
$data = \json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
if (isset($data["id"])) {
return $data["id"];
} else {
throw new Exception(__METHOD__ . " accounts-list is empty");
}
throw new Exception(__METHOD__ . " user with name $userName not found");
}
/**
@@ -4059,14 +3872,11 @@ class FeatureContext extends BehatVariablesContext {
$this->getAdminPassword(),
$groupName
);
if ($response) {
$data = $this->getJsonDecodedResponse($response);
if (isset($data["id"])) {
return $data["id"];
} else {
throw new Exception(__METHOD__ . " accounts-list is empty");
}
$data = $this->getJsonDecodedResponse($response);
if (isset($data["id"])) {
return $data["id"];
} else {
throw new Exception(__METHOD__ . " accounts-list is empty");
}
throw new Exception(__METHOD__ . " Group with name $groupName not found");
}
}

View File

@@ -33,11 +33,7 @@ require_once 'bootstrap.php';
* Steps that relate to files_versions app
*/
class FilesVersionsContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @param string $fileId
@@ -240,8 +236,8 @@ class FilesVersionsContext implements Context {
Assert::assertEquals(
$length,
(int) $xmlPart[$index],
"The content length of file {$path} with version {$index} for user {$user} was
expected to be {$length} but the actual content length is {$xmlPart[$index]}"
"The content length of file $path with version $index for user $user was
expected to be $length but the actual content length is $xmlPart[$index]"
);
}

View File

@@ -26,17 +26,12 @@ require_once 'bootstrap.php';
* Context for the provisioning specific steps using the Graph API
*/
class GraphContext implements Context {
/**
* @var FeatureContext
*/
private FeatureContext $featureContext;
/**
* application Entity
*
* @var array
*/
private $appEntity = [];
private array $appEntity = [];
/**
* This will run before EVERY scenario.
@@ -195,7 +190,7 @@ class GraphContext implements Context {
* @throws Exception
*/
public function theUserEnablesUserToUsingTheGraphApi(string $byUser, string $user): void {
$response = $this->editUserUsingTheGraphApi($byUser, $user, null, null, null, null, true);
$response = $this->editUserUsingTheGraphApi($byUser, $user);
$this->featureContext->setResponse($response);
}
@@ -257,7 +252,7 @@ class GraphContext implements Context {
public function adminHasRetrievedUserUsingTheGraphApi(string $user): void {
$user = $this->featureContext->getActualUsername($user);
$userId = $this->featureContext->getAttributeOfCreatedUser($user, "id");
$userId = $userId ? $userId : $user;
$userId = $userId ?: $user;
$result = GraphHelper::getUser(
$this->featureContext->getBaseUrl(),
$this->featureContext->getStepLineRef(),
@@ -1162,7 +1157,7 @@ class GraphContext implements Context {
*
* @return void
*/
public function userGetsAllTheMembersOfGroupUsingTheGraphApi($user, $group): void {
public function userGetsAllTheMembersOfGroupUsingTheGraphApi(string $user, string $group): void {
$this->featureContext->setResponse($this->listGroupMembers($group, $user));
}
@@ -1231,7 +1226,7 @@ class GraphContext implements Context {
*
* @param string $oldGroupId
* @param string $newGroup
* @param string $user
* @param string|null $user
*
* @return ResponseInterface
* @throws GuzzleException
@@ -1682,7 +1677,7 @@ class GraphContext implements Context {
$groupId = $this->featureContext->getAttributeOfCreatedGroup($group, "id");
foreach ($table->getHash() as $row) {
$userId = $this->featureContext->getAttributeOfCreatedUser($row['username'], "id");
$userIds[] = $userId ? $userId : WebDavHelper::generateUUIDv4();
$userIds[] = $userId ?: WebDavHelper::generateUUIDv4();
}
$this->addMultipleUsersToGroup($user, $userIds, $groupId, $table);
}
@@ -1781,7 +1776,7 @@ class GraphContext implements Context {
public function userGetsAllUsersOfTwoGroupsUsingTheGraphApi(string $user, string $groups) {
$groupsIdArray = [];
foreach (explode(',', $groups) as $group) {
array_push($groupsIdArray, $this->featureContext->getGroupIdByGroupName($group));
$groupsIdArray[] = $this->featureContext->getGroupIdByGroupName($group);
}
$response = GraphHelper::getUsersOfTwoGroups(
$this->featureContext->getBaseUrl(),
@@ -2066,7 +2061,7 @@ class GraphContext implements Context {
$this->addMultipleUsersToGroup($user, $userIds, $groupId, $table);
$response = $this->featureContext->getResponse();
if ($response->getStatusCode() !== 204) {
$$this->throwHttpException($response, "Cannot add users to group '$group'");
$this->throwHttpException($response, "Cannot add users to group '$group'");
}
$this->featureContext->emptyLastHTTPStatusCodesArray();
}

View File

@@ -18,20 +18,9 @@ require_once 'bootstrap.php';
* Defines application features from the specific context.
*/
class NotificationContext implements Context {
/**
* @var FeatureContext
*/
private $featureContext;
/**
* @var string
*/
private FeatureContext $featureContext;
private string $notificationEndpointPath = '/apps/notifications/api/v1/notifications?format=json';
/**
* @var array[]
*/
private $notificationIds;
private array $notificationIds;
/**
* @return array[]

View File

@@ -35,11 +35,7 @@ require_once 'bootstrap.php';
* steps needed to send requests to the OCS API
*/
class OCSContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @When /^the user sends HTTP method "([^"]*)" to OCS API endpoint "([^"]*)"$/
@@ -50,7 +46,7 @@ class OCSContext implements Context {
* @return void
*/
public function theUserSendsToOcsApiEndpoint(string $verb, string $url):void {
$this->theUserSendsToOcsApiEndpointWithBody($verb, $url, null);
$this->theUserSendsToOcsApiEndpointWithBody($verb, $url);
}
/**
@@ -62,7 +58,7 @@ class OCSContext implements Context {
* @return void
*/
public function theUserHasSentToOcsApiEndpoint(string $verb, string $url):void {
$this->theUserSendsToOcsApiEndpointWithBody($verb, $url, null);
$this->theUserSendsToOcsApiEndpointWithBody($verb, $url);
$this->featureContext->theHTTPStatusCodeShouldBeSuccess();
}
@@ -129,14 +125,10 @@ class OCSContext implements Context {
/**
* array of the data to be sent in the body.
* contains $body data converted to an array
*
* @var array $bodyArray
*/
$bodyArray = [];
if ($body instanceof TableNode) {
$bodyArray = $body->getRowsHash();
} elseif ($body !== null && \is_array($body)) {
$bodyArray = $body;
}
if ($user !== 'UNAUTHORIZED_USER') {
@@ -233,7 +225,7 @@ class OCSContext implements Context {
* @param string $verb
* @param string $url
* @param TableNode|null $body
* @param string $password
* @param string|null $password
*
* @return void
*/
@@ -793,7 +785,7 @@ class OCSContext implements Context {
* @return void
* @throws Exception
*/
public function theOCSStatusCodeShouldBe(string $statusCode, $message = ""):void {
public function theOCSStatusCodeShouldBe(string $statusCode, string $message = ""):void {
$statusCodes = explode(",", $statusCode);
$responseStatusCode = $this->getOCSResponseStatusCode(
$this->featureContext->getResponse()

View File

@@ -25,7 +25,6 @@ use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
use PHPUnit\Framework\Assert;
use TestHelpers\OcsApiHelper;
use TestHelpers\SetupHelper;
use TestHelpers\UserHelper;
use TestHelpers\HttpRequestHelper;
use TestHelpers\OcisHelper;
@@ -40,48 +39,20 @@ trait Provisioning {
/**
* list of users that were created on the local server during test runs
* key is the lowercase username, value is an array of user attributes
*
* @var array
*/
private $createdUsers = [];
private array $createdUsers = [];
/**
* list of users that were created on the remote server during test runs
* key is the lowercase username, value is an array of user attributes
*
* @var array
*/
private $createdRemoteUsers = [];
/**
* @var array
*/
private $enabledApps = [];
/**
* @var array
*/
private $disabledApps = [];
/**
* @var array
*/
private $startingGroups = [];
/**
* @var array
*/
private $createdRemoteGroups = [];
/**
* @var array
*/
private $createdGroups = [];
/**
* @var array
*/
private $userResponseFields = [
private array $createdRemoteUsers = [];
private array $enabledApps = [];
private array $disabledApps = [];
private array $startingGroups = [];
private array $createdRemoteGroups = [];
private array $createdGroups = [];
private array $userResponseFields = [
"enabled", "quota", "email", "displayname", "home", "two_factor_auth_enabled",
"quota definition", "quota free", "quota user", "quota total", "quota relative"
];
@@ -558,10 +529,10 @@ trait Provisioning {
foreach ($items as $item) {
if (isset($item["objectclass"])) {
if (\in_array("posixGroup", $item["objectclass"])) {
\array_push($this->ldapCreatedGroups, $item["cn"][0]);
$this->ldapCreatedGroups[] = $item["cn"][0];
$this->addGroupToCreatedGroupsList($item["cn"][0]);
} elseif (\in_array("inetOrgPerson", $item["objectclass"])) {
\array_push($this->ldapCreatedUsers, $item["uid"][0]);
$this->ldapCreatedUsers[] = $item["uid"][0];
$this->addUserToCreatedUsersList($item["uid"][0], $item["userpassword"][0]);
}
}
@@ -578,8 +549,6 @@ trait Provisioning {
* @throws \LdapException
*/
public function connectToLdap(array $suiteParameters):void {
$useSsl = false;
$this->ldapBaseDN = OcisHelper::getBaseDN();
$this->ldapUsersOU = OcisHelper::getUsersOU();
$this->ldapGroupsOU = OcisHelper::getGroupsOU();
@@ -609,7 +578,7 @@ trait Provisioning {
$this->ldap = new Ldap($options);
$this->ldap->bind();
$ldifFile = __DIR__ . (string)$suiteParameters['ldapInitialUserFilePath'];
$ldifFile = __DIR__ . $suiteParameters['ldapInitialUserFilePath'];
if (OcisHelper::isTestingParallelDeployment()) {
$behatYml = \getenv("BEHAT_YML");
if ($behatYml) {
@@ -686,7 +655,7 @@ trait Provisioning {
$userId = \str_replace('+', '\+', $setting["userid"]);
$newDN = 'uid=' . $userId . ',ou=' . $ou . ',' . $this->ldapBaseDN;
//pick a high uidnumber to make sure there are no conflicts with existing uidnumbers
//pick a high uid number to make sure there are no conflicts with existing uid numbers
$uidNumber = \count($this->ldapCreatedUsers) + 30000;
$entry = [];
$entry['cn'] = $userId;
@@ -903,7 +872,7 @@ trait Provisioning {
$useGraph = true;
}
foreach ($usersAttributes as $i => $userAttributes) {
foreach ($usersAttributes as $userAttributes) {
if ($useLdap) {
$this->createLdapUser($userAttributes);
} else {
@@ -988,10 +957,7 @@ trait Provisioning {
// Create requests for setting displayname and email for the newly created users.
// These values cannot be set while creating the user, so we have to edit the newly created user to set these values.
$users = [];
$editData = [];
foreach ($usersAttributes as $userAttributes) {
$users[] = $userAttributes['userid'];
if ($useGraph) {
// for graph api, we need to save the user id to be able to add it in some group
// can be fetched with the "onPremisesSamAccountName" i.e. userid
@@ -1195,7 +1161,7 @@ trait Provisioning {
*/
public function userEnablesOrDisablesApp(string $user, string $action, string $app):void {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/apps/$app";
. "/ocs/v$this->ocsApiVersion.php/cloud/apps/$app";
if ($action === 'enables') {
$this->response = HttpRequestHelper::post(
$fullUrl,
@@ -1615,7 +1581,7 @@ trait Provisioning {
* @Given the administrator has reset the password of user :username to :password
*
* @param string $username of the user whose password is reset
* @param string $password
* @param string|null $password
*
* @return void
*/
@@ -2766,7 +2732,7 @@ trait Provisioning {
* @return void
*/
public function userGetsAllTheMembersOfGroupUsingTheProvisioningApi(string $user, string $group):void {
$fullUrl = $this->getBaseUrl() . "/ocs/v{$this->ocsApiVersion}.php/cloud/groups/$group";
$fullUrl = $this->getBaseUrl() . "/ocs/v$this->ocsApiVersion.php/cloud/groups/$group";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -2781,7 +2747,7 @@ trait Provisioning {
* @return ResponseInterface
*/
public function getAllGroups():ResponseInterface {
$fullUrl = $this->getBaseUrl() . "/ocs/v{$this->ocsApiVersion}.php/cloud/groups";
$fullUrl = $this->getBaseUrl() . "/ocs/v$this->ocsApiVersion.php/cloud/groups";
return HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -2809,7 +2775,7 @@ trait Provisioning {
* @throws Exception
*/
public function userTriesToGetAllTheGroupsUsingTheProvisioningApi(string $user):void {
$fullUrl = $this->getBaseUrl() . "/ocs/v{$this->ocsApiVersion}.php/cloud/groups";
$fullUrl = $this->getBaseUrl() . "/ocs/v$this->ocsApiVersion.php/cloud/groups";
$actualUser = $this->getActualUsername($user);
$actualPassword = $this->getUserPassword($actualUser);
$this->response = HttpRequestHelper::get(
@@ -2843,7 +2809,7 @@ trait Provisioning {
*/
public function userGetsAllTheGroupsOfUser(string $user, string $otherUser):void {
$actualOtherUser = $this->getActualUsername($otherUser);
$fullUrl = $this->getBaseUrl() . "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$actualOtherUser/groups";
$fullUrl = $this->getBaseUrl() . "/ocs/v$this->ocsApiVersion.php/cloud/users/$actualOtherUser/groups";
$actualUser = $this->getActualUsername($user);
$actualPassword = $this->getUserPassword($actualUser);
$this->response = HttpRequestHelper::get(
@@ -2872,7 +2838,7 @@ trait Provisioning {
* @throws Exception
*/
public function userGetsTheListOfAllUsersUsingTheProvisioningApi(string $user):void {
$fullUrl = $this->getBaseUrl() . "/ocs/v{$this->ocsApiVersion}.php/cloud/users";
$fullUrl = $this->getBaseUrl() . "/ocs/v$this->ocsApiVersion.php/cloud/users";
$actualUser = $this->getActualUsername($user);
$actualPassword = $this->getUserPassword($actualUser);
$this->response = HttpRequestHelper::get(
@@ -2894,14 +2860,13 @@ trait Provisioning {
*/
public function initializeUser(string $user, string $password):void {
$url = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$user";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$user";
HttpRequestHelper::get(
$url,
$this->getStepLineRef(),
$user,
$password
);
$this->lastUploadTime = \time();
}
/**
@@ -3011,7 +2976,7 @@ trait Provisioning {
* @param bool $skeleton
*
* @return void
* @throws Exception
* @throws Exception|GuzzleException
*/
public function createUser(
?string $user,
@@ -3064,7 +3029,7 @@ trait Provisioning {
$setting["displayName"] = $displayName;
$setting["password"] = $password;
$setting["email"] = $email;
\array_push($settings, $setting);
$settings[] = $setting;
try {
$this->usersHaveBeenCreated(
$initialize,
@@ -3074,7 +3039,7 @@ trait Provisioning {
);
} catch (LdapException $exception) {
throw new Exception(
__METHOD__ . " cannot create a LDAP user with provided data. Error: {$exception}"
__METHOD__ . " cannot create a LDAP user with provided data. Error: $exception"
);
}
break;
@@ -3203,7 +3168,6 @@ trait Provisioning {
*/
public function userShouldBelongToGroup(string $user, string $group):void {
$user = $this->getActualUsername($user);
$respondedArray = [];
if (OcisHelper::isTestingWithGraphApi()) {
$this->graphContext->userShouldBeMemberInGroupUsingTheGraphApi(
$user,
@@ -3535,7 +3499,7 @@ trait Provisioning {
);
} catch (LdapException $exception) {
throw new Exception(
"User " . $user . " cannot be added to " . $group . " . Error: {$exception}"
"User $user cannot be added to $group Error: $exception"
);
};
break;
@@ -3781,7 +3745,7 @@ trait Provisioning {
$this->createLdapGroup($group);
} catch (LdapException $e) {
throw new Exception(
"could not create group '$group'. Error: {$e}"
"could not create group '$group'. Error: $e"
);
}
break;
@@ -3831,8 +3795,6 @@ trait Provisioning {
if ($ou === null) {
$ou = $this->getLdapGroupsOU();
}
$memberAttr = "";
$memberValue = "";
if ($this->ldapGroupSchema == "rfc2307") {
$memberAttr = "memberUID";
$memberValue = "$user";
@@ -3875,8 +3837,6 @@ trait Provisioning {
if ($ou === null) {
$ou = $this->getLdapGroupsOU();
}
$memberAttr = "";
$memberValue = "";
if ($this->ldapGroupSchema == "rfc2307") {
$memberAttr = "memberUID";
$memberValue = "$user";
@@ -4447,7 +4407,7 @@ trait Provisioning {
$actualSubadminUsername = $this->getActualUsername($otherUser);
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$actualSubadminUsername/subadmins";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$actualSubadminUsername/subadmins";
$body = ['groupid' => $group];
$this->response = HttpRequestHelper::post(
$fullUrl,
@@ -4468,7 +4428,7 @@ trait Provisioning {
*/
public function theAdministratorGetsAllTheGroupsWhereUserIsSubadminUsingTheProvisioningApi(string $user):void {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$user/subadmins";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$user/subadmins";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -4490,7 +4450,7 @@ trait Provisioning {
public function userTriesToGetAllTheGroupsWhereUserIsSubadminUsingTheProvisioningApi(string $user, string $otherUser):void {
$actualOtherUser = $this->getActualUsername($otherUser);
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$actualOtherUser/subadmins";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$actualOtherUser/subadmins";
$actualUser = $this->getActualUsername($user);
$actualPassword = $this->getUserPassword($actualUser);
$this->response = HttpRequestHelper::get(
@@ -4549,7 +4509,7 @@ trait Provisioning {
*/
public function userGetsAllTheSubadminsOfGroupUsingTheProvisioningApi(string $user, string $group):void {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/groups/$group/subadmins";
. "/ocs/v$this->ocsApiVersion.php/cloud/groups/$group/subadmins";
$actualUser = $this->getActualUsername($user);
$actualPassword = $this->getUserPassword($actualUser);
$this->response = HttpRequestHelper::get(
@@ -4596,7 +4556,7 @@ trait Provisioning {
):void {
$actualOtherUser = $this->getActualUsername($otherUser);
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$actualOtherUser/subadmins";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$actualOtherUser/subadmins";
$actualUser = $this->getActualUsername($user);
$actualPassword = $this->getUserPassword($actualUser);
$this->response = HttpRequestHelper::delete(
@@ -5101,9 +5061,7 @@ trait Provisioning {
public function getArrayOfUsersResponded(ResponseInterface $resp):array {
$listCheckedElements
= $this->getResponseXml($resp, __METHOD__)->data[0]->users[0]->element;
$extractedElementsArray
= \json_decode(\json_encode($listCheckedElements), true);
return $extractedElementsArray;
return \json_decode(\json_encode($listCheckedElements), true);
}
/**
@@ -5117,9 +5075,7 @@ trait Provisioning {
public function getArrayOfGroupsResponded(ResponseInterface $resp):array {
$listCheckedElements
= $this->getResponseXml($resp, __METHOD__)->data[0]->groups[0]->element;
$extractedElementsArray
= \json_decode(\json_encode($listCheckedElements), true);
return $extractedElementsArray;
return \json_decode(\json_encode($listCheckedElements), true);
}
/**
@@ -5133,9 +5089,7 @@ trait Provisioning {
public function getArrayOfAppsResponded(ResponseInterface $resp):array {
$listCheckedElements
= $this->getResponseXml($resp, __METHOD__)->data[0]->apps[0]->element;
$extractedElementsArray
= \json_decode(\json_encode($listCheckedElements), true);
return $extractedElementsArray;
return \json_decode(\json_encode($listCheckedElements), true);
}
/**
@@ -5149,9 +5103,7 @@ trait Provisioning {
public function getArrayOfSubadminsResponded(ResponseInterface $resp):array {
$listCheckedElements
= $this->getResponseXml($resp, __METHOD__)->data[0]->element;
$extractedElementsArray
= \json_decode(\json_encode($listCheckedElements), true);
return $extractedElementsArray;
return \json_decode(\json_encode($listCheckedElements), true);
}
/**
@@ -5165,9 +5117,7 @@ trait Provisioning {
public function getArrayOfAppInfoResponded(ResponseInterface $resp):array {
$listCheckedElements
= $this->getResponseXml($resp, __METHOD__)->data[0];
$extractedElementsArray
= \json_decode(\json_encode($listCheckedElements), true);
return $extractedElementsArray;
return \json_decode(\json_encode($listCheckedElements), true);
}
/**
@@ -5263,7 +5213,7 @@ trait Provisioning {
public function userShouldBeDisabled(string $user):void {
$user = $this->getActualUsername($user);
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$user";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$user";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -5303,7 +5253,7 @@ trait Provisioning {
public function userShouldBeEnabled(string $user):void {
$user = $this->getActualUsername($user);
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$user";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$user";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -5355,8 +5305,7 @@ trait Provisioning {
"PUT",
"/cloud/users/$user",
$this->getStepLineRef(),
$body,
2
$body
);
}
@@ -5395,26 +5344,6 @@ trait Provisioning {
$this->theQuotaOfUserHasBeenSetTo($user, 'none');
}
/**
* Returns home path of the given user
*
* @param string $user
*
* @return string
* @throws Exception
*/
public function getUserHome(string $user):string {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$user";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
$this->getAdminUsername(),
$this->getAdminPassword()
);
return $this->getResponseXml(null, __METHOD__)->data[0]->home;
}
/**
* @Then /^the user attributes returned by the API should include$/
*
@@ -5455,8 +5384,7 @@ trait Provisioning {
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$this->getAdminUsername(),
"GET",
"/cloud/users/$user",
null
"/cloud/users/$user"
);
$this->checkUserAttributes($body);
}
@@ -5551,11 +5479,11 @@ trait Provisioning {
public function cleanupDatabaseUsers():void {
$previousServer = $this->currentServer;
$this->usingServer('LOCAL');
foreach ($this->createdUsers as $user => $userData) {
foreach ($this->createdUsers as $userData) {
$this->deleteUser($userData['actualUsername']);
}
$this->usingServer('REMOTE');
foreach ($this->createdRemoteUsers as $remoteUser => $userData) {
foreach ($this->createdRemoteUsers as $userData) {
$this->deleteUser($userData['actualUsername']);
}
$this->usingServer($previousServer);
@@ -5616,7 +5544,7 @@ trait Provisioning {
$actualOtherUser = $this->getActualUsername($otherUser);
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/users/$actualOtherUser/$action";
. "/ocs/v$this->ocsApiVersion.php/cloud/users/$actualOtherUser/$action";
$this->response = HttpRequestHelper::put(
$fullUrl,
$this->getStepLineRef(),
@@ -5634,7 +5562,7 @@ trait Provisioning {
*/
public function getAllApps():array {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/apps";
. "/ocs/v$this->ocsApiVersion.php/cloud/apps";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -5652,7 +5580,7 @@ trait Provisioning {
*/
public function getEnabledApps():array {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/apps?filter=enabled";
. "/ocs/v$this->ocsApiVersion.php/cloud/apps?filter=enabled";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),
@@ -5670,7 +5598,7 @@ trait Provisioning {
*/
public function getDisabledApps():array {
$fullUrl = $this->getBaseUrl()
. "/ocs/v{$this->ocsApiVersion}.php/cloud/apps?filter=disabled";
. "/ocs/v$this->ocsApiVersion.php/cloud/apps?filter=disabled";
$this->response = HttpRequestHelper::get(
$fullUrl,
$this->getStepLineRef(),

View File

@@ -22,9 +22,9 @@
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use GuzzleHttp\Exception\GuzzleException;
use PHPUnit\Framework\Assert;
use TestHelpers\HttpRequestHelper;
use TestHelpers\OcisHelper;
use TestHelpers\WebDavHelper;
require_once 'bootstrap.php';
@@ -33,11 +33,7 @@ require_once 'bootstrap.php';
* context file for steps that execute actions as "the public".
*/
class PublicWebDavContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @When /^the public downloads the last public link shared file with range "([^"]*)" using the (old|new) public WebDAV API$/
@@ -390,13 +386,7 @@ class PublicWebDavContext implements Context {
"COPY",
null,
null,
$headers,
null,
null,
null,
false,
0,
null
$headers
);
$this->featureContext->setResponse($response);
}
@@ -1115,10 +1105,9 @@ class PublicWebDavContext implements Context {
* @Then /^the public upload to the last publicly shared folder using the (old|new) public WebDAV API should fail with HTTP status code "([^"]*)"$/
*
* @param string $publicWebDAVAPIVersion
* @param string $expectedHttpCode
* @param string|null $expectedHttpCode
*
* @return void
* @throws Exception
*/
public function publiclyUploadingShouldNotWork(
string $publicWebDAVAPIVersion,
@@ -1285,8 +1274,7 @@ class PublicWebDavContext implements Context {
$this->downloadPublicFileWithRange(
"",
$publicWebDAVAPIVersion,
""
$publicWebDAVAPIVersion
);
$this->featureContext->checkDownloadedContentMatches(
@@ -1581,7 +1569,7 @@ class PublicWebDavContext implements Context {
*
* @param string $method
* @param string $publicWebDAVAPIVersion
* @param string $password
* @param string|null $password
*
* @return void
* @throws GuzzleException
@@ -1602,6 +1590,8 @@ class PublicWebDavContext implements Context {
<oc:public-link-share-owner/>
</d:prop>
</d:propfind>';
} else {
$body = null;
}
$token = $this->featureContext->getLastPublicShareToken();
$davPath = WebDavHelper::getDavPath(

View File

@@ -19,25 +19,9 @@ require_once 'bootstrap.php';
* Context for the TUS-specific steps using the Graph API
*/
class RoleAssignmentContext implements Context {
/**
* @var FeatureContext
*/
private FeatureContext $featureContext;
/**
* @var SpacesContext
*/
private SpacesContext $spacesContext;
/**
* @var string
*/
private string $baseUrl;
/**
* @var string
*/
private string $settingsUrl = '/api/v0/settings/';
/**
@@ -121,7 +105,6 @@ class RoleAssignmentContext implements Context {
*
* @return void
*
* @throws GuzzleException
* @throws Exception
*/
public function theAdministratorHasGivenUserTheRole(string $user, string $role): void {
@@ -137,7 +120,7 @@ class RoleAssignmentContext implements Context {
*
* @return string
*/
public function userGetRoleIdByRoleName($user, $role): string {
public function userGetRoleIdByRoleName(string $user, string $role): string {
$this->getAllExistingRoles($user);
if ($this->featureContext->getResponse()) {
@@ -149,6 +132,8 @@ class RoleAssignmentContext implements Context {
__METHOD__ . " could not find bundles in body"
);
$bundles = $decodedBody["bundles"];
} else {
$bundles = [];
}
$roleToAssign = "";
@@ -171,7 +156,7 @@ class RoleAssignmentContext implements Context {
* @return void
* @throws Exception
*/
public function setRoleToUser($user, $userId, $roleId): void {
public function setRoleToUser(string $user, string $userId, string $roleId): void {
$this->sendRequestToAssignRoleToUser($user, $userId, $roleId);
if ($this->featureContext->getResponse()) {
@@ -183,6 +168,8 @@ class RoleAssignmentContext implements Context {
__METHOD__ . " could not find assignment in body"
);
$assignment = $decodedBody["assignment"];
} else {
$assignment = [];
}
Assert::assertEquals($userId, $assignment["accountUuid"]);

View File

@@ -24,7 +24,6 @@ use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\TableNode;
use PHPUnit\Framework\Assert;
use TestHelpers\OcisHelper;
use TestHelpers\WebDavHelper;
require_once 'bootstrap.php';
@@ -33,11 +32,7 @@ require_once 'bootstrap.php';
* context containing search related API steps
*/
class SearchContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @When user :user searches for :pattern using the WebDAV API
@@ -183,7 +178,7 @@ class SearchContext implements Context {
$expectedEntriesArray = [];
$responseResourcesArray = $this->featureContext->findEntryFromReportResponse($user);
foreach ($expectedEntries as $item) {
\array_push($expectedEntriesArray, $item[0]);
$expectedEntriesArray[] = $item[0];
}
Assert::assertEqualsCanonicalizing($expectedEntriesArray, $responseResourcesArray);
}

View File

@@ -34,17 +34,8 @@ require_once 'bootstrap.php';
* Sharees context.
*/
class ShareesContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
/**
*
* @var OCSContext
*/
private $ocsContext;
private FeatureContext $featureContext;
private OCSContext $ocsContext;
/**
* @When /^the user gets the sharees using the sharing API with parameters$/
@@ -73,21 +64,18 @@ class ShareesContext implements Context {
$user = $this->featureContext->getActualUsername($user);
$url = '/apps/files_sharing/api/v1/sharees';
$this->featureContext->verifyTableNodeColumnsCount($body, 2);
if ($body instanceof TableNode) {
$parameters = [];
foreach ($body->getRowsHash() as $key => $value) {
$parameters[] = "$key=$value";
}
if (!empty($parameters)) {
$url .= '?' . \implode('&', $parameters);
}
$parameters = [];
foreach ($body->getRowsHash() as $key => $value) {
$parameters[] = "$key=$value";
}
if (!empty($parameters)) {
$url .= '?' . \implode('&', $parameters);
}
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
'GET',
$url,
null
$url
);
}

View File

@@ -27,20 +27,15 @@ use Behat\Gherkin\Node\TableNode;
use Psr\Http\Message\ResponseInterface;
use PHPUnit\Framework\Assert;
use TestHelpers\OcsApiHelper;
use TestHelpers\OcisHelper;
use TestHelpers\SharingHelper;
use TestHelpers\HttpRequestHelper;
use TestHelpers\SetupHelper;
use TestHelpers\TranslationHelper;
/**
* Sharing trait
*/
trait Sharing {
/**
* @var int
*/
private $sharingApiVersion = 1;
private int $sharingApiVersion = 1;
/**
* Contains the API response to the last share that was created by each user
@@ -48,7 +43,7 @@ trait Sharing {
*
* @var SimpleXMLElement[]
*/
private $lastShareDataByUser = [];
private array $lastShareDataByUser = [];
/**
* Contains the share id of the last share that was created by each user,
@@ -56,51 +51,33 @@ trait Sharing {
*
* @var string[]
*/
private $lastShareIdByUser = [];
private array $lastShareIdByUser = [];
/**
* @var string
*/
private $userWhoCreatedLastShare = null;
private ?string $userWhoCreatedLastShare = null;
/**
* @var string
*/
private $userWhoCreatedLastPublicShare = null;
private ?string $userWhoCreatedLastPublicShare = null;
/**
* Contains the API response to the last public link share that was created
* by the test-runner using the Sharing API.
* Shares created on the webUI do not have an entry.
*
* @var SimpleXMLElement
*/
private $lastPublicShareData = null;
private ?SimpleXMLElement $lastPublicShareData = null;
/**
* Contains the share id of the last public link share that was created by
* the test-runner, either using the Sharing API or on the web UI.
*
* @var string
*/
private $lastPublicShareId = null;
private ?string $lastPublicShareId = null;
/**
* @var int
*/
private $savedShareId = null;
private ?int $savedShareId = null;
/**
* @var int
*/
private $localLastShareTime = null;
private ?float $localLastShareTime = null;
/**
* Defines the fields that can be provided in a share request.
*
* @var array
*/
private $shareFields = [
private array $shareFields = [
'path', 'name', 'publicUpload', 'password', 'expireDate',
'expireDateAsString', 'permissions', 'shareWith', 'shareType'
];
@@ -114,7 +91,7 @@ trait Sharing {
*
* @var array fields that are possible in a share response
*/
private $shareResponseFields = [
private array $shareResponseFields = [
'id', 'share_type', 'uid_owner', 'displayname_owner', 'stime', 'parent',
'expiration', 'token', 'uid_file_owner', 'displayname_file_owner', 'path',
'item_type', 'mimetype', 'storage_id', 'storage', 'item_source',
@@ -126,7 +103,7 @@ trait Sharing {
* Contains information about the public links that have been created with the webUI.
* Each entry in the array has a "name", "url" and "path".
*/
private $createdPublicLinks = [];
private array $createdPublicLinks = [];
/**
* @return array
@@ -244,9 +221,9 @@ trait Sharing {
}
/**
* @return int
* @return float|null
*/
public function getLocalLastShareTime():int {
public function getLocalLastShareTime():?float {
return $this->localLastShareTime;
}
@@ -263,7 +240,7 @@ trait Sharing {
* @return string
*/
public function getSharesEndpointPath(?string $postfix = ''):string {
return "/apps/files_sharing/api/v{$this->sharingApiVersion}/shares$postfix";
return "/apps/files_sharing/api/v$this->sharingApiVersion/shares$postfix";
}
/**
@@ -308,7 +285,7 @@ trait Sharing {
*/
public function getServerShareTimeFromLastResponse():int {
$stime = $this->getResponseXml(null, __METHOD__)->xpath("//stime");
if ((bool) $stime) {
if ($stime) {
return (int) $stime[0];
}
throw new Exception("Last share time (i.e. 'stime') could not be found in the response.");
@@ -875,58 +852,6 @@ trait Sharing {
return \json_decode(\json_encode($this->getLastShareData()->data->mimetype), true)[0];
}
/**
* @param string $url
* @param string|null $user
* @param string|null $password
* @param string|null $mimeType
*
* @return void
*/
private function checkDownload(
string $url,
?string $user = null,
?string $password = null,
?string $mimeType = null
) {
$password = $this->getActualPassword($password);
$headers = ['X-Requested-With' => 'XMLHttpRequest'];
$this->response = HttpRequestHelper::get(
$url,
$this->getStepLineRef(),
$user,
$password,
$headers
);
Assert::assertEquals(
200,
$this->response->getStatusCode(),
__METHOD__
. " Expected status code is '200' but got '"
. $this->response->getStatusCode()
. "'"
);
$buf = '';
$body = $this->response->getBody();
while (!$body->eof()) {
// read everything
$buf .= $body->read(8192);
}
$body->close();
if ($mimeType !== null) {
$finfo = new finfo;
Assert::assertEquals(
$mimeType,
$finfo->buffer($buf, FILEINFO_MIME_TYPE),
__METHOD__
. " Expected mimeType '$mimeType' but got '"
. $finfo->buffer($buf, FILEINFO_MIME_TYPE)
);
}
}
/**
* @Then /^user "([^"]*)" should not be able to create a public link share of (file|folder) "([^"]*)" using the sharing API$/
*
@@ -2065,8 +1990,7 @@ trait Sharing {
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
"DELETE",
$url,
null
$url
);
}
@@ -2192,7 +2116,7 @@ trait Sharing {
/**
* @Then /^as "([^"]*)" the info about the last share by user "([^"]*)" with user "([^"]*)" should include$/
*
* @param string $requestor
* @param string $requester
* @param string $sharer
* @param string $sharee
* @param TableNode $table
@@ -2201,12 +2125,12 @@ trait Sharing {
* @throws Exception
*/
public function asLastShareInfoAboutUserSharingWithUserShouldInclude(
string $requestor,
string $sharer,
string $sharee,
string $requester,
string $sharer,
string $sharee,
TableNode $table
) {
$this->userGetsInfoOfLastShareUsingTheSharingApi($requestor);
$this->userGetsInfoOfLastShareUsingTheSharingApi($requester);
$this->ocsContext->assertOCSResponseIndicatesSuccess();
$this->checkFieldsOfLastResponseToUser($sharer, $sharee, $table);
}
@@ -2297,7 +2221,7 @@ trait Sharing {
* @return string|null
*/
public function getLastShareIdForUser(string $user):?string {
if ($user === null) {
if ($user === "") {
throw new Exception(
__METHOD__ . " user not specified. Probably no user or group shares have been created yet in the test scenario."
);
@@ -2370,8 +2294,7 @@ trait Sharing {
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
'GET',
$url,
null
$url
);
}
@@ -2383,7 +2306,7 @@ trait Sharing {
*
* @return void
*/
public function userGetsTheLastShareSharedWithHimUsingTheSharingApi(string $user, $table):void {
public function userGetsTheLastShareSharedWithHimUsingTheSharingApi(string $user, TableNode $table):void {
$user = $this->getActualUsername($user);
$shareId = $this->getLastPublicLinkShareId();
$this->getShareData($user, $shareId);
@@ -2419,8 +2342,7 @@ trait Sharing {
'GET',
$this->getSharesEndpointPath(
"?shared_with_me=true" . $pendingClause . "&share_types=" . $rawShareTypes
),
null
)
);
}
@@ -2435,12 +2357,11 @@ trait Sharing {
public function userGetsAllSharesSharedWithHimFromFileOrFolderUsingTheProvisioningApi(string $user, string $path):void {
$user = $this->getActualUsername($user);
$url = "/apps/files_sharing/api/"
. "v{$this->sharingApiVersion}/shares?shared_with_me=true&path=$path";
. "v$this->sharingApiVersion/shares?shared_with_me=true&path=$path";
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
'GET',
$url,
null
$url
);
}
@@ -2918,7 +2839,7 @@ trait Sharing {
$responseXml = $this->getResponseXml(null, __METHOD__)->data[0];
$actualAttributesElement = $responseXml->xpath('//attributes');
if ((bool) $actualAttributesElement) {
if ($actualAttributesElement) {
$actualAttributes = (array) $actualAttributesElement[0];
if (empty($actualAttributes)) {
throw new Exception(
@@ -3004,17 +2925,13 @@ trait Sharing {
$user = $this->getActualUsername($user);
$this->downloadFileAsUserUsingPassword($user, $fileName);
$receivedErrorMessage = $this->getResponseXml(null, __METHOD__)->xpath('//s:message');
if ((bool) $errorMessage) {
Assert::assertEquals(
$errorMessage,
(string) $receivedErrorMessage[0],
"Expected error message was '$errorMessage' but got '"
. (string) $receivedErrorMessage[0]
. "'"
);
return;
}
throw new Exception("No 's:message' element found on the response.");
Assert::assertEquals(
$errorMessage,
(string) $receivedErrorMessage[0],
"Expected error message was '$errorMessage' but got '"
. (string) $receivedErrorMessage[0]
. "'"
);
}
/**
@@ -3072,7 +2989,7 @@ trait Sharing {
$user,
$this->getPasswordForUser($user),
"DELETE",
$this->getSharesEndpointPath("/{$id}"),
$this->getSharesEndpointPath("/$id"),
$this->getStepLineRef(),
[],
$this->ocsApiVersion
@@ -3185,7 +3102,7 @@ trait Sharing {
(string) $elementResponded->path[0],
__METHOD__
. " Expected '${expectedElementsArray['path']}' but got '"
. (string) $elementResponded->path[0]
. $elementResponded->path[0]
. "'"
);
Assert::assertEquals(
@@ -3193,7 +3110,7 @@ trait Sharing {
(string) $elementResponded->permissions[0],
__METHOD__
. " Expected '${expectedElementsArray['permissions']}' but got '"
. (string) $elementResponded->permissions[0]
. $elementResponded->permissions[0]
. "'"
);
$nameFound = true;
@@ -3268,8 +3185,7 @@ trait Sharing {
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
"DELETE",
$url,
null
$url
);
}
@@ -3362,19 +3278,19 @@ trait Sharing {
$shareId,
__METHOD__ . " could not find share $share, offered by $offeredBy to $user"
);
$url = "/apps/files_sharing/api/v{$this->sharingApiVersion}" .
$url = "/apps/files_sharing/api/v$this->sharingApiVersion" .
"/shares/pending/$shareId";
if (\substr($action, 0, 7) === "decline") {
$httpRequestMethod = "DELETE";
} elseif (\substr($action, 0, 6) === "accept") {
} else {
// do a POST to accept the share
$httpRequestMethod = "POST";
}
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
$httpRequestMethod,
$url,
null
$url
);
$this->pushToLastStatusCodesArrays();
}
@@ -3420,19 +3336,19 @@ trait Sharing {
$shareId = $this->substituteInLineCodes($share_id, $user);
$url = "/apps/files_sharing/api/v{$this->sharingApiVersion}" .
$url = "/apps/files_sharing/api/v$this->sharingApiVersion" .
"/shares/pending/$shareId";
if (\substr($action, 0, 7) === "decline") {
$httpRequestMethod = "DELETE";
} elseif (\substr($action, 0, 6) === "accept") {
} else {
// do a POST to accept the share
$httpRequestMethod = "POST";
}
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
$httpRequestMethod,
$url,
null
$url
);
}
@@ -3451,8 +3367,7 @@ trait Sharing {
$this->userReactsToShareOfferedBy($user, $action, $share, $offeredBy);
if ($action === 'declined') {
$actionText = 'decline';
}
if ($action === 'accepted') {
} else {
$actionText = 'accept';
}
$this->theHTTPStatusCodeShouldBe(
@@ -3641,15 +3556,13 @@ trait Sharing {
throw new InvalidArgumentException(
__METHOD__ . ' invalid "state" given'
);
break;
}
$url = $this->getSharesEndpointPath("?format=json&shared_with_me=true&state=$stateCode");
$this->ocsContext->userSendsHTTPMethodToOcsApiEndpointWithBody(
$user,
"GET",
$url,
null
$url
);
if ($this->response->getStatusCode() !== 200) {
throw new Exception(
@@ -3973,7 +3886,7 @@ trait Sharing {
$adminUser,
$this->getAdminPassword(),
'POST',
"/apps/testing/api/v1/expire-share/{$shareId}",
"/apps/testing/api/v1/expire-share/$shareId",
$this->getStepLineRef(),
[],
$this->getOcsApiVersion()

View File

@@ -41,65 +41,20 @@ require_once 'bootstrap.php';
* Context for ocis spaces specific steps
*/
class SpacesContext implements Context {
/**
* @var FeatureContext
*/
private FeatureContext $featureContext;
/**
* @var OCSContext
*/
private OCSContext $ocsContext;
/**
* @var TrashbinContext
*/
private TrashbinContext $trashbinContext;
/**
* @var WebDavPropertiesContext
*/
private WebDavPropertiesContext $webDavPropertiesContext;
/**
* @var FavoritesContext
*/
private FavoritesContext $favoritesContext;
/**
* @var ChecksumContext
*/
private ChecksumContext $checksumContext;
/**
* @var FilesVersionsContext
*/
private FilesVersionsContext $filesVersionsContext;
/**
* @var GraphContext
*/
private GraphContext $graphContext;
/**
* @var string
*/
private string $baseUrl;
/**
* @var array key is space name and value is the username that created the space
* key is space name and value is the username that created the space
*/
private array $createdSpaces;
/**
* @var string
*/
private string $ocsApiUrl = '/ocs/v2.php/apps/files_sharing/api/v1/shares';
/**
* @var string
*/
private string $davSpacesUrl = '/remote.php/dav/spaces/';
/**
@@ -117,7 +72,7 @@ class SpacesContext implements Context {
* ]
* ]
*/
private $storedEtags = [];
private array $storedEtags = [];
/**
* @param string $spaceName
@@ -144,8 +99,6 @@ class SpacesContext implements Context {
private array $availableSpaces = [];
private array $lastPublicLinkData = [];
/**
* @return array
*/
@@ -185,13 +138,6 @@ class SpacesContext implements Context {
$this->responseXml = $responseXml;
}
/**
* space id from last propfind request
*
* @var string
*/
private string $responseSpaceId;
/**
* Get SpaceId by Name
*
@@ -441,7 +387,6 @@ class SpacesContext implements Context {
$this->favoritesContext = $environment->getContext('FavoritesContext');
$this->checksumContext = $environment->getContext('ChecksumContext');
$this->filesVersionsContext = $environment->getContext('FilesVersionsContext');
$this->graphContext = $environment->getContext('GraphContext');
// Run the BeforeScenario function in OCSContext to set it up correctly
$this->ocsContext->before($scope);
$this->baseUrl = \trim($this->featureContext->getBaseUrl(), "/");
@@ -614,7 +559,7 @@ class SpacesContext implements Context {
public function theUserLooksUpTheSingleSpaceUsingTheGraphApiByUsingItsId(string $user, string $spaceName, string $ownerUser = ''): void {
$space = $this->getSpaceByName(($ownerUser !== "") ? $ownerUser : $user, $spaceName);
Assert::assertIsArray($space);
Assert::assertNotEmpty($spaceId = $space["id"]);
Assert::assertNotEmpty($space["id"]);
Assert::assertNotEmpty($space["root"]["webDavUrl"]);
$this->featureContext->setResponse(
GraphHelper::getSingleSpace(
@@ -2284,7 +2229,7 @@ class SpacesContext implements Context {
*
* @param string $user
* @param string $spaceName
* @param string $owner
* @param string $owner
*
* @return void
* @throws GuzzleException
@@ -2292,7 +2237,7 @@ class SpacesContext implements Context {
public function sendDeleteSpaceRequest(
string $user,
string $spaceName,
$owner = ''
string $owner = ''
): void {
$space = $this->getSpaceByName(($owner !== "") ? $owner : $user, $spaceName);
@@ -3242,12 +3187,11 @@ class SpacesContext implements Context {
* @param string $recipientType
* @param string $recipient
* @param string $role
* @param string $expirationDate
* @param string|null $expirationDate
*
* @return void
*
* @throws GuzzleException
* @throws Exception
*/
public function theUserShouldHaveSpaceWithRecipient(
string $user,

View File

@@ -12,9 +12,7 @@ declare(strict_types=1);
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use GuzzleHttp\Exception\GuzzleException;
use TestHelpers\HttpRequestHelper;
use Behat\Gherkin\Node\TableNode;
use TestHelpers\WebDavHelper;
require_once 'bootstrap.php';
@@ -22,27 +20,10 @@ require_once 'bootstrap.php';
* Context for the TUS-specific steps using the Graph API
*/
class SpacesTUSContext implements Context {
/**
* @var FeatureContext
*/
private FeatureContext $featureContext;
/**
* @var TUSContext
*/
private TUSContext $tusContext;
/**
* @var SpacesContext
*/
private SpacesContext $spacesContext;
/**
* @var string
*/
private string $baseUrl;
/**
* This will run before EVERY scenario.
* It will set the properties for this object.
@@ -60,7 +41,6 @@ class SpacesTUSContext implements Context {
$this->featureContext = $environment->getContext('FeatureContext');
$this->spacesContext = $environment->getContext('SpacesContext');
$this->tusContext = $environment->getContext('TUSContext');
$this->baseUrl = \trim($this->featureContext->getBaseUrl(), "/");
}
/**
@@ -88,7 +68,6 @@ class SpacesTUSContext implements Context {
* @param string $source
* @param string $destination
* @param string $spaceName
* @param array|null $uploadMetadata
*
* @return void
* @throws Exception
@@ -98,8 +77,7 @@ class SpacesTUSContext implements Context {
string $user,
string $source,
string $destination,
string $spaceName,
?array $uploadMetadata = null
string $spaceName
): void {
$this->spacesContext->setSpaceIDByName($user, $spaceName);
$this->tusContext->userUploadsUsingTusAFileTo($user, $source, $destination);

View File

@@ -37,13 +37,9 @@ require_once 'bootstrap.php';
* TUS related test steps
*/
class TUSContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
private $resourceLocation = null;
private ?string $resourceLocation = null;
/**
* @When user :user creates a new TUS resource on the WebDAV API with these headers:
@@ -196,8 +192,7 @@ class TUSContext implements Context {
$this->featureContext->getDavPathVersion(),
"files",
WebDavHelper::$SPACE_ID_FROM_OCIS
? WebDavHelper::$SPACE_ID_FROM_OCIS
: $this->featureContext->getPersonalSpaceIdForUser($user)
?: $this->featureContext->getPersonalSpaceIdForUser($user)
)
);
WebDavHelper::$SPACE_ID_FROM_OCIS = '';
@@ -433,7 +428,7 @@ class TUSContext implements Context {
string $content
): void {
$this->sendsAChunkToTUSLocationWithOffsetAndData($user, $offset, $content, $checksum);
$this->featureContext->theHTTPStatusCodeShouldBe(204, "");
$this->featureContext->theHTTPStatusCodeShouldBe(204);
}
/**
@@ -464,7 +459,7 @@ class TUSContext implements Context {
*/
public function userHasUploadedChunkFileWithChecksum(string $user, string $offset, string $data, string $checksum): void {
$this->sendsAChunkToTUSLocationWithOffsetAndData($user, $offset, $data, $checksum);
$this->featureContext->theHTTPStatusCodeShouldBe(204, "");
$this->featureContext->theHTTPStatusCodeShouldBe(204);
}
/**

View File

@@ -31,15 +31,7 @@ require_once 'bootstrap.php';
* Acceptance test steps related to testing tags features
*/
class TagContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
/**
* @var SpacesContext
*/
private FeatureContext $featureContext;
private SpacesContext $spacesContext;
/**
@@ -60,11 +52,6 @@ class TagContext implements Context {
$this->spacesContext = $environment->getContext('SpacesContext');
}
/**
* @var array
*/
private $createdTags = [];
/**
* @When /^user "([^"]*)" creates the following tags for (folder|file)\s?"([^"]*)" of space "([^"]*)":$/
*
@@ -80,7 +67,7 @@ class TagContext implements Context {
public function theUserCreatesFollowingTags(string $user, string $fileOrFolder, string $resource, string $space, TableNode $table):void {
$tagNameArray = [];
foreach ($table->getRows() as $value) {
array_push($tagNameArray, $value[0]);
$tagNameArray[] = $value[0];
}
if ($fileOrFolder === 'folder') {
@@ -173,7 +160,7 @@ class TagContext implements Context {
public function userRemovesTagsFromResourceOfTheSpace(string $user, string $fileOrFolder, string $resource, string $space, TableNode $table):void {
$tagNameArray = [];
foreach ($table->getRows() as $value) {
array_push($tagNameArray, $value[0]);
$tagNameArray[] = $value[0];
}
if ($fileOrFolder === 'folder') {

View File

@@ -22,6 +22,7 @@
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\TableNode;
use GuzzleHttp\Exception\GuzzleException;
use PHPUnit\Framework\Assert;
use Psr\Http\Message\ResponseInterface;
use TestHelpers\HttpRequestHelper;
@@ -33,11 +34,7 @@ require_once 'bootstrap.php';
* Trashbin context
*/
class TrashbinContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @When user :user empties the trashbin using the trashbin API
@@ -438,11 +435,6 @@ class TrashbinContext implements Context {
*/
public function theLastWebdavResponseShouldContainFollowingElements(TableNode $elements):void {
$files = $this->getTrashbinContentFromResponseXml($this->featureContext->getResponseXmlObject());
if (!($elements instanceof TableNode)) {
throw new InvalidArgumentException(
'$expectedElements has to be an instance of TableNode'
);
}
$elementRows = $elements->getHash();
foreach ($elementRows as $expectedElement) {
$found = false;
@@ -516,7 +508,7 @@ class TrashbinContext implements Context {
public function userTriesToDeleteFromTrashbinOfUserUsingPassword(?string $asUser, ?string $path, ?string $user, ?string $password):void {
$user = $this->featureContext->getActualUsername($user);
$asUser = $this->featureContext->getActualUsername($asUser);
$numItemsDeleted = $this->tryToDeleteFileFromTrashbin($user, $path, $asUser, $password);
$this->tryToDeleteFileFromTrashbin($user, $path, $asUser, $password);
}
/**
@@ -678,6 +670,8 @@ class TrashbinContext implements Context {
if (\count($sections) !== 1) {
// TODO: handle deeper structures
$listing = $this->listTrashbinFolderCollection($user, \basename(\rtrim($firstEntry['href'], '/')));
} else {
$listing = [];
}
// query was on the main element ?
@@ -736,9 +730,11 @@ class TrashbinContext implements Context {
* @param string|null $asUser - To send request as another user
* @param string|null $password
*
* @return ResponseInterface
* @return void
* @throws JsonException
* @throws GuzzleException
*/
private function sendUndeleteRequest(string $user, string $trashItemHRef, string $destinationPath, ?string $asUser = null, ?string $password = null):ResponseInterface {
private function sendUndeleteRequest(string $user, string $trashItemHRef, string $destinationPath, ?string $asUser = null, ?string $password = null):void {
$asUser = $asUser ?? $user;
$destinationPath = \trim($destinationPath, '/');
$destinationValue = $this->featureContext->getBaseUrl() . "/remote.php/dav/files/$user/$destinationPath";
@@ -759,7 +755,6 @@ class TrashbinContext implements Context {
$user
);
$this->featureContext->setResponse($response);
return $response;
}
/**
@@ -770,10 +765,11 @@ class TrashbinContext implements Context {
* @param string|null $asUser - To send request as another user
* @param string|null $password
*
* @return ResponseInterface|null
* @throws Exception
* @return void
* @throws JsonException
* @throws GuzzleException
*/
private function restoreElement(string $user, string $originalPath, ?string $destinationPath = null, bool $throwExceptionIfNotFound = true, ?string $asUser = null, ?string $password = null):?ResponseInterface {
private function restoreElement(string $user, string $originalPath, ?string $destinationPath = null, bool $throwExceptionIfNotFound = true, ?string $asUser = null, ?string $password = null):void {
$asUser = $asUser ?? $user;
$listing = $this->listTrashbinFolder($user);
$originalPath = \trim($originalPath, '/');
@@ -782,13 +778,14 @@ class TrashbinContext implements Context {
}
foreach ($listing as $entry) {
if ($entry['original-location'] === $originalPath) {
return $this->sendUndeleteRequest(
$this->sendUndeleteRequest(
$user,
$entry['href'],
$destinationPath,
$asUser,
$password
);
return;
}
}
// The requested element to restore was not even in the trashbin.
@@ -800,7 +797,6 @@ class TrashbinContext implements Context {
. " cannot restore from trashbin because no element was found for user $user at original path $originalPath"
);
}
return null;
}
/**
@@ -1018,7 +1014,7 @@ class TrashbinContext implements Context {
TableNode $table
):void {
$this->featureContext->verifyTableNodeColumns($table, ["path"]);
$paths = $table->getHash($table);
$paths = $table->getHash();
foreach ($paths as $originalPath) {
$this->elementIsNotInTrashCheckingOriginalPath($user, $originalPath["path"]);
@@ -1039,7 +1035,7 @@ class TrashbinContext implements Context {
TableNode $table
):void {
$this->featureContext->verifyTableNodeColumns($table, ["path"]);
$paths = $table->getHash($table);
$paths = $table->getHash();
foreach ($paths as $originalPath) {
$this->elementIsInTrashCheckingOriginalPath($user, $originalPath["path"]);
@@ -1101,7 +1097,7 @@ class TrashbinContext implements Context {
$responseMtime = '';
foreach ($files as $file) {
if (\ltrim((string)$resource, "/") === \ltrim((string)$file['original-location'], "/")) {
if (\ltrim($resource, "/") === \ltrim((string)$file['original-location'], "/")) {
$responseMtime = $file['mtime'];
$mtime_difference = \abs((int)\trim((string)$expectedMtime) - (int)\trim($responseMtime));

View File

@@ -24,13 +24,9 @@ use Behat\Gherkin\Node\TableNode;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Ring\Exception\ConnectException;
use Helmich\JsonAssert\JsonAssertions;
use PHPUnit\Framework\Assert;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Stream\StreamInterface;
use TestHelpers\OcisHelper;
use TestHelpers\OcsApiHelper;
use TestHelpers\SetupHelper;
use TestHelpers\UploadHelper;
use TestHelpers\WebDavHelper;
use TestHelpers\HttpRequestHelper;
@@ -40,82 +36,56 @@ use TestHelpers\Asserts\WebDav as WebDavAssert;
* WebDav functions
*/
trait WebDav {
/**
* @var string
*/
private $davPath = "remote.php/webdav";
/**
* @var boolean
*/
private $usingOldDavPath = true;
/**
* @var boolean
*/
private $usingSpacesDavPath = false;
private string $davPath = "remote.php/webdav";
private bool $usingOldDavPath = true;
private bool $usingSpacesDavPath = false;
/**
* @var ResponseInterface[]
*/
private $uploadResponses;
private array $uploadResponses;
/**
* @var integer
* @var int|string|null
*/
private $storedFileID = null;
/**
* @var int
*/
private $lastUploadDeleteTime = null;
private ?int $lastUploadDeleteTime = null;
/**
* a variable that contains the DAV path without "remote.php/(web)dav"
* when setting $this->davPath directly by usingDavPath()
*
* @var string
*/
private $customDavPath = null;
private $previousAsyncSetting = null;
private ?string $customDavPath = null;
/**
* response content parsed from XML to an array
*
* @var array
*/
private $responseXml = [];
private array $responseXml = [];
/**
* add resource created by admin in an array
* This array is used while cleaning up the resource created by admin during test run
* As of now it tracks only for (files|folder) creation
* This can be expanded and modified to track other actions like (upload, deleted ..)
*
* @var array
*/
private $adminResources = [];
private array $adminResources = [];
/**
* response content parsed into a SimpleXMLElement
*
* @var SimpleXMLElement
*/
private $responseXmlObject;
private ?SimpleXMLElement $responseXmlObject;
private $httpRequestTimeout = 0;
private int $httpRequestTimeout = 0;
private $chunkingToUse = null;
private ?int $chunkingToUse = null;
/**
* The ability to do requests with depth infinity is disabled by default.
* This remembers when the setting dav.propfind.depth_infinity has been
* enabled, so that test code can make use of it as appropriate.
*
* @var bool
*/
private $davPropfindDepthInfinityEnabled = false;
private bool $davPropfindDepthInfinityEnabled = false;
/**
* @return void
@@ -328,7 +298,7 @@ trait WebDav {
public function getFullDavFilesPath(string $user):string {
$spaceId = null;
if ($this->getDavPathVersion() === WebDavHelper::DAV_VERSION_SPACES) {
$spaceId = (WebDavHelper::$SPACE_ID_FROM_OCIS) ? WebDavHelper::$SPACE_ID_FROM_OCIS : WebDavHelper::getPersonalSpaceIdForUser(
$spaceId = (WebDavHelper::$SPACE_ID_FROM_OCIS) ?: WebDavHelper::getPersonalSpaceIdForUser(
$this->getBaseUrl(),
$user,
$this->getPasswordForUser($user),
@@ -564,7 +534,7 @@ trait WebDav {
* @return void
*/
public function setHttpTimeout(int $timeout):void {
$this->httpRequestTimeout = (int) $timeout;
$this->httpRequestTimeout = $timeout;
}
/**
@@ -651,11 +621,7 @@ trait WebDav {
foreach ($table->getHash() as $row) {
// Allow the "filename" column to be optionally be called "foldername"
// to help readability of scenarios that test moving folders
if (isset($row['foldername'])) {
$targetName = $row['foldername'];
} else {
$targetName = $row['filename'];
}
$targetName = $row['foldername'] ?? $row['filename'];
$this->userMovesFileUsingTheAPI(
$user,
$fileSource,
@@ -1124,7 +1090,7 @@ trait WebDav {
* @return void
*
*/
public function theDownloadedContentForMultipartByterangeShouldBe(int $statusCode, PyStringNode $content):void {
public function theDownloadedContentForMultipartByteRangeShouldBe(int $statusCode, PyStringNode $content):void {
$actualStatusCode = $this->response->getStatusCode();
if ($actualStatusCode === $statusCode) {
$actualContent = (string) $this->response->getBody();
@@ -1524,14 +1490,11 @@ trait WebDav {
public function publicGetsSizeOfLastSharedPublicLinkUsingTheWebdavApi():void {
$tokenArray = $this->getLastPublicShareData()->data->token;
$token = (string)$tokenArray[0];
$url = $this->getBaseUrl() . "/remote.php/dav/public-files/{$token}";
$url = $this->getBaseUrl() . "/remote.php/dav/public-files/$token";
$this->response = HttpRequestHelper::sendRequest(
$url,
$this->getStepLineRef(),
"PROPFIND",
null,
null,
null
"PROPFIND"
);
}
@@ -1602,19 +1565,15 @@ trait WebDav {
$returnedHeader = $this->response->getHeader($headerName);
$expectedHeaderValue = $this->substituteInLineCodes($expectedHeaderValue);
if (\is_array($returnedHeader)) {
if (empty($returnedHeader)) {
throw new Exception(
\sprintf(
"Missing expected header '%s'",
$headerName
)
);
}
$headerValue = $returnedHeader[0];
} else {
$headerValue = $returnedHeader;
if (empty($returnedHeader)) {
throw new Exception(
\sprintf(
"Missing expected header '%s'",
$headerName
)
);
}
$headerValue = $returnedHeader[0];
Assert::assertEquals(
$expectedHeaderValue,
@@ -2488,7 +2447,7 @@ trait WebDav {
$duplicateRemovedStatusCodes = \array_unique($this->lastHttpStatusCodesArray);
if (\count($duplicateRemovedStatusCodes) === 1) {
Assert::assertSame(
\intval($statusCode),
$statusCode,
\intval($duplicateRemovedStatusCodes[0]),
'Responses did not return expected http status code'
);
@@ -3217,7 +3176,7 @@ trait WebDav {
$fileIds = [];
foreach ($files as $destination) {
$fileId = $this->userHasUploadedAFileWithContentTo($user, $content, $destination["path"])[0];
\array_push($fileIds, $fileId);
$fileIds[] = $fileId;
}
return $fileIds;
}
@@ -3409,7 +3368,7 @@ trait WebDav {
$this->userDeletesFile($user, $entry);
// If the file or folder was there and got deleted then we get a 204
// That is good and the expected status
// If the file or folder was already not there then then we get a 404
// If the file or folder was already not there then we get a 404
// That is not expected. Scenarios that use "Given user has deleted..."
// should only be using such steps when it is a file that exists and needs
// to be deleted.
@@ -3552,7 +3511,7 @@ trait WebDav {
public function userOnHasDeletedFile(string $user, string $server, string $deletedOrUnshared, string $fileOrFolder, string $entry):void {
$this->userOnDeletesFile($user, $server, $entry);
// If the file was there and got deleted then we get a 204
// If the file was already not there then then get a 404
// If the file was already not there then we get a 404
// Either way, the outcome of the "given" step is OK
if ($deletedOrUnshared === "deleted") {
$deleteText = "delete";
@@ -4382,9 +4341,8 @@ trait WebDav {
*/
public function encodePath(string $path):string {
// slashes need to stay
$encodedPath = \str_replace('%2F', '/', \rawurlencode($path));
// in ocis even brackets are encoded
return $encodedPath;
return \str_replace('%2F', '/', \rawurlencode($path));
}
/**
@@ -4446,11 +4404,7 @@ trait WebDav {
$headerName = $header['header'];
$headerValue = $this->response->getHeader($headerName);
//Note: getHeader returns an empty array if the named header does not exist
if (isset($headerValue[0])) {
$headerValue0 = $headerValue[0];
} else {
$headerValue0 = '';
}
$headerValue0 = $headerValue[0] ?? '';
Assert::assertEmpty(
$headerValue,
"header $headerName should not exist " .
@@ -4782,7 +4736,7 @@ trait WebDav {
$currentFileID,
$this->storedFileID,
__METHOD__
. " User '$user' $fileOrFolder '$path' does not have the previously stored id '{$this->storedFileID}', but has '$currentFileID'."
. " User '$user' $fileOrFolder '$path' does not have the previously stored id '$this->storedFileID', but has '$currentFileID'."
);
}
@@ -4880,7 +4834,7 @@ trait WebDav {
public function thePropfindResultShouldNotContainAnyEntries(
string $user
):void {
$multistatusResults = $this->getMultistatusResultFromPropfindResult($user);
$multistatusResults = $this->getMultiStatusResultFromPropfindResult($user);
Assert::assertEmpty($multistatusResults, 'The propfind response was expected to be empty but was not');
}
@@ -4942,11 +4896,11 @@ trait WebDav {
$multistatusResults = [];
}
Assert::assertEquals(
(int) $numFiles,
$numFiles,
\count($multistatusResults),
__METHOD__
. " Expected result to contain '"
. (int) $numFiles
. $numFiles
. "' files/entries, but got '"
. \count($multistatusResults)
. "' files/entries."
@@ -5135,7 +5089,7 @@ trait WebDav {
$hrefParts = \explode("/", (string)$href[0]);
if (\in_array($user, $hrefParts)) {
$entry = \urldecode(\end($hrefParts));
\array_push($responseResources, $entry);
$responseResources[] = $entry;
} else {
throw new Error("Expected user: $hrefParts[5] but found: $user");
}
@@ -5154,7 +5108,7 @@ trait WebDav {
public function getNumberOfEntriesInPropfindResponse(
?string $user = null
):int {
$multistatusResults = $this->getMultistatusResultFromPropfindResult($user);
$multistatusResults = $this->getMultiStatusResultFromPropfindResult($user);
return \count($multistatusResults);
}
@@ -5166,7 +5120,7 @@ trait WebDav {
*
* @return array
*/
public function getMultistatusResultFromPropfindResult(
public function getMultiStatusResultFromPropfindResult(
?string $user = null
):array {
//if we are using that step the second time in a scenario e.g. 'But ... should not'
@@ -5257,32 +5211,30 @@ trait WebDav {
default:
throw new Exception("error");
}
$multistatusResults = $this->getMultistatusResultFromPropfindResult($user);
$multistatusResults = $this->getMultiStatusResultFromPropfindResult($user);
$results = [];
if ($multistatusResults !== null) {
foreach ($multistatusResults as $multistatusResult) {
$entryPath = $multistatusResult['value'][0]['value'];
if ($method === "REPORT") {
if ($entryNameToSearch !== null && str_ends_with($entryPath, $entryNameToSearch)) {
return $multistatusResult;
} else {
$spaceId = (WebDavHelper::$SPACE_ID_FROM_OCIS) ? WebDavHelper::$SPACE_ID_FROM_OCIS : WebDavHelper::getPersonalSpaceIdForUser(
$this->getBaseUrl(),
$user,
$this->getPasswordForUser($user),
$this->getStepLineRef()
);
$topWebDavPath = "/remote.php/dav/spaces/" . $spaceId . "/" . $folderPath;
}
}
$entryName = \str_replace($topWebDavPath, "", $entryPath);
$entryName = \rawurldecode($entryName);
$entryName = \trim($entryName, "/");
if ($trimmedEntryNameToSearch === $entryName) {
foreach ($multistatusResults as $multistatusResult) {
$entryPath = $multistatusResult['value'][0]['value'];
if ($method === "REPORT") {
if ($entryNameToSearch !== null && str_ends_with($entryPath, $entryNameToSearch)) {
return $multistatusResult;
} else {
$spaceId = (WebDavHelper::$SPACE_ID_FROM_OCIS) ?: WebDavHelper::getPersonalSpaceIdForUser(
$this->getBaseUrl(),
$user,
$this->getPasswordForUser($user),
$this->getStepLineRef()
);
$topWebDavPath = "/remote.php/dav/spaces/" . $spaceId . "/" . $folderPath;
}
\array_push($results, $entryName);
}
$entryName = \str_replace($topWebDavPath, "", $entryPath);
$entryName = \rawurldecode($entryName);
$entryName = \trim($entryName, "/");
if ($trimmedEntryNameToSearch === $entryName) {
return $multistatusResult;
}
$results[] = $entryName;
}
if ($entryNameToSearch === null) {
return $results;

View File

@@ -36,23 +36,14 @@ require_once 'bootstrap.php';
* context containing API steps needed for the locking mechanism of webdav
*/
class WebDavLockingContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
/**
*
* @var PublicWebDavContext
*/
private $publicWebDavContext;
private FeatureContext $featureContext;
private PublicWebDavContext $publicWebDavContext;
/**
*
* @var string[][]
*/
private $tokenOfLastLock = [];
private array $tokenOfLastLock = [];
/**
*
@@ -65,11 +56,11 @@ class WebDavLockingContext implements Context {
* @return void
*/
private function lockFile(
$user,
$file,
string $user,
string $file,
TableNode $properties,
$public = false,
$expectToSucceed = true
bool $public = false,
bool $expectToSucceed = true
) {
$user = $this->featureContext->getActualUsername($user);
$baseUrl = $this->featureContext->getBaseUrl();
@@ -131,7 +122,7 @@ class WebDavLockingContext implements Context {
*
* @return void
*/
public function lockFileUsingWebDavAPI($user, $file, TableNode $properties) {
public function lockFileUsingWebDavAPI(string $user, string $file, TableNode $properties) {
$this->lockFile($user, $file, $properties, false, false);
}
@@ -144,8 +135,8 @@ class WebDavLockingContext implements Context {
*
* @return void
*/
public function userHasLockedFile($user, $file, TableNode $properties) {
$this->lockFile($user, $file, $properties, false, true);
public function userHasLockedFile(string $user, string $file, TableNode $properties) {
$this->lockFile($user, $file, $properties);
}
/**
@@ -190,7 +181,7 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function publicHasLockedFileLastSharedFolder(
$file,
string $file,
TableNode $properties
) {
$this->lockFile(
@@ -211,8 +202,8 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function publicLocksFileLastSharedFolder(
$file,
$publicWebDAVAPIVersion,
string $file,
string $publicWebDAVAPIVersion,
TableNode $properties
) {
$this->lockFile(
@@ -232,7 +223,7 @@ class WebDavLockingContext implements Context {
*
* @return void
*/
public function unlockLastLockUsingWebDavAPI($user, $file) {
public function unlockLastLockUsingWebDavAPI(string $user, string $file) {
$this->unlockItemWithLastLockOfUserAndItemUsingWebDavAPI(
$user,
$file,
@@ -251,9 +242,9 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function unlockItemWithLastLockOfOtherItemUsingWebDavAPI(
$user,
$itemToUnlock,
$itemToUseLockOf
string $user,
string $itemToUnlock,
string $itemToUseLockOf
) {
$this->unlockItemWithLastLockOfUserAndItemUsingWebDavAPI(
$user,
@@ -273,9 +264,9 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function unlockItemWithLastPublicLockOfOtherItemUsingWebDavAPI(
$user,
$itemToUnlock,
$itemToUseLockOf
string $user,
string $itemToUnlock,
string $itemToUseLockOf
) {
$lockOwner = $this->featureContext->getLastPublicShareToken();
$this->unlockItemWithLastLockOfUserAndItemUsingWebDavAPI(
@@ -291,14 +282,14 @@ class WebDavLockingContext implements Context {
* @param string $user
* @param string $itemToUnlock
*
* @return int|void
* @return int
*
* @throws Exception|GuzzleException
*/
private function countLockOfResources(
string $user,
string $itemToUnlock
) {
):int {
$user = $this->featureContext->getActualUsername($user);
$baseUrl = $this->featureContext->getBaseUrl();
$password = $this->featureContext->getPasswordForUser($user);
@@ -340,11 +331,11 @@ class WebDavLockingContext implements Context {
* @throws Exception|GuzzleException
*/
public function hasUnlockItemWithTheLastCreatedLock(
$user,
$itemToUnlock,
$lockOwner,
$itemToUseLockOf,
$public = false
string $user,
string $itemToUnlock,
string $lockOwner,
string $itemToUseLockOf,
bool $public = false
) {
$lockCount = $this->countLockOfResources($user, $itemToUnlock);
@@ -424,9 +415,9 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function unlockItemAsPublicWithLastLockOfUserAndItemUsingWebDavAPI(
$itemToUnlock,
$lockOwner,
$itemToUseLockOf
string $itemToUnlock,
string $lockOwner,
string $itemToUseLockOf
) {
$user = $this->featureContext->getLastPublicShareToken();
$this->unlockItemWithLastLockOfUserAndItemUsingWebDavAPI(
@@ -445,7 +436,7 @@ class WebDavLockingContext implements Context {
*
* @return void
*/
public function unlockItemAsPublicUsingWebDavAPI($itemToUnlock) {
public function unlockItemAsPublicUsingWebDavAPI(string $itemToUnlock) {
$user = $this->featureContext->getLastPublicShareToken();
$this->unlockItemWithLastLockOfUserAndItemUsingWebDavAPI(
$user,
@@ -467,10 +458,10 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function moveItemSendingLockToken(
$user,
$fileSource,
$fileDestination,
$itemToUseLockOf
string $user,
string $fileSource,
string $fileDestination,
string $itemToUseLockOf
) {
$this->moveItemSendingLockTokenOfUser(
$user,
@@ -493,11 +484,11 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function moveItemSendingLockTokenOfUser(
$user,
$fileSource,
$fileDestination,
$itemToUseLockOf,
$lockOwner
string $user,
string $fileSource,
string $fileDestination,
string $itemToUseLockOf,
string $lockOwner
) {
$user = $this->featureContext->getActualUsername($user);
$lockOwner = $this->featureContext->getActualUsername($lockOwner);
@@ -533,10 +524,10 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function userUploadsAFileWithContentTo(
$user,
$content,
$destination,
$itemToUseLockOf
string $user,
string $content,
string $destination,
string $itemToUseLockOf
) {
$user = $this->featureContext->getActualUsername($user);
$token = $this->tokenOfLastLock[$user][$itemToUseLockOf];
@@ -565,11 +556,11 @@ class WebDavLockingContext implements Context {
*
*/
public function publicUploadFileSendingLockTokenOfUser(
$filename,
$content,
$itemToUseLockOf,
$lockOwner,
$publicWebDAVAPIVersion
string $filename,
string $content,
string $itemToUseLockOf,
string $lockOwner,
string $publicWebDAVAPIVersion
) {
$lockOwner = $this->featureContext->getActualUsername($lockOwner);
$headers = [
@@ -596,10 +587,10 @@ class WebDavLockingContext implements Context {
* @return void
*/
public function publicUploadFileSendingLockTokenOfPublic(
$filename,
$content,
$itemToUseLockOf,
$publicWebDAVAPIVersion
string $filename,
string $content,
string $itemToUseLockOf,
string $publicWebDAVAPIVersion
) {
$lockOwner = $this->featureContext->getLastPublicShareToken();
$this->publicUploadFileSendingLockTokenOfUser(
@@ -621,7 +612,7 @@ class WebDavLockingContext implements Context {
* @return void
* @throws GuzzleException
*/
public function numberOfLockShouldBeReported($count, $file, $user) {
public function numberOfLockShouldBeReported(int $count, string $file, string $user) {
$lockCount = $this->countLockOfResources($user, $file);
Assert::assertEquals(
$count,
@@ -639,7 +630,7 @@ class WebDavLockingContext implements Context {
*
* @throws Exception
*/
public function groupShouldExistAsLockBreakerGroups($expectedGroup) {
public function groupShouldExistAsLockBreakerGroups(string $expectedGroup) {
$baseUrl = $this->featureContext->getBaseUrl();
$admin = $this->featureContext->getAdminUsername();
$password = $this->featureContext->getAdminPassword();

View File

@@ -34,17 +34,13 @@ require_once 'bootstrap.php';
* Steps that relate to managing file/folder properties via WebDav
*/
class WebDavPropertiesContext implements Context {
/**
*
* @var FeatureContext
*/
private $featureContext;
private FeatureContext $featureContext;
/**
* @var array map with user as key and another map as value,
* which has path as key and etag as value
*/
private $storedETAG = null;
private array $storedETAG = [];
/**
* @When /^user "([^"]*)" gets the properties of (?:file|folder|entry) "([^"]*)" using the WebDAV API$/
@@ -111,10 +107,8 @@ class WebDavPropertiesContext implements Context {
$properties = null;
$this->featureContext->verifyTableNodeColumns($propertiesTable, ["propertyName"]);
$this->featureContext->verifyTableNodeColumnsCount($propertiesTable, 1);
if ($propertiesTable instanceof TableNode) {
foreach ($propertiesTable->getColumnsHash() as $row) {
$properties[] = $row["propertyName"];
}
foreach ($propertiesTable->getColumnsHash() as $row) {
$properties[] = $row["propertyName"];
}
$depth = "1";
$this->featureContext->setResponseXmlObject(
@@ -146,10 +140,8 @@ class WebDavPropertiesContext implements Context {
$properties = null;
$this->featureContext->verifyTableNodeColumns($propertiesTable, ["propertyName"]);
$this->featureContext->verifyTableNodeColumnsCount($propertiesTable, 1);
if ($propertiesTable instanceof TableNode) {
foreach ($propertiesTable->getColumnsHash() as $row) {
$properties[] = $row["propertyName"];
}
foreach ($propertiesTable->getColumnsHash() as $row) {
$properties[] = $row["propertyName"];
}
$user = $this->featureContext->getActualUsername($user);
@@ -299,10 +291,8 @@ class WebDavPropertiesContext implements Context {
public function publicGetsThePropertiesOfFolder(string $path, TableNode $propertiesTable):void {
$user = $this->featureContext->getLastPublicShareToken();
$properties = null;
if ($propertiesTable instanceof TableNode) {
foreach ($propertiesTable->getRows() as $row) {
$properties[] = $row[0];
}
foreach ($propertiesTable->getRows() as $row) {
$properties[] = $row[0];
}
$this->featureContext->setResponseXmlObject(
$this->featureContext->listFolderAndReturnResponseXml(