Create some new test code.

This commit is contained in:
James Cole
2020-10-04 10:56:10 +02:00
parent a2eedb3742
commit 6671c6d45c
9 changed files with 271 additions and 32 deletions

View File

@@ -32,6 +32,7 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use JsonException;
use Log; use Log;
/** /**
@@ -60,6 +61,7 @@ class CorrectOpeningBalanceCurrencies extends Command
*/ */
public function handle(): int public function handle(): int
{ {
Log::debug(sprintf('Now in %s', __METHOD__));
// get all OB journals: // get all OB journals:
$set = TransactionJournal $set = TransactionJournal
::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
@@ -70,16 +72,23 @@ class CorrectOpeningBalanceCurrencies extends Command
$count = 0; $count = 0;
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
foreach ($set as $journal) { foreach ($set as $journal) {
Log::debug(sprintf('Going to fix journal #%d', $journal->id));
$count += $this->correctJournal($journal); $count += $this->correctJournal($journal);
Log::debug(sprintf('Done, count is now %d', $count));
} }
if ($count > 0) { if ($count > 0) {
$this->line(sprintf('Corrected %d opening balance transactions.', $count)); $message = sprintf('Corrected %d opening balance transaction(s).', $count);
Log::debug($message);
$this->line($message);
} }
if (0 === $count) { if (0 === $count) {
$this->info('There was nothing to fix in the opening balance transactions.'); $message = 'There was nothing to fix in the opening balance transactions.';
Log::debug($message);
$this->info($message);
} }
Log::debug(sprintf('Done with %s', __METHOD__));
return 0; return 0;
} }
@@ -94,18 +103,18 @@ class CorrectOpeningBalanceCurrencies extends Command
// get the asset account for this opening balance: // get the asset account for this opening balance:
$account = $this->getAccount($journal); $account = $this->getAccount($journal);
if (null === $account) { if (null === $account) {
$this->warn(sprintf('Transaction journal #%d has no valid account. Cant fix this line.', $journal->id)); $message = sprintf('Transaction journal #%d has no valid account. Cant fix this line.', $journal->id);
Log::warning($message);
$this->warn($message);
return 0; return 0;
} }
Log::debug(sprintf('Found %s #%d "%s".', $account->accountType->type, $account->id, $account->name)); Log::debug(sprintf('Found "%s" #%d "%s".', $account->accountType->type, $account->id, $account->name));
$currency = $this->getCurrency($account); $currency = $this->getCurrency($account);
Log::debug(sprintf('Found currency #%d (%s)', $currency->id, $currency->code)); Log::debug(sprintf('Found currency #%d (%s)', $currency->id, $currency->code));
// update journal and all transactions: // update journal and all transactions:
$this->setCurrency($journal, $currency); return $this->setCurrency($journal, $currency);
return 1;
} }
/** /**
@@ -115,22 +124,27 @@ class CorrectOpeningBalanceCurrencies extends Command
*/ */
private function getAccount(TransactionJournal $journal): ?Account private function getAccount(TransactionJournal $journal): ?Account
{ {
$transactions = $journal->transactions()->with(['account', 'account.accountType'])->get(); $transactions = $journal->transactions()->get();
Log::debug(sprintf('Found %d transactions for journal #%d.', $transactions->count(), $journal->id));
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
$account = $transaction->account; Log::debug(sprintf('Testing transaction #%d', $transaction->id));
if ((null !== $account) && AccountType::INITIAL_BALANCE !== $account->accountType->type) { /** @var Account $account */
$account = $transaction->account()->first();
if (null !== $account && AccountType::INITIAL_BALANCE !== $account->accountType()->first()->type) {
Log::debug(sprintf('Account of transaction #%d is opposite of IB account (%s).', $transaction->id, $account->accountType()->first()->type));
return $account; return $account;
} }
} }
Log::debug('Found no IB account in transactions of journal.');
return null; return null;
} }
/** /**
* @param Account $account * @param Account $account
*
* @return TransactionCurrency * @return TransactionCurrency
* @throws JsonException
*/ */
private function getCurrency(Account $account): TransactionCurrency private function getCurrency(Account $account): TransactionCurrency
{ {
@@ -144,16 +158,30 @@ class CorrectOpeningBalanceCurrencies extends Command
/** /**
* @param TransactionJournal $journal * @param TransactionJournal $journal
* @param TransactionCurrency $currency * @param TransactionCurrency $currency
* @return int
*/ */
private function setCurrency(TransactionJournal $journal, TransactionCurrency $currency): void private function setCurrency(TransactionJournal $journal, TransactionCurrency $currency): int
{ {
$journal->transaction_currency_id = $currency->id; Log::debug('Now in setCurrency');
$journal->save(); $count = 0;
if ((int) $journal->transaction_currency_id !== (int) $currency->id) {
Log::debug(sprintf('Currency ID of journal #%d was #%d, now set to #%d', $journal->id, $journal->transaction_currency_id, $currency->id));
$journal->transaction_currency_id = $currency->id;
$journal->save();
$count = 1;
}
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($journal->transactions as $transaction) { foreach ($journal->transactions as $transaction) {
$transaction->transaction_currency_id = $currency->id; if ((int) $transaction->transaction_currency_id !== (int) $currency->id) {
$transaction->save(); Log::debug(sprintf('Currency ID of transaction #%d was #%d, now set to #%d', $transaction->id, $transaction->transaction_currency_id, $currency->id));
$transaction->transaction_currency_id = $currency->id;
$transaction->save();
$count = 1;
}
} }
Log::debug(sprintf('Return %d', $count));
return $count;
} }
} }

View File

@@ -301,9 +301,6 @@ class Amount
*/ */
public function getDefaultCurrencyByUser(User $user): TransactionCurrency public function getDefaultCurrencyByUser(User $user): TransactionCurrency
{ {
if ('testing' === config('app.env')) {
Log::warning(sprintf('%s should NOT be called in the TEST environment!', __METHOD__));
}
$cache = new CacheProperties; $cache = new CacheProperties;
$cache->addProperty('getDefaultCurrency'); $cache->addProperty('getDefaultCurrency');
$cache->addProperty($user->id); $cache->addProperty($user->id);
@@ -314,7 +311,7 @@ class Amount
$currencyPrefStr = $currencyPreference ? $currencyPreference->data : 'EUR'; $currencyPrefStr = $currencyPreference ? $currencyPreference->data : 'EUR';
// at this point the currency preference could be encrypted, if coming from an old version. // at this point the currency preference could be encrypted, if coming from an old version.
Log::debug('Going to try to decrypt users currency preference.'); //Log::debug('Going to try to decrypt users currency preference.');
$currencyCode = $this->tryDecrypt((string) $currencyPrefStr); $currencyCode = $this->tryDecrypt((string) $currencyPrefStr);
// could still be json encoded: // could still be json encoded:
@@ -354,7 +351,7 @@ class Amount
try { try {
$value = Crypt::decrypt($value); // verified $value = Crypt::decrypt($value); // verified
} catch (DecryptException $e) { } catch (DecryptException $e) {
Log::debug(sprintf('Could not decrypt "%s". %s', $value, $e->getMessage())); //Log::debug(sprintf('Could not decrypt "%s". %s', $value, $e->getMessage()));
} }
return $value; return $value;

View File

@@ -607,7 +607,7 @@ class OperatorQuerySearch implements SearchInterface
$accounts = $this->accountRepository->searchAccount($value, $searchTypes, 25); $accounts = $this->accountRepository->searchAccount($value, $searchTypes, 25);
if (0 === $accounts->count()) { if (0 === $accounts->count()) {
Log::debug('Found zero accounts, search for invalid account.'); Log::debug('Found zero accounts, search for invalid account.');
$account = new Account; $account = new Account;
$account->id = 0; $account->id = 0;
$this->collector->$collectorMethod(new Collection([$account])); $this->collector->$collectorMethod(new Collection([$account]));
@@ -620,7 +620,7 @@ class OperatorQuerySearch implements SearchInterface
if (0 === $filtered->count()) { if (0 === $filtered->count()) {
Log::debug('Left with zero accounts, search for invalid account.'); Log::debug('Left with zero accounts, search for invalid account.');
$account = new Account; $account = new Account;
$account->id = 0; $account->id = 0;
$this->collector->$collectorMethod(new Collection([$account])); $this->collector->$collectorMethod(new Collection([$account]));
return; return;
@@ -669,7 +669,7 @@ class OperatorQuerySearch implements SearchInterface
$accounts = $this->accountRepository->searchAccountNr($value, $searchTypes, 25); $accounts = $this->accountRepository->searchAccountNr($value, $searchTypes, 25);
if (0 === $accounts->count()) { if (0 === $accounts->count()) {
Log::debug('Found zero accounts, search for invalid account.'); Log::debug('Found zero accounts, search for invalid account.');
$account = new Account; $account = new Account;
$account->id = 0; $account->id = 0;
$this->collector->$collectorMethod(new Collection([$account])); $this->collector->$collectorMethod(new Collection([$account]));
return; return;
@@ -679,7 +679,7 @@ class OperatorQuerySearch implements SearchInterface
Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count())); Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count()));
$filtered = $accounts->filter(function (Account $account) use ($value, $stringMethod) { $filtered = $accounts->filter(function (Account $account) use ($value, $stringMethod) {
// either IBAN or account number! // either IBAN or account number!
$ibanMatch = $stringMethod(strtolower($account->iban), strtolower($value)); $ibanMatch = $stringMethod(strtolower((string) $account->iban), strtolower((string) $value));
$accountNrMatch = false; $accountNrMatch = false;
/** @var AccountMeta $meta */ /** @var AccountMeta $meta */
foreach ($account->accountMeta as $meta) { foreach ($account->accountMeta as $meta) {
@@ -692,7 +692,7 @@ class OperatorQuerySearch implements SearchInterface
if (0 === $filtered->count()) { if (0 === $filtered->count()) {
Log::debug('Left with zero, search for invalid account'); Log::debug('Left with zero, search for invalid account');
$account = new Account; $account = new Account;
$account->id = 0; $account->id = 0;
$this->collector->$collectorMethod(new Collection([$account])); $this->collector->$collectorMethod(new Collection([$account]));
return; return;

View File

@@ -0,0 +1,37 @@
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
$factory->define(Account::class, function (Faker $faker) {
return [
'user_id' => 1,
'account_type_id' => 1,
'name' => $faker->words(3, true),
'virtual_balance' => '0',
'active' => 1,
'encrypted' => 0,
'order' => 1,
];
});
$factory->state(Account::class, AccountType::ASSET, function ($faker) {
return [
'account_type_id' => 3,
];
});
$factory->state(Account::class, AccountType::INITIAL_BALANCE, function ($faker) {
return [
'account_type_id' => 6,
];
});
$factory->state(Account::class, AccountType::EXPENSE, function ($faker) {
return [
'account_type_id' => 4,
];
});

View File

@@ -0,0 +1,66 @@
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use FireflyIII\Model;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
$factory->define(TransactionJournal::class, function (Faker $faker) {
return [
'user_id' => 1,
'transaction_type_id' => 1,
'description' => $faker->words(3, true),
'tag_count' => 0,
'date' => $faker->date('Y-m-d'),
];
});
$factory->state(TransactionJournal::class, TransactionType::OPENING_BALANCE, function ($faker) {
return [
'transaction_type_id' => 4,
];
});
$factory->state(TransactionJournal::class, 'ob_broken', function ($faker) {
return [
'transaction_type_id' => 4,
];
});
$factory->afterCreatingState(TransactionJournal::class, TransactionType::OPENING_BALANCE, function ($journal, $faker) {
$obAccount = factory(Account::class)->state(AccountType::INITIAL_BALANCE)->create();
$assetAccount = factory(Account::class)->state(AccountType::ASSET)->create();
$sourceTransaction = factory(Transaction::class)->create(
[
'account_id' => $obAccount->id,
'transaction_journal_id' => $journal->id,
]);
$destTransaction = factory(Transaction::class)->create(
[
'account_id' => $assetAccount->id,
'transaction_journal_id' => $journal->id,
]);
});
$factory->afterCreatingState(TransactionJournal::class, 'ob_broken', function ($journal, $faker) {
$ob1 = factory(Account::class)->state(AccountType::INITIAL_BALANCE)->create();
$ob2 = factory(Account::class)->state(AccountType::INITIAL_BALANCE)->create();
$sourceTransaction = factory(Transaction::class)->create(
[
'account_id' => $ob1->id,
'transaction_journal_id' => $journal->id,
]);
$destTransaction = factory(Transaction::class)->create(
[
'account_id' => $ob2->id,
'transaction_journal_id' => $journal->id,
]);
});

View File

@@ -0,0 +1,14 @@
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use FireflyIII\Models\Transaction;
$factory->define(Transaction::class, function (Faker $faker) {
return [
'transaction_journal_id' => 0,
'account_id' => 0,
'amount' => 5,
];
});

View File

@@ -35,20 +35,31 @@
</include> </include>
</coverage> </coverage>
<listeners> <listeners>
<listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener"/> <listener class="JohnKary\PHPUnit\Listener\SpeedTrapListener">
<arguments>
<array>
<element key="slowThreshold">
<integer>1000</integer>
</element>
</array>
</arguments>
</listener>
</listeners> </listeners>
<testsuites> <testsuites>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<!-- <!--
<testsuite name="Api"> <testsuite name="Api">
<directory suffix="Test.php">./tests/Api</directory> <directory suffix="Test.php">./tests/Api</directory>
</testsuite> </testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
-->
<testsuite name="Unit"> <testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory> <directory suffix="Test.php">./tests/Unit</directory>
</testsuite> </testsuite>
-->
</testsuites> </testsuites>
<php> <php>
<env name="APP_ENV" value="testing"/> <env name="APP_ENV" value="testing"/>

View File

@@ -0,0 +1,86 @@
<?php
/*
* CorrectOpeningBalanceCurrenciesTest.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/>.
*/
namespace Tests\Feature\Console\Commands\Correction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use Log;
use Tests\TestCase;
/**
* Class CorrectOpeningBalanceCurrenciesTest
* @package Tests\Feature\Console\Commands\Correction
*/
class CorrectOpeningBalanceCurrenciesTest extends TestCase
{
/**
* @covers \FireflyIII\Console\Commands\Correction\CorrectOpeningBalanceCurrencies
*/
public function testBasic(): void
{
$this->assertTrue(true);
}
/**
* @covers \FireflyIII\Console\Commands\Correction\CorrectOpeningBalanceCurrencies
*/
public function testHandleOK(): void
{
// run command
$this->artisan('firefly-iii:fix-ob-currencies')
->expectsOutput('There was nothing to fix in the opening balance transactions.')
->assertExitCode(0);
}
/**
* @covers \FireflyIII\Console\Commands\Correction\CorrectOpeningBalanceCurrencies
*/
public function testHandleBroken(): void
{
// create opening balance journal for test. Is enough to trigger this test.
$journal = factory(TransactionJournal::class)->state(TransactionType::OPENING_BALANCE)->create();
// run command
$this->artisan('firefly-iii:fix-ob-currencies')
->expectsOutput('Corrected 1 opening balance transaction(s).')
->assertExitCode(0);
}
/**
* @covers \FireflyIII\Console\Commands\Correction\CorrectOpeningBalanceCurrencies
*/
public function testHandleNoAccount(): void
{
Log::debug('Now in testHandleNoAccount');
// create opening balance journal for test. Is enough to trigger this test.
$journal = factory(TransactionJournal::class)->state('ob_broken')->create();
// run command
$this->artisan('firefly-iii:fix-ob-currencies')
->expectsOutput(sprintf('Transaction journal #%d has no valid account. Cant fix this line.', $journal->id))
//->expectsOutput('Cant fix this line.')
->assertExitCode(0);
}
}

View File

@@ -34,7 +34,7 @@ use Tests\Traits\TestHelpers;
*/ */
abstract class TestCase extends BaseTestCase abstract class TestCase extends BaseTestCase
{ {
use CreatesApplication, MocksDefaultValues, TestHelpers, CollectsValues; use CreatesApplication, CollectsValues;//, MocksDefaultValues, TestHelpers, ;
/** /**
* @return array * @return array