firefly-iii/tests/Traits/TestHelpers.php

472 lines
19 KiB
PHP
Raw Normal View History

2020-07-30 14:16:14 -05:00
<?php
/*
* TestHelpers.php
* Copyright (c) 2020 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Tests\Traits;
2021-03-13 05:01:01 -06:00
2020-07-30 14:16:14 -05:00
use Exception;
2021-03-13 06:26:45 -06:00
use JsonException;
2020-07-30 14:16:14 -05:00
use Log;
/**
* Trait TestHelpers
*/
trait TestHelpers
{
2021-03-19 00:12:28 -05:00
/**
* @return int
*/
public function randomInt(): int
{
$result = 4;
try {
$result = random_int(1, 100000);
} catch (Exception $e) {
Log::debug(sprintf('Could not generate random number: %s', $e->getMessage()));
}
return $result;
}
2021-03-13 05:01:01 -06:00
/**
* @param array $minimalSets
* @param array $startOptionalSets
* @param array $regenConfig
*
* @return array
*/
protected function genericDataProvider(array $minimalSets, array $startOptionalSets, array $regenConfig): array
{
$submissions = [];
2021-03-13 23:20:23 -06:00
/**
2021-03-14 10:08:49 -05:00
* @var string $i
2021-03-13 23:20:23 -06:00
* @var array $set
*/
2021-03-14 10:08:49 -05:00
foreach ($minimalSets as $i => $set) {
2021-03-13 05:01:01 -06:00
$body = [];
2021-03-14 10:08:49 -05:00
foreach ($set['fields'] as $ii => $value) {
$body[$ii] = $value;
2021-03-13 05:01:01 -06:00
}
// minimal set is part of all submissions:
2021-03-13 23:20:23 -06:00
$submissions[] = [[
'fields' => $body,
'parameters' => $set['parameters'] ?? [],
'ignore' => $set['ignore'] ?? [],
]];
2021-03-13 05:01:01 -06:00
// then loop and add fields:
$optionalSets = $startOptionalSets;
$keys = array_keys($optionalSets);
2021-03-13 21:55:48 -06:00
$count = count($keys) > self::MAX_ITERATIONS ? self::MAX_ITERATIONS : count($keys);
2021-03-14 10:08:49 -05:00
for ($iii = 1; $iii <= $count; $iii++) {
$combinations = $this->combinationsOf($iii, $keys);
2021-03-13 05:01:01 -06:00
// expand body with N extra fields:
2021-03-14 10:08:49 -05:00
foreach ($combinations as $iv => $extraFields) {
2021-03-13 05:01:01 -06:00
$second = $body;
2021-03-13 23:20:23 -06:00
$ignore = $set['ignore'] ?? []; // unused atm.
2021-03-14 10:08:49 -05:00
foreach ($extraFields as $v => $extraField) {
2021-03-13 05:01:01 -06:00
// now loop optional sets on $extraField and add whatever the config is:
2021-03-14 10:08:49 -05:00
foreach ($optionalSets[$extraField]['fields'] as $vi => $newValue) {
// if the newValue is an array, we must merge it with whatever may
// or may not already be there. Its the optional field for one of the
// (maybe existing?) fields:
if (is_array($newValue) && array_key_exists($vi, $second) && is_array($second[$vi])) {
// loop $second[$vi] and merge it with whatever is in $newValue[$someIndex]
foreach ($second[$vi] as $vii => $iiValue) {
$second[$vi][$vii] = $iiValue + $newValue[$vii];
}
}
if (!is_array($newValue)) {
$second[$vi] = $newValue;
}
}
if (array_key_exists('remove_fields', $optionalSets[$extraField])) {
foreach ($optionalSets[$extraField]['remove_fields'] as $removed) {
unset($second[$removed]);
}
2021-03-13 05:01:01 -06:00
}
}
$second = $this->regenerateValues($second, $regenConfig);
2021-03-13 23:20:23 -06:00
$submissions[] = [[
'fields' => $second,
'parameters' => $set['parameters'] ?? [],
'ignore' => $ignore,
]];
2021-03-13 05:01:01 -06:00
}
}
unset($second);
}
2021-03-13 21:55:48 -06:00
2021-03-13 05:01:01 -06:00
return $submissions;
}
/**
* @param $set
* @param $opts
*
* @return array
*/
protected function regenerateValues($set, $opts): array
{
2021-03-14 10:08:49 -05:00
foreach ($opts as $i => $func) {
if (array_key_exists($i, $set)) {
2021-03-14 14:03:27 -05:00
if (!is_array($set[$i])) {
2021-03-14 10:08:49 -05:00
$set[$i] = $func();
}
2021-03-14 14:03:27 -05:00
if (is_array($set[$i])) {
foreach ($set[$i] as $ii => $lines) {
foreach ($lines as $iii => $value) {
if (isset($opts[$i][$ii][$iii])) {
2021-03-14 10:08:49 -05:00
$set[$i][$ii][$iii] = $opts[$i][$ii][$iii]();
}
}
}
}
2021-03-13 05:01:01 -06:00
}
}
return $set;
}
2021-03-19 00:12:28 -05:00
/**
* @param string $route
* @param array $content
*/
protected function updatedStoreAndCompare(string $route, array $content): void
{
$submission = $content['submission'];
$expected = $content['expected'];
$ignore = $content['ignore'];
// submit body
$response = $this->post($route, $submission, ['Accept' => 'application/json']);
$responseBody = $response->content();
$responseJson = json_decode($responseBody, true);
$status = $response->getStatusCode();
$this->assertEquals($status, 200, sprintf("Submission:\n%s\nResponse: %s", json_encode($submission), $responseBody));
$response->assertHeader('Content-Type', 'application/vnd.api+json');
// get return and compare each field
$responseAttributes = $responseJson['data']['attributes'];
$this->updatedCompareStorageArray($submission, $responseAttributes, $expected, $ignore);
// ignore fields too!
}
/**
* @param array $submission
* @param array $response
* @param array $expected
* @param array $ignore
*/
protected function updatedCompareStorageArray(array $submission, array $response, array $expected, array $ignore): void
{
foreach ($response as $key => $value) {
if (is_array($value) && array_key_exists($key, $expected) && is_array($expected[$key])) {
$this->updatedCompareStorageArray($submission, $value, $expected[$key], $ignore[$key] ?? []);
}
if (isset($expected[$key])) {
if (in_array($key, $ignore, true)) {
continue;
}
if (!in_array($key, $ignore, true)) {
$message = sprintf(
"Field '%s' with value %s is expected to be %s.\nSubmitted:\n%s\nIgnored: %s\nReturned\n%s",
$key,
var_export($value, true),
var_export($expected[$key], true),
json_encode($submission),
json_encode($ignore),
json_encode($response)
);
$this->assertEquals($value, $expected[$key], $message);
}
// if($value !== $expected[$key]) {
// }
// var_dump($key);
// var_dump($value);
// var_dump($expected[$key]);
// exit;
}
}
}
/**
* @param string $route
* @param array $content
*/
protected function storeAndCompare(string $route, array $content): void
{
2021-03-20 01:02:06 -05:00
$submission = $content['fields'];
$parameters = $content['parameters'];
$ignore = $content['ignore'];
2021-03-19 00:12:28 -05:00
$response = $this->post(route($route, $parameters), $submission, ['Accept' => 'application/json']);
$responseBody = $response->content();
$responseJson = json_decode($responseBody, true);
$status = $response->getStatusCode();
$this->assertEquals($status, 200, sprintf("Submission:\n%s\nResponse: %s", json_encode($submission), $responseBody));
$response->assertHeader('Content-Type', 'application/vnd.api+json');
// compare results:
foreach ($responseJson['data']['attributes'] as $returnName => $returnValue) {
if (array_key_exists($returnName, $submission) && !in_array($returnName, $ignore, true)) {
// TODO still based on account routine:
if ($this->ignoreCombination($route, $submission['type'] ?? 'blank', $returnName)) {
continue;
}
// check if is array, if so we need something smart:
if (is_array($returnValue) && is_array($submission[$returnName])) {
$this->compareArray($submission, $returnName, $submission[$returnName], $returnValue);
}
if (!is_array($returnValue) && !is_array($submission[$returnName])) {
$message = sprintf(
"Main: Return value '%s' of key '%s' does not match submitted value '%s'.\n%s\n%s", $returnValue, $returnName, $submission[$returnName],
json_encode($submission), $responseBody
);
$this->assertEquals($returnValue, $submission[$returnName], $message);
}
}
}
}
2021-03-20 01:02:06 -05:00
/**
* @param string $route
* @param array $content
*/
protected function updatedUpdateAndCompare(string $route, array $content): void
{
$submission = $content['submission'];
$ignore = $content['ignore'];
$response = $this->put($route, $submission, ['Accept' => 'application/json']);
$responseBody = $response->content();
$responseJson = json_decode($responseBody, true);
$status = $response->getStatusCode();
$this->assertEquals($status, 200, sprintf("Submission:\n%s\nResponse: %s", json_encode($submission), $responseBody));
$response->assertHeader('Content-Type', 'application/vnd.api+json');
// get return and compare each field
$responseAttributes = $responseJson['data']['attributes'];
$this->updatedCompareUpdatedArray($route, $submission, $responseAttributes, $ignore);
}
/**
* @param string $url
* @param array $submission
* @param array $response
* @param array $ignore
*/
private function updatedCompareUpdatedArray(string $url, array $submission, array $response, array $ignore): void
{
foreach ($response as $key => $value) {
if (is_array($value) && array_key_exists($key, $submission) && is_array($submission[$key])) {
$this->updatedCompareUpdatedArray($url, $submission[$key], $value, $ignore[$key] ?? []);
}
if (isset($submission[$key])) {
if (in_array($key, $ignore, true)) {
continue;
}
if (!in_array($key, $ignore, true)) {
$message = sprintf(
"Field '%s' with value %s is expected to be %s.\nSubmitted:\n%s\nIgnored: %s\nReturned\n%s\nURL: %s",
$key,
var_export($value, true),
var_export($submission[$key], true),
json_encode($submission),
json_encode($ignore),
json_encode($response),
$url
);
$this->assertEquals($value, $submission[$key], $message);
}
}
}
}
2021-03-19 00:12:28 -05:00
/**
* Some specials:
*
* @param string $area
* @param string $left
* @param string $right
*
* @return bool
*/
protected function ignoreCombination(string $area, string $left, string $right): bool
{
if ('api.v1.accounts.store' === $area) {
if ('expense' === $left
&& in_array($right, ['order', 'virtual_balance', 'opening_balance', 'opening_balance_date'])) {
return true;
}
}
return false;
}
2021-03-13 06:26:45 -06:00
/**
* @param string $route
* @param array $submission
*
* @throws JsonException
*/
protected function updateAndCompare(string $route, array $submission, array $ignored): void
{
// get original values:
$response = $this->get($route, ['Accept' => 'application/json']);
2021-03-14 10:08:49 -05:00
$status = $response->getStatusCode();
2021-03-14 04:41:17 -05:00
$this->assertEquals($status, 200, sprintf(sprintf('%s failed with 404.', $route)));
2021-03-13 06:26:45 -06:00
$response->assertStatus(200);
2021-03-13 07:33:48 -06:00
$originalString = $response->content();
$originalArray = json_decode($originalString, true, 512, JSON_THROW_ON_ERROR);
$originalAttributes = $originalArray['data']['attributes'];
2021-03-13 06:26:45 -06:00
// submit whatever is in submission:
// loop the fields we will update in Firefly III:
$submissionArray = [];
$fieldsToUpdate = array_keys($submission['fields']);
foreach ($fieldsToUpdate as $currentFieldName) {
$submissionArray[$currentFieldName] = $submission['fields'][$currentFieldName]['test_value'];
}
2021-03-13 07:33:48 -06:00
Log::debug(sprintf('Will PUT %s to %s', json_encode($submissionArray), $route));
$response = $this->put($route, $submissionArray, ['Accept' => 'application/json']);
2021-03-13 06:26:45 -06:00
$responseString = $response->content();
2021-03-13 09:47:29 -06:00
$status = $response->getStatusCode();
$this->assertEquals($status, 200, sprintf("Submission: %s\nResponse: %s", json_encode($submissionArray), $responseString));
//$response->assertStatus(200);
2021-03-13 07:33:48 -06:00
$responseArray = json_decode($responseString, true, 512, JSON_THROW_ON_ERROR);
2021-03-13 06:26:45 -06:00
$responseAttributes = $responseArray['data']['attributes'] ?? [];
2021-03-13 07:33:48 -06:00
Log::debug(sprintf('Before: %s', json_encode($originalAttributes)));
Log::debug(sprintf('AFTER : %s', json_encode($responseAttributes)));
2021-03-13 06:26:45 -06:00
// loop it and compare:
foreach ($responseAttributes as $rKey => $rValue) {
// field should be ignored?
if (in_array($rKey, $ignored) || in_array($rKey, $submission['extra_ignore'])) {
continue;
}
// field in response was also in body:
if (array_key_exists($rKey, $submissionArray)) {
2021-03-14 14:03:27 -05:00
// comparison must be on array:
if (is_array($submissionArray[$rKey]) && is_array($rValue)) {
2021-03-15 13:51:55 -05:00
$this->compareArray($submissionArray, $rKey, $submissionArray[$rKey], $rValue);
2021-03-14 14:03:27 -05:00
}
2021-03-13 06:26:45 -06:00
2021-03-14 14:03:27 -05:00
if (!is_array($submissionArray[$rKey]) && !is_array($rValue)) {
if ($submissionArray[$rKey] !== $rValue) {
$message = sprintf(
"Expected field '%s' to be %s but its %s\nOriginal: %s\nSubmission: %s\nResult: %s",
$rKey,
var_export($submissionArray[$rKey], true),
var_export($rValue, true),
$originalString,
json_encode($submissionArray),
$responseString
);
$this->assertTrue(false, $message);
continue;
}
2021-03-13 06:26:45 -06:00
}
continue;
}
// field in response was not in body, but should be the same:
if (!array_key_exists($rKey, $submissionArray)) {
// original has this key too:
2021-03-13 07:33:48 -06:00
if (array_key_exists($rKey, $originalAttributes)) {
// but we can ignore it!
2021-03-13 09:47:29 -06:00
if (in_array($rKey, $submission['extra_ignore'])) {
2021-03-13 07:33:48 -06:00
continue;
}
2021-03-13 06:26:45 -06:00
// but it is different?
2021-03-13 07:33:48 -06:00
if ($originalAttributes[$rKey] !== $rValue) {
$message = sprintf(
"Untouched field '%s' should still be %s but changed to %s\nOriginal: %s\nSubmission: %s\nResult: %s",
$rKey,
var_export($originalAttributes[$rKey], true),
var_export($rValue, true),
$originalString,
json_encode($submissionArray),
$responseString
);
2021-03-13 06:26:45 -06:00
$this->assertTrue(false, $message);
}
}
continue;
}
}
}
2021-03-14 10:08:49 -05:00
/**
2021-03-14 14:03:27 -05:00
* @param array $fullOriginal
2021-03-14 10:08:49 -05:00
* @param string $key
* @param array $original
* @param array $returned
*/
2021-03-14 10:42:10 -05:00
protected function compareArray(array $fullOriginal, string $key, array $original, array $returned)
2021-03-14 10:08:49 -05:00
{
2021-03-14 14:03:27 -05:00
// TODO this should be configurable but OK
2021-03-19 00:12:28 -05:00
if (in_array($key, ['transactions', 'repetitions'], true) && 0 === count($original) && 0 !== count($returned)) {
2021-03-14 14:03:27 -05:00
// accept this.
return;
}
2021-03-14 10:08:49 -05:00
$ignore = ['id', 'created_at', 'updated_at'];
foreach ($returned as $objectKey => $object) {
// each object is a transaction, a rule trigger, a rule action, whatever.
// assume the original also contains this key:
if (!array_key_exists($objectKey, $original)) {
$message = sprintf('Sub: Original array "%s" does not have returned key %d.', $key, $objectKey);
$this->assertTrue(false, $message);
}
2021-03-13 05:01:01 -06:00
2021-03-14 10:08:49 -05:00
foreach ($object as $returnKey => $returnValue) {
if (in_array($returnKey, $ignore, true)) {
continue;
}
if (array_key_exists($returnKey, $original[$objectKey])) {
$message = sprintf(
2021-03-14 10:42:10 -05:00
"Sub-array '%s' returned value %s does not match sent value %s.\n%s\n%s",
$key, var_export($returnValue, true), var_export($original[$objectKey][$returnKey], true),
json_encode($fullOriginal),
json_encode($returned),
2021-03-14 10:08:49 -05:00
);
$this->assertEquals($original[$objectKey][$returnKey], $returnValue, $message);
}
2021-03-13 05:01:01 -06:00
}
}
}
2020-07-30 14:16:14 -05:00
}