Firefly III: a personal finances manager
PHP accountingbudgetbudgetingbudgetscash-flowcashflowcredit-carddockerexpensesfinancefinancesfinanciallinuxmoneypaycheckpersonal-financephpphp7
Expand API test to bill store.
James Colec9f7f877c0ec
diff --git a/app/Api/V1/Controllers/Models/AvailableBudget/StoreController.php b/app/Api/V1/Controllers/Models/AvailableBudget/StoreController.phpindex ac60e870e8..e4f57915ee 100644--- a/app/Api/V1/Controllers/Models/AvailableBudget/StoreController.php+++ b/app/Api/V1/Controllers/Models/AvailableBudget/StoreController.php@@ -57,6 +57,7 @@ class StoreController extends Controller});}+/*** Store a newly created resource in storage.*@@ -70,14 +71,14 @@ class StoreController extends Controller$data['start']->startOfDay();$data['end']->endOfDay();- /** @var TransactionCurrencyFactory $factory */- $factory = app(TransactionCurrencyFactory::class);- $currency = $factory->find($data['currency_id'], $data['currency_code']);-- if (null === $currency) {- $currency = app('amount')->getDefaultCurrency();+ // currency is not mandatory:+ if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {+ $factory = app(TransactionCurrencyFactory::class);+ $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null);+ $data['currency_id'] = $currency->id;+ unset($data['currency_code']);}- $data['currency'] = $currency;+$availableBudget = $this->abRepository->store($data);$manager = $this->getManager();diff --git a/app/Api/V1/Controllers/Models/AvailableBudget/UpdateController.php b/app/Api/V1/Controllers/Models/AvailableBudget/UpdateController.phpindex 5196b13bc4..e9c8bb53ad 100644--- a/app/Api/V1/Controllers/Models/AvailableBudget/UpdateController.php+++ b/app/Api/V1/Controllers/Models/AvailableBudget/UpdateController.php@@ -72,20 +72,15 @@ class UpdateController extends Controller{$data = $request->getAll();- /** @var TransactionCurrencyFactory $factory */- $factory = app(TransactionCurrencyFactory::class);- /** @var TransactionCurrency $currency */- $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null);-- if (null === $currency) {- // use default currency:- $currency = app('amount')->getDefaultCurrency();+ // find and validate currency ID+ if(array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {+ $factory = app(TransactionCurrencyFactory::class);+ $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null) ?? app('amount')->getDefaultCurrency();+ $currency->enabled = true;+ $currency->save();+ unset($data['currency_code']);+ $data['currency_id'] = $currency->id;}- $currency->enabled = true;- $currency->save();- unset($data['currency_code']);- $data['currency_id'] = $currency->id;-$this->abRepository->updateAvailableBudget($availableBudget, $data);$manager = $this->getManager();diff --git a/app/Api/V1/Controllers/Models/Bill/StoreController.php b/app/Api/V1/Controllers/Models/Bill/StoreController.phpindex ef1dbe8106..7cb6c2847f 100644--- a/app/Api/V1/Controllers/Models/Bill/StoreController.php+++ b/app/Api/V1/Controllers/Models/Bill/StoreController.php@@ -74,7 +74,8 @@ class StoreController extends Controller*/public function store(StoreRequest $request): JsonResponse{- $bill = $this->repository->store($request->getAll());+ $data = $request->getAll();+ $bill = $this->repository->store($data);$manager = $this->getManager();/** @var BillTransformer $transformer */diff --git a/app/Api/V1/Requests/Models/AvailableBudget/Request.php b/app/Api/V1/Requests/Models/AvailableBudget/Request.phpindex 78d8f0f2bb..c421d2a9df 100644--- a/app/Api/V1/Requests/Models/AvailableBudget/Request.php+++ b/app/Api/V1/Requests/Models/AvailableBudget/Request.php@@ -23,9 +23,11 @@ declare(strict_types=1);namespace FireflyIII\Api\V1\Requests\Models\AvailableBudget;+use Carbon\Carbon;use FireflyIII\Support\Request\ChecksLogin;use FireflyIII\Support\Request\ConvertsDataTypes;use Illuminate\Foundation\Http\FormRequest;+use Illuminate\Validation\Validator;/*** Class Request@@ -43,13 +45,16 @@ class Request extends FormRequest*/public function getAll(): array{- return [- 'currency_id' => $this->integer('currency_id'),- 'currency_code' => $this->string('currency_code'),- 'amount' => $this->string('amount'),- 'start' => $this->date('start'),- 'end' => $this->date('end'),+ // this is the way:+ $fields = [+ 'currency_id' => ['currency_id', 'integer'],+ 'currency_code' => ['currency_code', 'string'],+ 'amount' => ['amount', 'string'],+ 'start' => ['start', 'date'],+ 'end' => ['end', 'date'],];++ return $this->getAllData($fields);}/**@@ -62,11 +67,35 @@ class Request extends FormRequestreturn ['currency_id' => 'numeric|exists:transaction_currencies,id','currency_code' => 'min:3|max:3|exists:transaction_currencies,code',- 'amount' => 'required|numeric|gt:0',- 'start' => 'required|date|before:end',- 'end' => 'required|date|after:start',+ 'amount' => 'numeric|gt:0',+ 'start' => 'date',+ 'end' => 'date',];}+ /**+ * Configure the validator instance with special rules for after the basic validation rules.+ *+ * @param Validator $validator+ *+ * @return void+ */+ public function withValidator(Validator $validator): void+ {+ $validator->after(+ function (Validator $validator) {+ // validate start before end only if both are there.+ $data = $validator->getData();+ if (array_key_exists('start', $data) && array_key_exists('end', $data)) {+ $start = new Carbon($data['start']);+ $end = new Carbon($data['end']);+ if ($end->isBefore($start)) {+ $validator->errors()->add('end', (string)trans('validation.date_after'));+ }+ }+ }+ );+ }+}diff --git a/app/Api/V1/Requests/Models/Bill/StoreRequest.php b/app/Api/V1/Requests/Models/Bill/StoreRequest.phpindex 76571b28ad..f3f0e1ed6c 100644--- a/app/Api/V1/Requests/Models/Bill/StoreRequest.php+++ b/app/Api/V1/Requests/Models/Bill/StoreRequest.php@@ -29,6 +29,7 @@ use FireflyIII\Support\Request\ChecksLogin;use FireflyIII\Support\Request\ConvertsDataTypes;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\Validator;+use Log;/*** Class StoreRequest@@ -46,24 +47,24 @@ class StoreRequest extends FormRequest*/public function getAll(): array{- $active = true;- if (null !== $this->get('active')) {- $active = $this->boolean('active');- }-- return [- 'name' => $this->string('name'),- 'amount_min' => $this->string('amount_min'),- 'amount_max' => $this->string('amount_max'),- 'currency_id' => $this->integer('currency_id'),- 'currency_code' => $this->string('currency_code'),- 'date' => $this->date('date'),- 'repeat_freq' => $this->string('repeat_freq'),- 'skip' => $this->integer('skip'),- 'active' => $active,- 'order' => $this->integer('order'),- 'notes' => $this->nlString('notes'),+ Log::debug('Raw fields in Bill StoreRequest', $this->all());+ $fields = [+ 'name' => ['name', 'string'],+ 'amount_min' => ['amount_min', 'string'],+ 'amount_max' => ['amount_max', 'string'],+ 'currency_id' => ['currency_id', 'integer'],+ 'currency_code' => ['currency_code', 'string'],+ 'date' => ['date', 'date'],+ 'repeat_freq' => ['repeat_freq', 'string'],+ 'skip' => ['skip', 'integer'],+ 'active' => ['active', 'boolean'],+ 'order' => ['order', 'integer'],+ 'notes' => ['notes', 'nlString'],+ 'object_group_id' => ['object_group_id', 'integer'],+ 'object_group_title' => ['object_group_title', 'string'],];++ return $this->getAllData($fields);}/**@@ -99,10 +100,10 @@ class StoreRequest extends FormRequest$validator->after(static function (Validator $validator) {$data = $validator->getData();- $min = (float) ($data['amount_min'] ?? 0);- $max = (float) ($data['amount_max'] ?? 0);+ $min = (float)($data['amount_min'] ?? 0);+ $max = (float)($data['amount_max'] ?? 0);if ($min > $max) {- $validator->errors()->add('amount_min', (string) trans('validation.amount_min_over_max'));+ $validator->errors()->add('amount_min', (string)trans('validation.amount_min_over_max'));}});diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.phpindex d68c68b68d..88c2ad614e 100644--- a/app/Factory/BillFactory.php+++ b/app/Factory/BillFactory.php@@ -26,7 +26,6 @@ namespace FireflyIII\Factory;use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\Bill;-use FireflyIII\Models\TransactionCurrency;use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;use FireflyIII\Services\Internal\Support\BillServiceTrait;use FireflyIII\User;@@ -50,15 +49,14 @@ class BillFactory*/public function create(array $data): ?Bill{- /** @var TransactionCurrencyFactory $factory */- $factory = app(TransactionCurrencyFactory::class);- /** @var TransactionCurrency $currency */- $currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null));+ Log::debug(sprintf('Now in %s', __METHOD__), $data);+ $factory = app(TransactionCurrencyFactory::class);+ $currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)) ??+ app('amount')->getDefaultCurrencyByUser($this->user);- if (null === $currency) {- $currency = app('amount')->getDefaultCurrencyByUser($this->user);- }try {+ $skip = array_key_exists('skip', $data) ? $data['skip'] : 0;+ $active = array_key_exists('active', $data) ? $data['active'] : 0;/** @var Bill $bill */$bill = Bill::create([@@ -70,9 +68,9 @@ class BillFactory'amount_max' => $data['amount_max'],'date' => $data['date'],'repeat_freq' => $data['repeat_freq'],- 'skip' => $data['skip'],+ 'skip' => $skip,'automatch' => true,- 'active' => $data['active'] ?? true,+ 'active' => $active,]);} catch (QueryException $e) {@@ -84,8 +82,7 @@ class BillFactoryif (array_key_exists('notes', $data)) {$this->updateNote($bill, (string)$data['notes']);}-- $objectGroupTitle = $data['object_group'] ?? '';+ $objectGroupTitle = $data['object_group_title'] ?? '';if ('' !== $objectGroupTitle) {$objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle);if (null !== $objectGroup) {diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.phpindex df50397925..64854c7c29 100644--- a/app/Repositories/Budget/AvailableBudgetRepository.php+++ b/app/Repositories/Budget/AvailableBudgetRepository.php@@ -25,7 +25,6 @@ namespace FireflyIII\Repositories\Budget;use Carbon\Carbon;use Exception;-use FireflyIII\Exceptions\FireflyException;use FireflyIII\Models\AvailableBudget;use FireflyIII\Models\TransactionCurrency;use FireflyIII\User;@@ -246,7 +245,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterfacereturn AvailableBudget::create(['user_id' => $this->user->id,- 'transaction_currency_id' => $data['currency']->id,+ 'transaction_currency_id' => $data['currency_id'],'amount' => $data['amount'],'start_date' => $start,'end_date' => $end,@@ -276,35 +275,34 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface* @param array $data** @return AvailableBudget- * @throws FireflyException*/public function updateAvailableBudget(AvailableBudget $availableBudget, array $data): AvailableBudget{- $existing = $this->user->availableBudgets()- ->where('transaction_currency_id', $data['currency_id'])- ->where('start_date', $data['start']->format('Y-m-d'))- ->where('end_date', $data['end']->format('Y-m-d'))- ->where('id', '!=', $availableBudget->id)- ->first();-- if (null !== $existing) {- throw new FireflyException(sprintf('An entry already exists for these parameters: available budget object with ID #%d', $existing->id));+ if (array_key_exists('start', $data)) {+ $start = $data['start'];+ if ($start instanceof Carbon) {+ $start = $data['start']->startOfDay();+ $availableBudget->start_date = $start;+ $availableBudget->save();+ }}- $start = $data['start'];- if ($start instanceof Carbon) {- $start = $data['start']->startOfDay();+ if (array_key_exists('end', $data)) {+ $end = $data['end'];+ if ($end instanceof Carbon) {+ $end = $data['end']->endOfDay();+ $availableBudget->end_date = $end;+ $availableBudget->save();+ }}- $end = $data['end'];- if ($end instanceof Carbon) {- $end = $data['end']->endOfDay();+ if (array_key_exists('currency_id', $data)) {+ $availableBudget->transaction_currency_id = $data['currency_id'];+ $availableBudget->save();+ }+ if (array_key_exists('amount', $data)) {+ $availableBudget->amount = $data['amount'];+ $availableBudget->save();}-- $availableBudget->transaction_currency_id = $data['currency_id'];- $availableBudget->start_date = $start;- $availableBudget->end_date = $end;- $availableBudget->amount = $data['amount'];- $availableBudget->save();return $availableBudget;diff --git a/phpunit.xml b/phpunit.xmlindex 62175fb34e..06b5c1ada3 100644--- a/phpunit.xml+++ b/phpunit.xml@@ -35,9 +35,18 @@</include></coverage><testsuites>- <testsuite name="Api">+ <testsuite name="ApiAccount"><directory suffix="Test.php">./tests/Api/Models/Account</directory></testsuite>+ <testsuite name="ApiAttachment">+ <directory suffix="Test.php">./tests/Api/Models/Attachment</directory>+ </testsuite>+ <testsuite name="ApiAb">+ <directory suffix="Test.php">./tests/Api/Models/AvailableBudget</directory>+ </testsuite>+ <testsuite name="ApiBill">+ <directory suffix="Test.php">./tests/Api/Models/Bill</directory>+ </testsuite><!--<testsuite name="Api">diff --git a/tests/Api/Models/Account/StoreControllerTest.php b/tests/Api/Models/Account/StoreControllerTest.phpindex ce3792034b..4490fb285b 100644--- a/tests/Api/Models/Account/StoreControllerTest.php+++ b/tests/Api/Models/Account/StoreControllerTest.php@@ -61,7 +61,7 @@ class StoreControllerTest extends TestCase}// run account store with a minimal data set:$route = 'api.v1.accounts.store';- $this->submitAndCompare($route, $submission);+ $this->storeAndCompare($route, $submission);}/**@@ -106,79 +106,81 @@ class StoreControllerTest extends TestCase*/private function optionalSets(): array{- $faker = Factory::create();- $currencies = [+ $faker = Factory::create();+ $currencies = [1 => 'EUR',2 => 'HUF',3 => 'GBP',4 => 'UAH',];- $rand = rand(1, 4);+ $rand = rand(1, 4);+ // rand+return [- 'active' => [+ 'active' => ['fields' => ['active' => $faker->boolean,],],- // 'iban' => [- // 'fields' => [- // 'iban' => $faker->iban(),- // ],- // ],- // 'bic' => [- // 'fields' => [- // 'bic' => $faker->swiftBicNumber,- // ],- // ],- // 'account_number' => [- // 'fields' => [- // 'account_number' => $faker->iban(),- // ],- // ],- // 'ob' => [- // 'fields' => [- // 'opening_balance' => $this->getRandomAmount(),- // 'opening_balance_date' => $this->getRandomDateString(),- // ],- // ],- // 'virtual_balance' => [- // 'fields' => [- // 'virtual_balance' => $this->getRandomAmount(),- // ],- // ],- // 'currency_id' => [- // 'fields' => [- // 'currency_id' => $rand,- // ],- // ],- // 'currency_code' => [- // 'fields' => [- // 'currency_code' => $currencies[$rand],- // ],- // ],- // 'order' => [- // 'fields' => [- // 'order' => $faker->numberBetween(1, 5),- // ],- // ],- // 'include_net_worth' => [- // 'fields' => [- // 'include_net_worth' => $faker->boolean,- // ],- // ],- // 'notes' => [- // 'fields' => [- // 'notes' => join(' ', $faker->words(5)),- // ],- // ],- // 'location' => [- // 'fields' => [- // 'latitude' => $faker->latitude,- // 'longitude' => $faker->longitude,- // 'zoom_level' => $faker->numberBetween(1, 10),- // ],- // ],+ 'iban' => [+ 'fields' => [+ 'iban' => $faker->iban(),+ ],+ ],+ 'bic' => [+ 'fields' => [+ 'bic' => $faker->swiftBicNumber,+ ],+ ],+ 'account_number' => [+ 'fields' => [+ 'account_number' => $faker->iban(),+ ],+ ],+ 'ob' => [+ 'fields' => [+ 'opening_balance' => $this->getRandomAmount(),+ 'opening_balance_date' => $this->getRandomDateString(),+ ],+ ],+ 'virtual_balance' => [+ 'fields' => [+ 'virtual_balance' => $this->getRandomAmount(),+ ],+ ],+ 'currency_id' => [+ 'fields' => [+ 'currency_id' => $rand,+ ],+ ],+ 'currency_code' => [+ 'fields' => [+ 'currency_code' => $currencies[$rand],+ ],+ ],+ 'order' => [+ 'fields' => [+ 'order' => $faker->numberBetween(1, 5),+ ],+ ],+ 'include_net_worth' => [+ 'fields' => [+ 'include_net_worth' => $faker->boolean,+ ],+ ],+ 'notes' => [+ 'fields' => [+ 'notes' => join(' ', $faker->words(5)),+ ],+ ],+ 'location' => [+ 'fields' => [+ 'latitude' => $faker->latitude,+ 'longitude' => $faker->longitude,+ 'zoom_level' => $faker->numberBetween(1, 10),+ ],+ ],];}diff --git a/tests/Api/Models/Account/UpdateControllerTest.php b/tests/Api/Models/Account/UpdateControllerTest.phpindex a07ea37468..efc20be5fc 100644--- a/tests/Api/Models/Account/UpdateControllerTest.php+++ b/tests/Api/Models/Account/UpdateControllerTest.php@@ -92,7 +92,7 @@ class UpdateControllerTest extends TestCase$accountRoles = ['defaultAsset', 'sharedAsset', 'savingAsset'];$accountRole = $accountRoles[rand(0, count($accountRoles) - 1)];- $liabilityRoles = ['loan', 'debt', 'asset'];+ $liabilityRoles = ['loan', 'debt', 'mortgage'];$liabilityRole = $liabilityRoles[rand(0, count($liabilityRoles) - 1)];$interestPeriods = ['daily', 'monthly', 'yearly'];@@ -179,7 +179,7 @@ class UpdateControllerTest extends TestCase'notes' => ['id' => 1,'fields' => [- 'notes' => ['test_value' => $faker->randomAscii],+ 'notes' => ['test_value' => join(' ', $faker->words(3))],],'extra_ignore' => [],],diff --git a/tests/Api/Models/Attachment/StoreControllerTest.php b/tests/Api/Models/Attachment/StoreControllerTest.phpindex 7a5ffdba1f..af50e72899 100644--- a/tests/Api/Models/Attachment/StoreControllerTest.php+++ b/tests/Api/Models/Attachment/StoreControllerTest.php@@ -61,7 +61,7 @@ class StoreControllerTest extends TestCase}// run account store with a minimal data set:$route = 'api.v1.attachments.store';- $this->submitAndCompare($route, $submission);+ $this->storeAndCompare($route, $submission);}/**@@ -81,23 +81,7 @@ class StoreControllerTest extends TestCase{$minimalSets = $this->minimalSets();$optionalSets = $this->optionalSets();- $regenConfig = [- // 'name' => function () {- // $faker = Factory::create();- //- // return $faker->name;- // },- // 'iban' => function () {- // $faker = Factory::create();- //- // return $faker->iban();- // },- // 'account_number' => function () {- // $faker = Factory::create();- //- // return $faker->iban();- // },- ];+ $regenConfig = [];return $this->genericDataProvider($minimalSets, $optionalSets, $regenConfig);}@@ -122,7 +106,7 @@ class StoreControllerTest extends TestCasereturn ['default_file' => ['fields' => [- 'filename' => $faker->randomAscii,+ 'filename' => join(' ', $faker->words(3)),'attachable_type' => $type,'attachable_id' => '1',],@@ -139,7 +123,7 @@ class StoreControllerTest extends TestCasereturn ['title' => ['fields' => [- 'title' => $faker->randomAscii,+ 'title' => join(' ', $faker->words(3)),],],'notes' => [diff --git a/tests/Api/Models/AvailableBudget/StoreControllerTest.php b/tests/Api/Models/AvailableBudget/StoreControllerTest.phpnew file mode 100644index 0000000000..66c4032bc1--- /dev/null+++ b/tests/Api/Models/AvailableBudget/StoreControllerTest.php@@ -0,0 +1,135 @@+<?php+/*+ * StoreControllerTest.php+ * Copyright (c) 2021 [email protected]+ *+ * 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/>.+ */++namespace Tests\Api\Models\AvailableBudget;+++use Faker\Factory;+use Laravel\Passport\Passport;+use Log;+use Tests\TestCase;+use Tests\Traits\CollectsValues;+use Tests\Traits\RandomValues;+use Tests\Traits\TestHelpers;++/**+ * Class StoreControllerTest+ */+class StoreControllerTest extends TestCase+{+ use RandomValues, TestHelpers, CollectsValues;++ /**+ *+ */+ public function setUp(): void+ {+ parent::setUp();+ Passport::actingAs($this->user());+ Log::info(sprintf('Now in %s.', get_class($this)));+ }+++ /**+ * @param array $submission+ *+ * @dataProvider storeDataProvider+ * @ data Provider emptyDataProvider+ */+ public function testStore(array $submission): void+ {+ if ([] === $submission) {+ $this->markTestSkipped('Empty data provider');+ }+ // run account store with a minimal data set:+ $route = 'api.v1.available_budgets.store';+ $this->storeAndCompare($route, $submission);+ }++ /**+ * @return array+ */+ public function emptyDataProvider(): array+ {+ return [[[]]];++ }++ /**+ * @return array+ */+ public function storeDataProvider(): array+ {+ $minimalSets = $this->minimalSets();+ $optionalSets = $this->optionalSets();+ $regenConfig = [];++ return $this->genericDataProvider($minimalSets, $optionalSets, $regenConfig);+ }+++ /**+ * @return array+ */+ private function minimalSets(): array+ {+ $faker = Factory::create();++ return [+ 'default_ab' => [+ 'fields' => [+ 'amount' => number_format($faker->randomFloat(2, 10, 100), 2),+ 'start' => $faker->dateTimeBetween('-2 year', '-1 year')->format('Y-m-d'),+ 'end' => $faker->dateTimeBetween('-1 year', 'now')->format('Y-m-d'),+ ],+ ],+ ];+ }+++ /**+ * @return \array[][]+ */+ private function optionalSets(): array+ {+ $currencies = [+ 1 => 'EUR',+ 2 => 'HUF',+ 3 => 'GBP',+ 4 => 'UAH',+ ];+ $rand = rand(1, 4);++ return [+ 'currency_by_id' => [+ 'fields' => [+ 'currency_id' => $rand,+ ],+ ],+ 'currency_by_code' => [+ 'fields' => [+ 'currency_code' => $currencies[$rand],+ ],+ ],+ ];+ }++}\ No newline at end of filediff --git a/tests/Api/Models/AvailableBudget/UpdateControllerTest.php b/tests/Api/Models/AvailableBudget/UpdateControllerTest.phpnew file mode 100644index 0000000000..3366aefdef--- /dev/null+++ b/tests/Api/Models/AvailableBudget/UpdateControllerTest.php@@ -0,0 +1,139 @@+<?php+/*+ * UpdateControllerTest.php+ * Copyright (c) 2021 [email protected]+ *+ * 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/>.+ */++namespace Tests\Api\Models\AvailableBudget;+++use Faker\Factory;+use Laravel\Passport\Passport;+use Log;+use Tests\TestCase;+use Tests\Traits\CollectsValues;+use Tests\Traits\RandomValues;+use Tests\Traits\TestHelpers;++/**+ * Class UpdateControllerTest+ */+class UpdateControllerTest extends TestCase+{+ use RandomValues, TestHelpers, CollectsValues;++ /**+ *+ */+ public function setUp(): void+ {+ parent::setUp();+ Passport::actingAs($this->user());+ Log::info(sprintf('Now in %s.', get_class($this)));+ }+++ /**+ * @dataProvider updateDataProvider+ */+ public function testUpdate(array $submission): void+ {+ $ignore = [+ 'created_at',+ 'updated_at',+ ];+ $route = route('api.v1.available_budgets.update', [$submission['id']]);++ $this->updateAndCompare($route, $submission, $ignore);+ }+++ /**+ * @return array+ */+ public function updateDataProvider(): array+ {+ $submissions = [];+ $all = $this->updateDataSet();+ foreach ($all as $name => $data) {+ $submissions[] = [$data];+ }++ return $submissions;+ }+++ /**+ * @return array+ */+ public function updateDataSet(): array+ {+ $faker = Factory::create();+ $currencies = ['EUR', 'GBP', 'USD', 'HUF'];+ $currencyCode = $currencies[rand(0, count($currencies) - 1)];+ $set = [+ 'currency_id' => [+ 'id' => 1,+ 'fields' => [+ 'currency_id' => ['test_value' => (string)$faker->numberBetween(1, 10)],+ ],+ 'extra_ignore' => ['currency_code', 'currency_symbol'],+ ],+ 'currency_code' => [+ 'id' => 1,+ 'fields' => [+ 'currency_code' => ['test_value' => $currencyCode],+ ],+ 'extra_ignore' => ['currency_id', 'currency_symbol'],+ ],+ 'amount' => [+ 'id' => 1,+ 'fields' => [+ 'amount' => ['test_value' => number_format($faker->randomFloat(2, 10, 100), 2)],+ ],+ 'extra_ignore' => [],+ ],+ 'start' => [+ 'id' => 1,+ 'fields' => [+ 'start' => ['test_value' => $faker->dateTimeBetween('-2 year', '-1 year')->format('Y-m-d')],+ ],+ 'extra_ignore' => [],+ ],+ 'end' => [+ 'id' => 1,+ 'fields' => [+ 'end' => ['test_value' => $faker->dateTimeBetween('-1 year', 'now')->format('Y-m-d')],+ ],+ 'extra_ignore' => [],+ ],+ 'both' => [+ 'id' => 1,+ 'fields' => [+ 'start' => ['test_value' => $faker->dateTimeBetween('-2 year', '-1 year')->format('Y-m-d')],+ 'end' => ['test_value' => $faker->dateTimeBetween('-1 year', 'now')->format('Y-m-d')],+ ],+ 'extra_ignore' => [],+ ],+ ];++ return $set;+ }+++}\ No newline at end of filediff --git a/tests/Api/Models/Bill/StoreControllerTest.php b/tests/Api/Models/Bill/StoreControllerTest.phpnew file mode 100644index 0000000000..92da32a0d3--- /dev/null+++ b/tests/Api/Models/Bill/StoreControllerTest.php@@ -0,0 +1,200 @@+<?php+/*+ * StoreControllerTest.php+ * Copyright (c) 2021 [email protected]+ *+ * 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/>.+ */++namespace Tests\Api\Models\Bill;+++use Faker\Factory;+use Laravel\Passport\Passport;+use Log;+use Tests\TestCase;+use Tests\Traits\CollectsValues;+use Tests\Traits\RandomValues;+use Tests\Traits\TestHelpers;++/**+ * Class StoreControllerTest+ */+class StoreControllerTest extends TestCase+{+ use RandomValues, TestHelpers, CollectsValues;++ /**+ *+ */+ public function setUp(): void+ {+ parent::setUp();+ Passport::actingAs($this->user());+ Log::info(sprintf('Now in %s.', get_class($this)));+ }+++ /**+ * @param array $submission+ *+ * @dataProvider storeDataProvider+ * @ data Provider emptyDataProvider+ */+ public function testStore(array $submission): void+ {+ if ([] === $submission) {+ $this->markTestSkipped('Empty data provider');+ }+ // run account store with a minimal data set:+ $route = 'api.v1.bills.store';+ $this->storeAndCompare($route, $submission);+ }++ /**+ * @return array+ */+ public function emptyDataProvider(): array+ {+ return [[[]]];++ }++ /**+ * @return array+ */+ public function storeDataProvider(): array+ {+ $minimalSets = $this->minimalSets();+ $optionalSets = $this->optionalSets();+ $regenConfig = [+ 'name' => function () {+ $faker = Factory::create();++ return join(' ', $faker->words(5));+ },+ ];++ return $this->genericDataProvider($minimalSets, $optionalSets, $regenConfig);+ }+++ /**+ * @return array+ */+ private function minimalSets(): array+ {+ $faker = Factory::create();+ $repeatFreqs = ['yearly', 'weekly', 'monthly'];+ $repeatFreq = $repeatFreqs[rand(0, count($repeatFreqs) - 1)];++ return [+ 'default_bill' => [+ 'fields' => [+ 'name' => join(',', $faker->words(5)),+ 'amount_min' => number_format($faker->randomFloat(2, 10, 50), 2),+ 'amount_max' => number_format($faker->randomFloat(2, 60, 90), 2),+ 'date' => $faker->dateTimeBetween('-1 year', 'now')->format('Y-m-d'),+ 'repeat_freq' => $repeatFreq,+ ],+ ],+ ];+ }+++ /**+ * @return \array[][]+ */+ private function optionalSets(): array+ {+ $faker = Factory::create();+ $repeatFreqs = ['weekly', 'monthly', 'yearly'];+ $repeatFreq = $repeatFreqs[rand(0, count($repeatFreqs) - 1)];+ $currencies = [+ 1 => 'EUR',+ 2 => 'HUF',+ 3 => 'GBP',+ 4 => 'UAH',+ ];+ $rand = rand(1, 4);+ $objectGroupId = $faker->numberBetween(1, 2);+ $objectGroupName = sprintf('Object group %d', $objectGroupId);++ return [+ 'currency_by_id' => [+ 'fields' => [+ 'currency_id' => $rand,+ ],+ ],+ 'currency_by_code' => [+ 'fields' => [+ 'currency_code' => $currencies[$rand],+ ],+ ],+ 'name' => [+ 'fields' => [+ 'name' => join(' ', $faker->words(5)),+ ],+ ],+ 'amount_min' => [+ 'fields' => [+ 'amount_min' => number_format($faker->randomFloat(2, 10, 50), 2),+ ],+ ],+ 'amount_max' => [+ 'fields' => [+ 'amount_max' => number_format($faker->randomFloat(2, 60, 590), 2),+ ],+ ],+ 'date' => [+ 'fields' => [+ 'date' => $faker->dateTimeBetween('-1 year', 'now')->format('Y-m-d'),+ ],+ ],+ 'repeat_freq' => [+ 'fields' => [+ 'repeat_freq' => $repeatFreq,+ ],+ ],+ 'skip' => [+ 'fields' => [+ 'skip' => $faker->numberBetween(0, 5),+ ],+ ],+ 'active' => [+ 'fields' => [+ 'active' => $faker->boolean,+ ],+ ],+ 'notes' => [+ 'fields' => [+ 'notes' => join(' ', $faker->words(5)),+ ],+ ],+ 'object_group_id' => [+ 'fields' => [+ 'object_group_id' => $objectGroupId,+ ],+ ],+ 'object_group_title' => [+ 'fields' => [+ 'object_group_title' => $objectGroupName,+ ],+ ],+ ];+ }++}\ No newline at end of filediff --git a/tests/Traits/TestHelpers.php b/tests/Traits/TestHelpers.phpindex 08b630a453..b05e4c1297 100644--- a/tests/Traits/TestHelpers.php+++ b/tests/Traits/TestHelpers.php@@ -135,7 +135,9 @@ trait TestHelpers$response = $this->put($route, $submissionArray, ['Accept' => 'application/json']);$responseString = $response->content();- $response->assertStatus(200);+ $status = $response->getStatusCode();+ $this->assertEquals($status, 200, sprintf("Submission: %s\nResponse: %s", json_encode($submissionArray), $responseString));+ //$response->assertStatus(200);$responseArray = json_decode($responseString, true, 512, JSON_THROW_ON_ERROR);$responseAttributes = $responseArray['data']['attributes'] ?? [];@@ -171,7 +173,7 @@ trait TestHelpers// original has this key too:if (array_key_exists($rKey, $originalAttributes)) {// but we can ignore it!- if(in_array($rKey, $submission['extra_ignore'])) {+ if (in_array($rKey, $submission['extra_ignore'])) {continue;}// but it is different?@@ -187,7 +189,6 @@ trait TestHelpers);-$this->assertTrue(false, $message);}}@@ -248,18 +249,27 @@ trait TestHelpers* @param string $route* @param array $submission*/- protected function submitAndCompare(string $route, array $submission): void+ protected function storeAndCompare(string $route, array $submission, ?array $ignore = null): void{+ $ignore = $ignore ?? [];// submit!$response = $this->post(route($route), $submission, ['Accept' => 'application/json']);$responseBody = $response->content();$responseJson = json_decode($responseBody, true);- $message = sprintf('Status code is %d and body is %s', $response->getStatusCode(), $responseBody);- $this->assertEquals($response->getStatusCode(), 200, $message);+ $status = $response->getStatusCode();+ $this->assertEquals($status, 200, sprintf("Submission: %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 (in_array($returnName, $ignore)) {+ Log::debug(sprintf('Ignore value of "%s".', $returnName));+ continue;+ }++if (array_key_exists($returnName, $submission)) {// TODO still based on account routine:if ($this->ignoreCombination($route, $submission['type'] ?? 'blank', $returnName)) {