Skip to content

Commit

Permalink
wip tests
Browse files Browse the repository at this point in the history
  • Loading branch information
d8vjork committed Feb 26, 2024
1 parent 6b14575 commit 25737b4
Show file tree
Hide file tree
Showing 8 changed files with 142 additions and 45 deletions.
24 changes: 6 additions & 18 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,9 @@ jobs:
fail-fast: true
matrix:
os: [ ubuntu-latest ]
php: [ 8.0, 8.1, 8.2 ]
laravel: [ 9.*, 10.* ]
dependency-version: [ prefer-stable ]
include:
- laravel: 9.*
testbench: 7.*
php: [ 8.0, 8.1, 8.2, 8.3 ]

- laravel: 10.*
testbench: 8.*
exclude:
- laravel: 10.*
php: 8.0

name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }}
name: P${{ matrix.php }} - ${{ matrix.os }}

steps:
- name: Checkout code
Expand All @@ -45,17 +34,16 @@ jobs:
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-${{ matrix.dependency-version }}-
restore-keys: ${{ runner.os }}-composer-

- name: Install dependencies
run: |
composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update
composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest
run: composer install --prefer-dist --no-interaction --no-suggest

- name: Execute tests
run: vendor/bin/phpunit -c phpunit.coverage.dist.xml
run: vendor/bin/pest --coverage-clover clover.xml

- name: Upload coverage reports to Codecov
if: matrix.php == '8.3'
uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
Expand Down
19 changes: 6 additions & 13 deletions phpunit.coverage.dist.xml
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.0/phpunit.xsd"
bootstrap="vendor/autoload.php"
backupGlobals="false"
colors="true"
processIsolation="true"
stopOnFailure="false"
cacheDirectory=".phpunit.cache"
backupStaticProperties="false"
>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd" bootstrap="vendor/autoload.php" backupGlobals="false" colors="true" processIsolation="true" stopOnFailure="false" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
<report>
<clover outputFile="clover.xml"/>
</report>
Expand All @@ -27,4 +15,9 @@
<env name="DB_CONNECTION" value="sqlite" force="true"/>
<env name="DB_DATABASE" value=":memory:" force="true"/>
</php>
<source>
<include>
<directory suffix=".php">src</directory>
</include>
</source>
</phpunit>
25 changes: 17 additions & 8 deletions src/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;

use Psr\Http\Message\StreamInterface;

use function OpenSoutheners\LaravelHelpers\Utils\build_http_query;

class ApiClient
Expand All @@ -39,10 +41,10 @@ class ApiClient

public function __construct(
private string $baseUrl,
?SocketClient $socket = null,
?RequestFactoryInterface $requestFactory = null,
?StreamFactoryInterface $streamFactory = null,
?PluginClientFactory $pluginFactory = null,
SocketClient $socket = null,
RequestFactoryInterface $requestFactory = null,
StreamFactoryInterface $streamFactory = null,
PluginClientFactory $pluginFactory = null,
private array $headers = []
) {
$requestFactory ??= Psr17FactoryDiscovery::findRequestFactory();
Expand All @@ -51,7 +53,7 @@ public function __construct(
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;

$socket ??= new SocketClient($this->requestFactory, [
$socket ??= new SocketClient([
'remote_socket' => 'unix:///var/run/docker.sock',
]);

Expand Down Expand Up @@ -143,6 +145,11 @@ public function contentType(string $value): static
return $this->usingHeader('Content-Type', $value);
}

public function acceptResponseType(string $value): static
{
return $this->usingHeader('Accept', $value);
}

public function usingHeader(string $header, string $value): static
{
$this->headers[$header] = $value;
Expand All @@ -167,15 +174,17 @@ private function executeRequest(RequestInterface $request): mixed
/**
* Get parsed body using Content-Type header.
*/
private function applySentBodyParsing(mixed $body): mixed
private function applySentBodyParsing(mixed $body): StreamInterface
{
return match ($this->headers['Content-Type'] ?? null) {
$parsedBody = match ($this->headers['Content-Type'] ?? null) {
static::JSON_CONTENT_TYPE => json_encode($body),
static::RAW_CONTENT_TYPE => $body,
// TODO:
// static::STREAM_CONTENT_TYPE =>
default => $body,
};

return $this->streamFactory->createStream($parsedBody);

Check failure on line 187 in src/ApiClient.php

View workflow job for this annotation

GitHub Actions / PHPStan

Parameter #1 $content of method Psr\Http\Message\StreamFactoryInterface::createStream() expects string, mixed given.
}

/**
Expand All @@ -196,7 +205,7 @@ private function applyResponseParsing(ResponseInterface $response): mixed

private function parseResponse(ResponseInterface $response): mixed
{
if ($response->getStatusCode() === 204) {
if (in_array($response->getStatusCode(), [204, 304], true)) {
return null;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function __construct(
$this->system = new System($this->apiClient);
}

public function compose(string $file = null)
public function compose(string $file = null): Builder
{
return new Builder($file);
}
Expand Down
7 changes: 4 additions & 3 deletions src/Endpoints/Containers.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ public function list(?ContainersListQuery $query = null): mixed
return $this->client->get(self::PATH . '/json', $query ?? []);
}

public function create(array $body): mixed
public function create(array $body, ?string $name = null, string $arch = ''): mixed
{
return $this->client->post(self::PATH . '/create', $body);
return $this->client->post(self::PATH . '/create', $body, compact('name', 'arch'));
}

public function inspect(string $id, ?ContainersInspectQuery $query): mixed
Expand Down Expand Up @@ -111,7 +111,8 @@ public function wait(string $id): mixed

public function remove(string $id): mixed
{
return $this->client->delete(self::PATH . "/{$id}");
return $this->client->contentType(ApiClient::RAW_CONTENT_TYPE)
->delete(self::PATH . "/{$id}");
}

public function filesystem(string $id): mixed
Expand Down
4 changes: 2 additions & 2 deletions src/Endpoints/Delegates/HandlesContainers.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ public function getContainers(?ContainersListQuery $query = null): mixed
return $this->containers->list($query);
}

public function createContainer(array $body): mixed
public function createContainer(array $body, ?string $name = null, string $arch = ''): mixed
{
return $this->containers->create($body);
return $this->containers->create($body, $name, $arch);
}

public function getContainer(string $id, ?ContainersInspectQuery $query = null): mixed
Expand Down
61 changes: 61 additions & 0 deletions tests/ContainersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

use OpenSoutheners\Docker\Client;

beforeEach(function () {
$this->client = new Client('http://localhost:2375');
});

test('create container returns array result with no warnings', function () {
$container = $this->client->createContainer([
'Image' => 'alpine:3.18',
], 'docker_php_test');

expect($container)->toBeArray();

expect($container['Warnings'])->toBeArray();
expect($container['Warnings'])->toBeEmpty();
expect($container['Id'])->toBeString();

$this->containerId = $container['Id'];
});

test('list running containers returns array', function () {
$containers = $this->client->getContainers();

expect($containers)->toBeArray();

$firstContainer = reset($containers);

expect($firstContainer)->toBeArray();
expect($firstContainer)->toHaveKeys([
'Id', 'Names', 'Image', 'ImageID', 'Command',
'Created', 'Ports', 'Labels', 'State', 'Status',
'HostConfig', 'NetworkSettings', 'Mounts',
]);
});

test('get container by ID returns array', function () {
$container = $this->client->getContainer('ec214ba23641');

expect($container)->toBeArray();
expect($container)->toHaveKeys([
'Id', 'Created', 'Path', 'Args', 'State',
'Image', 'ResolvConfPath', 'HostnamePath', 'HostsPath', 'LogPath',
'Name', 'RestartCount', 'Driver', 'Platform', 'MountLabel',
'ProcessLabel', 'AppArmorProfile', 'ExecIDs', 'HostConfig',
'GraphDriver', 'Mounts', 'Config', 'NetworkSettings'
]);
});

test('stop container returns empty response', function () {
$result = $this->client->stopContainer('docker_php_test');

expect($result)->toBeNull();
})->depends('create container returns array result with no warnings');

test('remove container returns array result with no warnings', function () {
$result = $this->client->removeContainer('docker_php_test');

expect($result)->toBeNull();
})->depends('stop container returns empty response');
45 changes: 45 additions & 0 deletions tests/Pest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "uses()" function to bind a different classes or traits.
|
*/

// uses(Tests\TestCase::class)->in('Feature');

/*
|--------------------------------------------------------------------------
| Expectations
|--------------------------------------------------------------------------
|
| When you're writing tests, you often need to check that values meet certain conditions. The
| "expect()" function gives you access to a set of "expectations" methods that you can use
| to assert different things. Of course, you may extend the Expectation API at any time.
|
*/

expect()->extend('toBeOne', function () {
return $this->toBe(1);
});

/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
| project that you don't want to repeat in every file. Here you can also expose helpers as
| global functions to help you to reduce the number of lines of code in your test files.
|
*/

function something()
{
// ..
}

0 comments on commit 25737b4

Please sign in to comment.