From 6dcaf9c2a1239a2fce597c211afcd05b7955e033 Mon Sep 17 00:00:00 2001 From: amrita-shrestha Date: Thu, 20 Feb 2025 13:18:41 +0545 Subject: [PATCH] replace inbucket with mailpit --- .drone.star | 44 +-- docs/ocis/development/testing.md | 10 +- tests/acceptance/TestHelpers/CliHelper.php | 3 - tests/acceptance/TestHelpers/EmailHelper.php | 206 +++++---------- .../TestHelpers/OcisConfigHelper.php | 1 - .../acceptance/TestHelpers/SettingsHelper.php | 1 - tests/acceptance/bootstrap/EmailContext.php | 250 ++++++++++++++++++ tests/acceptance/bootstrap/FeatureContext.php | 13 - .../bootstrap/NotificationContext.php | 248 +++-------------- tests/acceptance/config/behat.yml | 3 + .../features/apiOcm/createInvitation.feature | 2 +- tests/acceptance/run.sh | 12 +- 12 files changed, 395 insertions(+), 398 deletions(-) create mode 100644 tests/acceptance/bootstrap/EmailContext.php diff --git a/.drone.star b/.drone.star index 48aee709a9d..d7f41b467c8 100644 --- a/.drone.star +++ b/.drone.star @@ -12,7 +12,7 @@ ALPINE_GIT = "alpine/git:latest" APACHE_TIKA = "apache/tika:2.8.0.0" CHKO_DOCKER_PUSHRM = "chko/docker-pushrm:1" COLLABORA_CODE = "collabora/code:24.04.5.1.1" -INBUCKET_INBUCKET = "inbucket/inbucket" +AXLLENT_MAILPIT = "axllent/mailpit:v1.22.3" MINIO_MC = "minio/mc:RELEASE.2021-10-07T04-19-58Z" OC_CI_ALPINE = "owncloudci/alpine:latest" OC_CI_BAZEL_BUILDIFIER = "owncloudci/bazel-buildifier:latest" @@ -66,6 +66,12 @@ FED_OCIS_SERVER_NAME = "federation-ocis-server" OCIS_FED_URL = "https://%s:10200" % FED_OCIS_SERVER_NAME OCIS_FED_DOMAIN = "%s:10200" % FED_OCIS_SERVER_NAME +# emails +EMAIL_PORT = "8025" +EMAIL_SMTP_PORT = "1025" +EMAIL_SMTP_HOST = "email" +EMAIL_SMTP_SENDER = "ownCloud " + # configuration config = { "cs3ApiTests": { @@ -99,15 +105,15 @@ config = { "withRemotePhp": [True], "emailNeeded": True, "extraEnvironment": { - "EMAIL_HOST": "email", - "EMAIL_PORT": "9000", + "EMAIL_HOST": EMAIL_SMTP_HOST, + "EMAIL_PORT": EMAIL_PORT, }, "extraServerEnvironment": { "OCIS_ADD_RUN_SERVICES": "notifications", - "NOTIFICATIONS_SMTP_HOST": "email", - "NOTIFICATIONS_SMTP_PORT": "2500", + "NOTIFICATIONS_SMTP_HOST": EMAIL_SMTP_HOST, + "NOTIFICATIONS_SMTP_PORT": EMAIL_SMTP_PORT, "NOTIFICATIONS_SMTP_INSECURE": "true", - "NOTIFICATIONS_SMTP_SENDER": "ownCloud ", + "NOTIFICATIONS_SMTP_SENDER": EMAIL_SMTP_SENDER, "NOTIFICATIONS_DEBUG_ADDR": "0.0.0.0:9174", }, }, @@ -192,15 +198,15 @@ config = { "withRemotePhp": [True], "emailNeeded": True, "extraEnvironment": { - "EMAIL_HOST": "email", - "EMAIL_PORT": "9000", + "EMAIL_HOST": EMAIL_SMTP_HOST, + "EMAIL_PORT": EMAIL_PORT, }, "extraServerEnvironment": { "OCIS_ADD_RUN_SERVICES": "notifications", - "NOTIFICATIONS_SMTP_HOST": "email", - "NOTIFICATIONS_SMTP_PORT": "2500", + "NOTIFICATIONS_SMTP_HOST": EMAIL_SMTP_HOST, + "NOTIFICATIONS_SMTP_PORT": EMAIL_SMTP_PORT, "NOTIFICATIONS_SMTP_INSECURE": "true", - "NOTIFICATIONS_SMTP_SENDER": "ownCloud ", + "NOTIFICATIONS_SMTP_SENDER": EMAIL_SMTP_SENDER, "NOTIFICATIONS_DEBUG_ADDR": "0.0.0.0:9174", }, }, @@ -235,8 +241,8 @@ config = { "federationServer": True, "emailNeeded": True, "extraEnvironment": { - "EMAIL_HOST": "email", - "EMAIL_PORT": "9000", + "EMAIL_HOST": EMAIL_SMTP_HOST, + "EMAIL_PORT": EMAIL_PORT, }, "extraServerEnvironment": { "OCIS_ADD_RUN_SERVICES": "ocm,notifications", @@ -246,10 +252,10 @@ config = { "OCM_OCM_STORAGE_PROVIDER_INSECURE": True, "OCM_OCM_PROVIDER_AUTHORIZER_PROVIDERS_FILE": "%s" % dirs["ocmProviders"], # mail notifications - "NOTIFICATIONS_SMTP_HOST": "email", - "NOTIFICATIONS_SMTP_PORT": "2500", + "NOTIFICATIONS_SMTP_HOST": EMAIL_SMTP_HOST, + "NOTIFICATIONS_SMTP_PORT": EMAIL_SMTP_PORT, "NOTIFICATIONS_SMTP_INSECURE": "true", - "NOTIFICATIONS_SMTP_SENDER": "ownCloud ", + "NOTIFICATIONS_SMTP_SENDER": EMAIL_SMTP_SENDER, }, }, "wopi": { @@ -3133,8 +3139,8 @@ def restoreWebPnpmCache(): def emailService(): return [{ - "name": "email", - "image": INBUCKET_INBUCKET, + "name": EMAIL_SMTP_HOST, + "image": AXLLENT_MAILPIT, }] def waitForEmailService(): @@ -3142,7 +3148,7 @@ def waitForEmailService(): "name": "wait-for-email", "image": OC_CI_WAIT_FOR, "commands": [ - "wait-for -it email:9000 -t 600", + "wait-for -it email:%s -t 600" % EMAIL_PORT, ], }] diff --git a/docs/ocis/development/testing.md b/docs/ocis/development/testing.md index 7f1f1539c31..6888c60dca7 100644 --- a/docs/ocis/development/testing.md +++ b/docs/ocis/development/testing.md @@ -335,14 +335,14 @@ While writing tests for a new oCIS ENV configuration, please make sure to follow ## Running Test Suite With Email Service (@email) -Test suites that are tagged with `@email` require an email service. We use inbucket as the email service in our tests. +Test suites that are tagged with `@email` require an email service. We use mailpit as the email service in our tests. -### Setup Inbucket +### Setup Mailpit -Run the following command to setup inbucket +Run the following command to setup mailpit ```bash -docker run -d -p9000:9000 -p2500:2500 --name inbucket inbucket/inbucket +docker run -d --restart unless-stopped --name=mailpit -p 8025:8025 -p 1025:1025 axllent/mailpit:v1.22.3 ``` ### Run oCIS @@ -371,7 +371,7 @@ Run the acceptance test with the following command: ```bash TEST_SERVER_URL="https://localhost:9200" \ EMAIL_HOST="localhost" \ -EMAIL_PORT=9000 \ +EMAIL_PORT=8025 \ BEHAT_FEATURE="tests/acceptance/features/apiNotification/emailNotification.feature" \ make test-acceptance-api ``` diff --git a/tests/acceptance/TestHelpers/CliHelper.php b/tests/acceptance/TestHelpers/CliHelper.php index bf281b5c772..287582f123f 100644 --- a/tests/acceptance/TestHelpers/CliHelper.php +++ b/tests/acceptance/TestHelpers/CliHelper.php @@ -22,11 +22,8 @@ namespace TestHelpers; -use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\GuzzleException; -use GuzzleHttp\Psr7\Request; use Psr\Http\Message\ResponseInterface; -use TestHelpers\OcisConfigHelper; /** * A helper class for running oCIS CLI commands diff --git a/tests/acceptance/TestHelpers/EmailHelper.php b/tests/acceptance/TestHelpers/EmailHelper.php index 42ac600301a..878aea91211 100644 --- a/tests/acceptance/TestHelpers/EmailHelper.php +++ b/tests/acceptance/TestHelpers/EmailHelper.php @@ -3,7 +3,8 @@ * ownCloud * * @author Prajwol Amatya - * @copyright Copyright (c) 2023 Prajwol Amatya prajwol@jankaritech.com + * @author Amrita Shrestha + * @copyright Copyright (c) 2023 JankariTech * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, @@ -22,7 +23,6 @@ namespace TestHelpers; -use Exception; use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; @@ -30,15 +30,13 @@ use Psr\Http\Message\ResponseInterface; * A helper class for managing emails */ class EmailHelper { - public const MAILBOX_ENDPOINT = "/api/v1/mailbox"; - /** - * @param string $emailAddress + * @param string $path * * @return string */ - public static function getMailBoxFromEmail(string $emailAddress): string { - return explode("@", $emailAddress)[0]; + public static function getEmailAPIUrl(string $path): string { + return self::getEmailBaseUrl() . '/api/v1/' . $path; } /** @@ -47,27 +45,10 @@ class EmailHelper { * * @return string */ - public static function getLocalEmailUrl(): string { - $localEmailHost = self::getLocalEmailHost(); - $emailPort = \getenv('EMAIL_PORT'); - if ($emailPort === false) { - $emailPort = "9000"; - } - return "http://$localEmailHost:$emailPort"; - } - - /** - * Returns the host name or address of the Email server as seen from the - * point of view of the system-under-test. - * - * @return string - */ - public static function getEmailHost(): string { - $emailHost = \getenv('EMAIL_HOST'); - if ($emailHost === false) { - $emailHost = "127.0.0.1"; - } - return $emailHost; + public static function getEmailBaseUrl(): string { + $emailHost = self::getEmailHost(); + $emailPort = \getenv('EMAIL_PORT') ?: "8025"; + return "http://$emailHost:$emailPort"; } /** @@ -76,137 +57,92 @@ class EmailHelper { * * @return string */ - public static function getLocalEmailHost(): string { - $localEmailHost = \getenv('LOCAL_EMAIL_HOST'); - if ($localEmailHost === false) { - $localEmailHost = self::getEmailHost(); - } - return $localEmailHost; + public static function getEmailHost(): string { + return \getenv('LOCAL_EMAIL_HOST') ?? \getenv('EMAIL_HOST') ?? "127.0.0.1"; } /** - * Returns general response information about the provided mailbox - * A mailbox is created automatically in InBucket for every unique email sender|receiver + * list all email * - * @param string $mailBox * @param string|null $xRequestId * - * @return array + * @return ResponseInterface * @throws GuzzleException */ - public static function getMailBoxInformation(string $mailBox, ?string $xRequestId = null): array { - $url = self::getLocalEmailUrl() . self::MAILBOX_ENDPOINT . "/$mailBox"; - $headers = ['Content-Type' => 'application/json']; - $response = HttpRequestHelper::get( - $url, - $xRequestId, - null, - null, - $headers - ); - - $emails = \json_decode($response->getBody()->getContents()); - if (empty($emails)) { - echo "[INFO] Mailbox is empty...\n"; - // Wait for 1 second and try again - // the mailbox might not be created yet - sleep(1); - $response = HttpRequestHelper::get( - $url, - $xRequestId, - null, - null, - $headers - ); - $emails = \json_decode($response->getBody()->getContents()); - } - - return $emails; - } - - /** - * returns body content of a specific email (mailBox) with email ID (mailbox Id) - * - * @param string $mailBox - * @param string $mailboxId - * @param string|null $xRequestId - * - * @return object - * @throws GuzzleException - */ - public static function getBodyOfAnEmailById( - string $mailBox, - string $mailboxId, - ?string $xRequestId = null - ): object { - $response = HttpRequestHelper::get( - self::getLocalEmailUrl() . self::MAILBOX_ENDPOINT . "/$mailBox/$mailboxId", + public static function listAllEmails( + ?string $xRequestId, + ): ResponseInterface { + return HttpRequestHelper::get( + self::getEmailAPIUrl("messages"), $xRequestId, null, null, ['Content-Type' => 'application/json'] ); - return \json_decode($response->getBody()->getContents()); } /** - * Returns the body of the last received email for the provided receiver according to the provided email address and the serial number - * For email number, 1 means the latest one - * - * @param string $emailAddress + * @param string $id when $id set to 'latest' returns the latest message. + * @param string $query * @param string|null $xRequestId - * @param int|null $emailNumber For email number, 1 means the latest one - * @param int|null $waitTimeSec Time to wait for the email if the email has been delivered - * - * @return string - * @throws GuzzleException - * @throws Exception - */ - public static function getBodyOfLastEmail( - string $emailAddress, - string $xRequestId, - ?int $emailNumber = 1, - ?int $waitTimeSec = EMAIL_WAIT_TIMEOUT_SEC - ): string { - $currentTime = \time(); - $endTime = $currentTime + $waitTimeSec; - $mailBox = self::getMailBoxFromEmail($emailAddress); - while ($currentTime <= $endTime) { - $mailboxResponse = self::getMailboxInformation($mailBox, $xRequestId); - if (!empty($mailboxResponse) && \sizeof($mailboxResponse) >= $emailNumber) { - $mailboxId = $mailboxResponse[\sizeof($mailboxResponse) - $emailNumber]->id; - $response = self::getBodyOfAnEmailById($mailBox, $mailboxId, $xRequestId); - $body = \str_replace( - "\r\n", - "\n", - \quoted_printable_decode($response->body->text . "\n" . $response->body->html) - ); - return $body; - } - \usleep(STANDARD_SLEEP_TIME_MICROSEC * 50); - $currentTime = \time(); - } - throw new Exception("Could not find the email to the address: " . $emailAddress); - } - - /** - * Deletes all the emails for the provided mailbox - * - * @param string $localInbucketUrl - * @param string|null $xRequestId - * @param string $mailBox * * @return ResponseInterface * @throws GuzzleException */ - public static function deleteAllEmailsForAMailbox( - string $localInbucketUrl, + public static function getEmailById( + string $id, + string $query, + ?string $xRequestId, + ): ResponseInterface { + return HttpRequestHelper::get( + self::getEmailAPIUrl("message/$id") . "?query=$query", + $xRequestId, + null, + null, + ['Content-Type' => 'application/json'] + ); + } + + /** + * search email + * + * @param string $query + * @param string|null $xRequestId + * + * @return ResponseInterface + * @throws GuzzleException + */ + public static function searchEmails( + string $query, + ?string $xRequestId, + ): ResponseInterface { + $url = self::getEmailAPIUrl("search") . "?query=$query"; + return HttpRequestHelper::get( + $url, + $xRequestId, + null, + null, + ['Content-Type' => 'application/json'] + ); + } + + /** + * Deletes all email + * + * @param string|null $xRequestId + * + * @return ResponseInterface + * @throws GuzzleException + */ + public static function deleteAllEmails( ?string $xRequestId, - string $mailBox ): ResponseInterface { return HttpRequestHelper::delete( - $localInbucketUrl . self::MAILBOX_ENDPOINT . "/$mailBox", - $xRequestId + self::getEmailAPIUrl("messages"), + $xRequestId, + null, + null, + ['Content-Type' => 'application/json'] ); } } diff --git a/tests/acceptance/TestHelpers/OcisConfigHelper.php b/tests/acceptance/TestHelpers/OcisConfigHelper.php index e45340b7837..ebee6f08f83 100644 --- a/tests/acceptance/TestHelpers/OcisConfigHelper.php +++ b/tests/acceptance/TestHelpers/OcisConfigHelper.php @@ -23,7 +23,6 @@ namespace TestHelpers; use GuzzleHttp\Exception\ConnectException; -use TestHelpers\HttpRequestHelper; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Request; use Psr\Http\Message\ResponseInterface; diff --git a/tests/acceptance/TestHelpers/SettingsHelper.php b/tests/acceptance/TestHelpers/SettingsHelper.php index 3f53dd13321..35eb9b0ed9b 100644 --- a/tests/acceptance/TestHelpers/SettingsHelper.php +++ b/tests/acceptance/TestHelpers/SettingsHelper.php @@ -22,7 +22,6 @@ namespace TestHelpers; -use TestHelpers\HttpRequestHelper; use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; use PHPUnit\Framework\Assert; diff --git a/tests/acceptance/bootstrap/EmailContext.php b/tests/acceptance/bootstrap/EmailContext.php new file mode 100644 index 00000000000..52d9b297a41 --- /dev/null +++ b/tests/acceptance/bootstrap/EmailContext.php @@ -0,0 +1,250 @@ + + * @copyright Copyright (c) 2025 Amrita Shrestha amrita@jankaritech.com + */ + +use Behat\Behat\Context\Context; +use Behat\Behat\Hook\Scope\BeforeScenarioScope; +use Behat\Gherkin\Node\PyStringNode; +use PHPUnit\Framework\Assert; +use GuzzleHttp\Exception\GuzzleException; +use TestHelpers\EmailHelper; +use TestHelpers\GraphHelper; +use TestHelpers\BehatHelper; + +require_once 'bootstrap.php'; + +/** + * Defines application features from the specific context. + */ +class EmailContext implements Context { + private FeatureContext $featureContext; + private SpacesContext $spacesContext; + + /** + * @BeforeScenario + * + * @param BeforeScenarioScope $scope + * + * @return void + * @throws Exception + */ + public function before(BeforeScenarioScope $scope): void { + // Get the environment + $environment = $scope->getEnvironment(); + // Get all the contexts you need in this context + $this->featureContext = BehatHelper::getContext($scope, $environment, 'FeatureContext'); + $this->spacesContext = BehatHelper::getContext($scope, $environment, 'SpacesContext'); + // if oCIS has been setup with notification configuration + // event related step generates emails + // so deleting all email + $this->clearAllEmails(); + } + + /** + * @AfterScenario @email + * + * @return void + * @throws GuzzleException + */ + public function clearAllEmails(): void { + try { + EmailHelper::deleteAllEmails($this->featureContext->getStepLineRef()); + } catch (Exception $e) { + echo __METHOD__ . + " could not delete email messages?\n" . + $e->getMessage(); + } + } + + /** + * @Then user :user should have received the following email from user :sender about the share of project space :spaceName + * + * @param string $user + * @param string $sender + * @param string $spaceName + * @param PyStringNode $content + * + * @return void + * @throws Exception + */ + public function userShouldHaveReceivedTheFollowingEmailFromUserAboutTheShareOfProjectSpace( + string $user, + string $sender, + string $spaceName, + PyStringNode $content + ): void { + $rawExpectedEmailBodyContent = \str_replace("\r\n", "\n", $content->getRaw()); + $this->featureContext->setResponse( + GraphHelper::getMySpaces( + $this->featureContext->getBaseUrl(), + $user, + $this->featureContext->getPasswordForUser($user), + '', + $this->featureContext->getStepLineRef() + ) + ); + $expectedEmailBodyContent = $this->featureContext->substituteInLineCodes( + $rawExpectedEmailBodyContent, + $sender, + [], + [ + [ + "code" => "%space_id%", + "function" => + [$this->spacesContext, "getSpaceIdByName"], + "parameter" => [$sender, $spaceName] + ], + ] + ); + $this->assertEmailContains($user, $expectedEmailBodyContent); + } + + /** + * @Then user :user should have received the following email from user :sender + * + * @param string $user + * @param string $sender + * @param PyStringNode $content + * + * @return void + * @throws Exception + */ + public function userShouldHaveReceivedTheFollowingEmailFromUser( + string $user, + string $sender, + PyStringNode $content + ): void { + $rawExpectedEmailBodyContent = \str_replace("\r\n", "\n", $content->getRaw()); + $expectedEmailBodyContent = $this->featureContext->substituteInLineCodes( + $rawExpectedEmailBodyContent, + $sender + ); + $this->assertEmailContains($user, $expectedEmailBodyContent); + } + + /** + * @Then user :user should have :count emails + * + * @param string $user + * @param int $count + * + * @return void + * @throws GuzzleException + */ + public function userShouldHaveEmail(string $user, int $count): void { + $address = $this->featureContext->getEmailAddressForUser($user); + $query = 'to:' . $address; + $response = EmailHelper::searchEmails($query, $this->featureContext->getStepLineRef()); + $emails = $this->featureContext->getJsonDecodedResponse($response); + if ($emails["messages_count"] <= $count) { + echo "[INFO] Mailbox is empty...\n"; + // Wait for 1 second and try again + // the mailbox might not be created yet + sleep(1); + $response = EmailHelper::searchEmails($query, $this->featureContext->getStepLineRef()); + $emails = $this->featureContext->getJsonDecodedResponse($response); + } + + Assert::assertSame( + $count, + $emails["messages_count"], + "Expected '$address' received mail total '$count' email but got " . $emails["messages_count"] . " email" + ); + } + + /** + * @Then user :user should have received the following email from user :sender ignoring whitespaces + * + * @param string $user + * @param string $sender + * @param PyStringNode $content + * + * @return void + * @throws Exception + */ + public function userShouldHaveReceivedTheFollowingEmailFromUserIgnoringWhitespaces( + string $user, + string $sender, + PyStringNode $content + ): void { + $rawExpectedEmailBodyContent = \str_replace("\r\n", "\n", $content->getRaw()); + $expectedEmailBodyContent = $this->featureContext->substituteInLineCodes( + $rawExpectedEmailBodyContent, + $sender + ); + $this->assertEmailContains($user, $expectedEmailBodyContent, true); + } + + /*** + * @param string $user + * @param string $expectedEmailBodyContent + * @param bool $ignoreWhiteSpace + * + * @return void + * @throws GuzzleException + */ + public function assertEmailContains( + string $user, + string $expectedEmailBodyContent, + $ignoreWhiteSpace = false + ): void { + $address = $this->featureContext->getEmailAddressForUser($user); + $actualEmailBodyContent = $this->getBodyOfLastEmail($address, $this->featureContext->getStepLineRef()); + if ($ignoreWhiteSpace) { + $expectedEmailBodyContent = preg_replace('/\s+/', '', $expectedEmailBodyContent); + $actualEmailBodyContent = preg_replace('/\s+/', '', $actualEmailBodyContent); + } + Assert::assertStringContainsString( + $expectedEmailBodyContent, + $actualEmailBodyContent, + "The email address '$address' should have received an" + . "email with the body containing $expectedEmailBodyContent + but the received email is $actualEmailBodyContent" + ); + } + + /** + * Returns the body of the last received email for the provided receiver according to the provided email address and the serial number + * For email number, 1 means the latest one + * + * @param string $emailAddress + * @param string|null $xRequestId + * @param int|null $waitTimeSec Time to wait for the email if the email has been delivered + * + * @return string + * @throws GuzzleException + * @throws Exception + */ + public function getBodyOfLastEmail( + string $emailAddress, + ?string $xRequestId, + ?int $waitTimeSec = EMAIL_WAIT_TIMEOUT_SEC + ): string { + $currentTime = \time(); + $endTime = $currentTime + $waitTimeSec; + while ($currentTime <= $endTime) { + $query = 'to:' . $emailAddress; + $mailResponse = $this->featureContext->getJsonDecodedResponse( + EmailHelper::searchEmails($query, $xRequestId) + ); + if ($mailResponse["messages_count"] > 0) { + $lastEmail = $this->featureContext->getJsonDecodedResponse( + EmailHelper::getEmailById("latest", $query, $xRequestId) + ); + $body = \str_replace( + "\r\n", + "\n", + \quoted_printable_decode($lastEmail["Text"] . "\n" . $lastEmail["HTML"]) + ); + return $body; + } + \usleep(STANDARD_SLEEP_TIME_MICROSEC * 50); + $currentTime = \time(); + } + throw new Exception("Could not find the email to the address: " . $emailAddress); + } +} diff --git a/tests/acceptance/bootstrap/FeatureContext.php b/tests/acceptance/bootstrap/FeatureContext.php index 6612d8a7dba..9315bca436d 100644 --- a/tests/acceptance/bootstrap/FeatureContext.php +++ b/tests/acceptance/bootstrap/FeatureContext.php @@ -148,7 +148,6 @@ class FeatureContext extends BehatVariablesContext { private int $ocsApiVersion = 1; private ?ResponseInterface $response = null; private string $responseUser = ''; - public array $emailRecipients = []; private CookieJar $cookieJar; private string $requestToken; private array $createdFiles = []; @@ -281,18 +280,6 @@ class FeatureContext extends BehatVariablesContext { } } - /** - * @param string $emailAddress - * - * @return void - */ - public function pushEmailRecipientAsMailBox(string $emailAddress): void { - $mailBox = explode("@", $emailAddress)[0]; - if (!\in_array($mailBox, $this->emailRecipients)) { - $this->emailRecipients[] = $mailBox; - } - } - private Ldap $ldap; private string $ldapBaseDN; private string $ldapHost; diff --git a/tests/acceptance/bootstrap/NotificationContext.php b/tests/acceptance/bootstrap/NotificationContext.php index a358a3ceb56..38d3d58841d 100644 --- a/tests/acceptance/bootstrap/NotificationContext.php +++ b/tests/acceptance/bootstrap/NotificationContext.php @@ -13,9 +13,7 @@ use Behat\Gherkin\Node\PyStringNode; use PHPUnit\Framework\Assert; use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; -use TestHelpers\EmailHelper; use TestHelpers\OcsApiHelper; -use TestHelpers\GraphHelper; use TestHelpers\SettingsHelper; use TestHelpers\BehatHelper; @@ -26,85 +24,11 @@ require_once 'bootstrap.php'; */ class NotificationContext implements Context { private FeatureContext $featureContext; - private SpacesContext $spacesContext; - private SettingsContext $settingsContext; private string $notificationEndpointPath = '/apps/notifications/api/v1/notifications?format=json'; private string $globalNotificationEndpointPath = '/apps/notifications/api/v1/notifications/global'; private array $notificationIds; - /** - * @return array[] - */ - public function getNotificationIds(): array { - return $this->notificationIds; - } - - /** - * @return array[] - */ - public function getLastNotificationId(): array { - return \end($this->notificationIds); - } - - /** - * delete all in-app notifications - * - * @return void - * @throws GuzzleException - */ - public function deleteDeprovisioningNotification(): void { - $payload["ids"] = ["deprovision"]; - - OcsApiHelper::sendRequest( - $this->featureContext->getBaseUrl(), - $this->featureContext->getAdminUsername(), - $this->featureContext->getAdminPassword(), - 'DELETE', - $this->globalNotificationEndpointPath, - $this->featureContext->getStepLineRef(), - json_encode($payload) - ); - } - - /** - * Delete all the emails - * - * @return void - * @throws GuzzleException - */ - public function clearAllEmails(): void { - try { - $usersList = $this->featureContext->getCreatedUsers(); - foreach ($usersList as $emailRecipient) { - EmailHelper::deleteAllEmailsForAMailbox( - EmailHelper::getLocalEmailUrl(), - $this->featureContext->getStepLineRef(), - $emailRecipient['email'] - ); - } - } catch (Exception $e) { - echo __METHOD__ . - " could not delete inbucket messages, is inbucket set up?\n" . - $e->getMessage(); - } - } - - /** - * @AfterScenario @notification - * - * @return void - * @throws GuzzleException - * @throws JsonException - */ - public function deleteAllNotifications(): void { - $this->deleteDeprovisioningNotification(); - $this->clearAllEmails(); - } - - /** - * @var string - */ private string $userRecipient; /** @@ -123,6 +47,20 @@ class NotificationContext implements Context { return $this->userRecipient; } + /** + * @return array[] + */ + public function getNotificationIds(): array { + return $this->notificationIds; + } + + /** + * @return array[] + */ + public function getLastNotificationId(): array { + return \end($this->notificationIds); + } + /** * @BeforeScenario * @@ -136,8 +74,28 @@ class NotificationContext implements Context { $environment = $scope->getEnvironment(); // Get all the contexts you need in this context $this->featureContext = BehatHelper::getContext($scope, $environment, 'FeatureContext'); - $this->spacesContext = BehatHelper::getContext($scope, $environment, 'SpacesContext'); - $this->settingsContext = BehatHelper::getContext($scope, $environment, 'SettingsContext'); + } + + /** + * delete all in-app notifications + * + * @AfterScenario @notification + * + * @return void + * @throws GuzzleException + */ + public function deleteDeprovisioningNotification(): void { + $payload["ids"] = ["deprovision"]; + + OcsApiHelper::sendRequest( + $this->featureContext->getBaseUrl(), + $this->featureContext->getAdminUsername(), + $this->featureContext->getAdminPassword(), + 'DELETE', + $this->globalNotificationEndpointPath, + $this->featureContext->getStepLineRef(), + json_encode($payload) + ); } /** @@ -562,140 +520,6 @@ class NotificationContext implements Context { ); } - /** - * @Then user :user should have received the following email from user :sender about the share of project space :spaceName - * - * @param string $user - * @param string $sender - * @param string $spaceName - * @param PyStringNode $content - * - * @return void - * @throws Exception - */ - public function userShouldHaveReceivedTheFollowingEmailFromUserAboutTheShareOfProjectSpace( - string $user, - string $sender, - string $spaceName, - PyStringNode $content - ): void { - $rawExpectedEmailBodyContent = \str_replace("\r\n", "\n", $content->getRaw()); - $this->featureContext->setResponse( - GraphHelper::getMySpaces( - $this->featureContext->getBaseUrl(), - $user, - $this->featureContext->getPasswordForUser($user), - '', - $this->featureContext->getStepLineRef() - ) - ); - $expectedEmailBodyContent = $this->featureContext->substituteInLineCodes( - $rawExpectedEmailBodyContent, - $sender, - [], - [ - [ - "code" => "%space_id%", - "function" => - [$this->spacesContext, "getSpaceIdByName"], - "parameter" => [$sender, $spaceName] - ], - ] - ); - $this->assertEmailContains($user, $expectedEmailBodyContent); - } - - /** - * @Then user :user should have received the following email from user :sender - * - * @param string $user - * @param string $sender - * @param PyStringNode $content - * - * @return void - * @throws Exception - */ - public function userShouldHaveReceivedTheFollowingEmailFromUser( - string $user, - string $sender, - PyStringNode $content - ): void { - $rawExpectedEmailBodyContent = \str_replace("\r\n", "\n", $content->getRaw()); - $expectedEmailBodyContent = $this->featureContext->substituteInLineCodes( - $rawExpectedEmailBodyContent, - $sender - ); - $this->assertEmailContains($user, $expectedEmailBodyContent); - } - - /** - * @Then user :user should have :count emails - * - * @param string $user - * @param int $count - * - * @return void - */ - public function userShouldHaveEmail(string $user, int $count): void { - $address = $this->featureContext->getEmailAddressForUser($user); - $this->featureContext->pushEmailRecipientAsMailBox($address); - $mailBox = EmailHelper::getMailBoxFromEmail($address); - $mailboxResponse = EmailHelper::getMailboxInformation($mailBox, $this->featureContext->getStepLineRef()); - Assert::assertCount($count, $mailboxResponse); - } - - /** - * @Then user :user should have received the following email from user :sender ignoring whitespaces - * - * @param string $user - * @param string $sender - * @param PyStringNode $content - * - * @return void - * @throws Exception - */ - public function userShouldHaveReceivedTheFollowingEmailFromUserIgnoringWhitespaces( - string $user, - string $sender, - PyStringNode $content - ): void { - $rawExpectedEmailBodyContent = \str_replace("\r\n", "\n", $content->getRaw()); - $expectedEmailBodyContent = $this->featureContext->substituteInLineCodes( - $rawExpectedEmailBodyContent, - $sender - ); - $this->assertEmailContains($user, $expectedEmailBodyContent, true); - } - - /*** - * @param string $user - * @param string $expectedEmailBodyContent - * @param bool $ignoreWhiteSpace - * - * @return void - * @throws GuzzleException - */ - public function assertEmailContains( - string $user, - string $expectedEmailBodyContent, - $ignoreWhiteSpace = false - ): void { - $address = $this->featureContext->getEmailAddressForUser($user); - $this->featureContext->pushEmailRecipientAsMailBox($address); - $actualEmailBodyContent = EmailHelper::getBodyOfLastEmail($address, $this->featureContext->getStepLineRef()); - if ($ignoreWhiteSpace) { - $expectedEmailBodyContent = preg_replace('/\s+/', '', $expectedEmailBodyContent); - $actualEmailBodyContent = preg_replace('/\s+/', '', $actualEmailBodyContent); - } - Assert::assertStringContainsString( - $expectedEmailBodyContent, - $actualEmailBodyContent, - "The email address '$address' should have received an" - . "email with the body containing $expectedEmailBodyContent - but the received email is $actualEmailBodyContent" - ); - } - /** * * @param string|null $user diff --git a/tests/acceptance/config/behat.yml b/tests/acceptance/config/behat.yml index ef0a07c05a2..6a963fadad1 100644 --- a/tests/acceptance/config/behat.yml +++ b/tests/acceptance/config/behat.yml @@ -191,6 +191,7 @@ default: context: *common_ldap_suite_context contexts: - NotificationContext: + - EmailContext: - FeatureContext: *common_feature_context_params - SpacesContext: - OCSContext: @@ -361,6 +362,7 @@ default: - SettingsContext: - SharingNgContext: - NotificationContext: + - EmailContext: - OcisConfigContext: apiSharingNgShareInvitation: @@ -406,6 +408,7 @@ default: - SpacesContext: - OcisConfigContext: - NotificationContext: + - EmailContext: - SettingsContext: - SpacesTUSContext: diff --git a/tests/acceptance/features/apiOcm/createInvitation.feature b/tests/acceptance/features/apiOcm/createInvitation.feature index 3f364eb6678..1cf70d46717 100755 --- a/tests/acceptance/features/apiOcm/createInvitation.feature +++ b/tests/acceptance/features/apiOcm/createInvitation.feature @@ -81,7 +81,7 @@ Feature: create invitation Given using server "REMOTE" And user "David" has been created with default attributes And using server "LOCAL" - When "Alice" has created the federation share invitation with email "david@example.com" and description "a share invitation from Alice" + When "Alice" has created the federation share invitation with email "david@example.org" and description "a share invitation from Alice" And user "David" should have received the following email from user "Alice" ignoring whitespaces """ Hi, diff --git a/tests/acceptance/run.sh b/tests/acceptance/run.sh index 85d9b0bc6eb..aa73e2ae730 100755 --- a/tests/acceptance/run.sh +++ b/tests/acceptance/run.sh @@ -488,26 +488,22 @@ then BEHAT_FILTER_TAGS="${BEHAT_FILTER_TAGS#&&}" fi -# EMAIL_HOST defines where the system-under-test can find the email server (inbucket) +# EMAIL_HOST defines where the system-under-test can find the email server (mailpit) # for sending email. if [ -z "${EMAIL_HOST}" ] then EMAIL_HOST="127.0.0.1" fi -# LOCAL_INBUCKET_HOST defines where this test script can find the Inbucket server -# for sending email. When testing a remote system, the Inbucket server somewhere +# LOCAL_EMAIL_HOST defines where this test script can find the mailpit server +# for sending email. When testing a remote system, the mailpit server somewhere # "in the middle" might have a different host name from the point of view of # the test script. if [ -z "${LOCAL_EMAIL_HOST}" ] then LOCAL_EMAIL_HOST="${EMAIL_HOST}" fi - -if [ -z "${EMAIL_SMTP_PORT}" ] -then - EMAIL_SMTP_PORT="2500" -fi +export LOCAL_EMAIL_HOST # If the caller did not mention specific tags, skip the skipped tests by default if [ "${BEHAT_TAGS_OPTION_FOUND}" = false ]