Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit tests #24

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 139 additions & 4 deletions .github/workflows/ci-linux.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,27 @@ on:
- 'feature/*'
- 'hotfix/*'
- 'release/*'
tags:
- '*'
pull_request:
# Enable manual run
workflow_dispatch:

concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: true

jobs:
ubuntu-latest:
lint:
runs-on: ubuntu-latest
name: "Lint on PHP ${{ matrix.php-versions }}"

strategy:
matrix:
php-versions: [ '8.1', '8.3' ]
coverage: [none]
fail-fast: false

name: PHP ${{ matrix.php-versions }} on ubuntu-latest

steps:
- name: PHP
uses: shivammathur/setup-php@v2
Expand Down Expand Up @@ -63,7 +70,7 @@ jobs:
- name: CS
run: |
cd galette-core/galette/plugins/plugin-auto
../../vendor/bin/phpcs lib/
../../vendor/bin/phpcs lib/ ./*.php

- name: Twig CS
run: |
Expand All @@ -86,3 +93,131 @@ jobs:
run: |
cd galette-core/galette/plugins/plugin-auto
../../vendor/bin/docheader --docheader=../../../.docheader check lib ./*.php

unit-tests:
runs-on: ubuntu-latest

strategy:
matrix:
include:
#always tests higher stable php version with lower db version
#enable coverage on higher stable php version with higher postrgesql version
#lower php version
- { php-version: "8.1", db-image: "mysql:5.7", coverage: none, always: false }
- { php-version: "8.1", db-image: "mysql:8.1", coverage: none, always: false }
- { php-version: "8.1", db-image: "mariadb:10.4", coverage: none, always: false }
- { php-version: "8.1", db-image: "mariadb:11", coverage: none, always: false }
- { php-version: "8.1", db-image: "postgres:11", coverage: none, always: false }
- { php-version: "8.1", db-image: "postgres:16", coverage: none, always: false }
#higher stable php version
- { php-version: "8.3", db-image: "mysql:5.7", coverage: none, always: true }
- { php-version: "8.3", db-image: "mysql:8.1", coverage: none, always: false }
- { php-version: "8.3", db-image: "mariadb:10.4", coverage: none, always: true }
- { php-version: "8.3", db-image: "mariadb:11", coverage: none, always: false }
- { php-version: "8.3", db-image: "postgres:11", coverage: none, always: true }
- { php-version: "8.3", db-image: "postgres:16", coverage: none, always: true }
fail-fast: false

env:
skip: ${{ matrix.always == false && (github.event_name == 'pull_request' || github.repository != 'galette/galette-auto' || !(github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/tags'))) }}
DB: ${{ matrix.db-image }}

services:
# Label used to access the service container
db:
# Docker Hub image
image: ${{ matrix.db-image }}
# Provide env variables for both mysql and pgsql
env:
POSTGRES_USER: galette_tests
POSTGRES_PASSWORD: g@l3tte
POSTGRES_DB: galette_tests
MYSQL_USER: galette_tests
MYSQL_PASSWORD: g@l3tte
MYSQL_ROOT_PASSWORD: g@l3tte
MYSQL_DATABASE: galette_tests
# Open network ports for both mysql and pgsql
ports:
- 3306:3306
- 5432:5432
# Set health checks to wait until postgres has started
options: >-
--health-cmd="bash -c 'if [[ -n $(command -v pg_isready) ]]; then pg_isready; else if [[ -n $(command -v mysqladmin) ]]; then mysqladmin ping; else mariadb-admin ping; fi fi'"
--health-interval=10s
--health-timeout=5s
--health-retries=10

name: PHP ${{ matrix.php-version }} ${{ matrix.db-image }} ${{ (matrix.always == false && (github.event_name == 'pull_request' || github.repository != 'galette/galette' || !(github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/tags')))) && ' (skipped)' || matrix.coverage == 'xdebug' && ' (with coverage)' || ''}}

steps:
- name: PHP
if: env.skip != 'true'
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
tools: composer, pecl
coverage: ${{ matrix.coverage }}
extensions: apcu
ini-values: apc.enable_cli=1

- name: "Show versions"
if: env.skip != 'true'
run: |
php --version
composer --version
echo "node $(node --version)"
echo "npm $(npm --version)"
docker exec ${{ job.services.db.id }} bash -c "if [[ -n \$(command -v psql) ]]; then psql --version; else if [[ -n \$(command -v mysql) ]]; then mysql --version; else mariadb --version; fi fi"

- name: Checkout Galette core
if: env.skip != 'true'
uses: actions/checkout@v4
with:
repository: galette/galette
path: galette-core
fetch-depth: 1
ref: develop

- name: Checkout plugin
uses: actions/checkout@v4
with:
path: galette-core/galette/plugins/plugin-auto

- name: "Restore dependencies cache"
if: env.skip != 'true'
uses: actions/cache@v4
with:
path: |
~/.composer/cache/
~/.npm/_cacache/
key: "${{ runner.os }}-galette-${{ matrix.php-version }}-${{ hashFiles('galette/composer.lock', 'package-lock.json') }}"
restore-keys: |
${{ runner.os }}-galette-${{ matrix.php-version }}-

- name: Install dependencies
if: env.skip != 'true'
run: |
cd galette-core
bin/install_deps

- name: Init for PostgreSQL
env:
POSTGRES_HOST: localhost
POSTGRES_PORT: 5432
run: |
PGPASSWORD=g@l3tte psql -d galette_tests -a -f galette-core/galette/install/scripts/pgsql.sql -U galette_tests -h localhost
PGPASSWORD=g@l3tte psql -d galette_tests -a -f galette-core/galette/plugins/plugin-auto/scripts/pgsql.sql -U galette_tests -h localhost
if: env.skip != 'true' && startsWith(matrix.db-image, 'postgres')

- name: Init for MariaDB
run: |
mysql -e 'create database IF NOT EXISTS galette_tests;' -u galette_tests --password=g@l3tte -h 127.0.0.1 -P 3306
mysql -e 'use galette_tests; source galette-core/galette/install/scripts/mysql.sql;' -u galette_tests --password=g@l3tte -h 127.0.0.1 -P 3306
mysql -e 'use galette_tests; source galette-core/galette/plugins/plugin-auto/scripts/mysql.sql;' -u galette_tests --password=g@l3tte -h 127.0.0.1 -P 3306
if: env.skip != 'true' && (startsWith(matrix.db-image, 'mysql') || startsWith(matrix.db-image, 'mariadb'))

- name: Unit tests
if: env.skip != 'true'
run: |
cd galette-core/galette/plugins/plugin-auto
../../vendor/bin/phpunit --test-suffix=.php --bootstrap tests/TestsBootstrap.php --no-coverage --process-isolation tests/GaletteAuto/
11 changes: 9 additions & 2 deletions lib/GaletteAuto/AbstractObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
* @author Johan Cwiklinski <[email protected]>
*
* @property int $id
* @property string $value
*/
abstract class AbstractObject
{
Expand Down Expand Up @@ -148,6 +149,12 @@ public function store(bool $new = false): bool
$insert = $this->zdb->insert($this->table);
$insert->values($values);
$this->zdb->execute($insert);
/** @phpstan-ignore-next-line */
$this->id = (int)$this->zdb->driver->getLastGeneratedValue(
$this->zdb->isPostgres() ?
PREFIX_DB . $this->table . '_id_seq'
: null
);
} else {
$update = $this->zdb->update($this->table);
$update->set($values)->where(
Expand All @@ -172,7 +179,7 @@ public function store(bool $new = false): bool
/**
* Delete some records
*
* @param array $ids Array of records id to delete
* @param int[] $ids Array of records id to delete
*
* @return boolean
*/
Expand Down Expand Up @@ -358,7 +365,7 @@ private function buildSelect(): Select
return $select;
} catch (\Exception $e) {
Analog::log(
'Cannot build SELECT clause for models | ' . $e->getMessage(),
'Cannot build SELECT clause | ' . $e->getMessage(),
Analog::WARNING
);
throw $e;
Expand Down
32 changes: 18 additions & 14 deletions lib/GaletteAuto/Auto.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ class Auto
private string $first_registration_date;
private string $first_circulation_date;
private $mileage;
private string $comment;
private string $chassis_number;
private ?string $comment;
private ?string $chassis_number;
private ?int $seats;
private ?int $horsepower;
private ?int $engine_size;
Expand All @@ -124,8 +124,8 @@ class Auto
private Transmission $transmission;
private Body $body;
private History $history;
private Adherent $owner;
private State $state;
private Adherent $owner;

public const FUEL_PETROL = 1;
public const FUEL_DIESEL = 2;
Expand Down Expand Up @@ -181,7 +181,8 @@ public function __construct(Plugins $plugins, Db $zdb, ArrayObject $args = null)
'state' => _T("state", "auto"),
'finition' => _T("finition", "auto"),
'transmission' => _T("transmission", "auto"),
'body' => _T("body", "auto")
'body' => _T("body", "auto"),
'fuel' => _T("fuel", "auto"),
);

$this->model = new Model($this->zdb);
Expand Down Expand Up @@ -218,7 +219,11 @@ public function load(int $id): bool
);

$results = $this->zdb->execute($select);
$this->loadFromRS($results->current());
$result = $results->current();
if (!$result instanceof ArrayObject) {
throw new \RuntimeException('Vehicle not found');
}
$this->loadFromRS($result);
return true;
} catch (\Exception $e) {
Analog::log(
Expand Down Expand Up @@ -279,6 +284,7 @@ private function loadFromRS(ArrayObject $r): void
*/
public function listFuels(): array
{
//TODO: make this list configurable?
$f = array(
self::FUEL_PETROL => _T("Petrol", "auto"),
self::FUEL_DIESEL => _T("Diesel", "auto"),
Expand Down Expand Up @@ -343,7 +349,7 @@ public function store(bool $new = false): bool
break;
case 'integer':
$values[$k] = (
($this->$propName != 0 && $this->$propName != '')
(!empty($this->$propName))
? $this->$propName
: new Expression('NULL')
);
Expand All @@ -365,7 +371,7 @@ public function store(bool $new = false): bool
/** @phpstan-ignore-next-line */
$this->id = (int)$this->zdb->driver->getLastGeneratedValue(
$this->zdb->isPostgres() ?
PREFIX_DB . AUTO_PREFIX . 'cars_id_seq'
PREFIX_DB . AUTO_PREFIX . self::TABLE . '_id_seq'
: null
);

Expand All @@ -374,6 +380,7 @@ public function store(bool $new = false): bool
_T("New car added", "auto"),
strtoupper($this->name)
);
$this->history->load((int)$this->id);

//handle picture for newly added cars
$this->picture = new Picture($this->plugins, (int)$this->id);
Expand Down Expand Up @@ -609,9 +616,6 @@ public function __set(string $name, $value): void
case 'state':
$this->state->load((int)$value);
break;
case 'owner':
$this->owner->load((int)$value);
break;
default:
$this->$name = $value;
break;
Expand Down Expand Up @@ -667,7 +671,7 @@ public function check(array $post): bool

if (($value == '' || $value == null) && in_array($prop, array_keys($required))) {
$this->errors[] = str_replace(
'%s',
'%field',
'<a href="#' . $prop . '">' . $this->getPropName($prop) . '</a>',
_T("- Mandatory field %field empty.")
);
Expand Down Expand Up @@ -728,7 +732,7 @@ public function check(array $post): bool
case 'seats':
case 'horsepower':
case 'engine_size':
if (is_numeric(str_replace(' ', '', $value))) {
if (is_numeric(str_replace(' ', '', $value ?? ''))) {
$this->$prop = (int)$value;
} elseif ($value != '') {
$this->errors[] = str_replace(
Expand Down Expand Up @@ -766,7 +770,7 @@ public function check(array $post): bool
}
break;
case 'owner':
if (isset($post['change_owner'])) {
if (isset($post['change_owner']) || !isset($this->id)) {
$value = (int)$value;
if ($value > 0) {
$this->$prop->load($value);
Expand All @@ -786,7 +790,7 @@ public function check(array $post): bool
}//switch
}//foreach

if ($this->id) {
if (isset($this->id)) {
//handle picture for updated cars
$this->handlePicture();
}
Expand Down
10 changes: 5 additions & 5 deletions lib/GaletteAuto/Autos.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function removeVehicles(int|array $ids): bool
$infos = null;
foreach ($vehicles as $vehicle) {
$str_v = $vehicle->id_car . ' - ' . $vehicle->car_name .
' (' . $vehicle->brand->brand . ' ' . $vehicle->model->model . ')';
' (' . $vehicle->brand . ' ' . $vehicle->model . ')';
$infos .= $str_v . "\n";

$p = new Picture($this->plugins, $vehicle->id_car);
Expand Down Expand Up @@ -269,12 +269,12 @@ public function getList(
/**
* Count vehicles from the query
*
* @param Select $select Original select
* @param AutosList $filters Filters
* @param Select $select Original select
* @param ?AutosList $filters Filters
*
* @return void
*/
private function proceedCount($select, AutosList $filters): void
private function proceedCount($select, ?AutosList $filters): void
{
try {
$countSelect = clone $select;
Expand All @@ -296,7 +296,7 @@ private function proceedCount($select, AutosList $filters): void

$results = $this->zdb->execute($countSelect);
$this->count = $results->current()->count;
if ($this->count > 0) {
if ($this->count > 0 && $filters !== null) {
$filters->setCounter($this->count);
}
} catch (\Exception $e) {
Expand Down
2 changes: 1 addition & 1 deletion lib/GaletteAuto/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ public function vehicleHistory(Request $request, Response $response, int $id): R

$apk = Auto::PK;
$params = [
'entries' => $history->entries,
'entries' => $history->getEntries(),
'page_title' => str_replace('%d', $history->$apk, _T("History of car #%d", "auto")),
'mode' => $request->getHeaderLine('X-Requested-With') === 'XMLHttpRequest' ? 'ajax' : ''
];
Expand Down
Loading