Skip to content

Commit

Permalink
Added basic tests and fixed upgraded dependency issue (#60)
Browse files Browse the repository at this point in the history
* Added basic tests and fixed upgraded dependency issue

* Fixed base branch detection after 4.3 stable branches

* fixup! Added basic tests and fixed upgraded dependency issue

* Make sonar happy
  • Loading branch information
mnocon authored Sep 26, 2022
1 parent ae9086e commit 3cba18c
Show file tree
Hide file tree
Showing 13 changed files with 292 additions and 50 deletions.
70 changes: 70 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: CI

on:
push:
branches:
- main
- '[0-9]+.[0-9]+'
pull_request: ~

jobs:
cs-fix:
name: Run code style check
runs-on: "ubuntu-20.04"
strategy:
matrix:
php:
- '8.0'
steps:
- uses: actions/checkout@v2

- name: Setup PHP Action
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: 'pdo_sqlite, gd'
tools: cs2pr

- uses: "ramsey/composer-install@v1"
with:
dependency-versions: "highest"

- name: Run code style check
run: composer run-script check-cs -- --format=checkstyle | cs2pr

tests:
name: Tests
runs-on: "ubuntu-20.04"
timeout-minutes: 10

strategy:
fail-fast: false
matrix:
php:
- '7.3'
- '7.4'
- '8.0'
- '8.1'

steps:
- uses: actions/checkout@v2

- name: Setup PHP Action
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: pdo_sqlite, gd
tools: cs2pr

- uses: "ramsey/composer-install@v1"
with:
dependency-versions: "highest"
composer-options: "--prefer-dist --no-progress"

- name: Setup problem matchers for PHPUnit
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"

- name: Run test suite
run: composer run-script --timeout=600 test
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/vendor/
composer.lock
.php_cs.cache
.phpunit.result.cache
5 changes: 4 additions & 1 deletion .php_cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
return EzSystems\EzPlatformCodeStyle\PhpCsFixer\EzPlatformInternalConfigFactory::build()
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__ . '/src')
->in([
__DIR__ . '/src',
__DIR__ . '/tests',
])
->files()->name('*.php')
)
;
4 changes: 2 additions & 2 deletions bin/ci
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ if (!class_exists('Symfony\Component\Console\Application', true)) {

$application = new Symfony\Component\Console\Application;

$application->add(new Ibexa\Platform\ContiniousIntegrationScripts\Command\LinkDependenciesCommand());
$application->add(new Ibexa\Platform\ContiniousIntegrationScripts\Command\RunRegressionCommand());
$application->add(new Ibexa\ContiniousIntegrationScripts\Command\LinkDependenciesCommand());
$application->add(new Ibexa\ContiniousIntegrationScripts\Command\RunRegressionCommand());

$application->run();
15 changes: 12 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@
},
"autoload": {
"psr-4": {
"Ibexa\\Platform\\ContiniousIntegrationScripts\\": "src/"
"Ibexa\\ContiniousIntegrationScripts\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Ibexa\\Tests\\ContiniousIntegrationScripts\\": "tests/"
}
},
"extra": {
Expand All @@ -32,11 +37,15 @@
],
"require-dev": {
"ezsystems/ezplatform-code-style": "^1.0@dev",
"phpstan/phpstan": "~0.12"
"phpstan/phpstan": "~0.12",
"phpunit/phpunit": "^9.5",
"mikey179/vfsstream": "^1.6"
},
"scripts": {
"phpstan": "phpstan analyse -c phpstan.neon",
"phpstan-baseline": "phpstan analyse -c phpstan.neon --generate-baseline",
"fix-cs": "php-cs-fixer fix -v --show-progress=estimating"
"fix-cs": "php-cs-fixer fix -v --show-progress=estimating",
"check-cs": "@fix-cs --dry-run",
"test": "phpunit -c phpunit.xml"
}
}
21 changes: 21 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
colors="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory>src</directory>
</include>
</coverage>
<testsuites>
<testsuite name="Tests">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
42 changes: 31 additions & 11 deletions src/Command/LinkDependenciesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@
*/
declare(strict_types=1);

namespace Ibexa\Platform\ContiniousIntegrationScripts\Command;
namespace Ibexa\ContiniousIntegrationScripts\Command;

use Github\AuthMethod;
use Github\Client;
use Ibexa\Platform\ContiniousIntegrationScripts\Helper\ComposerHelper;
use Ibexa\Platform\ContiniousIntegrationScripts\ValueObject\ComposerPullRequestData;
use Ibexa\Platform\ContiniousIntegrationScripts\ValueObject\Dependencies;
use Ibexa\ContiniousIntegrationScripts\Helper\ComposerLocalTokenProvider;
use Ibexa\ContiniousIntegrationScripts\ValueObject\ComposerPullRequestData;
use Ibexa\ContiniousIntegrationScripts\ValueObject\Dependencies;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Path;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
Expand All @@ -34,10 +36,24 @@ class LinkDependenciesCommand extends Command
/** @var string[] */
private $pullRequestUrls;

public function __construct()
/** @var \Github\Client */
private $githubClient;

/** @var string */
private $outputDirectory;

/**
* @var \Ibexa\ContiniousIntegrationScripts\Helper\ComposerLocalTokenProvider
*/
private $tokenProvider;

public function __construct($outputDirectory = null, ComposerLocalTokenProvider $tokenProvider = null)
{
parent::__construct();
$this->serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$this->githubClient = new Client();
$this->outputDirectory = $outputDirectory ?? '.';
$this->tokenProvider = $tokenProvider ?? new ComposerLocalTokenProvider();
}

public function execute(InputInterface $input, OutputInterface $output): int
Expand All @@ -63,20 +79,24 @@ protected function configure(): void

private function getPullRequestData(string $owner, string $repository, int $prNumber): ComposerPullRequestData
{
$client = new Client();
if ($this->token) {
$client->authenticate($this->token, null, Client::AUTH_ACCESS_TOKEN);
$this->githubClient->authenticate($this->token, null, AuthMethod::ACCESS_TOKEN);
}

$pullRequestDetails = $client->pullRequests()->show($owner, $repository, $prNumber);
$pullRequestDetails = $this->githubClient->pullRequests()->show($owner, $repository, $prNumber);

$pullRequestData = new ComposerPullRequestData();
$pullRequestData->repositoryUrl = $pullRequestDetails['head']['repo']['html_url'];
$pullRequestData->shouldBeAddedAsVCS = $pullRequestDetails['head']['repo']['private'] || $pullRequestDetails['head']['repo']['fork'];
$branchName = $pullRequestDetails['head']['ref'];
$targetBranch = $pullRequestDetails['base']['ref'];

$composerData = json_decode($client->repos()->contents()->download($owner, $repository, 'composer.json', $targetBranch), true);
$composerData = json_decode(
$this->githubClient->repos()->contents()->download($owner, $repository, 'composer.json', $targetBranch),
true,
512,
JSON_THROW_ON_ERROR
);

$aliases = array_keys($composerData['extra']['branch-alias']);
$branchAlias = $composerData['extra']['branch-alias'][$aliases[0]];
Expand All @@ -92,7 +112,7 @@ protected function interact(InputInterface $input, OutputInterface $output): voi
$io = new SymfonyStyle($input, $output);

if (!$input->getArgument('token')) {
$input->setArgument('token', ComposerHelper::getGitHubToken());
$input->setArgument('token', $this->tokenProvider->getGitHubToken());
}

$relatedPRsNumber = $io->ask('Please enter the number of related Pull Requests', '1', static function ($number) {
Expand Down Expand Up @@ -122,7 +142,7 @@ protected function interact(InputInterface $input, OutputInterface $output): voi
private function createDependenciesFile(Dependencies $dependencies, SymfonyStyle $io): void
{
$jsonContent = $this->serializer->serialize($dependencies, 'json', ['json_encode_options' => JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT]);
file_put_contents(self::DEPENDENCIES_FILE, $jsonContent);
file_put_contents(Path::join($this->outputDirectory, self::DEPENDENCIES_FILE), $jsonContent);
$io->success(sprintf('Successfully generated %s file', self::DEPENDENCIES_FILE));
}

Expand Down
72 changes: 47 additions & 25 deletions src/Command/RunRegressionCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
*/
declare(strict_types=1);

namespace Ibexa\Platform\ContiniousIntegrationScripts\Command;
namespace Ibexa\ContiniousIntegrationScripts\Command;

use Cz\Git\GitException;
use Cz\Git\GitRepository;
use CzProject\GitPhp\Git;
use CzProject\GitPhp\GitException;
use Github\Client;
use Ibexa\Platform\ContiniousIntegrationScripts\Helper\ComposerHelper;
use Ibexa\ContiniousIntegrationScripts\Helper\ComposerLocalTokenProvider;
use JsonException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
Expand All @@ -31,26 +31,47 @@ class RunRegressionCommand extends Command
/** @var ?string */
private $token;

/** @var \Github\Client */
private $githubClient;

/** @var \CzProject\GitPhp\Git */
private $repository;

/** @var \Ibexa\ContiniousIntegrationScripts\Helper\ComposerLocalTokenProvider */
private $tokenProvider;

public function __construct()
{
parent::__construct();
$this->githubClient = new Client();
$this->repository = new Git();
$this->tokenProvider = new ComposerLocalTokenProvider();
}

protected function interact(InputInterface $input, OutputInterface $output): void
{
$io = new SymfonyStyle($input, $output);

if (!$input->getArgument('token')) {
$input->setArgument('token', ComposerHelper::getGitHubToken());
$input->setArgument('token', $this->tokenProvider->getGitHubToken());
}

if (!$input->getArgument('productVersion')) {
$productVersion = $io->ask('Please enter the Ibexa DXP version', '4.1', static function (string $answer): string {
if (preg_match('/^(\d+)\.(\d+)$/', $answer) === 0) {
throw new \RuntimeException(
sprintf(
'Unrecognised version format: %s. Please use format X.Y instead, e.g. 3.3, 4.0, 4.1',
$answer)
);
}
$productVersion = $io->ask(
'Please enter the Ibexa DXP version',
'4.2',
static function (string $answer): string {
if (preg_match('/^(\d+)\.(\d+)$/', $answer) === 0) {
throw new \RuntimeException(
sprintf(
'Unrecognised version format: %s. Please use format X.Y instead, e.g. 3.3, 4.2, 4.3',
$answer)
);
}

return $answer;
});
return $answer;
}
);

$input->setArgument('productVersion', $productVersion);
}
Expand Down Expand Up @@ -99,13 +120,13 @@ public function execute(InputInterface $input, OutputInterface $output): int
private function createRegressionPullRequest(string $productEdition, string $baseBranch, string $regressionBranchName, SymfonyStyle $io): void
{
try {
$repo = GitRepository::cloneRepository(
$repo = $this->repository->cloneRepository(
sprintf('[email protected]:%s/%s.git', self::REPO_OWNER, $productEdition),
null, ['-b' => $baseBranch]
);
} catch (GitException $exception) {
// fallback to HTTPS if SSH fails
$repo = GitRepository::cloneRepository(
$repo = $this->repository->cloneRepository(
sprintf('https://github.com/%s/%s.git', self::REPO_OWNER, $productEdition),
null, ['-b' => $baseBranch]
);
Expand All @@ -118,18 +139,19 @@ private function createRegressionPullRequest(string $productEdition, string $bas

$repo->addFile(LinkDependenciesCommand::DEPENDENCIES_FILE);
$repo->commit(self::COMMIT_MESSAGE);
$repo->push('origin', [$regressionBranchName, '-u']);
$repo->push(['origin', $regressionBranchName]);

$io->success(sprintf('Successfuly pushed to %s/%s a branch called: %s', self::REPO_OWNER, $productEdition, $regressionBranchName));

$client = new Client();
if ($this->token) {
$client->authenticate($this->token, null, Client::AUTH_ACCESS_TOKEN);
$this->githubClient->authenticate($this->token, null, Client::AUTH_ACCESS_TOKEN);
}

$this->waitUntilBranchExists($client, $productEdition, $regressionBranchName);
$this->waitUntilBranchExists($productEdition, $regressionBranchName);

$response = $client->pullRequests()->create(self::REPO_OWNER, $productEdition,
$response = $this->githubClient->pullRequests()->create(
self::REPO_OWNER,
$productEdition,
[
'title' => 'Run regression for IBX-XXXX',
'base' => $baseBranch,
Expand Down Expand Up @@ -181,13 +203,13 @@ private function validate(): void
}
}

private function waitUntilBranchExists(Client $client, string $productEdition, string $branchName): void
private function waitUntilBranchExists(string $productEdition, string $branchName): void
{
$counter = 0;
$success = false;
while ($counter < 5) {
try {
$client->repo()->branches(self::REPO_OWNER, $productEdition, $branchName);
$this->githubClient->repo()->branches(self::REPO_OWNER, $productEdition, $branchName);
$success = true;
break;
} catch (\RuntimeException $e) {
Expand All @@ -203,6 +225,6 @@ private function waitUntilBranchExists(Client $client, string $productEdition, s

private function getBaseBranch(string $productVersion): string
{
return $productVersion === "4.2" ? "master" : $productVersion;
return $productVersion === '4.3' ? 'master' : $productVersion;
}
}
Loading

0 comments on commit 3cba18c

Please sign in to comment.