Remove old tests. To be reinstated later.

This commit is contained in:
James Cole
2020-10-10 11:20:52 +02:00
parent d75f33558d
commit 76cfdef27d
252 changed files with 0 additions and 50457 deletions

View File

@@ -1,512 +0,0 @@
<?php
/**
* AccountControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Exception;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Transformers\AccountTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
* Class AccountControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AccountControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Opening balance without date.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
* @throws Exception
*/
public function testStoreInvalidBalance(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
// data to submit
$data = [
'name' => 'Some new asset account #' . $this->randomInt(),
'type' => 'asset',
'account_role' => 'defaultAsset',
'opening_balance' => '123.45',
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'message' => 'The given data was invalid.',
'errors' => [
'opening_balance_date' => ['The opening balance date field is required when opening balance is present.'],
],
]
);
$response->assertHeader('Content-Type', 'application/json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\AccountController
*/
public function testShow(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
[
'id' => 1,
'attributes' => [
'name' => 'Account',
],
]);
$transformer->shouldReceive('setCurrentScope')->atLeast()->once();
$transformer->shouldReceive('getDefaultIncludes')->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->atLeast()->once()->andReturn([]);
// getAccountType
$account = $this->getRandomAsset();
$response = $this->get(route('api.v1.accounts.show', [$account->id]));
$response->assertStatus(200);
}
/**
* Send correct data. Should call account repository store method.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
* @throws Exception
*/
public function testStoreLiability(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
$account = $this->getRandomAsset();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->atLeast()->once()->andReturn($account);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// data to submit
$data = [
'name' => 'Some new liability account #' . $this->randomInt(),
'type' => 'liability',
'liability_amount' => '10000',
'liability_start_date' => '2016-01-01',
'liability_type' => 'mortgage',
'active' => true,
'interest' => '1',
'interest_period' => 'daily',
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'accounts', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* CC type present when account is a credit card.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
* @throws Exception
*/
public function testStoreNoCreditCardData(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$this->mock(AccountTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
// data to submit
$data = [
'name' => 'Some new asset account #' . $this->randomInt(),
'type' => 'asset',
'account_role' => 'ccAsset',
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'message' => 'The given data was invalid.',
'errors' => [
'credit_card_type' => ['The credit card type field is required when account role is ccAsset.'],
'monthly_payment_date' => ['The monthly payment date field is required when account role is ccAsset.'],
],
]
);
$response->assertHeader('Content-Type', 'application/json');
}
/**
* No currency information (is allowed).
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
* @throws Exception
*/
public function testStoreNoCurrencyInfo(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->once()->andReturn(new Account);
// data to submit
$data = [
'name' => 'Some new asset account #' . $this->randomInt(),
'type' => 'asset',
'account_role' => 'defaultAsset',
'include_net_worth' => false,
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Name already in use.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
*/
public function testStoreNotUnique(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$account = $this->getRandomAsset();
// data to submit
$data = [
'name' => $account->name,
'currency_id' => 1,
'type' => 'asset',
'active' => 1,
'include_net_worth' => 1,
'account_role' => 'defaultAsset',
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'message' => 'The given data was invalid.',
'errors' => [
'name' => ['This account name is already in use.'],
],
]
);
$response->assertHeader('Content-Type', 'application/json');
}
/**
* Send correct data. Should call account repository store method.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
* @throws Exception
*/
public function testStoreValid(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
$account = $this->getRandomAsset();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->atLeast()->once()->andReturn($account);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// data to submit
$data = [
'name' => 'Some new asset account #' . $this->randomInt(),
'type' => 'asset',
'account_role' => 'defaultAsset',
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'accounts', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Send correct data. Should call account repository store method.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountStoreRequest
* @covers \FireflyIII\Api\V1\Requests\Request
* @throws Exception
*/
public function testStoreWithCurrencyCode(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
$account = $this->getRandomAsset();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->atLeast()->once()->andReturn($account);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// data to submit
$data = [
'name' => 'Some new asset account #' . $this->randomInt(),
'currency_code' => 'EUR',
'type' => 'asset',
'account_role' => 'defaultAsset',
];
// test API
$response = $this->post(route('api.v1.accounts.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'accounts', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update first asset account we find. Name can be the same as it was.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountUpdateRequest
* @covers \FireflyIII\Api\V1\Requests\Request
*/
public function testUpdate(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('update')->atLeast()->once();
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$account = $this->getRandomAsset();
// data to submit
$data = [
'active' => true,
'include_net_worth' => true,
'name' => $account->name,
'type' => 'asset',
'account_role' => 'defaultAsset',
];
// test API
$response = $this->put(route('api.v1.accounts.update', [$account->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'accounts', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update first asset account we find. Name can be the same as it was.
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountUpdateRequest
* @covers \FireflyIII\Api\V1\Requests\Request
*/
public function testUpdateCurrencyCode(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('update')->atLeast()->once();
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$account = $this->getRandomAsset();
// data to submit
$data = [
'name' => $account->name,
'type' => 'asset',
'currency_code' => 'EUR',
'account_role' => 'defaultAsset',
];
// test API
$response = $this->put(route('api.v1.accounts.update', [$account->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'accounts', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update a liability
*
* @covers \FireflyIII\Api\V1\Controllers\AccountController
* @covers \FireflyIII\Api\V1\Requests\AccountUpdateRequest
* @covers \FireflyIII\Api\V1\Requests\Request
*/
public function testUpdateLiability(): void
{
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(AccountTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('update')->atLeast()->once();
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$account = $this->getRandomAsset();
// data to submit
$data = [
'active' => true,
'include_net_worth' => true,
'name' => $account->name,
'type' => 'liability',
'liability_type' => 'loan',
'liability_amount' => '100',
'interest' => '1',
'interest_period' => 'yearly',
'liability_start_date' => '2019-01-01',
'account_role' => 'defaultAsset',
];
// test API
$response = $this->put(route('api.v1.accounts.update', [$account->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'accounts', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,178 +0,0 @@
<?php
/**
* AttachmentControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Exception;
use FireflyIII\Models\Attachment;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Transformers\AttachmentTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class AttachmentControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AttachmentControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Test show attachment.
* @covers \FireflyIII\Api\V1\Controllers\AttachmentController
*/
public function testShow(): void
{
$transformer = $this->mock(AttachmentTransformer::class);
$repository = $this->mock(AttachmentRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
[
'id' => 1,
'attributes' => [
'file' => 'Test.pdf',
],
]);
$transformer->shouldReceive('setCurrentScope')->atLeast()->once();
$transformer->shouldReceive('getDefaultIncludes')->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->atLeast()->once()->andReturn([]);
$attachment = $this->user()->attachments()->inRandomOrder()->first();
// test API
$response = $this->get(route('api.v1.attachments.show', [$attachment->id]));
$response->assertStatus(200);
}
/**
* Store a new attachment.
*
* @covers \FireflyIII\Api\V1\Controllers\AttachmentController
* @throws Exception
*/
public function testStore(): void
{
/** @var Attachment $attachment */
$attachment = $this->user()->attachments()->first();
// mock stuff:
$repository = $this->mock(AttachmentRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$transformer = $this->mock(AttachmentTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$journal = $this->getRandomWithdrawal();
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->once()->andReturn($attachment);
$repository->shouldReceive('getNoteText')->andReturn('Hi There');
$journalRepos->shouldReceive('setUser')->once();
$journalRepos->shouldReceive('findNull')->once()->andReturn($journal);
// data to submit
$data = [
'filename' => 'Some new att',
'description' => sprintf('Attempt #%d', $this->randomInt()),
'attachable_type' => 'TransactionJournal',
'attachable_id' => $journal->id,
];
// test API
$response = $this->post(route('api.v1.attachments.store'), $data, ['accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'attachments', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update an attachment.
*
* @covers \FireflyIII\Api\V1\Controllers\AttachmentController
* @throws Exception
*/
public function testUpdate(): void
{
// mock repositories
$repository = $this->mock(AttachmentRepositoryInterface::class);
$transformer = $this->mock(AttachmentTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
/** @var Attachment $attachment */
$attachment = $this->user()->attachments()->first();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('update')->once()->andReturn($attachment);
$repository->shouldReceive('getNoteText')->andReturn('Hi There');
// data to submit
$data = [
'filename' => $attachment->filename,
'description' => sprintf('Attempt #%d', $this->randomInt()),
'attachable_type' => 'TransactionJournal',
'attachable_id' => 1,
];
// test API
$response = $this->put(route('api.v1.attachments.update', [$attachment->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'attachments', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,239 +0,0 @@
<?php
/**
* AvailableBudgetControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Amount;
use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Transformers\AvailableBudgetTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class AvailableBudgetControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AvailableBudgetControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Store new available budget.
*
* @covers \FireflyIII\Api\V1\Controllers\AvailableBudgetController
*/
public function testStore(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$abRepository = $this->mock(AvailableBudgetRepositoryInterface::class);
$transformer = $this->mock(AvailableBudgetTransformer::class);
$factory = $this->mock(TransactionCurrencyFactory::class);
$availableBudget = new AvailableBudget;
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$factory->shouldReceive('find')->withArgs([2, ''])->once()->andReturn(TransactionCurrency::find(2));
// mock calls:
$abRepository->shouldReceive('setUser')->atLeast()->once();
$abRepository->shouldReceive('store')->once()->andReturn($availableBudget);
// data to submit
$data = [
'currency_id' => '2',
'amount' => '100',
'start' => '2018-01-01',
'end' => '2018-01-31',
];
// test API
$response = $this->post(route('api.v1.available_budgets.store'), $data);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'available_budgets', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Store new available budget without a valid currency.
*
* @covers \FireflyIII\Api\V1\Controllers\AvailableBudgetController
*/
public function testStoreNoCurrencyAtAll(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
// mock stuff:
$transformer = $this->mock(AvailableBudgetTransformer::class);
$factory = $this->mock(TransactionCurrencyFactory::class);
$abRepository = $this->mock(AvailableBudgetRepositoryInterface::class);
$availableBudget = new AvailableBudget;
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$factory->shouldReceive('find')->withArgs([0, ''])->once()->andReturnNull();
Amount::shouldReceive('getDefaultCurrency')->once()->andReturn(TransactionCurrency::find(5));
// mock calls:
$abRepository->shouldReceive('setUser')->atLeast()->once();
$abRepository->shouldReceive('store')->once()->andReturn($availableBudget);
// data to submit
$data = [
'amount' => '100',
'start' => '2018-01-01',
'end' => '2018-01-31',
];
// test API
$response = $this->post(route('api.v1.available_budgets.store'), $data);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Store new available budget without a valid currency.
*
* @covers \FireflyIII\Api\V1\Controllers\AvailableBudgetController
*/
public function testStoreNoCurrencyId(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
/** @var AvailableBudget $availableBudget */
$availableBudget = $this->user()->availableBudgets()->first();
// mock stuff:
$abRepository = $this->mock(AvailableBudgetRepositoryInterface::class);
$transformer = $this->mock(AvailableBudgetTransformer::class);
$factory = $this->mock(TransactionCurrencyFactory::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$factory->shouldReceive('find')->withArgs([0, 'EUR'])->once()->andReturnNull();
Amount::shouldReceive('getDefaultCurrency')->once()->andReturn(TransactionCurrency::find(5));
// mock calls:
$abRepository->shouldReceive('setUser')->once();
$abRepository->shouldReceive('store')->once()->andReturn($availableBudget);
// data to submit
$data = [
'currency_code' => 'EUR',
'amount' => '100',
'start' => '2018-01-01',
'end' => '2018-01-31',
];
// test API
$response = $this->post(route('api.v1.available_budgets.store'), $data);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'available_budgets', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update available budget.
*
* @covers \FireflyIII\Api\V1\Controllers\AvailableBudgetController
*
*/
public function testUpdate(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
// mock repositories
$abRepository = $this->mock(AvailableBudgetRepositoryInterface::class);
$currencyRepository = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(AvailableBudgetTransformer::class);
$factory = $this->mock(TransactionCurrencyFactory::class);
$euro = $this->getEuro();
// mock facades:
Amount::shouldReceive('getDefaultCurrency')->atLeast()->once()->andReturn($euro);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$factory->shouldReceive('find')->withArgs([1, ''])->once()->andReturnNull();
/** @var AvailableBudget $availableBudget */
$availableBudget = $this->user()->availableBudgets()->first();
// mock calls:
$abRepository->shouldReceive('setUser');
$abRepository->shouldReceive('updateAvailableBudget')->once()->andReturn($availableBudget);
$currencyRepository->shouldReceive('findNull')->andReturn($this->getEuro());
// data to submit
$data = [
'currency_id' => '1',
'amount' => '100',
'start' => '2018-01-01',
'end' => '2018-01-31',
];
// test API
$response = $this->put(route('api.v1.available_budgets.update', $availableBudget->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'available_budgets', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,192 +0,0 @@
<?php
/**
* BillControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Exception;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Transformers\BillTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
* Class BillControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BillControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Store with minimum amount more than maximum amount
*
* @covers \FireflyIII\Api\V1\Controllers\BillController
* @throws Exception
*/
public function testStoreMinOverMax(): void
{
// create stuff
$bill = $this->user()->bills()->first();
$repository = $this->mock(BillRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('store')->andReturn($bill);
// data to submit:
$data = [
'name' => 'New bill #' . $this->randomInt(),
'match' => 'some,words,' . $this->randomInt(),
'amount_min' => '66.34',
'amount_max' => '45.67',
'date' => '2018-01-01',
'currency_id' => 1,
'repeat_freq' => 'monthly',
'skip' => 0,
'automatch' => 1,
'active' => 1,
];
// test API
$response = $this->post(route('api.v1.bills.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'message' => 'The given data was invalid.',
'errors' => [
'amount_min' => ['The minimum amount cannot be larger than the maximum amount.'],
],
]
);
$response->assertHeader('Content-Type', 'application/json');
}
/**
* Store a valid bill
*
* @covers \FireflyIII\Api\V1\Controllers\BillController
* @throws Exception
*/
public function testStoreValid(): void
{
// create stuff
$bill = $this->user()->bills()->first();
$repository = $this->mock(BillRepositoryInterface::class);
$transformer = $this->mock(BillTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->andReturn($bill);
// data to submit:
$data = [
'name' => 'New bill #' . $this->randomInt(),
'match' => 'some,words,' . $this->randomInt(),
'amount_min' => '12.34',
'amount_max' => '45.67',
'date' => '2018-01-01',
'repeat_freq' => 'monthly',
'skip' => 0,
'automatch' => 1,
'active' => 1,
'currency_id' => 1,
];
// test API
$response = $this->post(route('api.v1.bills.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'bills', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update a valid bill.
*
* @covers \FireflyIII\Api\V1\Controllers\BillController
* @throws Exception
*/
public function testUpdateValid(): void
{
// create stuff
$bill = $this->user()->bills()->first();
$repository = $this->mock(BillRepositoryInterface::class);
$transformer = $this->mock(BillTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('update')->andReturn($bill);
// data to submit:
$data = [
'name' => 'New bill #' . $this->randomInt(),
'match' => 'some,words,' . $this->randomInt(),
'amount_min' => '12.34',
'amount_max' => '45.67',
'date' => '2018-01-01',
'repeat_freq' => 'monthly',
'skip' => 0,
'automatch' => 1,
'active' => 1,
'currency_id' => 1,
];
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// test API
$response = $this->put(route('api.v1.bills.update', [$bill->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'bills', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,179 +0,0 @@
<?php
/**
* BudgetControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Transformers\BudgetLimitTransformer;
use FireflyIII\Transformers\BudgetTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class BudgetControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BudgetControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Store a new budget.
*
* @covers \FireflyIII\Api\V1\Controllers\BudgetController
*/
public function testStore(): void
{
/** @var Budget $budget */
$budget = new Budget;
// mock stuff:
$repository = $this->mock(BudgetRepositoryInterface::class);
$transformer = $this->mock(BudgetTransformer::class);
$blRepository = $this->mock(BudgetLimitRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$blRepository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('store')->once()->andReturn($budget);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// data to submit
$data = [
'name' => 'Some budget',
];
// test API
$response = $this->post(route('api.v1.budgets.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'budgets', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Store new budget limit.
*
* @covers \FireflyIII\Api\V1\Controllers\BudgetController
*/
public function testStoreBudgetLimit(): void
{
$budget = $this->user()->budgets()->first();
$budgetLimit = new BudgetLimit;
$data
= [
'budget_id' => $budget->id,
'start' => '2018-01-01',
'end' => '2018-01-31',
'amount' => 1,
];
// mock stuff:
$repository = $this->mock(BudgetRepositoryInterface::class);
$blRepository = $this->mock(BudgetLimitRepositoryInterface::class);
$transformer = $this->mock(BudgetLimitTransformer::class);
$blRepository->shouldReceive('storeBudgetLimit')->andReturn($budgetLimit)->once();
$blRepository->shouldReceive('setUser')->atLeast()->once();
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('storeBudgetLimit')->andReturn($budgetLimit);
// call API
$response = $this->post(route('api.v1.budgets.store_budget_limit', [$budget->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertSee('budget_limits');
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update a budget.
*
* @covers \FireflyIII\Api\V1\Controllers\BudgetController
*/
public function testUpdate(): void
{
// mock repositories
$repository = $this->mock(BudgetRepositoryInterface::class);
$transformer = $this->mock(BudgetTransformer::class);
$blRepository = $this->mock(BudgetLimitRepositoryInterface::class);
/** @var Budget $budget */
$budget = $this->user()->budgets()->first();
// mock calls:
$repository->shouldReceive('setUser');
$blRepository->shouldReceive('setUser');
$repository->shouldReceive('update')->once()->andReturn(new Budget);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// data to submit
$data = [
'name' => 'Some new budget',
'active' => '1',
];
// test API
$response = $this->put(route('api.v1.budgets.update', $budget->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'budgets', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,179 +0,0 @@
<?php
/**
* BudgetLimitControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Transformers\BudgetLimitTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class BudgetLimitControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BudgetLimitControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Store new budget limit.
*
* @covers \FireflyIII\Api\V1\Controllers\BudgetLimitController
*/
public function testStore(): void
{
$budget = $this->user()->budgets()->first();
$transformer = $this->mock(BudgetLimitTransformer::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$blRepository = $this->mock(BudgetLimitRepositoryInterface::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$budgetLimit = BudgetLimit::create(
[
'budget_id' => $budget->id,
'start_date' => '2018-01-01',
'end_date' => '2018-01-31',
'amount' => 1,
]
);
$data
= [
'budget_id' => $budget->id,
'start' => '2018-01-01',
'end' => '2018-01-31',
'amount' => 1,
];
// mock stuff:
$repository->shouldReceive('findNull')->andReturn($budget)->once();
$blRepository->shouldReceive('storeBudgetLimit')->andReturn($budgetLimit)->once();
// mock calls:
$repository->shouldReceive('setUser')->once();
$blRepository->shouldReceive('setUser')->once();
// call API
$response = $this->post(route('api.v1.budget_limits.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Store new budget limit, but give error
*
* @covers \FireflyIII\Api\V1\Controllers\BudgetLimitController
*/
public function testStoreBadBudget(): void
{
$data
= [
'budget_id' => '1',
'start' => '2018-01-01',
'end' => '2018-01-31',
'amount' => 1,
];
// mock stuff:
$repository = $this->mock(BudgetRepositoryInterface::class);
$transformer = $this->mock(BudgetLimitTransformer::class);
$blRepository = $this->mock(BudgetLimitRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->once();
// call API
Log::warning('The following error is part of a test.');
$response = $this->post(route('api.v1.budget_limits.store'), $data);
$response->assertStatus(500);
$response->assertSee('Unknown budget.');
}
/**
* Test update of budget limit.
*
* @covers \FireflyIII\Api\V1\Controllers\BudgetLimitController
*/
public function testUpdate(): void
{
$transformer = $this->mock(BudgetLimitTransformer::class);
$blRepository = $this->mock(BudgetLimitRepositoryInterface::class);
$budget = $this->user()->budgets()->first();
$budgetLimit = BudgetLimit::create(
[
'budget_id' => $budget->id,
'start_date' => '2018-01-01',
'end_date' => '2018-01-31',
'amount' => 1,
]
);
$data
= [
'budget_id' => $budget->id,
'start' => '2018-01-01',
'end' => '2018-01-31',
'amount' => 2,
];
// mock stuff:
$repository = $this->mock(BudgetRepositoryInterface::class);
$blRepository->shouldReceive('updateBudgetLimit')->andReturn($budgetLimit)->once();
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->once();
$blRepository->shouldReceive('setUser')->once();
// call API
$response = $this->put(route('api.v1.budget_limits.update', [$budgetLimit->id]), $data);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,132 +0,0 @@
<?php
/**
* CategoryControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Transformers\CategoryTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class CategoryControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CategoryControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Store a new category.
*
* @covers \FireflyIII\Api\V1\Controllers\CategoryController
*/
public function testStore(): void
{
/** @var Category $category */
$category = $this->user()->categories()->first();
// mock stuff:
$repository = $this->mock(CategoryRepositoryInterface::class);
$transformer = $this->mock(CategoryTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('store')->once()->andReturn($category);
// data to submit
$data = [
'name' => 'Some category',
'active' => '1',
];
// test API
$response = $this->post(route('api.v1.categories.store'), $data);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'categories', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update a category.
*
* @covers \FireflyIII\Api\V1\Controllers\CategoryController
*/
public function testUpdate(): void
{
// mock repositories
$repository = $this->mock(CategoryRepositoryInterface::class);
$transformer = $this->mock(CategoryTransformer::class);
/** @var Category $category */
$category = $this->user()->categories()->first();
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser');
$repository->shouldReceive('update')->once()->andReturn($category);
// data to submit
$data = [
'name' => 'Some new category',
'active' => '1',
];
// test API
$response = $this->put(route('api.v1.categories.update', $category->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'categories', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,186 +0,0 @@
<?php
/**
* AccountControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers\Chart;
use Amount;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Illuminate\Support\Collection;
use Laravel\Passport\Passport;
use Log;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class AccountControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AccountControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\Chart\AccountController
* @covers \FireflyIII\Api\V1\Requests\DateRequest
*/
public function testOverview(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$asset = $this->getRandomAsset();
$euro = $this->getEuro();
// mock calls
$repository->shouldReceive('setUser')->atLeast()->once();
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('getAccountsByType')->withArgs([[AccountType::ASSET]])->atLeast()->once()->andReturn(new Collection([$asset]));
$repository->shouldReceive('getAccountsById')->withArgs([[$asset->id]])->atLeast()->once()->andReturn(new Collection([$asset]));
$repository->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
// mock Steam:
Steam::shouldReceive('balanceInRange')->atLeast()->once()->andReturn(['2019-01-01' => '-123',]);
// mock Preferences:
$preference = new Preference;
$preference->data = [$asset->id];
Preferences::shouldReceive('get')->withArgs(['frontPageAccounts', [$asset->id]])->andReturn($preference);
// mock Amount
Amount::shouldReceive('getDefaultCurrency')->atLeast()->once()->andReturn($euro);
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(route('api.v1.chart.account.overview') . '?' . http_build_query($parameters), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\Chart\AccountController
* @covers \FireflyIII\Api\V1\Requests\DateRequest
*/
public function testRevenueOverview(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$revenue = $this->getRandomRevenue();
$euro = $this->getEuro();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('getAccountsByType')->withArgs([[AccountType::REVENUE]])
->atLeast()->once()->andReturn(new Collection([$revenue]));
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()->withArgs([1])->andReturn($euro);
// mock Steam, first start and then end.
$startBalances = [
$revenue->id => [
1 => '10',
],
];
$endBalances = [
$revenue->id => [
1 => '20',
],
];
Steam::shouldReceive('balancesPerCurrencyByAccounts')->times(2)
->andReturn($startBalances, $endBalances);
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(route('api.v1.chart.account.revenue') . '?' . http_build_query($parameters), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\Chart\AccountController
*/
public function testExpenseOverview(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
// mock repositories
$repository = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$expense = $this->getRandomExpense();
$euro = $this->getEuro();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('getAccountsByType')->withArgs([[AccountType::EXPENSE]])
->atLeast()->once()->andReturn(new Collection([$expense]));
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()->withArgs([1])->andReturn($euro);
// mock Steam, first start and then end.
$startBalances = [
$expense->id => [
1 => '-10',
],
];
$endBalances = [
$expense->id => [
1 => '-20',
],
];
Steam::shouldReceive('balancesPerCurrencyByAccounts')->times(2)
->andReturn($startBalances, $endBalances);
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(route('api.v1.chart.account.expense') . '?' . http_build_query($parameters), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
}

View File

@@ -1,132 +0,0 @@
<?php
/**
* AvailableBudgetControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers\Chart;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use Illuminate\Support\Collection;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
* Class AvailableBudgetControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AvailableBudgetControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\Chart\AvailableBudgetController
*/
public function testOverview(): void
{
$availableBudget = $this->user()->availableBudgets()->first();
$repository = $this->mock(BudgetRepositoryInterface::class);
$opsRepository = $this->mock(OperationsRepositoryInterface::class);
// get data:
$budget = $this->getBudget();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$opsRepository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('getActiveBudgets')->atLeast()->once()->andReturn(new Collection([$budget]));
$opsRepository->shouldReceive('spentInPeriodMc')->atLeast()->once()->andReturn(
[
[
'currency_id' => 1,
'currency_code' => 'EUR',
'currency_symbol' => 'x',
'currency_decimal_places' => 2,
'amount' => 321.21,
],
]
);
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(
route('api.v1.chart.ab.overview', [$availableBudget->id]) . '?'
. http_build_query($parameters), ['Accept' => 'application/json']
);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\Chart\AvailableBudgetController
*/
public function testOverviewNothingLeft(): void
{
$availableBudget = $this->user()->availableBudgets()->first();
$repository = $this->mock(BudgetRepositoryInterface::class);
$opsRepository = $this->mock(OperationsRepositoryInterface::class);
// get data:
$budget = $this->getBudget();
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$opsRepository->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('getActiveBudgets')->atLeast()->once()->andReturn(new Collection([$budget]));
$opsRepository->shouldReceive('spentInPeriodMc')->atLeast()->once()->andReturn(
[
[
'currency_id' => 1,
'currency_code' => 'EUR',
'currency_symbol' => 'x',
'currency_decimal_places' => 2,
'amount' => -3321.21,
],
]
);
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(
route('api.v1.chart.ab.overview', [$availableBudget->id]) . '?'
. http_build_query($parameters), ['Accept' => 'application/json']
);
$response->assertStatus(200);
}
}

View File

@@ -1,85 +0,0 @@
<?php
/**
* CategoryControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers\Chart;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
* Class CategoryControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CategoryControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\Chart\CategoryController
*/
public function testOverview(): void
{
$repository = $this->mock(CategoryRepositoryInterface::class);
$noCatRepos =$this->mock(NoCategoryRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$noCatRepos->shouldReceive('setUser')->atLeast()->once();
$opsRepos->shouldReceive('setUser')->atLeast()->once();
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->categoryListExpenses());
//$opsRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->categoryListIncome());
$noCatRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->noCategoryListExpenses());
//$noCatRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->noCategoryListIncome());
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(route('api.v1.chart.category.overview') . '?' . http_build_query($parameters), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
}

View File

@@ -1,242 +0,0 @@
<?php
/**
* CurrencyControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\CurrencyTransformer;
use Laravel\Passport\Passport;
use Log;
use Preferences;
use Tests\TestCase;
use Amount;
/**
* Class CurrencyControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CurrencyControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Store new currency.
*
* @covers \FireflyIII\Api\V1\Controllers\CurrencyController
*/
public function testStore(): void
{
$currency = $this->getEuro();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(CurrencyTransformer::class);
$this->mock(UserRepositoryInterface::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock facades.
Amount::shouldReceive('getDefaultCurrencyByUser')->atLeast()->once()->andReturn($currency);
Preferences::shouldReceive('mark');
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('store')->andReturn($currency);
// data to submit:
$data = [
'name' => 'New currency',
'code' => 'ABC',
'symbol' => 'A',
'decimal_places' => 2,
'default' => '0',
'enabled' => '1',
];
// test API
$response = $this->post(route('api.v1.currencies.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'currencies', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Store new currency and make it default.
*
* @covers \FireflyIII\Api\V1\Controllers\CurrencyController
*/
public function testStoreWithDefault(): void
{
$currency = $this->getEuro();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(CurrencyTransformer::class);
$userRepository = $this->mock(UserRepositoryInterface::class);
// mock facades.
Amount::shouldReceive('getDefaultCurrencyByUser')->atLeast()->once()->andReturn($currency);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$preference = new Preference;
$preference->data = 'EUR';
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('store')->andReturn($currency);
Preferences::shouldReceive('set')->withArgs(['currencyPreference', 'EUR'])->once();
Preferences::shouldReceive('mark')->once();
//Preferences::shouldReceive('lastActivity')->once();
//Preferences::shouldReceive('getForUser')->once()->andReturn($preference);
// data to submit:
$data = [
'name' => 'New currency',
'code' => 'ABC',
'symbol' => 'A',
'decimal_places' => 2,
'default' => '1',
'enabled' => '1',
];
// test API
$response = $this->post(route('api.v1.currencies.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'currencies', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update currency.
*
* @covers \FireflyIII\Api\V1\Controllers\CurrencyController
*/
public function testUpdate(): void
{
$currency = $this->getEuro();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(CurrencyTransformer::class);
$this->mock(UserRepositoryInterface::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
Preferences::shouldReceive('mark');
Amount::shouldReceive('getDefaultCurrencyByUser')->atLeast()->once()->andReturn($currency);
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('update')->andReturn($currency);
// data to submit:
$data = [
'name' => 'Updated currency',
'code' => 'ABC',
'symbol' => '$E',
'decimal_places' => '2',
'default' => '0',
'enabled' => '1',
];
// test API
$response = $this->put(route('api.v1.currencies.update', [$currency->code]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'currencies', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* Update currency and make default.
*
* @covers \FireflyIII\Api\V1\Controllers\CurrencyController
*/
public function testUpdateWithDefault(): void
{
$currency = $this->getEuro();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(CurrencyTransformer::class);
$this->mock(UserRepositoryInterface::class);
$preference = new Preference;
$preference->data = 'EUR';
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('update')->andReturn($currency);
Preferences::shouldReceive('set')->withArgs(['currencyPreference', 'EUR'])->once();
Preferences::shouldReceive('mark')->once();
//Preferences::shouldReceive('lastActivity')->once();
Amount::shouldReceive('getDefaultCurrencyByUser')->atLeast()->once()->andReturn($currency);
//Preferences::shouldReceive('getForUser')->once()->andReturn($preference);
// data to submit:
$data = [
'name' => 'Updated currency',
'code' => 'ABC',
'symbol' => '$E',
'decimal_places' => '2',
'default' => '1',
'enabled' => '1',
];
// test API
$response = $this->put(route('api.v1.currencies.update', [$currency->code]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'currencies', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,263 +0,0 @@
<?php
/**
* LinkTypeControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Exception;
use FireflyIII\Models\LinkType;
use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\LinkTypeTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class LinkTypeControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class LinkTypeControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\LinkTypeController
* @throws Exception
*/
public function testStore(): void
{
$linkType = LinkType::first();
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepository = $this->mock(UserRepositoryInterface::class);
$transformer = $this->mock(LinkTypeTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->once();
$repository->shouldReceive('store')->once()->andReturn($linkType);
$userRepository->shouldReceive('hasRole')->once()->andReturn(true);
// data to submit
$data = [
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
];
// test API
$response = $this->post(route('api.v1.link_types.store'), $data);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\LinkTypeController
* @throws Exception
*/
public function testStoreNotOwner(): void
{
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepository = $this->mock(UserRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->once();
$userRepository->shouldReceive('hasRole')->once()->andReturn(false);
// data to submit
$data = [
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
];
// test API
Log::warning('The following error is part of a test.');
$response = $this->post(route('api.v1.link_types.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertSee('200005');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\LinkTypeController
* @throws Exception
*/
public function testUpdate(): void
{
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepository = $this->mock(UserRepositoryInterface::class);
$transformer = $this->mock(LinkTypeTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$userRepository->shouldReceive('hasRole')->once()->andReturn(true);
// create editable link type:
$linkType = LinkType::create(
[
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
]
);
// mock calls:
$repository->shouldReceive('setUser');
$repository->shouldReceive('update')->once()->andReturn($linkType);
// data to submit
$data = [
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
];
// test API
$response = $this->put(route('api.v1.link_types.update', [$linkType->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\LinkTypeController
* @throws Exception
*/
public function testUpdateNotEditable(): void
{
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepository = $this->mock(UserRepositoryInterface::class);
// create editable link type:
$linkType = LinkType::create(
[
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => false,
]
);
// mock calls:
$repository->shouldReceive('setUser');
// data to submit
$data = [
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
];
// test API
Log::warning('The following error is part of a test.');
$response = $this->put(route('api.v1.link_types.update', [$linkType->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertSee('200020');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\LinkTypeController
* @throws Exception
*/
public function testUpdateNotOwner(): void
{
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepository = $this->mock(UserRepositoryInterface::class);
$userRepository->shouldReceive('hasRole')->once()->andReturn(false);
// create editable link type:
$linkType = LinkType::create(
[
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
]
);
// mock calls:
$repository->shouldReceive('setUser');
// data to submit
$data = [
'name' => 'random' . $this->randomInt(),
'outward' => 'outward' . $this->randomInt(),
'inward' => 'inward ' . $this->randomInt(),
'editable' => true,
];
// test API
Log::warning('The following error is part of a test.');
$response = $this->put(route('api.v1.link_types.update', [$linkType->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertSee('200005');
}
}

View File

@@ -1,229 +0,0 @@
<?php
/**
* PiggyBankControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Transformers\PiggyBankTransformer;
use Laravel\Passport\Passport;
use Log;
use Mockery;
use Tests\TestCase;
/**
*
* Class PiggyBankControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class PiggyBankControllerTest extends TestCase
{
/**
* Set up test
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PiggyBankController
* @throws Exception
*/
public function testStore(): void
{
// create stuff
$piggy = $this->user()->piggyBanks()->first();
// mock stuff:
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$transformer = $this->mock(PiggyBankTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser');
$repository->shouldReceive('store')->once()->andReturn($piggy);
$data = [
'name' => 'New piggy #' . $this->randomInt(),
'account_id' => 1,
'target_amount' => '100',
];
// test API
$response = $this->post(route('api.v1.piggy_banks.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'piggy_banks', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PiggyBankController
* @throws Exception
*/
public function testStoreThrowError(): void
{
// mock stuff:
$repository = $this->mock(PiggyBankRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser');
$repository->shouldReceive('store')->once()->andThrow(new FireflyException('400005'));
$data = [
'name' => 'New piggy #' . $this->randomInt(),
'account_id' => 1,
'target_amount' => '100',
];
// test API
Log::warning('The following error is part of a test.');
$response = $this->post(route('api.v1.piggy_banks.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertHeader('Content-Type', 'application/json');
$response->assertSee('400005');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PiggyBankController
* @throws Exception
*/
public function testUpdate(): void
{
// create stuff
$piggy = $this->user()->piggyBanks()->first();
// mock stuff:
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(PiggyBankTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser');
$repository->shouldReceive('update')->once()->andReturn($piggy);
$repository->shouldReceive('getCurrentAmount')->andReturn('12');
$repository->shouldReceive('getSuggestedMonthlyAmount')->andReturn('12');
//$accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$currencyRepos->shouldReceive('setUser');
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro());
$data = [
'name' => 'new pigy bank ' . $this->randomInt(),
'account_id' => 1,
'target_amount' => '100',
];
// test API
$response = $this->put(route('api.v1.piggy_banks.update', [$piggy->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'piggy_banks', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PiggyBankController
* @throws Exception
*/
public function testUpdateWithAmount(): void
{
// create stuff
$piggy = $this->getRandomPiggyBank();
// mock stuff:
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$transformer = $this->mock(PiggyBankTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser');
$repository->shouldReceive('update')->once()->andReturn($piggy);
$repository->shouldReceive('setCurrentAmount')->once();
$repository->shouldReceive('getCurrentAmount')->andReturn('0');
$repository->shouldReceive('getSuggestedMonthlyAmount')->andReturn('12');
//$accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$currencyRepos->shouldReceive('setUser');
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro());
$data = [
'name' => 'new pigy bank ' . $this->randomInt(),
'account_id' => 1,
'current_amount' => '5',
'target_amount' => '100',
];
// test API
$response = $this->put(route('api.v1.piggy_banks.update', [$piggy->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertJson(['data' => ['type' => 'piggy_banks', 'links' => true],]);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
}

View File

@@ -1,203 +0,0 @@
<?php
/**
* PreferencesControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Transformers\PreferenceTransformer;
use Laravel\Passport\Passport;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class PreferencesControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class PreferencesControllerTest extends TestCase
{
/**
* Set up test
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PreferenceController
*/
public function testUpdateArray(): void
{
$transformer = $this->mock(PreferenceTransformer::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock calls to preferences facade.
$pref = new Preference;
$pref->data = [1, 2, 3];
Preferences::shouldReceive('getForUser')->atLeast()->once()->withArgs([Mockery::any(), 'frontPageAccounts', []])->andReturn($pref);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['frontPageAccounts', ['4', '5', '6']])->atLeast()->once()->andReturn($pref);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->atLeast()->once();
///** @var Preference $preference */
//$preference = Preferences::setForUser($this->user(), 'frontPageAccounts', [1, 2, 3]);
$data = ['data' => '4,5,6'];
$response = $this->put(route('api.v1.preferences.update', ['frontPageAccounts']), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PreferenceController
*/
public function testUpdateBoolean(): void
{
$transformer = $this->mock(PreferenceTransformer::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock calls to preferences facade.
$pref = new Preference;
$pref->data = false;
$countable = new Preference;
$countable->data = [1];
$saved = new Preference;
$saved->user_id = $this->user()->id;
$saved->name = 'customFiscalYear';
$saved->data = false;
$saved->save();
Preferences::shouldReceive('getForUser')->atLeast()->once()->withArgs([Mockery::any(), 'frontPageAccounts', []])->andReturn($countable);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['customFiscalYear', '1'])->atLeast()->once()->andReturn($pref);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->atLeast()->once();
/** @var Preference $preference */
$data = ['data' => '1'];
$response = $this->put(route('api.v1.preferences.update', ['customFiscalYear']), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PreferenceController
*/
public function testUpdateDefault(): void
{
$transformer = $this->mock(PreferenceTransformer::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->atLeast()->once();
// mock calls to preferences facade.
$pref = new Preference;
$pref->data = 'EUR';
$countable = new Preference;
$countable->data = [1];
$saved = new Preference;
$saved->user_id = $this->user()->id;
$saved->name = 'customFiscalYear';
$saved->data = false;
$saved->save();
Preferences::shouldReceive('getForUser')->atLeast()->once()->withArgs([Mockery::any(), 'frontPageAccounts', []])->andReturn($countable);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['currencyPreference', 'EUR'])->atLeast()->once()->andReturn($pref);
$data = ['data' => 'EUR'];
$response = $this->put(route('api.v1.preferences.update', ['currencyPreference']), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\PreferenceController
*/
public function testUpdateInteger(): void
{
$transformer = $this->mock(PreferenceTransformer::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->atLeast()->once();
// mock calls to preferences facade.
$pref = new Preference;
$pref->data = 'EUR';
$countable = new Preference;
$countable->data = [1];
$saved = new Preference;
$saved->user_id = $this->user()->id;
$saved->name = 'listPageSize';
$saved->data = 200;
$saved->save();
Preferences::shouldReceive('getForUser')->atLeast()->once()->withArgs([Mockery::any(), 'frontPageAccounts', []])->andReturn($countable);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['listPageSize', '434'])->atLeast()->once()->andReturn($pref);
$data = ['data' => '434'];
$response = $this->put(route('api.v1.preferences.update', ['listPageSize']), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,404 +0,0 @@
<?php
/**
* RuleControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Models\Rule;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface;
use FireflyIII\TransactionRules\Engine\RuleEngine;
use FireflyIII\TransactionRules\TransactionMatcher;
use FireflyIII\Transformers\RuleTransformer;
use FireflyIII\Transformers\TransactionGroupTransformer;
use Laravel\Passport\Passport;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class RuleControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class RuleControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
* @covers \FireflyIII\Api\V1\Requests\RuleStoreRequest
*/
public function testStore(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$ruleRepos->shouldReceive('setUser')->once();
$rule = $this->user()->rules()->first();
$data = [
'title' => 'Store new rule',
'rule_group_id' => 1,
'trigger' => 'store-journal',
'strict' => 1,
'stop_processing' => 1,
'active' => 1,
'triggers' => [
[
'type' => 'description_is',
'value' => 'Hello',
'stop_processing' => 1,
],
],
'actions' => [
[
'type' => 'add_tag',
'value' => 'A',
'stop_processing' => 1,
],
],
];
$accountRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('store')->once()->andReturn($rule);
// test API
$response = $this->post(route('api.v1.rules.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
* @covers \FireflyIII\Api\V1\Requests\RuleStoreRequest
*/
public function testStoreNoActions(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$this->mock(RuleTransformer::class);
Preferences::shouldReceive('mark');
$accountRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
$data = [
'title' => 'Store new rule',
'rule_group_id' => 1,
'trigger' => 'store-journal',
'strict' => 1,
'stop_processing' => 1,
'active' => 1,
'triggers' => [
[
'type' => 'description_is',
'value' => 'Hello',
'stop_processing' => 1,
],
],
'actions' => [
],
];
// test API
$response = $this->post(route('api.v1.rules.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'title' => [
'Rule must have at least one action.',
],
],
'message' => 'The given data was invalid.',
]);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
* @covers \FireflyIII\Api\V1\Requests\RuleStoreRequest
*/
public function testStoreNoTriggers(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$this->mock(RuleTransformer::class);
$accountRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
$data = [
'title' => 'Store new rule',
'rule_group_id' => 1,
'trigger' => 'store-journal',
'strict' => 1,
'stop_processing' => 1,
'active' => 1,
'triggers' => [
],
'actions' => [
[
'type' => 'add_tag',
'value' => 'A',
'stop_processing' => 1,
],
],
];
// test API
$response = $this->post(route('api.v1.rules.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'title' => [
'Rule must have at least one trigger.',
],
],
'message' => 'The given data was invalid.',
]);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
* @covers \FireflyIII\Api\V1\Requests\RuleTestRequest
*/
public function testTestRule(): void
{
$rule = $this->user()->rules()->first();
// mock used classes.
$repository = $this->mock(AccountRepositoryInterface::class);
$matcher = $this->mock(TransactionMatcher::class);
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$transformer = $this->mock(TransactionGroupTransformer::class);
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$repository->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
$repository->shouldReceive('findNull')->withArgs([1])->andReturn($asset);
$repository->shouldReceive('findNull')->withArgs([2])->andReturn($expense);
$repository->shouldReceive('findNull')->withArgs([3])->andReturn(null);
$matcher->shouldReceive('setRule')->once();
$matcher->shouldReceive('setEndDate')->once();
$matcher->shouldReceive('setStartDate')->once();
$matcher->shouldReceive('setSearchLimit')->once();
$matcher->shouldReceive('setTriggeredLimit')->once();
$matcher->shouldReceive('setAccounts')->once();
$matcher->shouldReceive('findTransactionsByRule')->once()->andReturn([[1]]);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'listPageSize', 50])->atLeast()->once()->andReturn($pref);
$response = $this->get(route('api.v1.rules.test', [$rule->id]) . '?accounts=1,2,3');
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
* @covers \FireflyIII\Api\V1\Requests\RuleTriggerRequest
*/
public function testTriggerRule(): void
{
$rule = $this->user()->rules()->first();
$repository = $this->mock(AccountRepositoryInterface::class);
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
Preferences::shouldReceive('mark');
// new mocks for ruleEngine
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->atLeast()->once();
$collector->shouldReceive('setAccounts')->atLeast()->once();
$collector->shouldReceive('setRange')->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([['x']]);
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$repository->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
$repository->shouldReceive('findNull')->withArgs([1])->andReturn($asset);
$repository->shouldReceive('findNull')->withArgs([2])->andReturn($expense);
$repository->shouldReceive('findNull')->withArgs([3])->andReturn(null);
$response = $this->post(route('api.v1.rules.trigger', [$rule->id]) . '?accounts=1,2,3&start_date=2019-01-01&end_date=2019-01-02');
$response->assertStatus(204);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
*/
public function testMoveRuleDown(): void
{
/** @var Rule $rule */
$rule = $this->user()->rules()->first();
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('find')->once()->andReturn($rule);
$ruleRepos->shouldReceive('moveDown')->once();
// test API
$response = $this->post(route('api.v1.rules.down', [$rule->id]), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
*/
public function testMoveRuleUp(): void
{
/** @var Rule $rule */
$rule = $this->user()->rules()->first();
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('find')->once()->andReturn($rule);
$ruleRepos->shouldReceive('moveUp')->once();
// test API
$response = $this->post(route('api.v1.rules.up', [$rule->id]), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleController
* @covers \FireflyIII\Api\V1\Requests\RuleUpdateRequest
*/
public function testUpdate(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleRepos->shouldReceive('setUser')->once();
/** @var Rule $rule */
$rule = $this->user()->rules()->first();
$data = [
'title' => 'Store new rule',
'rule_group_id' => 1,
'trigger' => 'store-journal',
'strict' => 1,
'stop_processing' => 1,
'active' => 1,
'triggers' => [
[
'type' => 'description_is',
'value' => 'Hello',
'stop_processing' => 1,
],
],
'actions' => [
[
'type' => 'add_tag',
'value' => 'A',
'stop_processing' => 1,
],
],
];
$ruleRepos->shouldReceive('update')->once()->andReturn($rule);
// test API
$response = $this->put(route('api.v1.rules.update', [$rule->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
}

View File

@@ -1,324 +0,0 @@
<?php
/**
* RuleGroupControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Jobs\ExecuteRuleOnExistingTransactions;
use FireflyIII\Jobs\Job;
use FireflyIII\Models\Preference;
use FireflyIII\Models\RuleGroup;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
use FireflyIII\TransactionRules\Engine\RuleEngine;
use FireflyIII\TransactionRules\TransactionMatcher;
use FireflyIII\Transformers\RuleGroupTransformer;
use FireflyIII\Transformers\TransactionGroupTransformer;
use Illuminate\Support\Collection;
use Laravel\Passport\Passport;
use Log;
use Mockery;
use Preferences;
use Queue;
use Tests\TestCase;
/**
*
* Class RuleGroupControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class RuleGroupControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
* @covers \FireflyIII\Api\V1\Requests\RuleGroupRequest
*/
public function testStore(): void
{
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleGroupTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('setUser')->once();
$ruleGroup = $this->user()->ruleGroups()->first();
$data = [
'title' => 'Store new rule group ' . $this->randomInt(),
'active' => 1,
'description' => 'Hello',
];
$ruleGroupRepos->shouldReceive('store')->once()->andReturn($ruleGroup);
// test API
$response = $this->post(route('api.v1.rule_groups.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
* @covers \FireflyIII\Api\V1\Requests\RuleGroupTestRequest
*/
public function testTestGroupBasic(): void
{
$group = $this->user()->ruleGroups()->first();
$rule = $this->user()->rules()->first();
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$repository = $this->mock(AccountRepositoryInterface::class);
$matcher = $this->mock(TransactionMatcher::class);
$transformer = $this->mock(TransactionGroupTransformer::class);
// mock calls
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$ruleGroupRepos->shouldReceive('setUser')->once();
$repository->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('getActiveRules')->once()->andReturn(new Collection([$rule]));
$repository->shouldReceive('findNull')->withArgs([1])->andReturn($asset);
$repository->shouldReceive('findNull')->withArgs([2])->andReturn($expense);
$repository->shouldReceive('findNull')->withArgs([3])->andReturn(null);
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$matcher->shouldReceive('setRule')->once();
$matcher->shouldReceive('setEndDate')->once();
$matcher->shouldReceive('setStartDate')->once();
$matcher->shouldReceive('setSearchLimit')->once();
$matcher->shouldReceive('setTriggeredLimit')->once();
$matcher->shouldReceive('setAccounts')->once();
$matcher->shouldReceive('findTransactionsByRule')->once()->andReturn([]);
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'listPageSize', 50])->atLeast()->once()->andReturn($pref);
// call API
$response = $this->get(route('api.v1.rule_groups.test', [$group->id]) . '?accounts=1,2,3');
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
* @covers \FireflyIII\Api\V1\Requests\RuleGroupTestRequest
*/
public function testTestGroupEmpty(): void
{
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('getActiveRules')->once()->andReturn(new Collection);
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'listPageSize', 50])->atLeast()->once()->andReturn($pref);
// call API
$group = $this->user()->ruleGroups()->first();
Log::warning('The following error is part of a test.');
$response = $this->get(route('api.v1.rule_groups.test', [$group->id]), ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertSee('200023');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
* @covers \FireflyIII\Api\V1\Requests\RuleGroupTriggerRequest
*/
public function testTrigger(): void
{
$group = $this->user()->ruleGroups()->first();
$rule = $this->user()->rules()->first();
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$repository = $this->mock(AccountRepositoryInterface::class);
$matcher = $this->mock(TransactionMatcher::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
// new mocks for ruleEngine
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->atLeast()->once();
$collector->shouldReceive('setAccounts')->atLeast()->once();
$collector->shouldReceive('setRange')->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([['x']]);
$ruleGroupRepos->shouldReceive('setUser')->once();
$repository->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('getActiveRules')->once()->andReturn(new Collection([$rule]));
$repository->shouldReceive('findNull')->withArgs([1])->andReturn($asset);
$repository->shouldReceive('findNull')->withArgs([2])->andReturn($expense);
$repository->shouldReceive('findNull')->withArgs([3])->andReturn(null);
$repository->shouldReceive('isAsset')->withArgs([1])->andReturn(true);
$repository->shouldReceive('isAsset')->withArgs([2])->andReturn(false);
$response = $this->post(route('api.v1.rule_groups.trigger', [$group->id]) . '?accounts=1,2,3&start_date=2019-01-01&end_date=2019-01-02');
$response->assertStatus(204);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
* @covers \FireflyIII\Api\V1\Requests\RuleGroupRequest
*/
public function testUpdate(): void
{
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleGroupTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('setUser')->once();
$ruleGroup = $this->user()->ruleGroups()->first();
$data = [
'title' => 'Store new rule ' . $this->randomInt(),
'active' => 1,
'description' => 'Hello',
];
$ruleGroupRepos->shouldReceive('update')->once()->andReturn($ruleGroup);
// test API
$response = $this->put(route('api.v1.rule_groups.update', [$ruleGroup->id]), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
*/
public function testMoveRuleGroupDown(): void
{
/** @var RuleGroup $group */
$group = $this->user()->ruleGroups()->first();
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleGroupTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('find')->once()->andReturn($group);
$ruleGroupRepos->shouldReceive('moveDown')->once();
// test API
$response = $this->post(route('api.v1.rule_groups.down', [$group->id]), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\RuleGroupController
*/
public function testMoveRuleGroupUp(): void
{
/** @var RuleGroup $group */
$group = $this->user()->ruleGroups()->first();
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RuleGroupTransformer::class);
// mock calls to transformer:
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$accountRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('setUser')->once();
$ruleGroupRepos->shouldReceive('find')->once()->andReturn($group);
$ruleGroupRepos->shouldReceive('moveUp')->once();
// test API
$response = $this->post(route('api.v1.rule_groups.up', [$group->id]), ['Accept' => 'application/json']);
$response->assertStatus(200);
}
}

View File

@@ -1,280 +0,0 @@
<?php
/**
* SummaryControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Carbon\Carbon;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Illuminate\Support\Collection;
use Laravel\Passport\Passport;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class SummaryControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class SummaryControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Also includes NULL currencies for better coverage.
*
* @covers \FireflyIII\Api\V1\Controllers\SummaryController
*/
public function testBasicInTheFuture(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$billRepos = $this->mock(BillRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$netWorth = $this->mock(NetWorthInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon();
$date->addWeek();
// data
$euro = $this->getEuro();
$budget = $this->user()->budgets()->inRandomOrder()->first();
$account = $this->getRandomAsset();
$journals = [
[
'amount' => '10',
'currency_id' => 1,
],
[
'amount' => '10',
'currency_id' => 2,
],
];
$netWorthData = [
[
'currency' => $euro,
'balance' => '232',
],
[
'currency' => $euro,
'balance' => '0',
],
];
// mock calls.
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$billRepos->shouldReceive('setUser')->atLeast()->once();
$budgetRepos->shouldReceive('setUser')->atLeast()->once();
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
$netWorth->shouldReceive('setUser')->atLeast()->once();
$opsRepos->shouldReceive('setUser')->atLeast()->once();
$abRepos->shouldReceive('setUser')->atLeast()->once();
// mock collector calls:
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setPage')->atLeast()->once()->andReturnSelf();
// used to get balance information (deposits)
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->atLeast()->once()->andReturnSelf();
// same, but for withdrawals
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->atLeast()->once()->andReturnSelf();
// system always returns one basic transaction (see above)
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn($journals);
// currency repos does some basic collecting
$currencyRepos->shouldReceive('findNull')->withArgs([1])->atLeast()->once()->andReturn($euro);
$currencyRepos->shouldReceive('findNull')->withArgs([2])->atLeast()->once()->andReturn(null);
// bill repository return value
$billRepos->shouldReceive('getBillsPaidInRangePerCurrency')->atLeast()->once()->andReturn([1 => '123', 2 => '456']);
$billRepos->shouldReceive('getBillsUnpaidInRangePerCurrency')->atLeast()->once()->andReturn([1 => '123', 2 => '456']);
// budget repos
$abRepos->shouldReceive('getAvailableBudgetWithCurrency')->atLeast()->once()->andReturn([1 => '123', 2 => '456']);
$budgetRepos->shouldReceive('getActiveBudgets')->atLeast()->once()->andReturn(new Collection([$budget]));
// new stuff
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn([]);
//$opsRepos->shouldReceive('spentInPeriodMc')->atLeast()->once()->andReturn(
// [
// [
// 'currency_id' => 3,
// 'currency_code' => 'EUR',
// 'currency_symbol' => 'x',
// 'currency_decimal_places' => 2,
// 'amount' => 321.21,
// ],
// [
// 'currency_id' => 1,
// 'currency_code' => 'EUR',
// 'currency_symbol' => 'x',
// 'currency_decimal_places' => 2,
// 'amount' => 321.21,
// ],
//
// ]
// );
// account repos:
$accountRepos->shouldReceive('getActiveAccountsByType')->atLeast()->once()->withArgs([[AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE]])->andReturn(new Collection([$account]));
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->withArgs([Mockery::any(), 'include_net_worth'])->andReturn(true);
// net worth calculator
$netWorth->shouldReceive('getNetWorthByCurrency')->atLeast()->once()->andReturn($netWorthData);
$parameters = [
'start' => $date->format('Y-m-d'),
'end' => $date->addWeek()->format('Y-m-d'),
];
// TODO AFTER 4.8,0: check if JSON is correct
$response = $this->get(route('api.v1.summary.basic') . '?' . http_build_query($parameters));
$response->assertStatus(200);
//$response->assertSee('hi there');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\SummaryController
*/
public function testBasicInThePast(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$billRepos = $this->mock(BillRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$netWorth = $this->mock(NetWorthInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
// data
$euro = $this->getEuro();
$budget = $this->user()->budgets()->inRandomOrder()->first();
$account = $this->getRandomAsset();
$journals = [
[
'amount' => '10',
'currency_id' => 1,
],
];
$netWorthData = [
[
'currency' => $euro,
'balance' => '232',
],
];
// mock calls.
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$billRepos->shouldReceive('setUser')->atLeast()->once();
$budgetRepos->shouldReceive('setUser')->atLeast()->once();
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
$netWorth->shouldReceive('setUser')->atLeast()->once();
$abRepos->shouldReceive('setUser')->atLeast()->once();
$opsRepos->shouldReceive('setUser')->atLeast()->once();
// mock collector calls:
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setPage')->atLeast()->once()->andReturnSelf();
// used to get balance information (deposits)
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->atLeast()->once()->andReturnSelf();
// same, but for withdrawals
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->atLeast()->once()->andReturnSelf();
// system always returns one basic transaction (see above)
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn($journals);
// currency repos does some basic collecting
$currencyRepos->shouldReceive('findNull')->withArgs([1])->atLeast()->once()->andReturn($euro);
// bill repository return value
$billRepos->shouldReceive('getBillsPaidInRangePerCurrency')->atLeast()->once()->andReturn([1 => '123']);
$billRepos->shouldReceive('getBillsUnpaidInRangePerCurrency')->atLeast()->once()->andReturn([1 => '123']);
// budget repos
$abRepos->shouldReceive('getAvailableBudgetWithCurrency')->atLeast()->once()->andReturn([1 => '123']);
$budgetRepos->shouldReceive('getActiveBudgets')->atLeast()->once()->andReturn(new Collection([$budget]));
// new stuff
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn([]);
// $opsRepos->shouldReceive('spentInPeriodMc')->atLeast()->once()->andReturn(
// [
// [
// 'currency_id' => 1,
// 'currency_code' => 'EUR',
// 'currency_symbol' => 'x',
// 'currency_decimal_places' => 2,
// 'amount' => 321.21,
// ],
// ]
// );
// account repos:
$accountRepos->shouldReceive('getActiveAccountsByType')->atLeast()->once()->withArgs([[AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE]])->andReturn(new Collection([$account]));
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->withArgs([Mockery::any(), 'include_net_worth'])->andReturn(true);
// net worth calculator
$netWorth->shouldReceive('getNetWorthByCurrency')->atLeast()->once()->andReturn($netWorthData);
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-31',
];
$response = $this->get(route('api.v1.summary.basic') . '?' . http_build_query($parameters));
$response->assertStatus(200);
// TODO AFTER 4.8,0: check if JSON is correct
}
}

View File

@@ -1,153 +0,0 @@
<?php
/**
* TagControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\Transformers\TagTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
* Class TagControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TagControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Create Tag over API.
*
* @covers \FireflyIII\Api\V1\Controllers\TagController
* @covers \FireflyIII\Api\V1\Requests\TagStoreRequest
*/
public function testStore(): void
{
$tagRepos = $this->mock(TagRepositoryInterface::class);
$tag = $this->user()->tags()->inRandomOrder()->first();
$data = ['tag' => 'Some tag' . $this->randomInt(),];
$transformer = $this->mock(TagTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$tagRepos->shouldReceive('setUser')->times(1);
$tagRepos->shouldReceive('store')->times(1)->andReturn($tag);
// call API
$response = $this->post(route('api.v1.tags.store'), $data);
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TagController
*/
public function testCloud(): void
{
$tagRepos = $this->mock(TagRepositoryInterface::class);
$tags = $this->user()->tags()->inRandomOrder()->limit(3)->get();
$tagRepos->shouldReceive('setUser')->times(1);
$tagRepos->shouldReceive('get')->atLeast()->once()->andReturn($tags);
$tagRepos->shouldReceive('earnedInPeriod')->times(3)->andReturn('0');
$tagRepos->shouldReceive('spentInPeriod')->times(3)->andReturn('-10', '-20', '-30');
// call API
$parameters = [
'start' => '2019-01-01',
'end' => '2019-01-05',
];
$response = $this->get(route('api.v1.tag-cloud.cloud') . '?' . http_build_query($parameters));
$response->assertStatus(200);
$response->assertJson(
[
'tags' => [
[
'size' => 10,
'relative' => 0.3333,
],
[
'size' => 20,
'relative' => 0.6667,
],
[
'size' => 30,
'relative' => 1,
],
],
]);
}
/**
* Update Tag over API.
*
* @covers \FireflyIII\Api\V1\Controllers\TagController
* @covers \FireflyIII\Api\V1\Requests\TagUpdateRequest
*/
public function testUpdate(): void
{
$tagRepos = $this->mock(TagRepositoryInterface::class);
$tag = $this->user()->tags()->inRandomOrder()->first();
$data = ['tag' => 'Some tag' . $this->randomInt(),];
$transformer = $this->mock(TagTransformer::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$tagRepos->shouldReceive('setUser')->times(2);
$tagRepos->shouldReceive('update')->times(1)->andReturn($tag);
$tagRepos->shouldReceive('findByTag')->times(1)->andReturnNull();
$tagRepos->shouldReceive('findNull')->times(1)->andReturn($tag);
// call API
$response = $this->put(route('api.v1.tags.update', [$tag->id]), $data);
$response->assertStatus(200);
}
}

View File

@@ -1,916 +0,0 @@
<?php
/**
* TransactionControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Exception;
use FireflyIII\Events\StoredTransactionGroup;
use FireflyIII\Events\UpdatedTransactionGroup;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Repositories\Journal\JournalAPIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface;
use FireflyIII\Transformers\TransactionGroupTransformer;
use FireflyIII\Validation\AccountValidator;
use Illuminate\Support\Collection;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
* Class TransactionControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TransactionControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Submit empty description.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailDescription(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'transactions' => [
[
'description' => '',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.description' => ['The description field is required.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Fail the valid destination information test.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailDestination(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
/** fail destination */
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(false)
->andSet('destError', 'Some error');
$data = [
'transactions' => [
[
'description' => 'Fails anyway',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.destination_id' => ['Some error'],
'transactions.0.destination_name' => ['Some error'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Submit foreign currency info, but no foreign currency amount.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailForeignCurrencyAmount(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'transactions' => [
[
'description' => 'Test',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'foreign_currency_code' => 'USD',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.foreign_amount' => ['The content of this field is invalid without foreign amount information.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Submit foreign currency, but no foreign currency info.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailForeignCurrencyInfo(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'transactions' => [
[
'description' => 'Test',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'foreign_amount' => '11',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.foreign_amount' => ['The content of this field is invalid without currency information.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Fail the valid source information test.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailSource(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
/** source info returns FALSE **/
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(false)
->andSet('sourceError', 'Some error');
$data = [
'transactions' => [
[
'description' => 'Some withdrawal ',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.source_id' => ['Some error'],
'transactions.0.source_name' => ['Some error'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Submit multiple transactions but no group title.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailStoreGroupTitle(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'transactions' => [
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'group_title' => ['A group title is mandatory when there is more than one transaction.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Submit multiple transactions but no group title.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailStoreNoTransactions(): void
{
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
$data = [
'transactions' => [
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.description' => ['Need at least one transaction.', 'The description field is required.'],
'transactions.0.type' => ['Invalid transaction type.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Try to submit different transaction types for a withdrawal.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailTypes(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('setTransactionType')->withArgs(['deposit'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'group_title' => 'Hi there',
'transactions' => [
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'deposit',
'amount' => '10',
'destination_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.source_id' => ['All accounts in this field must be equal.'],
'transactions.0.type' => ['All splits must be of the same type.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Try to submit different transaction types for a deposit.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailTypesDeposit(): void
{
// mock data:
$source = $this->getRandomAsset();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('setTransactionType')->withArgs(['deposit'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'group_title' => 'Hi there',
'transactions' => [
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'deposit',
'amount' => '10',
'destination_id' => $source->id,
],
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.destination_id' => ['All accounts in this field must be equal.'],
'transactions.0.type' => ['All splits must be of the same type.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Try to submit different transaction types for a transfer.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreFailTypesTransfer(): void
{
// mock data:
$source = $this->getRandomAsset();
$dest = $this->getRandomAsset($source->id);
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['transfer'])->atLeast()->once();
$validator->shouldReceive('setTransactionType')->withArgs(['deposit'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'group_title' => 'Hi there',
'transactions' => [
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'transfer',
'amount' => '10',
'destination_id' => $source->id,
'source_id' => $dest->id,
],
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'deposit',
'amount' => '10',
'destination_id' => $dest->id,
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.destination_id' => ['All accounts in this field must be equal.'],
'transactions.0.source_id' => ['All accounts in this field must be equal.'],
'transactions.0.type' => ['All splits must be of the same type.'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Submit the minimum amount of data required to create a single, unsplit withdrawal.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionStoreRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testStoreOK(): void
{
// mock data:
$source = $this->getRandomAsset();
$group = $this->getRandomWithdrawalGroup();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$transformer = $this->mock(TransactionGroupTransformer::class);
$validator = $this->mock(AccountValidator::class);
$collector = $this->mock(GroupCollectorInterface::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$collector->shouldReceive('setUser')->atLeast()->once()->andReturnSelf();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
// transformer is called:
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 1]);
$transformer->shouldReceive('getDefaultIncludes')->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->atLeast()->once()->andReturn([]);
// collector is called:
$collector->shouldReceive('setTransactionGroup')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withAPIInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getGroups')->atLeast()->once()->andReturn(new Collection([[]]));
// expect to store the group:
$repository->shouldReceive('store')->atLeast()->once()->andReturn($group);
// expect the event:
try {
$this->expectsEvents(StoredTransactionGroup::class);
} catch (Exception $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
$this->assertTrue(false, $e->getMessage());
}
$data = [
'transactions' => [
[
'description' => 'Some description',
'date' => '2018-01-01',
'type' => 'withdrawal',
'amount' => '10',
'source_id' => $source->id,
],
],
];
// test API
$response = $this->post(route('api.v1.transactions.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertExactJson(
[
'data' => [
'attributes' => [],
'id' => '1',
'links' => [
'self' => 'http://localhost/api/v1/transactions/1',
],
'type' => 'transactions',
],
]
);
}
/**
* Submit a bad journal ID during update.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionUpdateRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testUpdateFailBadJournal(): void
{
// mock data:
$group = $this->getRandomWithdrawalGroup();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
$validator->shouldReceive('setTransactionType')->withArgs(['invalid'])->atLeast()->once();
//$validator->shouldReceive('validateSource')->withArgs([null, null])->atLeast()->once()->andReturn(true);
//$validator->shouldReceive('validateDestination')->withArgs([null, null])->atLeast()->once()->andReturn(true);
$data = [
'group_title' => 'Empty',
'transactions' => [
[
'order' => 0,
'transaction_journal_id' => -1,
'reconciled' => 'false',
'tags' => [],
'interest_date' => '2019-01-01',
'description' => 'Some new description',
],
[
'order' => 0,
'transaction_journal_id' => -1,
'reconciled' => 'false',
'tags' => [],
'interest_date' => '2019-01-01',
'description' => 'Some new description',
],
],
];
// test API
$response = $this->put(sprintf('/api/v1/transactions/%d', $group->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertExactJson(
[
'errors' => [
'transactions.0.source_name' => ['Each split must have transaction_journal_id (either valid ID or 0).'],
'transactions.1.source_name' => ['Each split must have transaction_journal_id (either valid ID or 0).'],
],
'message' => 'The given data was invalid.',
]
);
}
/**
* Update transaction but fail to submit equal transaction types.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionUpdateRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testUpdateFailTypes(): void
{
// mock data:
$group = $this->getRandomWithdrawalGroup();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('setTransactionType')->withArgs(['deposit'])->atLeast()->once();
//$validator->shouldReceive('validateSource')->withArgs([null, null])->atLeast()->once()->andReturn(true);
//$validator->shouldReceive('validateDestination')->withArgs([null, null])->atLeast()->once()->andReturn(true);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
$data = [
'group_title' => 'Empty',
'transactions' => [
[
'transaction_journal_id' => 0,
'order' => 0,
'reconciled' => 'false',
'tags' => [],
'interest_date' => '2019-01-01',
'type' => 'withdrawal',
'description' => 'Some new description',
],
[
'transaction_journal_id' => 0,
'order' => 0,
'reconciled' => 'false',
'tags' => [],
'interest_date' => '2019-01-01',
'type' => 'deposit',
'description' => 'Some new description',
],
],
];
// test API
$response = $this->put(sprintf('/api/v1/transactions/%d', $group->id), $data, ['Accept' => 'application/json']);
$response->assertExactJson(
[
'errors' => [
'transactions.0.type' => ['All splits must be of the same type.'],
],
'message' => 'The given data was invalid.',
]
);
$response->assertStatus(422);
}
/**
* Submit the minimum amount of data to update a single withdrawal.
*
* @covers \FireflyIII\Api\V1\Requests\TransactionUpdateRequest
* @covers \FireflyIII\Api\V1\Controllers\TransactionController
*/
public function testUpdateOK(): void
{
// mock data:
$group = $this->getRandomWithdrawalGroup();
// mock repository
$repository = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$transformer = $this->mock(TransactionGroupTransformer::class);
$validator = $this->mock(AccountValidator::class);
$collector = $this->mock(GroupCollectorInterface::class);
$apiRepos = $this->mock(JournalAPIRepositoryInterface::class);
$validator->shouldReceive('setTransactionType')->withArgs(['invalid'])->atLeast()->once();
//$validator->shouldReceive('validateSource')->withArgs([null, null])->atLeast()->once()->andReturn(true);
//$validator->shouldReceive('validateDestination')->withArgs([null, null])->atLeast()->once()->andReturn(true);
// some mock calls:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$collector->shouldReceive('setUser')->atLeast()->once()->andReturnSelf();
$repository->shouldReceive('setUser')->atLeast()->once();
$apiRepos->shouldReceive('setUser')->atLeast()->once();
// call stuff:
$repository->shouldReceive('update')->atLeast()->once()->andReturn($group);
// transformer is called:
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 1]);
$transformer->shouldReceive('getDefaultIncludes')->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->atLeast()->once()->andReturn([]);
// collector is called:
$collector->shouldReceive('setTransactionGroup')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withAPIInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getGroups')->atLeast()->once()->andReturn(new Collection([[]]));
$data = [
'group_title' => 'Empty',
'transactions' => [
[
'order' => 0,
'reconciled' => 'false',
'tags' => [],
'interest_date' => '2019-01-01',
'description' => 'Some new description',
],
],
];
// expect the event:
try {
$this->expectsEvents(UpdatedTransactionGroup::class);
} catch (Exception $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
$this->assertTrue(false, $e->getMessage());
}
// test API
$response = $this->put(sprintf('/api/v1/transactions/%d', $group->id), $data, ['Accept' => 'application/json']);
$response->assertExactJson(
[
'data' => [
'attributes' => [],
'id' => '1',
'links' => [
'self' => 'http://localhost/api/v1/transactions/1',
],
'type' => 'transactions',
],
]
);
$response->assertStatus(200);
}
}

View File

@@ -1,430 +0,0 @@
<?php
/**
* TransactionLinkControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Carbon\Carbon;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournalLink;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface;
use FireflyIII\Transformers\TransactionLinkTransformer;
use Laravel\Passport\Passport;
use Log;
use Tests\TestCase;
/**
*
* Class TransactionLinkControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TransactionLinkControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testStore(): void
{
$journalLink = TransactionJournalLink::first();
$journal = $this->user()->transactionJournals()->find(1);
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$transformer = $this->mock(TransactionLinkTransformer::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
$journalRepos->shouldReceive('findNull')->andReturn($journal)->atLeast()->once();
$repository->shouldReceive('storeLink')->once()->andReturn($journalLink);
$repository->shouldReceive('findLink')->once()->andReturn(false);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->post(route('api.v1.transaction_links.store'), $data);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* In this particular test the journal link request will fail.
*
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testStoreExistingLink(): void
{
$journal = $this->user()->transactionJournals()->find(1);
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->andReturn($journal);
$repository->shouldReceive('findLink')->once()->andReturn(true);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->post(route('api.v1.transaction_links.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertSee('Already have a link between inward and outward.');
$response->assertHeader('Content-Type', 'application/json');
}
/**
* In this particular test the TransactionLinkRequest will report the failure.
*
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testStoreInvalidInward(): void
{
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->once()->withArgs([1])->andReturn(null);
$journalRepos->shouldReceive('findNull')->once()->withArgs([2])->andReturn(null);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->post(route('api.v1.transaction_links.store'), $data, ['Accept' => 'application/json']);
$response->assertSee('Invalid inward ID.'); // the creation moment.
$response->assertStatus(422);
$response->assertHeader('Content-Type', 'application/json');
}
/**
* In this particular test the TransactionLinkRequest will report the failure.
*
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testStoreInvalidOutward(): void
{
$journal = $this->user()->transactionJournals()->find(1);
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->once()->withArgs([1])->andReturn($journal);
$journalRepos->shouldReceive('findNull')->once()->withArgs([2])->andReturn(null);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->post(route('api.v1.transaction_links.store'), $data, ['Accept' => 'application/json']);
$response->assertSee('Invalid outward ID.');
$response->assertStatus(422);
$response->assertHeader('Content-Type', 'application/json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testStoreNoJournal(): void
{
$journal = $this->user()->transactionJournals()->find(1);
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->twice()->withArgs([1])->andReturn($journal, null);
$journalRepos->shouldReceive('findNull')->twice()->withArgs([2])->andReturn($journal, null);
$repository->shouldReceive('findLink')->once()->andReturn(false);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
Log::warning('The following error is part of a test.');
$response = $this->post(route('api.v1.transaction_links.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertSee('200024'); // the creation moment.
$response->assertHeader('Content-Type', 'application/json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testStoreWithNull(): void
{
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock stuff:
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->andReturn(null);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->post(route('api.v1.transaction_links.store'), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertSee('Invalid inward ID.'); // error message
$response->assertHeader('Content-Type', 'application/json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testUpdate(): void
{
// mock repositories
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$transformer = $this->mock(TransactionLinkTransformer::class);
$journalLink = TransactionJournalLink::first();
$journal = $this->user()->transactionJournals()->find(1);
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->withAnyArgs()->atLeast()->once()->andReturnSelf();
$transformer->shouldReceive('getDefaultIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('getAvailableIncludes')->withAnyArgs()->atLeast()->once()->andReturn([]);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(['id' => 5]);
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->andReturn($journal);
$repository->shouldReceive('updateLink')->once()->andReturn($journalLink);
$repository->shouldReceive('findLink')->once()->andReturn(false);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->put(route('api.v1.transaction_links.update', $journalLink->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(200);
$response->assertHeader('Content-Type', 'application/vnd.api+json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testUpdateNoJournal(): void
{
// mock repositories
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$journalLink = TransactionJournalLink::first();
$journal = $this->user()->transactionJournals()->find(1);
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->twice()->withArgs([1])->andReturn($journal, null);
$journalRepos->shouldReceive('findNull')->twice()->withArgs([2])->andReturn($journal, null);
$repository->shouldReceive('findLink')->once()->andReturn(false);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
Log::warning('The following error is part of a test.');
$response = $this->put(route('api.v1.transaction_links.update', $journalLink->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(500);
$response->assertSee('200024'); // the creation moment.
$response->assertHeader('Content-Type', 'application/json');
}
/**
* @covers \FireflyIII\Api\V1\Controllers\TransactionLinkController
* @covers \FireflyIII\Api\V1\Requests\TransactionLinkRequest
*/
public function testUpdateWithNull(): void
{
// mock repositories
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$journalLink = TransactionJournalLink::first();
$transaction = Transaction::first();
$transaction->date = new Carbon;
$transaction->transaction_type_type = 'Withdrawal';
// mock calls:
$repository->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('findNull')->andReturn(null);
// data to submit
$data = [
'link_type_id' => '1',
'inward_id' => '1',
'outward_id' => '2',
'notes' => 'Some notes',
];
// test API
$response = $this->put(route('api.v1.transaction_links.update', $journalLink->id), $data, ['Accept' => 'application/json']);
$response->assertStatus(422);
$response->assertSee('Invalid inward ID.'); // the creation moment.
$response->assertHeader('Content-Type', 'application/json');
}
}

View File

@@ -1,72 +0,0 @@
<?php
/**
* UserControllerTest.php
* Copyright (c) 2019 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\Api\V1\Controllers;
use Faker\Factory;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\UserTransformer;
use Laravel\Passport\Passport;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class UserControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class UserControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
parent::setUp();
Passport::actingAs($this->user());
$this->mockDefaultConfiguration();
}
/**
* Store new user.
*
* @covers \FireflyIII\Api\V1\Controllers\UserController
* @covers \FireflyIII\Api\V1\Requests\UserStoreRequest
*/
public function testStoreBasic(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
// random user
$faker = Factory::create();
$data = ['email' => $faker->email,];
// test API
$response = $this->post(route('api.v1.users.store'), $data, ['Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json']);
$response->assertStatus(200);
}
}

View File

@@ -1,55 +0,0 @@
<?php
/**
* BasicTest.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\Feature;
use Tests\TestCase;
/**
* Class BasicTest
*/
class BasicTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest(): void
{
self::assertTrue(true);
}
/**
*
*/
public function testDatabase(): void
{
$this->assertDatabaseHas(
'users', [
'email' => 'james@firefly',
]
);
}
}

View File

@@ -1,147 +0,0 @@
<?php
/**
* DecryptDatabaseTest.php
* Copyright (c) 2019 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\Feature\Console\Commands;
use Crypt;
use FireflyConfig;
use FireflyIII\Models\Account;
use FireflyIII\Models\Configuration;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class DecryptDatabaseTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class DecryptDatabaseTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Console\Commands\DecryptDatabase
*/
public function testHandle(): void
{
// create encrypted account:
$name = 'Encrypted name';
$iban = 'HR1723600001101234565';
$account = Account::create(
[
'user_id' => 1,
'account_type_id' => 1,
'name' => Crypt::encrypt($name),
'iban' => Crypt::encrypt($iban),
]);
FireflyConfig::shouldReceive('get')->withArgs([Mockery::any(), false])->atLeast()->once()->andReturn(null);
FireflyConfig::shouldReceive('set')->withArgs([Mockery::any(), true])->atLeast()->once();
$this->artisan('firefly-iii:decrypt-all')
->expectsOutput('Done!')
->assertExitCode(0);
$this->assertCount(1, Account::where('id', $account->id)->where('name', $name)->get());
$this->assertCount(1, Account::where('id', $account->id)->where('iban', $iban)->get());
}
/**
* @covers \FireflyIII\Console\Commands\DecryptDatabase
*/
public function testHandleDecrypted(): void
{
// create encrypted account:
$name = 'Encrypted name';
$iban = 'HR1723600001101234565';
$encryptedName = Crypt::encrypt($name);
$encryptedIban = Crypt::encrypt($iban);
$account = Account::create(
[
'user_id' => 1,
'account_type_id' => 1,
'name' => $encryptedName,
'iban' => $encryptedIban,
]);
// pretend its not yet decrypted.
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs([Mockery::any(), false])->atLeast()->once()->andReturn($true);
$this->artisan('firefly-iii:decrypt-all')
->expectsOutput('Done!')
->assertExitCode(0);
$this->assertCount(1, Account::where('id', $account->id)->where('name', $encryptedName)->get());
$this->assertCount(1, Account::where('id', $account->id)->where('iban', $encryptedIban)->get());
}
/**
* Try to decrypt data that isn't actually encrypted.
*
* @covers \FireflyIII\Console\Commands\DecryptDatabase
*/
public function testHandleNotEncrypted(): void
{
// create encrypted account:
$name = 'Encrypted name';
$iban = 'HR1723600001101234565';
$account = Account::create(
[
'user_id' => 1,
'account_type_id' => 1,
'name' => $name,
'iban' => $iban,
]);
// pretend its not yet decrypted.
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs([Mockery::any(), false])->atLeast()->once()->andReturn($true);
$this->artisan('firefly-iii:decrypt-all')
->expectsOutput('Done!')
->assertExitCode(0);
$this->assertCount(1, Account::where('id', $account->id)->where('name', $name)->get());
$this->assertCount(1, Account::where('id', $account->id)->where('iban', $iban)->get());
}
}

View File

@@ -1,156 +0,0 @@
<?php
/**
* ReportEmptyObjectsTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Integrity;
use FireflyIII\Models\Account;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
use FireflyIII\Models\Tag;
use Log;
use Tests\TestCase;
/**
* Class ReportEmptyObjectsTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ReportEmptyObjectsTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Run basic test routine.
*
* @covers \FireflyIII\Console\Commands\Integrity\ReportEmptyObjects
*/
public function testHandleBudget(): void
{
$user = $this->user();
$budget = Budget::create(
[
'user_id' => $user->id,
'name' => 'Some budget',
]);
$budgetLine = sprintf('User #%d (%s) has budget #%d ("%s") which has no transaction journals.',
$user->id, $user->email, $budget->id, $budget->name);
$budgetLimitLine = sprintf('User #%d (%s) has budget #%d ("%s") which has no budget limits.',
$user->id, $user->email, $budget->id, $budget->name);
$this->artisan('firefly-iii:report-empty-objects')
->expectsOutput($budgetLine)
->expectsOutput($budgetLimitLine)
->assertExitCode(0);
$budget->forceDelete();
// this method changes no objects so there is nothing to verify.
}
/**
* Run basic test routine.
*
* @covers \FireflyIII\Console\Commands\Integrity\ReportEmptyObjects
*/
public function testHandleCategory(): void
{
$user = $this->user();
$category = Category::create(
[
'user_id' => $user->id,
'name' => 'Some category',
]);
$categoryLine = sprintf('User #%d (%s) has category #%d ("%s") which has no transaction journals.',
$user->id, $user->email, $category->id, $category->name);
$this->artisan('firefly-iii:report-empty-objects')
->expectsOutput($categoryLine)
->assertExitCode(0);
$category->forceDelete();
// this method changes no objects so there is nothing to verify.
}
/**
* Run basic test routine.
*
* @covers \FireflyIII\Console\Commands\Integrity\ReportEmptyObjects
*/
public function testHandleTag(): void
{
$user = $this->user();
$tag = Tag::create(
[
'user_id' => $user->id,
'tag' => 'Some tag',
'tagMode' => 'nothing',
]);
$tagLine = sprintf('User #%d (%s) has tag #%d ("%s") which has no transaction journals.',
$user->id, $user->email, $tag->id, $tag->tag);
$this->artisan('firefly-iii:report-empty-objects')
->expectsOutput($tagLine)
->assertExitCode(0);
$tag->forceDelete();
// this method changes no objects so there is nothing to verify.
}
/**
* Run basic test routine.
*
* @covers \FireflyIII\Console\Commands\Integrity\ReportEmptyObjects
*/
public function testHandleAccount(): void
{
$user = $this->user();
$account = Account::create(
[
'user_id' => $user->id,
'name' => 'Some account',
'account_type_id' => 1,
]);
$tagLine = sprintf('User #%d (%s) has account #%d ("%s") which has no transactions.',
$user->id, $user->email, $account->id, $account->name);
$this->artisan('firefly-iii:report-empty-objects')
->expectsOutput($tagLine)
->assertExitCode(0);
$account->forceDelete();
// this method changes no objects so there is nothing to verify.
}
}

View File

@@ -1,93 +0,0 @@
<?php
/**
* ReportSumTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Integrity;
use FireflyIII\Models\Transaction;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Tests\TestCase;
/**
* Class ReportSumTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ReportSumTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Console\Commands\Integrity\ReportSum
*/
public function testHandle(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
$this->artisan('firefly-iii:report-sum')
->expectsOutput(sprintf('Amount integrity OK for user #%d', $this->user()->id))
->assertExitCode(0);
// this method changes no objects so there is nothing to verify.
}
/**
* Create transaction to make balance uneven.
* @covers \FireflyIII\Console\Commands\Integrity\ReportSum
*/
public function testHandleUneven(): void
{
$transaction = Transaction::create(
[
'transaction_journal_id' => $this->getRandomWithdrawal()->id,
'user_id' => 1,
'account_id' => $this->getRandomAsset()->id,
'amount' => 10,
]
);
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
$this->artisan('firefly-iii:report-sum')
->expectsOutput(sprintf('Error: Transactions for user #%d (%s) are off by %s!', $this->user()->id, $this->user()->email, '10.0'))
->assertExitCode(0);
$transaction->forceDelete();
// this method changes no objects so there is nothing to verify.
}
}

View File

@@ -1,459 +0,0 @@
<?php
/**
* ApplyRulesTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Tools;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\TransactionRules\Engine\RuleEngine;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class ApplyRulesTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ApplyRulesTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic call with everything perfect (and ALL rules).
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandle(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
// data
$asset = $this->getRandomAsset();
$journal = $this->getRandomWithdrawal();
$group = $this->user()->ruleGroups()->first();
$rule = $this->user()->rules()->first();
$groups = new Collection([$group]);
$rules = new Collection([$rule]);
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([1])->andReturn($asset);
$journalRepos->shouldReceive('firstNull')->atLeast()->once()->andReturn($journal);
$ruleGroupRepos->shouldReceive('getActiveGroups')->atLeast()->once()->andReturn($groups);
$ruleGroupRepos->shouldReceive('getActiveStoreRules')->atLeast()->once()->andReturn($rules);
$collector->shouldReceive('setUser')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([[], [], []]);
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [
'--user=1',
'--token=token',
'--accounts=1',
'--all_rules',
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput('Will apply 1 rule(s) to 3 transaction(s).')
->expectsOutput('Done!')
->assertExitCode(0);
// this method changes no objects so there is nothing to verify.
}
/**
* Basic call with everything perfect (and ALL rules), but no rules will be selected.
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandEmpty(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
// data
$asset = $this->getRandomAsset();
$journal = $this->getRandomWithdrawal();
$group = $this->user()->ruleGroups()->first();
$groups = new Collection([$group]);
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([1])->andReturn($asset);
$journalRepos->shouldReceive('firstNull')->atLeast()->once()->andReturn($journal);
$ruleGroupRepos->shouldReceive('getActiveGroups')->atLeast()->once()->andReturn($groups);
$ruleGroupRepos->shouldReceive('getActiveStoreRules')->atLeast()->once()->andReturn(new Collection);
$parameters = [
'--user=1',
'--token=token',
'--accounts=1',
'--all_rules',
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput('No rules or rule groups have been included.')
->assertExitCode(1);
}
/**
* Basic call with everything perfect (and ALL rules) and dates.
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandleDate(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$this->mock(JournalRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
// data
$asset = $this->getRandomAsset();
$group = $this->user()->ruleGroups()->first();
$rule = $this->user()->rules()->first();
$groups = new Collection([$group]);
$rules = new Collection([$rule]);
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([1])->andReturn($asset);
$ruleGroupRepos->shouldReceive('getActiveGroups')->atLeast()->once()->andReturn($groups);
$ruleGroupRepos->shouldReceive('getActiveStoreRules')->atLeast()->once()->andReturn($rules);
$collector->shouldReceive('setUser')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([[], [], []]);
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [
'--user=1',
'--token=token',
'--accounts=1',
'--all_rules',
'--start_date=2019-01-31',
'--end_date=2019-01-01',
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput('Will apply 1 rule(s) to 3 transaction(s).')
->expectsOutput('Done!')
->assertExitCode(0);
}
/**
* Will submit some rules to apply.
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandleRules(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
// data
$asset = $this->getRandomAsset();
$journal = $this->getRandomWithdrawal();
$group = $this->user()->ruleGroups()->first();
$groups = new Collection([$group]);
$activeRule = $this->user()->rules()->where('active', 1)->inRandomOrder()->first();
$inactiveRule = $this->user()->rules()->where('active', 0)->inRandomOrder()->first();
$rules = new Collection([$activeRule]);
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([1])->andReturn($asset);
$journalRepos->shouldReceive('firstNull')->atLeast()->once()->andReturn($journal);
$ruleRepos->shouldReceive('find')->atLeast()->once()->withArgs([$activeRule->id])->andReturn($activeRule);
$ruleRepos->shouldReceive('find')->atLeast()->once()->withArgs([$inactiveRule->id])->andReturn($inactiveRule);
$ruleGroupRepos->shouldReceive('getActiveGroups')->atLeast()->once()->andReturn($groups);
$ruleGroupRepos->shouldReceive('getActiveStoreRules')->atLeast()->once()->andReturn($rules);
$collector->shouldReceive('setUser')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([[], [], []]);
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [
'--user=1',
'--token=token',
'--accounts=1',
sprintf('--rules=%d,%d', $activeRule->id, $inactiveRule->id),
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput('Will apply 1 rule(s) to 3 transaction(s).')
->expectsOutput('Done!')
->assertExitCode(0);
}
/**
* Basic call with two rule groups. One active, one inactive.
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandleRuleGroups(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$ruleEngine = $this->mock(RuleEngine::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$activeGroup = $this->user()->ruleGroups()->where('active', 1)->inRandomOrder()->first();
$inactiveGroup = $this->user()->ruleGroups()->where('active', 0)->inRandomOrder()->first();
// data
$asset = $this->getRandomAsset();
$journal = $this->getRandomWithdrawal();
$rule = $this->user()->rules()->first();
$groups = new Collection([$activeGroup]);
$rules = new Collection([$rule]);
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([1])->andReturn($asset);
$journalRepos->shouldReceive('firstNull')->atLeast()->once()->andReturn($journal);
$ruleGroupRepos->shouldReceive('getActiveGroups')->atLeast()->once()->andReturn($groups);
$ruleGroupRepos->shouldReceive('getActiveStoreRules')->atLeast()->once()->andReturn($rules);
$ruleGroupRepos->shouldReceive('find')->atLeast()->once()->withArgs([$activeGroup->id])->andReturn($activeGroup);
$ruleGroupRepos->shouldReceive('find')->atLeast()->once()->withArgs([$inactiveGroup->id])->andReturn($inactiveGroup);
$collector->shouldReceive('setUser')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([[], [], []]);
$ruleEngine->shouldReceive('setUser')->atLeast()->once();
$ruleEngine->shouldReceive('setRulesToApply')->atLeast()->once();
$ruleEngine->shouldReceive('processJournalArray')->times(3);
$ruleEngine->shouldReceive('setTriggerMode')->atLeast()->once()->withArgs([RuleEngine::TRIGGER_STORE]);
$parameters = [
'--user=1',
'--token=token',
'--accounts=1',
sprintf('--rule_groups=%d,%d', $activeGroup->id, $inactiveGroup->id),
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput(sprintf('Will ignore inactive rule group #%d ("%s")', $inactiveGroup->id, $inactiveGroup->title))
// one rule out of 2 groups:
->expectsOutput('Will apply 1 rule(s) to 3 transaction(s).')
->expectsOutput('Done!')
->assertExitCode(0);
}
/**
* Basic call but no accounts submitted.
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandleNoAccounts(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$this->mock(JournalRepositoryInterface::class);
$this->mock(GroupCollectorInterface::class);
$this->mock(AccountRepositoryInterface::class);
$this->mock(RuleEngine::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$parameters = [
'--user=1',
'--token=token',
'--accounts=',
'--all_rules',
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput('Please use the --accounts option to indicate the accounts to apply rules to.')
->assertExitCode(1);
}
/**
* Basic call but only one expense account submitted
*
* @covers \FireflyIII\Console\Commands\Tools\ApplyRules
*/
public function testHandleExpenseAccounts(): void
{
$ruleRepos = $this->mock(RuleRepositoryInterface::class);
$ruleGroupRepos = $this->mock(RuleGroupRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(RuleEngine::class);
$this->mock(JournalRepositoryInterface::class);
$this->mock(GroupCollectorInterface::class);
// data
$expense = $this->getRandomExpense();
// expected calls:
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$ruleRepos->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([$expense->id])->andReturn($expense);
$parameters = [
'--user=1',
'--token=token',
'--accounts=' . $expense->id,
'--all_rules',
];
// mock Preferences Facade:
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'access_token',null])->atLeast()->once()->andReturn($pref);
$this->artisan('firefly-iii:apply-rules ' . implode(' ', $parameters))
->expectsOutput('Please make sure all accounts in --accounts are asset accounts or liabilities.')
->assertExitCode(1);
}
}

View File

@@ -1,358 +0,0 @@
<?php
/**
* AccountCurrenciesTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\AccountMeta;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Preference;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class AccountCurrenciesTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AccountCurrenciesTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Perfect run without opening balance.
*
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandle(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = 'EUR';
$account = $this->getRandomAsset();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturn('1');
$accountRepos->shouldReceive('getOpeningBalance')->atLeast()->once()->andReturn(null);
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput('All accounts are OK.')
->assertExitCode(0);
// nothing changed, so nothing to verify.
}
/**
* Perfect run without opening balance.
*
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleNotNull(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = 'EUR';
$account = $this->getRandomAsset();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$journal = $this->getRandomWithdrawal();
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
// account reports USD
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturn('2');
// journal is EUR.
$accountRepos->shouldReceive('getOpeningBalance')->atLeast()->once()->andReturn($journal);
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput(sprintf('Account #%d ("%s") now has a correct currency for opening balance.', $account->id, $account->name))
->assertExitCode(0);
// check if currency has been changed for the journal + transactions.
$this->assertCount(1, TransactionJournal::where('id', $journal->id)->where('transaction_currency_id', 2)->get());
$this->assertCount(2, Transaction::where('transaction_journal_id', $journal->id)->where('transaction_currency_id', 2)->get());
}
/**
* Perfect run with opening balance.
*
* TODO this method crashes some times but not sure why.
* 2019-07-27 should be fixed.
*
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleOpeningBalance(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = 'EUR';
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$journal = $this->getRandomWithdrawal();
$euro = $this->getEuro();
$journal->transaction_currency_id = $euro->id;
$journal->save();
$journal->refresh();
$account = $this->getRandomAsset();
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturn('1');
$accountRepos->shouldReceive('getOpeningBalance')->atLeast()->once()->andReturn($journal);
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput('All accounts are OK.')
->assertExitCode(0);
// nothing changed, dont check output.
}
/**
* Perfect run with opening balance with different currencies
*
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleDifferent(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = 'USD';
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$journal = $this->getRandomWithdrawal();
$account = $this->getRandomAsset();
$euro = $this->getEuro();
$journal->transaction_currency_id = $euro->id;
$journal->save();
// delete meta data of account just in case:
AccountMeta::where('account_id', $account->id)->where('name', 'currency_id')->forceDelete();
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturn('0');
$accountRepos->shouldReceive('getOpeningBalance')->atLeast()->once()->andReturn($journal);
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput(sprintf('Account #%d ("%s") now has a currency setting (#%d).', $account->id, $account->name, $euro->id))
->assertExitCode(0);
// verify account meta data change.
$this->assertCount(1,
AccountMeta::where('account_id', $account->id)
->where('name', 'currency_id')
->where('data', $euro->id)->get());
}
/**
* No known currency preferences.
*
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleZeroPreference(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = 'EUR';
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$account = $this->getRandomAsset();
$euro = $this->getEuro();
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturn('0');
$accountRepos->shouldReceive('getOpeningBalance')->atLeast()->once()->andReturn(null);
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput(sprintf('Account #%d ("%s") now has a currency setting (%s).',
$account->id, $account->name, $euro->code
))
->expectsOutput('Corrected 1 account(s).')
->assertExitCode(0);
$this->assertCount(1, AccountMeta::where('account_id', $account->id)
->where('name', 'currency_id')
->where('data', $euro->id)->get());
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleNoPreference(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = false;
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$account = $this->getRandomAsset();
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturn('1');
$accountRepos->shouldReceive('getOpeningBalance')->atLeast()->once()->andReturn(null);
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput('All accounts are OK.')
->assertExitCode(0);
// nothing changed, so nothing to verify.
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleInvalidPreference(): void
{
$false = new Configuration;
$false->data = false;
$pref = new Preference;
$pref->data = 'ABC';
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$account = $this->getRandomAsset();
// mock calls
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getAccountsByType')->atLeast()->once()->andReturn(new Collection([$account]));
$userRepos->shouldReceive('all')->atLeast()->once()->andReturn(new Collection([$this->user()]));
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput('User has a preference for "ABC", but this currency does not exist.')
->assertExitCode(0);
// nothing changed, so nothing to verify.
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\AccountCurrencies
*/
public function testHandleAlreadyExecuted(): void
{
$true = new Configuration;
$true->data = true;
$pref = new Preference;
$pref->data = 'EUR';
$this->mock(AccountRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_account_currencies', false])->andReturn($true);
FireflyConfig::shouldReceive('set')->withArgs(['480_account_currencies', true]);
// check preferences:
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'currencyPreference', 'EUR'])->andReturn($pref);
$this->artisan('firefly-iii:account-currencies')
->expectsOutput('This command has already been executed.')
->assertExitCode(0);
// nothing changed, so nothing to verify.
}
}

View File

@@ -1,253 +0,0 @@
<?php
/**
* BackToJournalsTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Transaction;
use Log;
use Tests\TestCase;
/**
* Class BackToJournalsTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BackToJournalsTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Perfect run. Will report on nothing.
*
* @covers \FireflyIII\Console\Commands\Upgrade\BackToJournals
*/
public function testHandle(): void
{
// verify preference:
$false = new Configuration;
$false->data = false;
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs(['480_back_to_journals', false])->andReturn($false);
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($true);
// set new preference after running:
FireflyConfig::shouldReceive('set')->withArgs(['480_back_to_journals', true]);
$this->artisan('firefly-iii:back-to-journals')
->expectsOutput('Check 0 transaction journal(s) for budget info.')
->expectsOutput('Check 0 transaction journal(s) for category info.')
->assertExitCode(0);
}
/**
* Transaction has a budget, journal doesn't.
*
* @covers \FireflyIII\Console\Commands\Upgrade\BackToJournals
*/
public function testHandleBudget(): void
{
$journal = $this->getRandomWithdrawal();
/** @var Transaction $transaction */
$transaction = $journal->transactions()->first();
/** @var Budget $budget */
$budget = $this->user()->budgets()->first();
$transaction->budgets()->sync([$budget->id]);
$journal->budgets()->sync([]);
$journal->save();
$transaction->save();
// verify preference:
$false = new Configuration;
$false->data = false;
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs(['480_back_to_journals', false])->andReturn($false);
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($true);
// set new preference after running:
FireflyConfig::shouldReceive('set')->withArgs(['480_back_to_journals', true]);
$this->artisan('firefly-iii:back-to-journals')
->expectsOutput('Check 1 transaction journal(s) for budget info.')
->expectsOutput('Check 0 transaction journal(s) for category info.')
->assertExitCode(0);
// transaction should have no budget:
$this->assertEquals(0, $transaction->budgets()->count());
// journal should have one.
$this->assertEquals(1, $journal->budgets()->count());
// should be $budget:
$this->assertEquals($budget->id, $journal->budgets()->first()->id);
}
/**
* Transaction has a category, journal doesn't.
*
* @covers \FireflyIII\Console\Commands\Upgrade\BackToJournals
*/
public function testHandleCategory(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$journal = $this->getRandomWithdrawal();
/** @var Transaction $transaction */
$transaction = $journal->transactions()->first();
/** @var Category $category */
$category = $this->user()->categories()->first();
$transaction->categories()->sync([$category->id]);
$journal->categories()->sync([]);
$journal->save();
$transaction->save();
// verify preference:
$false = new Configuration;
$false->data = false;
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs(['480_back_to_journals', false])->andReturn($false);
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($true);
// set new preference after running:
FireflyConfig::shouldReceive('set')->withArgs(['480_back_to_journals', true]);
$this->artisan('firefly-iii:back-to-journals')
->expectsOutput('Check 0 transaction journal(s) for budget info.')
->expectsOutput('Check 1 transaction journal(s) for category info.')
->assertExitCode(0);
// transaction should have no category:
$this->assertEquals(0, $transaction->categories()->count());
// journal should have one.
$this->assertEquals(1, $journal->categories()->count());
// should be $category:
$this->assertEquals($category->id, $journal->categories()->first()->id);
}
/**
* Transaction has a budget, journal has another
*
* @covers \FireflyIII\Console\Commands\Upgrade\BackToJournals
*/
public function testHandleDifferentBudget(): void
{
$journal = $this->getRandomWithdrawal();
/** @var Transaction $transaction */
$transaction = $journal->transactions()->first();
/** @var Budget $budget */
$budget = $this->user()->budgets()->first();
$otherBudget = $this->user()->budgets()->where('id', '!=', $budget->id)->first();
$transaction->budgets()->sync([$budget->id]);
$journal->budgets()->sync([$otherBudget->id]);
$journal->save();
$transaction->save();
// verify preference:
$false = new Configuration;
$false->data = false;
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs(['480_back_to_journals', false])->andReturn($false);
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($true);
// set new preference after running:
FireflyConfig::shouldReceive('set')->withArgs(['480_back_to_journals', true]);
$this->artisan('firefly-iii:back-to-journals')
->expectsOutput('Check 1 transaction journal(s) for budget info.')
->expectsOutput('Check 0 transaction journal(s) for category info.')
->assertExitCode(0);
// transaction should have no budget:
$this->assertEquals(0, $transaction->budgets()->count());
// journal should have one.
$this->assertEquals(1, $journal->budgets()->count());
// should be $budget:
$this->assertEquals($budget->id, $journal->budgets()->first()->id);
}
/**
* Transaction has a category, journal has another
*
* @covers \FireflyIII\Console\Commands\Upgrade\BackToJournals
*/
public function testHandleDifferentCategory(): void
{
$journal = $this->getRandomWithdrawal();
/** @var Transaction $transaction */
$transaction = $journal->transactions()->first();
/** @var Category $category */
$category = $this->user()->categories()->first();
$otherCategory = $this->user()->categories()->where('id', '!=', $category->id)->first();
$transaction->categories()->sync([$category->id]);
$journal->categories()->sync([$otherCategory->id]);
$journal->save();
$transaction->save();
// verify preference:
$false = new Configuration;
$false->data = false;
$true = new Configuration;
$true->data = true;
FireflyConfig::shouldReceive('get')->withArgs(['480_back_to_journals', false])->andReturn($false);
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($true);
// set new preference after running:
FireflyConfig::shouldReceive('set')->withArgs(['480_back_to_journals', true]);
$this->artisan('firefly-iii:back-to-journals')
->expectsOutput('Check 0 transaction journal(s) for budget info.')
->expectsOutput('Check 1 transaction journal(s) for category info.')
->assertExitCode(0);
// transaction should have no category:
$this->assertEquals(0, $transaction->categories()->count());
// journal should have one.
$this->assertEquals(1, $journal->categories()->count());
// should be $category:
$this->assertEquals($category->id, $journal->categories()->first()->id);
}
}

View File

@@ -1,105 +0,0 @@
<?php
/**
* BudgetLimitCurrencyTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use Amount;
use FireflyConfig;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\Configuration;
use Log;
use Tests\TestCase;
/**
* Class BudgetLimitCurrencyTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BudgetLimitCurrencyTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\BudgetLimitCurrency
*/
public function testHandle(): void
{
BudgetLimit::whereNull('transaction_currency_id')->forceDelete();
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_bl_currency', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_bl_currency', true]);
$this->artisan('firefly-iii:bl-currency')
->expectsOutput('All budget limits are correct.')
->assertExitCode(0);
}
/**
* Create a bad budget limit.
* @covers \FireflyIII\Console\Commands\Upgrade\BudgetLimitCurrency
*/
public function testHandleBadLimit(): void
{
$false = new Configuration;
$false->data = false;
$budget = $this->user()->budgets()->first();
$limit = BudgetLimit::create(
[
'budget_id' => $budget->id,
'amount' => '10',
'start_date' => '2019-01-01',
'end_date' => '2019-01-31',
]);
FireflyConfig::shouldReceive('get')->withArgs(['480_bl_currency', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_bl_currency', true]);
$currency = $this->getEuro();
Amount::shouldReceive('getDefaultCurrencyByUser')->atLeast()->once()->andReturn($currency);
$this->artisan('firefly-iii:bl-currency')
->expectsOutput(
sprintf('Budget limit #%d (part of budget "%s") now has a currency setting (%s).',
$limit->id, $budget->name, 'Euro'
)
)
->assertExitCode(0);
// assume currency is filled in.
$this->assertCount(1, BudgetLimit::where('id', $limit->id)->where('transaction_currency_id', 1)->get());
}
}

View File

@@ -1,137 +0,0 @@
<?php
/**
* CCLiabilitiesTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Configuration;
use Log;
use Tests\TestCase;
/**
* Class CCLiabilitiesTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CCLiabilitiesTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\CCLiabilities
*/
public function testHandle(): void
{
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_cc_liabilities', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_cc_liabilities', true]);
$this->artisan('firefly-iii:cc-liabilities')
->expectsOutput('No incorrectly stored credit card liabilities.')
->assertExitCode(0);
// nothing changed, so nothing to verify.
}
/**
* Add type to make the script run.
*
* @covers \FireflyIII\Console\Commands\Upgrade\CCLiabilities
*/
public function testHandleEmpty(): void
{
$type = AccountType::create(
[
'type' => AccountType::CREDITCARD,
]
);
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_cc_liabilities', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_cc_liabilities', true]);
$this->artisan('firefly-iii:cc-liabilities')
->expectsOutput('No incorrectly stored credit card liabilities.')
->assertExitCode(0);
$type->forceDelete();
// nothing changed, so nothing to verify.
}
/**
* Add some things to make it trigger.
*
* @covers \FireflyIII\Console\Commands\Upgrade\CCLiabilities
*/
public function testHandleCase(): void
{
$type = AccountType::create(
[
'type' => AccountType::CREDITCARD,
]
);
$account = Account::create(
[
'name' => 'CC',
'user_id' => 1,
'account_type_id' => $type->id,
]
);
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_cc_liabilities', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_cc_liabilities', true]);
$this->artisan('firefly-iii:cc-liabilities')
->expectsOutput(sprintf('Converted credit card liability account "%s" (#%d) to generic debt liability.', $account->name, $account->id))
->expectsOutput('Credit card liability types are no longer supported and have been converted to generic debts. See: http://bit.ly/FF3-credit-cards')
->assertExitCode(0);
// verify new type.
$this->assertCount(0, Account::where('id', $account->id)->where('account_type_id', $type->id)->get());
$account->forceDelete();
$type->forceDelete();
}
}

View File

@@ -1,104 +0,0 @@
<?php
/**
* MigrateAttachmentsTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Attachment;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Note;
use FireflyIII\Models\TransactionJournal;
use Log;
use Tests\TestCase;
/**
* Class MigrateAttachmentsTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class MigrateAttachmentsTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateAttachments
*/
public function testHandle(): void
{
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrate_attachments', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrate_attachments', true]);
// assume all is well.
$this->artisan('firefly-iii:migrate-attachments')
->expectsOutput('All attachments are OK.')
->assertExitCode(0);
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateAttachments
*/
public function testHandleMigrate(): void
{
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrate_attachments', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrate_attachments', true]);
$attachment = Attachment::create(
[
'user_id' => 1,
'attachable_id' => 1,
'attachable_type' => TransactionJournal::class,
'description' => 'Hello',
'md5' => md5('hello'),
'filename' => 'test.pdf',
'mime' => 'text/plain',
'size' => 1,
]);
// assume all is well.
$this->artisan('firefly-iii:migrate-attachments')
->expectsOutput('Updated 1 attachment(s).')
->assertExitCode(0);
$this->assertCount(0, Attachment::where('id', $attachment->id)->where('description', '!=', '')->get());
$this->assertCount(1, Attachment::where('id', $attachment->id)->where('description', '=', '')->get());
$this->assertCount(1, Note::where('noteable_id', $attachment->id)->where('noteable_type', Attachment::class)->get());
$attachment->forceDelete();
}
}

View File

@@ -1,106 +0,0 @@
<?php
/**
* MigrateJournalNotesTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\TransactionJournalMeta;
use Log;
use Tests\TestCase;
/**
* Class MigrateJournalNotesTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class MigrateJournalNotesTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateJournalNotes
*/
public function testHandle(): void
{
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrate_notes', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrate_notes', true]);
// assume all is well.
$this->artisan('firefly-iii:migrate-notes')
->expectsOutput('No notes to migrate.')
->assertExitCode(0);
}
/**
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateJournalNotes
*/
public function testHandleNote(): void
{
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrate_notes', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrate_notes', true]);
$journal = $this->getRandomWithdrawal();
// delete any notes the journal may have already:
$journal->notes()->forceDelete();
$meta = TransactionJournalMeta::create(
[
'transaction_journal_id' => $journal->id,
'name' => 'notes',
'data' => json_encode('Some note.'),
'hash' => 'Some hash',
]
);
// assume one is fixed.
$this->artisan('firefly-iii:migrate-notes')
->expectsOutput('Migrated 1 note(s).')
->assertExitCode(0);
$this->assertCount(0, TransactionJournalMeta
::where('name', 'notes')
->where('id', $meta->id)
->whereNull('deleted_at')
->get());
}
}

View File

@@ -1,264 +0,0 @@
<?php
/**
* MigrateToGroupsTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Factory\TransactionGroupFactory;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Services\Internal\Destroy\JournalDestroyService;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class MigrateToGroupsTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class MigrateToGroupsTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic test. Assume nothing is wrong.
*
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateToGroups
*/
public function testHandle(): void
{
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$service = $this->mock(JournalDestroyService::class);
$groupFactory = $this->mock(TransactionGroupFactory::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
// mock calls:
$cliRepos->shouldReceive('getSplitJournals')
->atLeast()->once()
->andReturn(new Collection);
$cliRepos->shouldReceive('getJournalsWithoutGroup')
->atLeast()->once()
->andReturn([]);
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrated_to_groups', true]);
// assume all is well.
$this->artisan('firefly-iii:migrate-to-groups')
->expectsOutput('No journals to migrate to groups.')
->assertExitCode(0);
}
/**
* Return a journal without a group.
*
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateToGroups
*/
public function testHandleNoGroup(): void
{
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$service = $this->mock(JournalDestroyService::class);
$groupFactory = $this->mock(TransactionGroupFactory::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$journal = TransactionJournal::create(
[
'user_id' => 1,
'transaction_currency_id' => 1,
'transaction_type_id' => 1,
'description' => 'Test',
'tag_count' => 0,
'date' => '2019-01-01',
]
);
$one = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-10',
'identifier' => 1,
]
);
$two = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $expense->id,
'amount' => '10',
'identifier' => 1,
]
);
$array = $journal->toArray();
// mock calls:
$cliRepos->shouldReceive('getSplitJournals')
->atLeast()->once()
->andReturn(new Collection);
$cliRepos->shouldReceive('getJournalsWithoutGroup')
->atLeast()->once()
->andReturn([$array]);
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrated_to_groups', true]);
// assume all is well.
$this->artisan('firefly-iii:migrate-to-groups')
->expectsOutput('Migrated 1 transaction journal(s).')
->assertExitCode(0);
// no longer without a group.
$this->assertCount(0, TransactionJournal::where('id', $journal->id)->whereNull('transaction_group_id')->get());
$journal->transactionGroup()->forceDelete();
$one->forceDelete();
$two->forceDelete();
$journal->forceDelete();
}
/**
* Create split withdrawal and see what the system will do.
*
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateToGroups
*/
public function testHandleSplitJournal(): void
{
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$group = $this->getRandomWithdrawalGroup();
$journal = TransactionJournal::create(
[
'user_id' => 1,
'transaction_currency_id' => 1,
'transaction_type_id' => 1,
'description' => 'Test',
'tag_count' => 0,
'date' => '2019-01-01',
]
);
$one = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-10',
'identifier' => 1,
]
);
$two = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $expense->id,
'amount' => '10',
'identifier' => 1,
]
);
$three = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-12',
'identifier' => 2,
]
);
$four = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $expense->id,
'amount' => '12',
'identifier' => 2,
]
);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$service = $this->mock(JournalDestroyService::class);
$factory = $this->mock(TransactionGroupFactory::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
// mock calls:
$cliRepos->shouldReceive('setUser')->atLeast()->once();
$journalRepos->shouldReceive('setUser')->atLeast()->once();
// mock journal things:
$cliRepos->shouldReceive('getJournalBudgetId')->atLeast()->once()->andReturn(0);
$cliRepos->shouldReceive('getJournalCategoryId')->atLeast()->once()->andReturn(0);
$cliRepos->shouldReceive('getNoteText')->atLeast()->once()->andReturn('Some note.');
$cliRepos->shouldReceive('getTags')->atLeast()->once()->andReturn(['A', 'B']);
$cliRepos->shouldReceive('getMetaField')->atLeast()
->withArgs([Mockery::any(), Mockery::any()])
->once()->andReturn(null);
$cliRepos->shouldReceive('getMetaDate')->atLeast()
->withArgs([Mockery::any(), Mockery::any()])
->once()->andReturn(null);
// create a group
$factory->shouldReceive('create')->atLeast()->once()->andReturn($group);
$service->shouldReceive('destroy')->atLeast()->once();
$factory->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('getSplitJournals')
->atLeast()->once()
->andReturn(new Collection([$journal]));
$cliRepos->shouldReceive('getJournalsWithoutGroup')
->atLeast()->once()
->andReturn([]);
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_migrated_to_groups', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_migrated_to_groups', true]);
$this->artisan('firefly-iii:migrate-to-groups')
->expectsOutput('Migrated 1 transaction journal(s).')
->assertExitCode(0);
// delete the created stuff:
$one->forceDelete();
$two->forceDelete();
$three->forceDelete();
$four->forceDelete();
$journal->forceDelete();
// the calls above let me know it's OK.
}
}

View File

@@ -1,330 +0,0 @@
<?php
/**
* MigrateToRulesTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class MigrateToRulesTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class MigrateToRulesTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic test. Assume nothing is wrong.
*
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateToRules
*/
public function testHandle(): void
{
// mock repositories:
$userRepository = $this->mock(UserRepositoryInterface::class);
$ruleGroupRepository = $this->mock(RuleGroupRepositoryInterface::class);
$billRepository = $this->mock(BillRepositoryInterface::class);
$ruleRepository = $this->mock(RuleRepositoryInterface::class);
$group = $this->user()->ruleGroups()->inRandomOrder()->first();
$bill = $this->user()->bills()->inRandomOrder()->first();
// mock all calls.
$userRepository->shouldReceive('all')->atLeast()->once()
->andReturn(new Collection([$this->user()]));
$ruleRepository->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepository->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepository->shouldReceive('findByTitle')
->withArgs(['Rule group for bills'])->atLeast()->once()->andReturnNull();
// rule group repos should try to store a rule group in response to the result above.
$ruleGroupRepository->shouldReceive('store')->atLeast()->once()->andReturn($group);
// bill repos should return one rule.
$billRepository->shouldReceive('setUser')->atLeast()->once();
$billRepository->shouldReceive('getBills')->atLeast()->once()
->andReturn(new Collection([$bill]));
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_bills_to_rules', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_bills_to_rules', true]);
// preferences
$language = new Preference;
$language->data = 'en_US';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'language', 'en_US'])->andReturn($language);
// assume all is well.
$this->artisan('firefly-iii:bills-to-rules')
->expectsOutput('All bills are OK.')
->assertExitCode(0);
}
/**
* Basic test. Give command an unmigrated bill. This bill has the same amount_min
* as amount_max
*
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateToRules
*/
public function testHandleEvenBill(): void
{
$billName = 'I am a bill #' . $this->randomInt();
$bill = Bill::create(
[
'user_id' => $this->user()->id,
'transaction_currency_id' => null,
'name' => $billName,
'match' => 'some,kind,of,match',
'amount_min' => '30',
'amount_max' => '30',
'date' => '2019-01-01',
'repeat_freq' => 'monthly',
]
);
// mock repositories:
$userRepository = $this->mock(UserRepositoryInterface::class);
$ruleGroupRepository = $this->mock(RuleGroupRepositoryInterface::class);
$billRepository = $this->mock(BillRepositoryInterface::class);
$ruleRepository = $this->mock(RuleRepositoryInterface::class);
$group = $this->user()->ruleGroups()->inRandomOrder()->first();
// mock all calls.
$userRepository->shouldReceive('all')->atLeast()->once()
->andReturn(new Collection([$this->user()]));
$ruleRepository->shouldReceive('setUser')->atLeast()->once();
// this is what rule repos should receive:
$argumentRule = [
'rule_group_id' => $group->id,
'active' => true,
'strict' => false,
'stop_processing' => false, // field is no longer used.
'title' => sprintf('Auto-generated rule for bill "%s"', $billName),
'description' => sprintf('This rule is auto-generated to try to match bill "%s".', $billName),
'trigger' => 'store-journal',
'triggers' => [
[
'type' => 'description_contains',
'value' => 'some kind of match',
],
[
'type' => 'amount_exactly',
'value' => $bill->amount_min,
],
],
'actions' => [
[
'type' => 'link_to_bill',
'value' => $bill->name,
],
],
];
// this is what the bill repos should receive:
$argumentBill = [
'currency_id' => $bill->transaction_currency_id,
'name' => $bill->name,
'match' => 'MIGRATED_TO_RULES',
'amount_min' => $bill->amount_min,
'amount_max' => $bill->amount_max,
'date' => $bill->date,
'repeat_freq' => $bill->repeat_freq,
'skip' => $bill->skip,
'active' => $bill->active,
];
$ruleRepository->shouldReceive('store')->atLeast()->once()->withArgs([$argumentRule]);
// rule group repos should try to store a rule group in response to the result above.
$ruleGroupRepository->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepository->shouldReceive('findByTitle')
->withArgs(['Rule group for bills'])->atLeast()->once()->andReturnNull();
$ruleGroupRepository->shouldReceive('store')->atLeast()->once()->andReturn($group);
// bill repos should return one rule.
$billRepository->shouldReceive('setUser')->atLeast()->once();
$billRepository->shouldReceive('getBills')->atLeast()->once()
->andReturn(new Collection([$bill]));
$billRepository->shouldReceive('update')->atLeast()->once()
->withArgs([Mockery::any(), $argumentBill]);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_bills_to_rules', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_bills_to_rules', true]);
// preferences
$language = new Preference;
$language->data = 'en_US';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'language', 'en_US'])->andReturn($language);
// assume all is well.
$this->artisan('firefly-iii:bills-to-rules')
->expectsOutput('Verified and fixed 1 bill(s).')
->assertExitCode(0);
}
/**
* Basic test. Give command an unmigrated bill. This bill has a different amount_min
* from the amount_max
*
* @covers \FireflyIII\Console\Commands\Upgrade\MigrateToRules
*/
public function testHandleUnevenBill(): void
{
$billName = 'I am a bill #' . $this->randomInt();
$bill = Bill::create(
[
'user_id' => $this->user()->id,
'transaction_currency_id' => null,
'name' => $billName,
'match' => 'some,kind,of,match',
'amount_min' => '30',
'amount_max' => '40',
'date' => '2019-01-01',
'repeat_freq' => 'monthly',
]
);
// mock repositories:
$userRepository = $this->mock(UserRepositoryInterface::class);
$ruleGroupRepository = $this->mock(RuleGroupRepositoryInterface::class);
$billRepository = $this->mock(BillRepositoryInterface::class);
$ruleRepository = $this->mock(RuleRepositoryInterface::class);
$group = $this->user()->ruleGroups()->inRandomOrder()->first();
// mock all calls.
$userRepository->shouldReceive('all')->atLeast()->once()
->andReturn(new Collection([$this->user()]));
$ruleRepository->shouldReceive('setUser')->atLeast()->once();
// this is what rule repos should receive:
$argumentRule = [
'rule_group_id' => $group->id,
'active' => true,
'strict' => false,
'stop_processing' => false, // field is no longer used.
'title' => sprintf('Auto-generated rule for bill "%s"', $billName),
'description' => sprintf('This rule is auto-generated to try to match bill "%s".', $billName),
'trigger' => 'store-journal',
'triggers' => [
[
'type' => 'description_contains',
'value' => 'some kind of match',
],
[
'type' => 'amount_less',
'value' => $bill->amount_max,
],
[
'type' => 'amount_more',
'value' => $bill->amount_min,
],
],
'actions' => [
[
'type' => 'link_to_bill',
'value' => $bill->name,
],
],
];
// this is what the bill repos should receive:
$argumentBill = [
'currency_id' => $bill->transaction_currency_id,
'name' => $bill->name,
'match' => 'MIGRATED_TO_RULES',
'amount_min' => $bill->amount_min,
'amount_max' => $bill->amount_max,
'date' => $bill->date,
'repeat_freq' => $bill->repeat_freq,
'skip' => $bill->skip,
'active' => $bill->active,
];
$ruleRepository->shouldReceive('store')->atLeast()->once()->withArgs([$argumentRule]);
// rule group repos should try to store a rule group in response to the result above.
$ruleGroupRepository->shouldReceive('setUser')->atLeast()->once();
$ruleGroupRepository->shouldReceive('findByTitle')
->withArgs(['Rule group for bills'])->atLeast()->once()->andReturnNull();
$ruleGroupRepository->shouldReceive('store')->atLeast()->once()->andReturn($group);
// bill repos should return one rule.
$billRepository->shouldReceive('setUser')->atLeast()->once();
$billRepository->shouldReceive('getBills')->atLeast()->once()
->andReturn(new Collection([$bill]));
$billRepository->shouldReceive('update')->atLeast()->once()
->withArgs([Mockery::any(), $argumentBill]);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_bills_to_rules', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_bills_to_rules', true]);
// preferences
$language = new Preference;
$language->data = 'en_US';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'language', 'en_US'])->andReturn($language);
// assume all is well.
$this->artisan('firefly-iii:bills-to-rules')
->expectsOutput('Verified and fixed 1 bill(s).')
->assertExitCode(0);
}
}

View File

@@ -1,277 +0,0 @@
<?php
/**
* OtherCurrenciesCorrectionsTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Tests\TestCase;
/**
* Class OtherCurrenciesCorrectionsTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class OtherCurrenciesCorrectionsTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic test. Assume nothing is wrong. Submit a withdrawal and a deposit.
*
* @covers \FireflyIII\Console\Commands\Upgrade\OtherCurrenciesCorrections
*/
public function testHandle(): void
{
// mock classes:
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$withdrawal = $this->getRandomWithdrawal();
$deposit = $this->getRandomDeposit();
$euro = $this->getEuro();
// collect all journals:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('getAllJournals')
->atLeast()->once()
->withArgs([[TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION,]])
->andReturn(new Collection([$withdrawal, $deposit]));
// account repos
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
#$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()
# ->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
// collect currency
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
#$currencyRepos->shouldReceive('findNull')->atLeast()->once()
# ->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_other_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_other_currencies', true]);
// assume all is well.
$this->artisan('firefly-iii:other-currencies')
->expectsOutput('Verified 2 transaction(s) and journal(s).')
->assertExitCode(0);
}
/**
* Basic test. Assume nothing is wrong. Submit an opening balance.
* Also fixes transaction currency ID.
*
* @covers \FireflyIII\Console\Commands\Upgrade\OtherCurrenciesCorrections
*/
public function testHandleOB(): void
{
$type = TransactionType::where('type', TransactionType::OPENING_BALANCE)->first();
$asset = $this->getRandomAsset();
$initial = $this->getRandomInitialBalance();
$journal = TransactionJournal::create(
[
'user_id' => 1,
'transaction_currency_id' => 1,
'transaction_type_id' => $type->id,
'description' => 'Test',
'tag_count' => 0,
'date' => '2019-01-01',
]
);
$one = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-10',
'identifier' => 1,
]
);
$two = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $initial->id,
'amount' => '10',
'identifier' => 1,
]
);
// mock classes:
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$euro = $this->getEuro();
// collect all journals:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('getAllJournals')
->atLeast()->once()
->withArgs([[TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION,]])
->andReturn(new Collection([$journal]));
// account repos
$accountRepos->shouldReceive('setUser')->atLeast()->once();
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
// collect currency
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
#$currencyRepos->shouldReceive('findNull')->atLeast()->once()
# ->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_other_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_other_currencies', true]);
$this->artisan('firefly-iii:other-currencies')
->expectsOutput('Verified 1 transaction(s) and journal(s).')
->assertExitCode(0);
// assume currency has been fixed for both transactions:
$this->assertCount(1, Transaction::where('id', $one->id)->where('transaction_currency_id', $euro->id)->get());
$this->assertCount(1, Transaction::where('id', $two->id)->where('transaction_currency_id', $euro->id)->get());
$one->forceDelete();
$two->forceDelete();
$journal->forceDelete();
}
/**
* Basic test. Assume nothing is wrong. Submit an opening balance.
* Also fixes bad transaction currency ID.
*
* @covers \FireflyIII\Console\Commands\Upgrade\OtherCurrenciesCorrections
*/
public function testHandleReconciliation(): void
{
$type = TransactionType::where('type', TransactionType::RECONCILIATION)->first();
$asset = $this->getRandomAsset();
$reconciliation = $this->getRandomReconciliation();
$journal = TransactionJournal::create(
[
'user_id' => 1,
'transaction_currency_id' => 1,
'transaction_type_id' => $type->id,
'description' => 'Test',
'tag_count' => 0,
'date' => '2019-01-01',
]
);
$one = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-10',
'identifier' => 1,
'transaction_currency_id' => 2,
]
);
$two = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $reconciliation->id,
'amount' => '10',
'identifier' => 1,
'transaction_currency_id' => 2,
]
);
// mock classes:
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$euro = $this->getEuro();
// collect all journals:
$journalRepos->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('setUser')->atLeast()->once();
$cliRepos->shouldReceive('getAllJournals')
->atLeast()->once()
->withArgs([[TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION,]])
->andReturn(new Collection([$journal]));
// account repos
$accountRepos->shouldReceive('setUser')->atLeast()->once();
#$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()
# ->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
// collect currency
$currencyRepos->shouldReceive('setUser')->atLeast()->once();
#$currencyRepos->shouldReceive('findNull')->atLeast()->once()
# ->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_other_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_other_currencies', true]);
$this->artisan('firefly-iii:other-currencies')
->expectsOutput('Verified 1 transaction(s) and journal(s).')
->assertExitCode(0);
// assume currency has been fixed for both transactions:
$this->assertCount(1, Transaction::where('id', $one->id)->where('transaction_currency_id', $euro->id)->get());
$this->assertCount(1, Transaction::where('id', $two->id)->where('transaction_currency_id', $euro->id)->get());
$this->assertCount(1, Transaction::where('id', $one->id)->where('foreign_currency_id', 2)->get());
$this->assertCount(1, Transaction::where('id', $two->id)->where('foreign_currency_id', 2)->get());
$one->forceDelete();
$two->forceDelete();
$journal->forceDelete();
}
}

View File

@@ -1,108 +0,0 @@
<?php
/**
* RenameAccountMetaTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\AccountMeta;
use FireflyIII\Models\Configuration;
use Log;
use Tests\TestCase;
/**
* Class RenameAccountMetaTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class RenameAccountMetaTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic test. Assume nothing is wrong.
*
* @covers \FireflyIII\Console\Commands\Upgrade\RenameAccountMeta
*/
public function testHandle(): void
{
$false = new Configuration;
$false->data = false;
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_rename_account_meta', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_rename_account_meta', true]);
// assume all is well.
$this->artisan('firefly-iii:rename-account-meta')
->expectsOutput('All account meta is OK.')
->assertExitCode(0);
}
/**
* Create bad entry, then check if its renamed.
*
* @covers \FireflyIII\Console\Commands\Upgrade\RenameAccountMeta
*/
public function testHandleRename(): void
{
$false = new Configuration;
$false->data = false;
// check config
FireflyConfig::shouldReceive('get')->withArgs(['480_rename_account_meta', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_rename_account_meta', true]);
$expense = $this->getRandomExpense();
$meta = AccountMeta::create(
[
'name' => 'accountRole',
'data' => 'defaultAsset',
'account_id' => $expense->id,
]
);
// assume all is well.
$this->artisan('firefly-iii:rename-account-meta')
->expectsOutput('Renamed 1 account meta entries (entry).')
->assertExitCode(0);
$this->assertCount(0, AccountMeta::where('id', $meta->id)->where('name', 'accountRole')->get());
$this->assertCount(1, AccountMeta::where('id', $meta->id)->where('name', 'account_role')->get());
$meta->forceDelete();
}
}

View File

@@ -1,161 +0,0 @@
<?php
/**
* TransactionIdentifierTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Tests\TestCase;
/**
* Class TransactionIdentifierTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TransactionIdentifierTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic test. Assume nothing is wrong.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransactionIdentifier
*/
public function testHandle(): void
{
// mock classes:
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
// commands:
$cliRepos->shouldReceive('getSplitJournals')->andReturn(new Collection)
->atLeast()->once();
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transaction_identifier', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transaction_identifier', true]);
// assume all is well.
$this->artisan('firefly-iii:transaction-identifiers')
->expectsOutput('All split journal transaction identifiers are correct.')
->assertExitCode(0);
}
/**
* Basic test. Assume nothing is wrong.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransactionIdentifier
*/
public function testHandleSplit(): void
{
// create a split journal:
$asset = $this->getRandomAsset();
$expense = $this->getRandomExpense();
$journal = TransactionJournal::create(
[
'user_id' => 1,
'transaction_currency_id' => 1,
'transaction_type_id' => 1,
'description' => 'Test',
'tag_count' => 0,
'date' => '2019-01-01',
]
);
$one = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-10',
'identifier' => 0,
]
);
$two = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $expense->id,
'amount' => '10',
'identifier' => 0,
]
);
$three = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $asset->id,
'amount' => '-12',
'identifier' => 0,
]
);
$four = Transaction::create(
[
'transaction_journal_id' => $journal->id,
'account_id' => $expense->id,
'amount' => '12',
'identifier' => 0,
]
);
// mock classes:
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
// commands:
$cliRepos->shouldReceive('getSplitJournals')->andReturn(new Collection([$journal]))
->atLeast()->once();
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transaction_identifier', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transaction_identifier', true]);
// assume all is well.
$this->artisan('firefly-iii:transaction-identifiers')
->expectsOutput('Fixed 2 split journal transaction identifier(s).')
->assertExitCode(0);
// see results:
$this->assertCount(1, Transaction::where('id', $one->id)->where('identifier', 0)->get());
$this->assertCount(1, Transaction::where('id', $three->id)->where('identifier', 1)->get());
}
}

View File

@@ -1,562 +0,0 @@
<?php
/**
* TransferCurrenciesCorrectionsTest.php
* Copyright (c) 2019 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\Feature\Console\Commands\Upgrade;
use FireflyConfig;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class TransferCurrenciesCorrectionsTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TransferCurrenciesCorrectionsTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Basic test. Assume nothing is wrong.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandle(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
// assume all is well.
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('All transfers have correct currency information.')
->assertExitCode(0);
}
/**
* Basic test. Assume the transfer is OK.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleCorrectTransfer(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
#$accountRepos->shouldReceive('getMetaValue')
# ->atLeast()->once()
# ->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
// currency repos
#$currencyRepos->shouldReceive('findNull')
# ->atLeast()->once()
# ->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
// assume all is well.
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('All transfers have correct currency information.')
->assertExitCode(0);
}
/**
* Journal has bad currency info.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleInvalidJournalCurrency(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
$dollar = $this->getDollar();
$transfer->transaction_currency_id = $dollar->id;
$transfer->save();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
#$accountRepos->shouldReceive('getMetaValue')
# ->atLeast()->once()
# ->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
// currency repos
#$currencyRepos->shouldReceive('findNull')
# ->atLeast()->once()
# ->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0);
$this->assertCount(1, TransactionJournal::where('id', $transfer->id)->where('transaction_currency_id', 1)->get());
}
/**
* Missing source foreign amount information.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleMissingSourceForeignAmount(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
$dollar = $this->getDollar();
/** @var Transaction $destination */
$destination = $transfer->transactions()->where('amount', '>', 0)->first();
$destination->foreign_amount = '100';
$destination->save();
/** @var Transaction $destination */
$source = $transfer->transactions()->where('amount', '<', 0)->first();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([$dollar->id])->andReturn($dollar);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 2 transfer(s).')
->assertExitCode(0);
$this->assertCount(1, Transaction::where('id', $source->id)
->where('foreign_amount', '-100')->get()
);
}
/**
* Missing source foreign amount information.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleMissingDestForeignAmount(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
$dollar = $this->getDollar();
/** @var Transaction $destination */
$destination = $transfer->transactions()->where('amount', '>', 0)->first();
$destination->foreign_amount = null;
$destination->save();
/** @var Transaction $destination */
$source = $transfer->transactions()->where('amount', '<', 0)->first();
$source->foreign_amount = '-100';
$source->save();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
$accountRepos->shouldReceive('getMetaValue')
->atLeast()->once()
->withArgs([Mockery::any(), 'currency_id'])->andReturn('1', $dollar->id);
// currency repos
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([1])->andReturn($euro);
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([$dollar->id])->andReturn($dollar);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 3 transfer(s).')
->assertExitCode(0);
$this->assertCount(1, Transaction::where('id', $destination->id)
->where('foreign_amount', '100')->get()
);
}
/**
* Basic test. The foreign currency is broken and should be corrected.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleMismatchedForeignCurrency(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
$dollar = $this->getDollar();
// make sure that source and destination have the right currencies beforehand
$source = $transfer->transactions()->where('amount', '<', 0)->first();
$source->transaction_currency_id = $euro->id;
$source->save();
$dest = $transfer->transactions()->where('amount', '>', 0)->first();
$dest->transaction_currency_id = $dollar->id;
$dest->save();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
$accountRepos->shouldReceive('getMetaValue')
->atLeast()->once()
->withArgs([Mockery::any(), 'currency_id'])->andReturn('1', $dollar->id);
// currency repos
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([1])->andReturn($euro);
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([$dollar->id])->andReturn($dollar);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0);
// source and destination transaction should be corrected:
$this->assertCount(1, Transaction::where('id', $source->id)
->where('transaction_currency_id', $euro->id)
->where('foreign_currency_id', $dollar->id)
->get());
}
/**
* Basic test. Source transaction has no currency.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleTransferNoSourceCurrency(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
// get source transaction and remove currency:
/** @var Transaction $source */
$source = $transfer->transactions()->where('amount', '<', 0)->first();
$source->transaction_currency_id = null;
$source->save();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
$accountRepos->shouldReceive('getMetaValue')
->atLeast()->once()
->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
// currency repos
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0);
// assume problem is fixed:
$this->assertCount(1, Transaction::where('id', $source->id)->where('transaction_currency_id', 1)->get());
}
/**
* Basic test. Destination transaction has no currency.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleTransferNoDestCurrency(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
// get source transaction and remove currency:
/** @var Transaction $destination */
$destination = $transfer->transactions()->where('amount', '>', 0)->first();
$destination->transaction_currency_id = null;
$destination->save();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
$accountRepos->shouldReceive('getMetaValue')
->atLeast()->once()
->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
// currency repos
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0);
// assume problem is fixed:
$this->assertCount(1, Transaction::where('id', $destination->id)->where('transaction_currency_id', 1)->get());
}
/**
* Basic test. Source transaction has bad currency.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleTransferBadSourceCurrency(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
// get source transaction and remove currency:
/** @var Transaction $source */
$source = $transfer->transactions()->where('amount', '<', 0)->first();
$source->transaction_currency_id = 2;
$source->foreign_amount = null;
$source->save();
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
$accountRepos->shouldReceive('getMetaValue')
->atLeast()->once()
->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
// currency repos
$currencyRepos->shouldReceive('findNull')
->atLeast()->once()
->withArgs([1])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0);
// assume problem is fixed:
$this->assertCount(1, Transaction::where('id', $source->id)->where('transaction_currency_id', 1)->get());
}
/**
* Basic test. Source transaction has bad currency, and this must be fixed.
*
* TODO something in this test is too random, and it fails. Not sure why.
*
* @covers \FireflyIII\Console\Commands\Upgrade\TransferCurrenciesCorrections
*/
public function testHandleTransferBadDestCurrency(): void
{
Log::warning(sprintf('Now in test %s.', __METHOD__));
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$cliRepos = $this->mock(JournalCLIRepositoryInterface::class);
$transfer = $this->getRandomTransfer();
$euro = $this->getEuro();
$dollar = $this->getDollar();
// get destination transaction and remove currency:
$transfer->transaction_currency_id = $euro->id;
$transfer->save();
Log::debug(sprintf('Gave transfer #%d currency EUR', $transfer->id));
/** @var Transaction $destination */
$destination = $transfer->transactions()->where('amount', '>', 0)->first();
$destination->transaction_currency_id = $dollar->id;
$destination->save();
Log::debug(sprintf('Gave transaction #%d currency USD', $destination->id));
// mock calls:
$cliRepos->shouldReceive('getAllJournals')
->withArgs([[TransactionType::TRANSFER]])
->atLeast()->once()->andReturn(new Collection([$transfer]));
// account repos
$accountRepos->shouldReceive('getMetaValue')
->atLeast()->once()
->withArgs([Mockery::any(), 'currency_id'])->andReturn((string)$euro->id);
// currency repos
$currencyRepos->shouldReceive('findNull')->atLeast()->once()->withArgs([$euro->id])->andReturn($euro);
// configuration
$false = new Configuration;
$false->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['480_transfer_currencies', false])->andReturn($false);
FireflyConfig::shouldReceive('set')->withArgs(['480_transfer_currencies', true]);
$this->artisan('firefly-iii:transfer-currencies')
->expectsOutput('Verified currency information of 1 transfer(s).')
->assertExitCode(0);
// assume problem is fixed:
$this->assertCount(1, Transaction::where('id', $destination->id)->where('transaction_currency_id', $euro->id)->get());
}
}

View File

@@ -1,205 +0,0 @@
<?php
/**
* CreateControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class CreateControllerTest.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CreateControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Account\CreateController
*/
public function testCreate(): void
{
// mock stuff
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('get')->andReturn(new Collection);
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
// mock default calls
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_accounts_create_asset');
// get all types:
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Debt'])->andReturn(AccountType::find(11))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Loan'])->andReturn(AccountType::find(9))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Mortgage'])->andReturn(AccountType::find(12))->once();
$this->be($this->user());
$response = $this->get(route('accounts.create', ['asset']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\CreateController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testStore(): void
{
// mock stuff
$repository = $this->mock(AccountRepositoryInterface::class);
$asset = $this->getRandomAsset();
$repository->shouldReceive('store')->once()->andReturn($asset);
// mock default session stuff
$this->mockDefaultSession();
// change the preference:
$emptyPref = new Preference;
$emptyPref->data = [];
Preferences::shouldReceive('get')->atLeast()->once()->withArgs(['frontPageAccounts', []])->andReturn($emptyPref);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['frontPageAccounts', [$asset->id]]);
Preferences::shouldReceive('mark')->atLeast()->once()->withNoArgs();
$this->session(['accounts.create.uri' => 'http://localhost/x']);
$this->be($this->user());
$data = [
'name' => 'new account ' . $this->randomInt(),
'objectType' => 'asset',
];
$response = $this->post(route('accounts.store', ['asset']), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect('http://localhost/x');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\CreateController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testStoreAnother(): void
{
// mock stuff
$repository = $this->mock(AccountRepositoryInterface::class);
$asset = $this->getRandomAsset();
$repository->shouldReceive('store')->once()->andReturn($asset);
// change the preference:
$emptyPref = new Preference;
$emptyPref->data = [];
Preferences::shouldReceive('get')->atLeast()->once()->withArgs(['frontPageAccounts', []])->andReturn($emptyPref);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['frontPageAccounts', [$asset->id]]);
// mock default session stuff
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once()->withNoArgs();
$this->session(['accounts.create.uri' => 'http://localhost']);
$this->be($this->user());
$data = [
'name' => 'new account ' . $this->randomInt(),
'objectType' => 'asset',
'create_another' => 1,
];
$response = $this->post(route('accounts.store', ['asset']), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect('http://localhost/accounts/create/asset');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\CreateController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testStoreLiability(): void
{
// mock stuff
$repository = $this->mock(AccountRepositoryInterface::class);
$liability = $this->getRandomLoan();
$loan = AccountType::where('type', AccountType::LOAN)->first();
$repository->shouldReceive('store')->once()->andReturn($liability);
// mock default session stuff
$this->mockDefaultSession();
// change the preference:
$emptyPref = new Preference;
$emptyPref->data = [];
Preferences::shouldReceive('get')->atLeast()->once()->withArgs(['frontPageAccounts', []])->andReturn($emptyPref);
Preferences::shouldReceive('mark')->atLeast()->once()->withNoArgs();
$this->session(['accounts.create.uri' => 'http://localhost']);
$this->be($this->user());
$data = [
'name' => 'new liability account ' . $this->randomInt(),
'objectType' => 'liabilities',
'liability_type_id' => $loan->id,
'opening_balance' => '-100',
'opening_balance_date' => '2018-01-01',
];
$response = $this->post(route('accounts.store', ['liabilities']), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,108 +0,0 @@
<?php
/**
* DeleteControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class DeleteControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class DeleteControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Account\DeleteController
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testDelete(): void
{
// mock stuff
$repository = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$asset = $this->getRandomAsset();
$repository->shouldReceive('getAccountsByType')->withArgs([[AccountType::ASSET]])->andReturn(new Collection);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('accounts.delete', [$asset->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\DeleteController
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testDestroy(): void
{
// mock stuff
$repository = $this->mock(AccountRepositoryInterface::class);
$asset = $this->getRandomAsset();
$repository->shouldReceive('findNull')->withArgs([0])->once()->andReturn(null);
$repository->shouldReceive('destroy')->andReturn(true);
// mock default session stuff
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['accounts.delete.uri' => 'http://localhost/accounts/show/1']);
$this->be($this->user());
$response = $this->post(route('accounts.destroy', [$asset->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,268 +0,0 @@
<?php
/**
* EditControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class EditControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class EditControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Account\EditController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
*/
public function testEdit(): void
{
$repository = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$asset = $this->getRandomAsset();
$euro = $this->getEuro();
// mock default session stuff
$this->mockDefaultSession();
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('get')->andReturn(new Collection)->atLeast()->once();
$accountRepos->shouldReceive('getAccountCurrency')->andReturn($euro)->once();
$accountRepos->shouldReceive('getNoteText')->andReturn('Some text')->once();
$accountRepos->shouldReceive('getOpeningBalanceAmount')->andReturnNull()->atLeast()->once();
$accountRepos->shouldReceive('getOpeningBalanceDate')->andReturnNull()->atLeast()->once();
//$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_number'])->andReturn('123')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_role'])->andReturn('defaultAsset')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'cc_type'])->andReturn('')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'cc_monthly_payment_date'])->andReturn('')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'BIC'])->andReturn('BIC')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest'])->andReturn('1')->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest_period'])->andReturn('monthly')->atLeast()->once();
$accountRepos->shouldReceive('getLocation')->atLeast()->once()->andReturnNull();
// get all types:
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Debt'])->andReturn(AccountType::find(11))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Loan'])->andReturn(AccountType::find(9))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Mortgage'])->andReturn(AccountType::find(12))->once();
$this->be($this->user());
$response = $this->get(route('accounts.edit', [$asset->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
$response->assertSee('Some text');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\EditController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
*/
public function testEditLiability(): void
{
$repository = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$loan = $this->getRandomLoan();
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
//$repository->shouldReceive('findNull')->once()->andReturn($euro);
$repository->shouldReceive('get')->andReturn(new Collection);
$accountRepos->shouldReceive('getNoteText')->andReturn('Some text')->once();
$accountRepos->shouldReceive('getOpeningBalanceAmount')->andReturnNull();
$accountRepos->shouldReceive('getOpeningBalanceDate')->andReturnNull();
//$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_number'])->andReturn('123');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_role'])->andReturn('defaultAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'cc_type'])->andReturn('');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'cc_monthly_payment_date'])->andReturn('');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'BIC'])->andReturn('BIC');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest_period'])->andReturn('monthly');
$accountRepos->shouldReceive('getAccountCurrency')->andReturn($euro)->once();
$accountRepos->shouldReceive('getLocation')->atLeast()->once()->andReturnNull();
// get all types:
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Debt'])->andReturn(AccountType::find(11))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Loan'])->andReturn(AccountType::find(9))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Mortgage'])->andReturn(AccountType::find(12))->once();
// mock default session stuff
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('accounts.edit', [$loan->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
$response->assertSee('Some text');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\EditController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
*/
public function testEditNull(): void
{
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('get')->andReturn(new Collection);
$accountRepos->shouldReceive('getNoteText')->andReturn('Some text')->once();
$accountRepos->shouldReceive('getOpeningBalanceAmount')->andReturnNull();
$accountRepos->shouldReceive('getOpeningBalanceDate')->andReturnNull();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_number'])->andReturn('123');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_role'])->andReturn('defaultAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'cc_type'])->andReturn('');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'cc_monthly_payment_date'])->andReturn('');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'BIC'])->andReturn('BIC');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest_period'])->andReturn('monthly');
$accountRepos->shouldReceive('getAccountCurrency')->andReturn($euro)->once();
$accountRepos->shouldReceive('getLocation')->atLeast()->once()->andReturnNull();
// mock default session stuff
$this->mockDefaultSession();
// get all types:
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Debt'])->andReturn(AccountType::find(11))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Loan'])->andReturn(AccountType::find(9))->once();
$accountRepos->shouldReceive('getAccountTypeByType')->withArgs(['Mortgage'])->andReturn(AccountType::find(12))->once();
$this->be($this->user());
$account = $this->user()->accounts()->where('account_type_id', 3)->whereNull('deleted_at')->first();
$response = $this->get(route('accounts.edit', [$account->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
$response->assertSee('Some text');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\EditController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testUpdate(): void
{
// mock stuff
$account = $this->getRandomAsset();
$repository = $this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$repository->shouldReceive('update')->once();
Preferences::shouldReceive('mark')->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$this->session(['accounts.edit.uri' => 'http://localhost/javascript/account']);
$this->be($this->user());
$data = [
'name' => 'updated account ' . $this->randomInt(),
'active' => 1,
'what' => 'asset',
];
$response = $this->post(route('accounts.update', [$account->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\EditController
* @covers \FireflyIII\Http\Requests\AccountFormRequest
* @covers \FireflyIII\Http\Controllers\Controller
*/
public function testUpdateAgain(): void
{
// mock stuff
$account = $this->getRandomAsset();
$repository = $this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$repository->shouldReceive('update')->once();
$this->session(['accounts.edit.uri' => 'http://localhost']);
$this->be($this->user());
$data = [
'name' => 'updated account ' . $this->randomInt(),
'active' => 1,
'what' => 'asset',
'return_to_edit' => '1',
];
Preferences::shouldReceive('mark')->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$response = $this->post(route('accounts.update', [$account->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,108 +0,0 @@
<?php
/**
* IndexControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Account;
use Amount;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class IndexControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class IndexControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Account\IndexController
* @dataProvider dateRangeProvider
*
* @param string $range
*
*/
public function testIndex(string $range): void
{
// mock stuff
$this->mock(CurrencyRepositoryInterface::class);
$account = $this->getRandomAsset();
$repository = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$account]));
$repository->shouldReceive('getInactiveAccountsByType')->andReturn(new Collection);
$repository->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$repository->shouldReceive('getLocation')->atLeast()->once()->andReturnNull();
//
Steam::shouldReceive('balancesByAccounts')->andReturn([$account->id => '100']);
Steam::shouldReceive('getLastActivities')->andReturn([]);
// mock default session stuff
$this->mockDefaultSession();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Amount::shouldReceive('formatAnything')->andReturn('123');
$repository->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest'])->andReturn('1');
$repository->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'interest_period'])->andReturn('monthly');
$repository->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'account_number'])->andReturn('123');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('accounts.index', ['asset']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,182 +0,0 @@
<?php
/**
* ReconcileControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Account;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\TransactionGroupFactory;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class ConfigurationControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ReconcileControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Test showing the reconciliation.
*
* @covers \FireflyIII\Http\Controllers\Account\ReconcileController
*/
public function testReconcile(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$this->mock(GroupCollectorInterface::class);
$euro = $this->getEuro();
$asset = $this->getRandomAsset();
$date = new Carbon;
$userRepos->shouldReceive('hasRole')->atLeast()->once()->withArgs([Mockery::any(), 'owner'])->andReturnTrue();
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
Steam::shouldReceive('balance')->atLeast()->once()->andReturn('100');
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
// mock default session stuff
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('accounts.reconcile', [$asset->id, '20170101', '20170131']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* Submit reconciliation.
*
* @covers \FireflyIII\Http\Controllers\Account\ReconcileController
* @covers \FireflyIII\Http\Requests\ReconciliationStoreRequest
*/
public function testSubmit(): void
{
$repository = $this->mock(AccountRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$journalRepos = $this->mockDefaultSession();
$asset = $this->getRandomAsset();
$euro = $this->getEuro();
$date = new Carbon;
$factory = $this->mock(TransactionGroupFactory::class);
$group = $this->getRandomWithdrawalGroup();
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(GroupCollectorInterface::class);
Preferences::shouldReceive('mark')->atLeast()->once();
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$journalRepos->shouldReceive('reconcileById')->times(3);
$repository->shouldReceive('getReconciliation')->atLeast()->once()->andReturn($asset);
$repository->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$factory->shouldReceive('setUser')->atLeast()->once();
$factory->shouldReceive('create')->andReturn($group);
$data = [
'journals' => [1, 2, 3],
'reconcile' => 'create',
'difference' => '5',
'start' => '20170101',
'end' => '20170131',
];
$this->be($this->user());
$response = $this->post(route('accounts.reconcile.submit', [$asset->id, '20170101', '20170131']), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* Submit reconciliation, but throw an error.
*
* @covers \FireflyIII\Http\Controllers\Account\ReconcileController
* @covers \FireflyIII\Http\Requests\ReconciliationStoreRequest
*/
public function testSubmitError(): void
{
$repository = $this->mock(AccountRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$journalRepos = $this->mockDefaultSession();
$asset = $this->getRandomAsset();
$euro = $this->getEuro();
$date = new Carbon;
$factory = $this->mock(TransactionGroupFactory::class);
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(GroupCollectorInterface::class);
Preferences::shouldReceive('mark')->atLeast()->once();
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$journalRepos->shouldReceive('reconcileById')->times(3);
$repository->shouldReceive('getReconciliation')->atLeast()->once()->andReturn($asset);
$repository->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$factory->shouldReceive('setUser')->atLeast()->once();
$factory->shouldReceive('create')->andThrow(new FireflyException('Some error'));
$data = [
'journals' => [1, 2, 3],
'reconcile' => 'create',
'difference' => '5',
'start' => '20170101',
'end' => '20170131',
];
$this->be($this->user());
$response = $this->post(route('accounts.reconcile.submit', [$asset->id, '20170101', '20170131']), $data);
$response->assertStatus(302);
$response->assertSessionHas('error');
}
}

View File

@@ -1,175 +0,0 @@
<?php
/**
* ShowControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Account;
use Amount;
use Carbon\Carbon;
use Exception;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Account\AccountTaskerInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class ShowControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ShowControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Account\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testShow(string $range): void
{
$date = new Carbon;
$this->session(['start' => $date, 'end' => clone $date]);
// mock stuff:
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$repository = $this->mock(AccountRepositoryInterface::class);
$journal = $this->getRandomWithdrawalAsArray();
$group = $this->getRandomWithdrawalGroup();
$asset = $this->getRandomAsset();
$euro = $this->getEuro();
$this->mockDefaultSession();
// amount mocks:
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('-100');
$repository->shouldReceive('getAccountCurrency')->andReturn($euro)->atLeast()->once();
$repository->shouldReceive('oldestJournalDate')->andReturn(clone $date)->once();
$repository->shouldReceive('getLocation')->atLeast()->once()->andReturnNull();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$this->mockLastActivity();
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$journal]);
$collector->shouldReceive('withAccountInformation')->andReturnSelf();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([$group], 0, 10));
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('accounts.show', [$asset->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Account\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testShowAll(string $range): void
{
$date = new Carbon;
$this->session(['start' => $date, 'end' => clone $date]);
// mock stuff:
$this->mock(AccountTaskerInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$repository = $this->mock(AccountRepositoryInterface::class);
$journal = $this->getRandomWithdrawalAsArray();
$group = $this->getRandomWithdrawalGroup();
$euro = $this->getEuro();
$asset = $this->getRandomAsset();
$this->mockDefaultSession();
$repository->shouldReceive('isLiability')->andReturn(false)->atLeast()->once();
$repository->shouldReceive('getAccountCurrency')->andReturn($euro)->atLeast()->once();
$repository->shouldReceive('oldestJournalDate')->andReturn(clone $date)->once();
$repository->shouldReceive('getLocation')->atLeast()->once()->andReturnNull();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
// mock hasRole for user repository:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->andReturn([$journal]);
$collector->shouldReceive('withAccountInformation')->andReturnSelf();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([$group], 0, 10));
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('accounts.show.all', [$asset->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,115 +0,0 @@
<?php
/**
* ConfigurationControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Admin;
use FireflyConfig;
use FireflyIII\Models\Configuration;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class ConfigurationControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ConfigurationControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\ConfigurationController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
// for session
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
//Amount::shouldReceive('getDefaultCurrency')->atLeast()->once()->andReturn($euro);
$this->mockDefaultPreferences();
$this->be($this->user());
$falseConfig = new Configuration;
$falseConfig->data = false;
$trueConfig = new Configuration;
$trueConfig->data = true;
FireflyConfig::shouldReceive('get')->withArgs(['single_user_mode', true])->once()->andReturn($trueConfig);
//FireflyConfig::shouldReceive('get')->withArgs(['is_demo_site', false])->times(2)->andReturn($falseConfig);
$response = $this->get(route('admin.configuration.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\ConfigurationController
* @covers \FireflyIII\Http\Requests\ConfigurationRequest
*/
public function testPostIndex(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
// for session
//Amount::shouldReceive('getDefaultCurrency')->atLeast()->once()->andReturn($euro);
$this->mockDefaultPreferences();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$falseConfig = new Configuration;
$falseConfig->data = false;
//FireflyConfig::shouldReceive('get')->withArgs(['is_demo_site', false])->once()->andReturn($falseConfig);
FireflyConfig::shouldReceive('set')->withArgs(['single_user_mode', false])->once();
FireflyConfig::shouldReceive('set')->withArgs(['is_demo_site', false])->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->be($this->user());
$response = $this->post(route('admin.configuration.index.post'));
$response->assertSessionHas('success');
$response->assertStatus(302);
}
}

View File

@@ -1,94 +0,0 @@
<?php
/**
* HomeControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Admin;
use Event;
use FireflyIII\Events\AdminRequestedTestMessage;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class HomeControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class HomeControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\HomeController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
// default for session
$this->mockDefaultPreferences();
$this->mockDefaultConfiguration();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('admin.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\HomeController
*/
public function testTestMessage(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultPreferences();
$this->mockDefaultConfiguration();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
Event::fake();
$this->be($this->user());
$response = $this->post(route('admin.test-message'));
$response->assertStatus(302);
Event::assertDispatched(AdminRequestedTestMessage::class);
}
}

View File

@@ -1,387 +0,0 @@
<?php
/**
* LinkControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Admin;
use FireflyIII\Models\LinkType;
use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class LinkControllerTest
*
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class LinkControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testCreate(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(LinkTypeRepositoryInterface::class);
// mock default session stuff
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('admin.links.create'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testDeleteEditable(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
// create editable link type just in case:
$newType = LinkType::create(['editable' => 1, 'inward' => 'hello', 'outward' => 'bye', 'name' => 'Test type']);
// mock default session stuff
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$linkType = LinkType::where('editable', 1)->first();
$another = LinkType::where('editable', 0)->first();
$repository->shouldReceive('get')->once()->andReturn(new Collection([$linkType, $another]));
$repository->shouldReceive('countJournals')->andReturn(2);
$this->be($this->user());
$response = $this->get(route('admin.links.delete', [$linkType->id]));
$response->assertStatus(200);
$newType->forceDelete();
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testDeleteNonEditable(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(LinkTypeRepositoryInterface::class);
$linkType = LinkType::where('editable', 0)->first();
// mock default session stuff
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('admin.links.delete', [$linkType->id]));
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testDestroy(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// create editable link type just in case:
LinkType::create(['editable' => 1, 'inward' => 'hellox', 'outward' => 'byex', 'name' => 'Test typeX']);
$linkType = LinkType::where('editable', 1)->first();
$repository->shouldReceive('findNull')->andReturn($linkType);
$repository->shouldReceive('destroy');
$this->be($this->user());
$this->session(['link_types.delete.uri' => 'http://localhost']);
$response = $this->post(route('admin.links.destroy', [$linkType->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testEditEditable(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
// create editable link type just in case:
LinkType::create(['editable' => 1, 'inward' => 'hello Y', 'outward' => 'bye Y', 'name' => 'Test type Y']);
$linkType = LinkType::where('editable', 1)->first();
$this->be($this->user());
$response = $this->get(route('admin.links.edit', [$linkType->id]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testEditNonEditable(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$linkType = LinkType::where('editable', 0)->first();
$this->be($this->user());
$response = $this->get(route('admin.links.edit', [$linkType->id]));
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testIndex(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
//Preferences::shouldReceive('mark')->atLeast()->once();
$linkTypes = LinkType::inRandomOrder()->take(3)->get();
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$repository->shouldReceive('get')->andReturn($linkTypes);
$repository->shouldReceive('countJournals')->andReturn(3);
$this->be($this->user());
$response = $this->get(route('admin.links.index'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
*/
public function testShow(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('getJournalLinks')->andReturn(new Collection);
$this->mockDefaultSession();
$linkType = LinkType::first();
$this->be($this->user());
$response = $this->get(route('admin.links.show', [$linkType->id]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
* @covers \FireflyIII\Http\Requests\LinkTypeFormRequest
*/
public function testStore(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$data = [
'name' => sprintf('test %d', $this->randomInt()),
'inward' => sprintf('test inward %d', $this->randomInt()),
'outward' => sprintf('test outward %d', $this->randomInt()),
];
$repository->shouldReceive('store')->once()->andReturn(LinkType::first());
$repository->shouldReceive('findNull')->andReturn(LinkType::first());
$this->session(['link_types.create.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('admin.links.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
* @covers \FireflyIII\Http\Requests\LinkTypeFormRequest
*/
public function testStoreRedirect(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$data = [
'name' => sprintf('test %d', $this->randomInt()),
'inward' => sprintf('test inward %d', $this->randomInt()),
'outward' => sprintf('test outward %d', $this->randomInt()),
'create_another' => '1',
];
$repository->shouldReceive('store')->once()->andReturn(new LinkType);
$this->session(['link_types.create.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('admin.links.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
* @covers \FireflyIII\Http\Requests\LinkTypeFormRequest
*/
public function testUpdate(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// create editable link type just in case:
$linkType = LinkType::create(['editable' => 1, 'inward' => 'helloxz', 'outward' => 'bzyex', 'name' => 'Test tyzpeX']);
$repository->shouldReceive('update')->once()->andReturn(new $linkType);
// mock default session stuff
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'name' => sprintf('test %d', $this->randomInt()),
'inward' => sprintf('test inward %d', $this->randomInt()),
'outward' => sprintf('test outward %d', $this->randomInt()),
];
$this->session(['link_types.edit.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('admin.links.update', [$linkType->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
* @covers \FireflyIII\Http\Requests\LinkTypeFormRequest
*/
public function testUpdateNonEditable(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// mock default session stuff
$this->mockDefaultSession();
$linkType = LinkType::where('editable', 0)->first();
$data = [
'name' => sprintf('test %d', $this->randomInt()),
'inward' => sprintf('test inward %d', $this->randomInt()),
'outward' => sprintf('test outward %d', $this->randomInt()),
'return_to_edit' => '1',
];
$this->session(['link_types.edit.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('admin.links.update', [$linkType->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\LinkController
* @covers \FireflyIII\Http\Requests\LinkTypeFormRequest
*/
public function testUpdateRedirect(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository = $this->mock(LinkTypeRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
// create editable link type just in case:
$linkType = LinkType::create(['editable' => 1, 'inward' => 'healox', 'outward' => 'byaex', 'name' => 'Test tyapeX']);
// mock default session stuff
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'name' => sprintf('test %d', $this->randomInt()),
'inward' => sprintf('test inward %d', $this->randomInt()),
'outward' => sprintf('test outward %d', $this->randomInt()),
'return_to_edit' => '1',
];
$repository->shouldReceive('update')->once()->andReturn(new $linkType);
$this->session(['link_types.edit.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('admin.links.update', [$linkType->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,246 +0,0 @@
<?php
/**
* UpdateControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Admin;
use Carbon\Carbon;
use FireflyConfig;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Configuration;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Services\FireflyIIIOrg\Update\UpdateRequest;
use FireflyIII\Services\Github\Object\Release;
use Log;
use Mockery;
use Tests\TestCase;
/**
* Class UpdateControllerTest
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class UpdateControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UpdateController
*/
public function testIndex(): void
{
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
// mock calls
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->mockDefaultSession();
// mock update calls.
$config = new Configuration;
$config->data = -1;
$channelConfig = new Configuration;
$channelConfig->data = 'stable';
FireflyConfig::shouldReceive('get')->withArgs(['permission_update_check', -1])->once()->andReturn($config);
FireflyConfig::shouldReceive('get')->withArgs(['update_channel', 'stable'])->once()->andReturn($channelConfig);
// call service
$this->be($this->user());
$response = $this->get(route('admin.update-check'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UpdateController
*/
public function testPost(): void
{
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
// mock calls
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$this->mockDefaultSession();
// mock update calls
FireflyConfig::shouldReceive('set')->withArgs(['permission_update_check', 1])->once()->andReturn(new Configuration);
FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn(new Configuration);
FireflyConfig::shouldReceive('set')->withArgs(['update_channel','stable'])->once()->andReturn(new Configuration);
//FireflyConfig::shouldReceive('get')->withArgs(['update_channel', 'stable'])->once()->andReturn($channelConfig);
// call service
$this->be($this->user());
$response = $this->post(route('admin.update-check.post'), ['check_for_updates' => 1]);
$response->assertSessionHas('success');
$response->assertStatus(302);
$response->assertRedirect(route('admin.update-check'));
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UpdateController
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/
public function testUpdateCheck(): void
{
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
// mock calls
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn(new Configuration);
$this->mockDefaultSession();
$return = [
'version' => '2.0.0',
'date' => '2020-01-01'
];
// set some data
$updater = $this->mock(UpdateRequest::class);
$updater->shouldReceive('getVersion')->withArgs(['stable'])->atLeast()->once()
->andReturn($return);
$channelConfig = new Configuration;
$channelConfig->data = 'stable';
FireflyConfig::shouldReceive('get')->withArgs(['update_channel', 'stable'])->atleast()->once()->andReturn($channelConfig);
$this->be($this->user());
$response = $this->post(route('admin.update-check.manual'));
$response->assertStatus(200);
$response->assertSee(config('firefly.version'));
$response->assertSee('which is newer than the latest release');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UpdateController
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/
public function testUpdateCheckCurrent(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$this->mockDefaultSession();
FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn(new Configuration);
$channelConfig = new Configuration;
$channelConfig->data = 'stable';
FireflyConfig::shouldReceive('get')->withArgs(['update_channel', 'stable'])->atleast()->once()->andReturn($channelConfig);
$return = [
'version' => config('firefly.version'),
'date' => '2020-01-01'
];
// set some data
$updater = $this->mock(UpdateRequest::class);
$updater->shouldReceive('getVersion')->withArgs(['stable'])->atLeast()->once()
->andReturn($return);
$this->be($this->user());
$response = $this->post(route('admin.update-check.manual'));
$response->assertStatus(200);
$response->assertSee(config('firefly.version'));
$response->assertSee('the latest available release');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UpdateController
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/
public function testUpdateCheckError(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$this->mockDefaultSession();
FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn(new Configuration);
$channelConfig = new Configuration;
$channelConfig->data = 'stable';
FireflyConfig::shouldReceive('get')->withArgs(['update_channel', 'stable'])->atleast()->once()->andReturn($channelConfig);
$updater = $this->mock(UpdateRequest::class);
$updater->shouldReceive('getVersion')->withArgs(['stable'])->atLeast()->once()
->andThrow(new FireflyException('Something broke.'));
$this->be($this->user());
$response = $this->post(route('admin.update-check.manual'));
$response->assertStatus(200);
$response->assertSee('An error occurred while checking');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UpdateController
* @covers \FireflyIII\Helpers\Update\UpdateTrait
*/
public function testUpdateCheckNewer(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->andReturn(false)->atLeast()->once();
$this->mockDefaultSession();
FireflyConfig::shouldReceive('set')->withArgs(['last_update_check', Mockery::any()])->once()->andReturn(new Configuration);
$channelConfig = new Configuration;
$channelConfig->data = 'stable';
FireflyConfig::shouldReceive('get')->withArgs(['update_channel', 'stable'])->atleast()->once()->andReturn($channelConfig);
$return = [
'version' => '100',
'date' => '2020-01-01'
];
// set some data
$updater = $this->mock(UpdateRequest::class);
$updater->shouldReceive('getVersion')->withArgs(['stable'])->atLeast()->once()
->andReturn($return);
// expect a new release (because of .1)
$this->be($this->user());
$response = $this->post(route('admin.update-check.manual'));
$response->assertStatus(200);
$response->assertSee('A new version of Firefly III is available');
}
}

View File

@@ -1,176 +0,0 @@
<?php
/**
* UserControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Admin;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class UserControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class UserControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UserController
*/
public function testDelete(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('admin.users.delete', [$this->user()->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UserController
*/
public function testDestroy(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('destroy')->once();
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->once()->andReturn(true);
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->post(route('admin.users.destroy', [$this->user()->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UserController
*/
public function testEdit(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('admin.users.edit', [$this->user()->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UserController
*/
public function testIndex(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(3)->andReturn(true);
$user = $this->user();
$repository->shouldReceive('all')->andReturn(new Collection([$user]));
$this->mockDefaultSession();
$this->be($user);
$response = $this->get(route('admin.users'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UserController
*/
public function testShow(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$repository->shouldReceive('getUserData')->andReturn(
[
'export_jobs_success' => 0,
'attachments_size' => 0,
]
);
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('admin.users.show', [$this->user()->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Admin\UserController
* @covers \FireflyIII\Http\Requests\UserFormRequest
*/
public function testUpdate(): void
{
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('changePassword')->once();
$repository->shouldReceive('changeStatus')->once();
$repository->shouldReceive('updateEmail')->once();
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->once()->andReturn(true);
$this->mockDefaultSession();
Preferences::shouldReceive('mark');
$data = [
'id' => 1,
'email' => 'test@example.com',
'password' => 'james',
'password_confirmation' => 'james',
'blocked_code' => 'blocked',
'blocked' => 1,
];
$this->be($this->user());
$response = $this->post(route('admin.users.update', ['1']), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,238 +0,0 @@
<?php
/**
* AttachmentControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use FireflyIII\Models\Attachment;
use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class AttachmentControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AttachmentControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testDelete(): void
{
$this->mockDefaultSession();
// data
$attachment = $this->getRandomAttachment();
// mock stuff
$this->mock(AttachmentRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('attachments.delete', [$attachment->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testDestroy(): void
{
$this->mockDefaultSession();
// mock stuff
$attachment = $this->getRandomAttachment();
$repository = $this->mock(AttachmentRepositoryInterface::class);
$repository->shouldReceive('destroy')->andReturn(true);
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['attachments.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('attachments.destroy', [$attachment->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testDownload(): void
{
$this->mockDefaultSession();
// mock stuff
$attachment = $this->getRandomAttachment();
$repository = $this->mock(AttachmentRepositoryInterface::class);
$repository->shouldReceive('exists')->once()->andReturn(true);
$repository->shouldReceive('getContent')->once()->andReturn('This is attachment number one.');
$this->be($this->user());
$response = $this->get(route('attachments.download', [$attachment->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('This is attachment number one.');
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testDownloadFail(): void
{
$this->mockDefaultSession();
// mock stuff
$attachment = $this->getRandomAttachment();
$repository = $this->mock(AttachmentRepositoryInterface::class);
$repository->shouldReceive('exists')->once()->andReturn(false);
Log::warning('The following error is part of a test.');
$this->be($this->user());
$response = $this->get(route('attachments.download', [$attachment->id]));
$response->assertStatus(500);
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testEdit(): void
{
$this->mockDefaultSession();
$attachRepository = $this->mock(AttachmentRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$attachment = $this->getRandomAttachment();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$attachRepository->shouldReceive('getNoteText')->andReturn('OK');
$this->be($this->user());
$response = $this->get(route('attachments.edit', [$attachment->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$repository = $this->mock(AttachmentRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('get')->andReturn(new Collection([Attachment::first()]))->once();
$repository->shouldReceive('exists')->andReturn(true)->once();
$this->be($this->user());
$response = $this->get(route('attachments.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testUpdate(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(AttachmentRepositoryInterface::class);
$attachment = $this->getRandomAttachment();
$repository->shouldReceive('update')->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['attachments.edit.uri' => 'http://localhost']);
$data = [
'title' => 'Some updated title ' . $this->randomInt(),
'notes' => 'A',
'description' => 'B',
];
$this->be($this->user());
$response = $this->post(route('attachments.update', [$attachment->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testView(): void
{
$attachment = $this->getRandomAttachment();
$this->mockDefaultSession();
$repository = $this->mock(AttachmentRepositoryInterface::class);
$repository->shouldReceive('exists')->once()->andReturn(true);
$repository->shouldReceive('getContent')->once()->andReturn('This is attachment number one.');
$this->be($this->user());
$response = $this->get(route('attachments.view', [$attachment->id]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\AttachmentController
*/
public function testViewFail(): void
{
$this->mockDefaultSession();
$repository = $this->mock(AttachmentRepositoryInterface::class);
$attachment = $this->getRandomAttachment();
$repository->shouldReceive('exists')->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('attachments.view', [$attachment->id]));
$response->assertStatus(500);
}
}

View File

@@ -1,70 +0,0 @@
<?php
/**
* TwoFactorControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Auth;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Preference;
use Google2FA;
use Log;
use Preferences;
use Tests\TestCase;
use FireflyConfig;
/**
* Class TwoFactorControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TwoFactorControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Auth\TwoFactorController
*/
public function testLostTwoFactor(): void
{
$this->be($this->user());
$langPreference = new Preference;
$langPreference->data = 'en_US';
$falseConfig = new Configuration;
$falseConfig->data = false;
FireflyConfig::shouldReceive('get')->withArgs(['is_demo_site', false])->andReturn($falseConfig);
Preferences::shouldReceive('get')->withArgs(['language', 'en_US'])->andReturn($langPreference);
$response = $this->get(route('two-factor.lost'));
$response->assertStatus(200);
}
}

View File

@@ -1,490 +0,0 @@
<?php
/**
* BillControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use Amount;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Bill;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\TransactionRules\TransactionMatcher;
use FireflyIII\Transformers\BillTransformer;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\MessageBag;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class BillControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BillControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testCreate(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_bills_create');
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(AttachmentHelperInterface::class);
$this->mock(BillRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('bills.create'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testDelete(): void
{
$this->mockDefaultSession();
$bill = $this->getRandomBill();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(AttachmentHelperInterface::class);
$this->mock(BillRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('bills.delete', [$bill->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testDestroy(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(BillRepositoryInterface::class);
$this->mock(AttachmentHelperInterface::class);
Preferences::shouldReceive('mark')->atLeast()->once();
$repository->shouldReceive('destroy')->andReturn(true);
$this->session(['bills.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('bills.destroy', [1]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testEdit(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$billRepos = $this->mock(BillRepositoryInterface::class);
$this->mock(AttachmentHelperInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$billRepos->shouldReceive('getNoteText')->andReturn('Hello');
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('bills.edit', [1]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_bills_index');
Amount::shouldReceive('getDefaultCurrency')->andReturn($this->getEuro());
// mock stuff
$this->mock(AttachmentHelperInterface::class);
$bill = $this->getRandomBill();
$repository = $this->mock(BillRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$transformer = $this->mock(BillTransformer::class);
$euro = $this->getEuro();
//$pref = new Preference;
//$pref->data = 50;
//Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
['id' => 5, 'active' => true,
'name' => 'x', 'next_expected_match' => '2018-01-01',
'amount_min' => '10',
'amount_max' => '10',
'currency' => $this->getEuro(),
'currency_id' => $euro->id,
'currency_code' => $euro->code,
'pay_dates' => [],
'currency_symbol' => $euro->symbol,
'currency_decimal_places' => $euro->decimal_places,
]
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collection = new Collection([$bill]);
$repository->shouldReceive('getBills')->andReturn($collection)->once();
$repository->shouldReceive('setUser');
$repository->shouldReceive('getNoteText')->andReturn('Hi there');
$repository->shouldReceive('getRulesForBills')->andReturn([]);
$this->be($this->user());
$response = $this->get(route('bills.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testRescan(): void
{
$this->mockDefaultSession();
// mock stuff
$rule = $this->getRandomRule();
$repository = $this->mock(BillRepositoryInterface::class);
$this->mock(AttachmentHelperInterface::class);
$repository->shouldReceive('getRulesForBill')->andReturn(new Collection([$rule]));
$repository->shouldReceive('unlinkAll')->atLeast()->once();
//calls for transaction matcher:
$matcher = $this->mock(TransactionMatcher::class);
$matcher->shouldReceive('setSearchLimit')->once()->withArgs([100000]);
$matcher->shouldReceive('setTriggeredLimit')->once()->withArgs([100000]);
$matcher->shouldReceive('setRule')->once()->withArgs([Mockery::any()]);
$matcher->shouldReceive('findTransactionsByRule')->once()->andReturn([]);
$repository->shouldReceive('linkCollectionToBill')->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('bills.rescan', [1]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testRescanInactive(): void
{
$this->mockDefaultSession();
$bill = $this->getRandomInactiveBill();
$this->mock(AttachmentHelperInterface::class);
$this->mock(BillRepositoryInterface::class);
$this->be($this->user());
$response = $this->get(route('bills.rescan', [$bill->id]));
$response->assertStatus(302);
$response->assertSessionHas('warning');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
*/
public function testShow(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_bills_show');
// mock stuff
$repository = $this->mock(BillRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$transformer = $this->mock(BillTransformer::class);
$collector = $this->mock(GroupCollectorInterface::class);
$group = $this->getRandomWithdrawalGroup();
$this->mock(AttachmentHelperInterface::class);
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$paginator = new LengthAwarePaginator([$group], 1, 40, 1);
// mock collector:
$collector->shouldReceive('setBill')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setLimit')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setPage')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withBudgetInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withCategoryInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withAccountInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getPaginatedGroups')->atLeast()->once()->andReturn($paginator);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('setCurrentScope')->atLeast()->once();
$transformer->shouldReceive('getDefaultIncludes')->atLeast()->once();
$transformer->shouldReceive('getAvailableIncludes')->atLeast()->once();
$repository->shouldReceive('getAttachments')->atLeast()->once()->andReturn(new Collection);
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
['id' => 5, 'active' => true, 'name' => 'x', 'next_expected_match' => '2018-01-01',
'currency_symbol' => 'x', 'amount_min' => '10', 'amount_max' => '15',
]
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('getYearAverage')->andReturn('0');
$repository->shouldReceive('getOverallAverage')->andReturn('0');
$repository->shouldReceive('getRulesForBill')->andReturn(new Collection);
$this->be($this->user());
$response = $this->get(route('bills.show', [1]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
* @covers \FireflyIII\Http\Requests\BillFormRequest
* @covers \FireflyIII\Http\Requests\Request
*/
public function testStore(): void
{
$this->mockDefaultSession();
$this->be($this->user());
$bill = $this->user()->bills()->first();
// mock stuff
$attachHelper = $this->mock(AttachmentHelperInterface::class);
$repository = $this->mock(BillRepositoryInterface::class);
$repository->shouldReceive('store')->andReturn($bill);
$attachHelper->shouldReceive('saveAttachmentsForModel');
$attachHelper->shouldReceive('getMessages')->andReturn(new MessageBag);
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'name' => 'New Bill ' . $this->randomInt(),
'amount_min' => '100',
'transaction_currency_id' => 1,
'skip' => 0,
'strict' => 1,
'amount_max' => '100',
'date' => '2016-01-01',
'repeat_freq' => 'monthly',
];
$this->session(['bills.create.uri' => 'http://localhost']);
$response = $this->post(route('bills.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
* @covers \FireflyIII\Http\Requests\BillFormRequest
* @covers \FireflyIII\Http\Requests\Request
*/
public function testStoreCreateAnother(): void
{
$this->mockDefaultSession();
// mock stuff
$bill = $this->getRandomBill();
$attachHelper = $this->mock(AttachmentHelperInterface::class);
$repository = $this->mock(BillRepositoryInterface::class);
$repository->shouldReceive('store')->andReturn($bill);
$attachHelper->shouldReceive('saveAttachmentsForModel');
$attachHelper->shouldReceive('getMessages')->andReturn(new MessageBag);
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'name' => 'New Bill ' . $this->randomInt(),
'amount_min' => '100',
'transaction_currency_id' => 1,
'skip' => 0,
'create_another' => '1',
'strict' => 1,
'amount_max' => '100',
'date' => '2016-01-01',
'repeat_freq' => 'monthly',
];
$this->session(['bills.create.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('bills.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
* @covers \FireflyIII\Http\Requests\BillFormRequest
* @covers \FireflyIII\Http\Requests\Request
*/
public function testStoreError(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(BillRepositoryInterface::class);
$this->mock(AttachmentHelperInterface::class);
$repository->shouldReceive('store')->andThrow(new FireflyException('Could not store.'));
$data = [
'name' => 'New Bill ' . $this->randomInt(),
'amount_min' => '100',
'transaction_currency_id' => 1,
'skip' => 0,
'strict' => 1,
'amount_max' => '100',
'date' => '2016-01-01',
'repeat_freq' => 'monthly',
];
$this->be($this->user());
$response = $this->post(route('bills.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('error');
$response->assertRedirect(route('bills.create'));
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
* @covers \FireflyIII\Http\Requests\BillFormRequest
* @covers \FireflyIII\Http\Requests\Request
*/
public function testStoreNoGroup(): void
{
$this->mockDefaultSession();
// mock stuff
$attachHelper = $this->mock(AttachmentHelperInterface::class);
$repository = $this->mock(BillRepositoryInterface::class);
$bill = $this->getRandomBill();
$repository->shouldReceive('store')->andReturn($bill);
$attachHelper->shouldReceive('saveAttachmentsForModel');
$attachHelper->shouldReceive('getMessages')->andReturn(new MessageBag);
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'name' => 'New Bill ' . $this->randomInt(),
'amount_min' => '100',
'transaction_currency_id' => 1,
'skip' => 0,
'create_another' => '1',
'strict' => 1,
'amount_max' => '100',
'date' => '2016-01-01',
'repeat_freq' => 'monthly',
];
$this->session(['bills.create.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('bills.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\BillController
* @covers \FireflyIII\Http\Requests\BillFormRequest
* @covers \FireflyIII\Http\Requests\Request
*/
public function testUpdate(): void
{
$this->mockDefaultSession();
// mock stuff
$attachHelper = $this->mock(AttachmentHelperInterface::class);
$repository = $this->mock(BillRepositoryInterface::class);
$repository->shouldReceive('update')->andReturn(new Bill);
$attachHelper->shouldReceive('saveAttachmentsForModel');
$attachHelper->shouldReceive('getMessages')->andReturn(new MessageBag);
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'id' => 1,
'name' => 'Updated Bill ' . $this->randomInt(),
'amount_min' => '100',
'transaction_currency_id' => 1,
'skip' => 0,
'amount_max' => '100',
'date' => '2016-01-01',
'repeat_freq' => 'monthly',
];
$this->session(['bills.edit.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('bills.update', [1]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,104 +0,0 @@
<?php
/**
* CreateControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Budget;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class CreateControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CreateControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\CreateController
*/
public function testCreate(): void
{
$this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('budgets.create'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\CreateController
*/
public function testStore(): void
{
Log::debug('Now in testStore()');
// mock stuff
$budget = $this->getRandomBudget();
$repository = $this->mock(BudgetRepositoryInterface::class);
$repository->shouldReceive('findNull')->andReturn($budget);
$repository->shouldReceive('store')->andReturn($budget);
$repository->shouldReceive('cleanupBudgets');
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['budgets.create.uri' => 'http://localhost']);
$data = [
'name' => sprintf('New Budget %s', $this->randomInt()),
];
$this->be($this->user());
$response = $this->post(route('budgets.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,99 +0,0 @@
<?php
/**
* DeleteControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Budget;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class DeleteControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class DeleteControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\DeleteController
*/
public function testDelete(): void
{
$this->mockDefaultSession();
$budget = $this->getRandomBudget();
Log::debug('Now in testDelete()');
// mock stuff
$this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('budgets.delete', [$budget->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\DeleteController
*/
public function testDestroy(): void
{
$this->mockDefaultSession();
$budget = $this->getRandomBudget();
Log::debug('Now in testDestroy()');
// mock stuff
$repository = $this->mock(BudgetRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
Preferences::shouldReceive('mark')->atLeast()->once();
$repository->shouldReceive('destroy')->andReturn(true);
$this->session(['budgets.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('budgets.destroy', [$budget->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,103 +0,0 @@
<?php
/**
* EditControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Budget;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class EditControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class EditControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\EditController
*/
public function testEdit(): void
{
Log::debug('Now in testEdit()');
// mock stuff
$this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('budgets.edit', [1]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\EditController
*/
public function testUpdate(): void
{
Log::debug('Now in testUpdate()');
// mock stuff
$budget = $this->getRandomBudget();
$repository = $this->mock(BudgetRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('findNull')->andReturn($budget);
$repository->shouldReceive('update');
$repository->shouldReceive('cleanupBudgets');
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['budgets.edit.uri' => 'http://localhost']);
$data = [
'name' => 'Updated Budget ' . $this->randomInt(),
'active' => 1,
];
$this->be($this->user());
$response = $this->post(route('budgets.update', [1]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,302 +0,0 @@
<?php
/**
* IndexControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Budget;
use Amount;
use Carbon\Carbon;
use Exception;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
*
* Class IndexControllerTest
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class IndexControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\IndexController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testIndex(string $range): void
{
// mock stuff
$budget = $this->getRandomBudget();
$budgetLimit = $this->getRandomBudgetLimit();
$budgetLimit->start_date = Carbon::now()->startOfMonth();
$budgetLimit->end_date = Carbon::now()->endOfMonth();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('cleanupBudgets')->atLeast()->once();
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection([$budget]))->atLeast()->once();
$repository->shouldReceive('getInactiveBudgets')->andReturn(new Collection)->atLeast()->once();
$abRepos->shouldReceive('get')->atLeast()->once()->andReturn(new Collection);
$blRepos->shouldReceive('budgeted')->andReturn('1')->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->andReturn(new Collection)->atLeast()->once();
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$currencyRepos->shouldReceive('getEnabled')->atLeast()->once()->andReturn(new Collection([$this->getEuro()]));
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_budgets_index');
Amount::shouldReceive('formatAnything')->andReturn('123');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\IndexController
* @dataProvider dateRangeProvider
*
* @param string $range
*
* @throws Exception
*/
public function testIndexOutOfRange(string $range): void
{
$budget = $this->getRandomBudget();
$budgetLimit = $this->getRandomBudgetLimit();
$budgetInfo = [
$budget->id => [
'spent' => '0',
'budgeted' => '0',
'currentRep' => false,
],
];
// set budget limit to current month:
$budgetLimit->start_date = Carbon::now()->startOfMonth();
$budgetLimit->end_date = Carbon::now()->endOfMonth();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('cleanupBudgets')->atLeast()->once();
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection([$budget]))->atLeast()->once();
$repository->shouldReceive('getInactiveBudgets')->andReturn(new Collection)->atLeast()->once();
$abRepos->shouldReceive('get')->atLeast()->once()->andReturn(new Collection);
$blRepos->shouldReceive('budgeted')->andReturn('1')->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->andReturn(new Collection)->atLeast()->once();
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$currencyRepos->shouldReceive('getEnabled')->atLeast()->once()->andReturn(new Collection([$this->getEuro()]));
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_budgets_index');
Amount::shouldReceive('formatAnything')->andReturn('123');
$this->be($this->user());
$today = new Carbon;
$today->startOfMonth();
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.index', [$today->format('Y-m-d')]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\IndexController
* @dataProvider dateRangeProvider
*
* @param string $range
*
* @throws Exception
*/
public function testIndexWithDate(string $range): void
{
$budget = $this->getRandomBudget();
$budgetLimit = $this->getRandomBudgetLimit();
$budgetInfo = [
$budget->id => [
'spent' => '0',
'budgeted' => '0',
'currentRep' => false,
],
];
// set budget limit to current month:
$budgetLimit->start_date = Carbon::now()->startOfMonth();
$budgetLimit->end_date = Carbon::now()->endOfMonth();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$repository->shouldReceive('cleanupBudgets')->atLeast()->once();
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection([$budget]))->atLeast()->once();
$repository->shouldReceive('getInactiveBudgets')->andReturn(new Collection)->atLeast()->once();
$abRepos->shouldReceive('get')->atLeast()->once()->andReturn(new Collection);
$blRepos->shouldReceive('budgeted')->andReturn('1')->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->andReturn(new Collection)->atLeast()->once();
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$currencyRepos->shouldReceive('getEnabled')->atLeast()->once()->andReturn(new Collection([$this->getEuro()]));
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_budgets_index');
Amount::shouldReceive('formatAnything')->andReturn('123');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.index', ['2017-01-01']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\IndexController
* @dataProvider dateRangeProvider
*
* @param string $range
*
* @throws Exception
*/
public function testIndexWithInvalidDate(string $range): void
{
$budgetLimit = $this->getRandomBudgetLimit();
// set budget limit to current month:
$budgetLimit->start_date = Carbon::now()->startOfMonth();
$budgetLimit->end_date = Carbon::now()->endOfMonth();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$accountRepos->shouldReceive('getAccountsByType')->andReturn(new Collection);
$repository->shouldReceive('cleanupBudgets');
$this->mockDefaultSession();
Amount::shouldReceive('formatAnything')->andReturn('123');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.index', ['Hello-there']));
$response->assertStatus(404);
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\IndexController
*/
public function testReorder(): void
{
$this->mockDefaultSession();
$repository = $this->mock(BudgetRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$abRepos = $this->mock(AvailableBudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$data = [
'budgetIds' => [1, 2],
'page' => 1,
];
$repository->shouldReceive('cleanupBudgets')->atLeast()->once();
$repository->shouldReceive('findNull')->atLeast()->once()->andReturn(new Budget);
$repository->shouldReceive('setBudgetOrder')->atLeast()->once();
$this->be($this->user());
$response = $this->post(route('budgets.reorder', $data));
$response->assertStatus(200);
}
}

View File

@@ -1,264 +0,0 @@
<?php
/**
* ShowControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Budget;
use Amount;
use Carbon\Carbon;
use Exception;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class ShowControllerTest
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ShowControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
*
*/
public function testNoBudget(string $range): void
{
$this->mock(BudgetRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = null;
$this->mockDefaultSession();
try {
$date = new Carbon;
} catch (Exception $e) {
$e->getMessage();
}
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
// mock calls
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withoutBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([])->atLeast()->once();
$this->session(['start' => $date, 'end' => clone $date]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.no-budget', ['2019-01-01', '2019-01-31']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testNoBudgetAll(string $range): void
{
$this->mock(BudgetRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$date = null;
$this->mockDefaultSession();
try {
$date = new Carbon;
} catch (Exception $e) {
$e->getMessage();
}
// mock calls
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withoutBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
try {
$date = new Carbon;
} catch (Exception $e) {
$e->getMessage();
}
$this->session(['start' => $date, 'end' => clone $date]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.no-budget', ['all']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testShow(string $range): void
{
$budgetLimit = $this->getRandomBudgetLimit();
$userRepos = $this->mock(UserRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$this->mockDefaultSession();
// mock calls
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('-100');
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->andReturn(new Collection([$budgetLimit]))->atLeast()->once();
$opsRepos->shouldReceive('spentInPeriod')->andReturn('-1')->atLeast()->once();
try {
$date = new Carbon;
$date->subDay();
$this->session(['first' => $date]);
} catch (Exception $e) {
$e->getMessage();
}
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.show', [1]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Budget\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testShowByBudgetLimit(string $range): void
{
$accountRepository = $this->mock(AccountRepositoryInterface::class);
$budgetRepository = $this->mock(BudgetRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$this->mockDefaultSession();
// mock calls
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->andReturn(new Collection)->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('budgets.show.limit', [1, 1]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,99 +0,0 @@
<?php
/**
* CreateControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Category;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class CreateControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CreateControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Category\CreateController
*/
public function testCreate(): void
{
Log::debug('TestCreate()');
// mock stuff
$this->mock(CategoryRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('categories.create'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Category\CreateController
* @covers \FireflyIII\Http\Requests\CategoryFormRequest
*/
public function testStore(): void
{
Log::debug('Test store()');
$repository = $this->mock(CategoryRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
$repository->shouldReceive('findNull')->andReturn(new Category);
$repository->shouldReceive('store')->andReturn(new Category);
Preferences::shouldReceive('mark')->atLeast()->once()->withNoArgs();
$this->session(['categories.create.uri' => 'http://localhost']);
$data = [
'name' => 'New Category ' . $this->randomInt(),
];
$this->be($this->user());
$response = $this->post(route('categories.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,95 +0,0 @@
<?php
/**
* DeleteControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Category;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class DeleteControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class DeleteControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Category\DeleteController
*/
public function testDelete(): void
{
Log::debug('Test Delete()');
// mock stuff
$this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->be($this->user());
$response = $this->get(route('categories.delete', [1]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Category\DeleteController
*/
public function testDestroy(): void
{
Log::debug('Test destroy()');
// mock stuff
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once()->withNoArgs();
$categoryRepos->shouldReceive('destroy')->andReturn(true);
$this->session(['categories.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('categories.destroy', [1]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,105 +0,0 @@
<?php
/**
* EditControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Category;
use FireflyIII\Models\Category;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class EditControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class EditControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Category\EditController
*/
public function testEdit(): void
{
Log::debug('Test edit()');
// mock stuff
$this->mock(CategoryRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->be($this->user());
$response = $this->get(route('categories.edit', [1]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Category\EditController
* @covers \FireflyIII\Http\Requests\CategoryFormRequest
*/
public function testUpdate(): void
{
Log::debug('Test update()');
$category = Category::first();
$repository = $this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once()->withNoArgs();
$repository->shouldReceive('update');
$repository->shouldReceive('findNull')->andReturn($category);
$this->session(['categories.edit.uri' => 'http://localhost']);
$data = [
'name' => 'Updated Category ' . $this->randomInt(),
'active' => 1,
];
$this->be($this->user());
$response = $this->post(route('categories.update', [1]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,86 +0,0 @@
<?php
/**
* IndexControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Category;
use Carbon\Carbon;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class IndexControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class IndexControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Category\IndexController
*/
public function testIndex(): void
{
Log::debug('Test index()');
// mock stuff
$category = $this->getRandomCategory();
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$categoryRepos->shouldReceive('getCategories')->andReturn(new Collection([$category]))->once();
$categoryRepos->shouldReceive('lastUseDate')->andReturn(new Carbon)->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->mockDefaultSession();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$this->be($this->user());
$response = $this->get(route('categories.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,202 +0,0 @@
<?php
/**
* NoCategoryControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Category;
use Carbon\Carbon;
use Exception;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use Log;
use Mockery;
use Navigation;
use Preferences;
use Tests\TestCase;
/**
*
* Class NoCategoryControllerTest
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class NoCategoryControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Category\NoCategoryController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testNoCategory(string $range): void
{
$collector = $this->mock(GroupCollectorInterface::class);
$this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$this->mockLastActivity();
// get the journal with the most recent date for firstNull:
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withoutCategory')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([])->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('categories.no-category'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Category\NoCategoryController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testNoCategoryAll(string $range): void
{
$collector = $this->mock(GroupCollectorInterface::class);
$this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$this->mockDefaultSession();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$fiscalHelper->shouldReceive('startOfFiscalYear')->andReturn(new Carbon);
$fiscalHelper->shouldReceive('endOfFiscalYear')->andReturn(new Carbon);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withoutCategory')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('categories.no-category', ['all']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Category\NoCategoryController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testNoCategoryDate(string $range): void
{
$collector = $this->mock(GroupCollectorInterface::class);
$this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$this->mockDefaultSession();
// list size
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$this->mockLastActivity();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->andReturn(true)->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withoutCategory')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([], 0, 10))->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([])->atLeast()->once();
$collector->shouldReceive('setPage')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->atLeast()->once();
Navigation::shouldReceive('updateStartDate')->andReturn(new Carbon);
Navigation::shouldReceive('updateEndDate')->andReturn(new Carbon);
Navigation::shouldReceive('startOfPeriod')->andReturn(new Carbon);
Navigation::shouldReceive('endOfPeriod')->andReturn(new Carbon);
Navigation::shouldReceive('periodShow')->andReturn('Some date');
Navigation::shouldReceive('blockPeriods')->andReturn([['period' => '1M', 'start' => new Carbon, 'end' => new Carbon]])->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('categories.no-category', ['2016-01-01']));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,158 +0,0 @@
<?php
/**
* ShowControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Category;
use Carbon\Carbon;
use Exception;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Navigation;
use Preferences;
use Tests\TestCase;
/**
*
* Class ShowControllerTest
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ShowControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Category\ShowController
*
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testShow(string $range): void
{
$withdrawal = $this->getRandomWithdrawalAsArray();
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
// mock stuff
$categoryRepos->shouldReceive('spentInPeriodCollection')->andReturn(new Collection);
$categoryRepos->shouldReceive('earnedInPeriodCollection')->andReturn(new Collection);
$categoryRepos->shouldReceive('firstUseDate')->andReturnNull();
$collector->shouldReceive('setPage')->andReturnSelf()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->times(2);
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->once();
$collector->shouldReceive('setCategory')->andReturnSelf()->atLeast()->times(2);
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([$withdrawal], 0, 10))->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([])->atLeast()->once();
Navigation::shouldReceive('updateStartDate')->andReturn(new Carbon);
Navigation::shouldReceive('updateEndDate')->andReturn(new Carbon);
Navigation::shouldReceive('startOfPeriod')->andReturn(new Carbon);
Navigation::shouldReceive('endOfPeriod')->andReturn(new Carbon);
Navigation::shouldReceive('periodShow')->andReturn('Some date');
Navigation::shouldReceive('blockPeriods')->andReturn([['period' => '1M', 'start' => new Carbon, 'end' => new Carbon]])->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('categories.show', [1]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Category\ShowController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testShowAll(string $range): void
{
$withdrawal = $this->getRandomWithdrawalAsArray();
$repository = $this->mock(CategoryRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$collector->shouldReceive('setPage')->andReturnSelf()->once();
$collector->shouldReceive('setLimit')->andReturnSelf()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->once();
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->once();
$collector->shouldReceive('setCategory')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getPaginatedGroups')->andReturn(new LengthAwarePaginator([$withdrawal], 0, 10))->once();
$repository->shouldReceive('firstUseDate')->andReturn(new Carbon);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('categories.show', [1, 'all']));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,498 +0,0 @@
<?php
/**
* AccountControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use Exception;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class AccountControllerTest
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AccountControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testExpenseAccounts(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$euro = $this->getEuro();
$dollar = $this->getDollar();
// grab two expense accounts from the current user.
$accounts = $this->user()->accounts()->where('account_type_id', 4)->take(2)->get();
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$firstId = $accounts->first()->id;
$secondId = $accounts->first()->id;
// for each a set of balances:
$start = [$firstId => [1 => '123.45', 2 => '200.01',], $secondId => [1 => '123.45', 2 => '200.01',],];
$end = [$firstId => [1 => '121.45', 2 => '234.01',], $secondId => [1 => '121.45', 2 => '234.01',],];
// return them when collected:
$accountRepos->shouldReceive('getAccountsByType')->withArgs([[AccountType::EXPENSE]])->andReturn($accounts);
// and return start and end balances:
Steam::shouldReceive('balancesPerCurrencyByAccounts')->twice()->andReturn($start, $end);
// currency should be looking for the currency ID's:
$currencyRepos->shouldReceive('findNull')->withArgs([1])->once()->andReturn($euro);
$currencyRepos->shouldReceive('findNull')->withArgs([2])->once()->andReturn($dollar);
$generator->shouldReceive('multiSet')->andReturn([])->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.expense'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testExpenseBudget(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$budget = $this->user()->budgets()->find($withdrawal['budget_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->atLeast()->once();
$budgetRepos->shouldReceive('getBudgets')->andReturn(new Collection([$budget]))->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.expense-budget', [1, '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testExpenseBudgetAll(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(FiscalHelperInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$budget = $this->user()->budgets()->find($withdrawal['budget_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withBudgetInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([]);
$budgetRepos->shouldReceive('getBudgets')->andReturn(new Collection([$budget]));
$accountRepos->shouldReceive('oldestJournalDate')->andReturn(Carbon::createFromFormat('U', time())->startOfMonth());
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.expense-budget-all', [1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testExpenseCategory(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$category = $this->user()->categories()->find($withdrawal['category_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([]);
$categoryRepos->shouldReceive('getCategories')->andReturn(new Collection([$category]));
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.expense-category', [1, '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testExpenseCategoryAll(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$category = $this->user()->categories()->find($withdrawal['category_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([]);
$categoryRepos->shouldReceive('getCategories')->andReturn(new Collection([$category]));
$accountRepos->shouldReceive('oldestJournalDate')->andReturn(Carbon::createFromFormat('U', time())->startOfMonth());
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.expense-category-all', [1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testFrontpage(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$fiscalHelper->shouldReceive('endOfFiscalYear')->andReturn(new Carbon);
$fiscalHelper->shouldReceive('startOfFiscalYear')->andReturn(new Carbon);
// change the preference:
$emptyPref = new Preference;
$emptyPref->data = [];
Preferences::shouldReceive('get')->atLeast()->once()->withArgs(['frontPageAccounts', []])->andReturn($emptyPref);
Preferences::shouldReceive('set')->atLeast()->once()->withArgs(['frontPageAccounts', []]);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$accountRepos->shouldReceive('getAccountsByType')->withArgs([[AccountType::DEFAULT, AccountType::ASSET]])->andReturn(new Collection);
$accountRepos->shouldReceive('getAccountsById')->andReturn(new Collection);
Steam::shouldReceive('balanceInRange')->andReturn([]);
$generator->shouldReceive('multiSet')->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.frontpage'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testIncomeCategory(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$category = $this->user()->categories()->find($withdrawal['category_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([]);
$categoryRepos->shouldReceive('getCategories')->andReturn(new Collection([$category]));
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.income-category', [1, '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testIncomeCategoryAll(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$category = $this->user()->categories()->find($withdrawal['category_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$collector->shouldReceive('setAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::DEPOSIT]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([]);
$categoryRepos->shouldReceive('getCategories')->andReturn(new Collection([$category]));
$accountRepos->shouldReceive('oldestJournalDate')->andReturn(Carbon::createFromFormat('U', time())->startOfMonth());
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.income-category-all', [1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testPeriod(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$accountRepos->shouldReceive('oldestJournalDate')->andReturn(new Carbon);
Steam::shouldReceive('balanceInRange')->andReturn(['2012-01-01' => '0']);
$generator->shouldReceive('singleSet')->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.period', [1, '2012-01-01', '2012-01-31']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
*/
public function testReport(): void
{
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->andReturn($this->getEuro(), null);
$generator->shouldReceive('multiSet')->andReturn([]);
Steam::shouldReceive('balanceInRange')->andReturn(['2012-01-01' => '0']);
$this->be($this->user());
$response = $this->get(route('chart.account.report', ['1,2', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\AccountController
* @dataProvider dateRangeProvider
*
* @param string $range
* @throws Exception
*/
public function testRevenueAccounts(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->andReturn(new Carbon);
$fiscalHelper->shouldReceive('startOfFiscalYear')->andReturn(new Carbon);
// grab two expense accounts from the current user.
$accounts = $this->user()->accounts()->where('account_type_id', 5)->take(2)->get();
$firstId = $accounts->first()->id;
$secondId = $accounts->first()->id;
// for each a set of balances:
$start = [$firstId => [1 => '123.45', 2 => '200.01',], $secondId => [1 => '123.45', 2 => '200.01',],];
$end = [$firstId => [1 => '121.45', 2 => '234.01',], $secondId => [1 => '121.45', 2 => '234.01',],];
// return them when collected:
$accountRepos->shouldReceive('getAccountsByType')->withArgs([[AccountType::REVENUE]])->andReturn($accounts);
// and return start and end balances:
Steam::shouldReceive('balancesPerCurrencyByAccounts')->twice()->andReturn($start, $end);
// currency should be looking for the currency ID's:
$currencyRepos->shouldReceive('findNull')->withArgs([1])->once()->andReturn($this->getEuro());
$currencyRepos->shouldReceive('findNull')->withArgs([2])->once()->andReturn(TransactionCurrency::find(2));
$generator->shouldReceive('multiSet')->andReturn([])->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.account.revenue'));
$response->assertStatus(200);
}
}

View File

@@ -1,108 +0,0 @@
<?php
/**
* BillControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Log;
use Preferences;
use Tests\TestCase;
/**
* Class BillControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BillControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BillController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testFrontpage(string $range): void
{
$generator = $this->mock(GeneratorInterface::class);
$repository = $this->mock(BillRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$amounts = [
1 => '100',
2 => '100',
];
$currencyRepos->shouldReceive('findNull')->once()->andReturn($this->getEuro())->withArgs([1]);
$currencyRepos->shouldReceive('findNull')->once()->andReturn(TransactionCurrency::find(2))->withArgs([2]);
$repository->shouldReceive('getBillsPaidInRangePerCurrency')->once()->andReturn($amounts);
$repository->shouldReceive('getBillsUnpaidInRangePerCurrency')->once()->andReturn($amounts);
$generator->shouldReceive('multiCurrencyPieChart')->once()->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.bill.frontpage'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BillController
*/
public function testSingle(): void
{
$withdrawal = $this->getRandomWithdrawalAsArray();
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$collector->shouldReceive('setBill')->andReturnSelf()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->once();
$generator->shouldReceive('multiSet')->once()->andReturn([]);
$this->be($this->user());
$response = $this->get(route('chart.bill.single', [1]));
$response->assertStatus(200);
}
}

View File

@@ -1,444 +0,0 @@
<?php
/**
* BudgetControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use Exception;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\NoBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class BudgetControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BudgetControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testBudget(string $range): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
try {
$date = new Carbon('2015-01-01');
} catch (Exception $e) {
$e->getMessage();
}
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$repository->shouldReceive('firstUseDate')->andReturn($date)->atLeast()->once();
$opsRepos->shouldReceive('sumExpenses')->andReturn([])->atLeast()->once();
// multiSet
$generator->shouldReceive('multiSet')->andReturn([])->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.budget', [1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testBudgetLimit(string $range): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$opsRepos->shouldReceive('spentInPeriod')->andReturn('-100')->atLeast()->once();
$generator->shouldReceive('singleSet')->andReturn([])->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.budget-limit', [1, 1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
*/
public function testBudgetLimitWrongLimit(): void
{
$this->mock(BudgetRepositoryInterface::class);
$this->mock(GeneratorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$budget = $this->getRandomBudget();
$limit = BudgetLimit::where('budget_id', '!=', $budget->id)->first();
// mock default session
$this->mockDefaultSession();
Log::warning('The following error is part of a test.');
$this->be($this->user());
$response = $this->get(route('chart.budget.budget-limit', [$budget->id, $limit->id]));
$response->assertStatus(500);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testExpenseAsset(string $range): void
{
$this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$destination = $this->user()->accounts()->find($withdrawal['destination_account_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$accountRepos->shouldReceive('getAccountsByType')->andReturn(new Collection([$destination]))->atLeast()->once();
$collector->shouldReceive('setBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setCurrency')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->atLeast()->once()->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.expense-asset', [1, 1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testExpenseCategory(string $range): void
{
$this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$catRepos = $this->mock(CategoryRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$category = $this->user()->categories()->find($withdrawal['category_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$collector->shouldReceive('setBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('withCategoryInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$collector->shouldReceive('setCurrency')->andReturnSelf()->atLeast()->once();
$catRepos->shouldReceive('getCategories')->andReturn(new Collection([$category]))->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.expense-category', [1, 1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testExpenseExpense(string $range): void
{
$this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$withdrawal = $this->getRandomWithdrawalAsArray();
$destination = $this->user()->accounts()->find($withdrawal['destination_account_id']);
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$collector->shouldReceive('withAccountInformation')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setBudget')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setCurrency')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$accountRepos->shouldReceive('getAccountsByType')->andReturn(new Collection([$destination]))->atLeast()->once();
$generator->shouldReceive('multiCurrencyPieChart')->once()->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.expense-expense', [1, 1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testFrontPage(string $range): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$budget = $this->getRandomBudget();
$budgetLimit = $this->getRandomBudgetLimit();
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection([$budget]))->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->atLeast()->once()->andReturn(new Collection([$budgetLimit]));
//$opsRepos->shouldReceive('spentInPeriod')->andReturn('-100')->atLeast()->once();
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
//$collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->atLeast()->once();
//$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
//$collector->shouldReceive('withoutBudget')->andReturnSelf()->atLeast()->once();
//$collector->shouldReceive('getSum')->andReturn('-100')->atLeast()->once();
$generator->shouldReceive('multiSet')->andReturn([])->atLeast()->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.frontpage'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testFrontpageMultiLimit(string $range): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$budget = $this->getRandomBudget();
$limit1 = $this->getRandomBudgetLimit();
$limit2 = $this->getRandomBudgetLimit();
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection([$budget]))->once();
$blRepos->shouldReceive('getBudgetLimits')->once()->andReturn(new Collection([$limit1, $limit2]));
//$opsRepos->shouldReceive('spentInPeriod')->andReturn('-100')->atLeast()->once();
// $collector->shouldReceive('setTypes')->withArgs([[TransactionType::WITHDRAWAL]])->andReturnSelf()->once();
// $collector->shouldReceive('setRange')->andReturnSelf()->once();
// $collector->shouldReceive('withoutBudget')->andReturnSelf()->once();
// $collector->shouldReceive('getSum')->andReturn('-100')->atLeast()->once();
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$generator->shouldReceive('multiSet')->once()->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.frontpage'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testFrontpageNoLimits(string $range): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$budget = $this->getRandomBudget();
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection([$budget]))->atLeast()->once();
$blRepos->shouldReceive('getBudgetLimits')->once()->andReturn(new Collection);
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$generator->shouldReceive('multiSet')->once()->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.budget.frontpage'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
*/
public function testPeriod(): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$budgetLimit = $this->getRandomBudgetLimit();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$date = new Carbon;
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$blRepos->shouldReceive('find')->atLeast()->once()->andReturn($budgetLimit);
$generator->shouldReceive('multiSet')->once()->andReturn([]);
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$this->be($this->user());
$response = $this->get(route('chart.budget.period', [$budgetLimit->budget_id, 1, 1, '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetController
*/
public function testPeriodNoBudget(): void
{
$repository = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$date = new Carbon;
// mock default session
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('singleSet')->once()->andReturn([]);
$nbRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->budgetSumExpenses());
$this->be($this->user());
$response = $this->get(route('chart.budget.period.no-budget', ['1','1', '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,126 +0,0 @@
<?php
/**
* BudgetReportControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class BudgetReportControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BudgetReportControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\BudgetReportController
*/
public function testBudgetExpense(): void
{
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->budgetListExpenses());
// mock default session
$this->mockDefaultSession();
//Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.budget.budget-expense', ['1', '1', '20120101', '20120131', 0]));
$response->assertStatus(200);
}
/**
* TODO something in this method makes it return a 404.
*
* @covers \FireflyIII\Http\Controllers\Chart\BudgetReportController
*/
public function testMainChart(): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$withdrawal = $this->getRandomWithdrawalAsArray();
$asset = $this->getRandomAsset();
$budget = $this->getRandomBudget();
$limit1 = $this->getRandomBudgetLimit();
$limit2 = $this->getRandomBudgetLimit();
// need to update at least one budget limit so it fits the limits that have been set below.
$limit3 = new BudgetLimit;
$limit3->budget_id = $budget->id;
$limit3->start_date = new Carbon('2012-01-01');
$limit3->end_date = new Carbon('2012-01-31');
$limit3->amount = '100';
$limit3->save();
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$this->mockDefaultSession();
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->budgetListExpenses());
$generator->shouldReceive('multiSet')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.budget.main', [$asset->id, $budget->id, '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,243 +0,0 @@
<?php
/**
* CategoryControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use FireflyIII\Support\Chart\Category\WholePeriodChartGenerator;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class CategoryControllerTest
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CategoryControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryController
* @dataProvider dateRangeProvider
*
* @param string $range
*
* @throws FireflyException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function testAll(string $range): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$repository = $this->mock(CategoryRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$chartGen = $this->mock(WholePeriodChartGenerator::class);
$firstUseDate = null;
switch ($range) {
default:
throw new FireflyException(sprintf('No case for %s', $range));
case '1D':
$firstUseDate = Carbon::now()->subDays(3);
break;
case '1W':
$firstUseDate = Carbon::now()->subDays(12);
break;
case '1M':
$firstUseDate = Carbon::now()->subDays(40);
break;
case '3M':
$firstUseDate = Carbon::now()->subDays(120);
break;
case '6M':
$firstUseDate = Carbon::now()->subDays(160);
break;
case '1Y':
$firstUseDate = Carbon::now()->subDays(365);
break;
case 'custom':
$firstUseDate = Carbon::now()->subDays(20);
break;
}
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$chartGen->shouldReceive('generate')->atLeast()->once()->andReturn([]);
$repository->shouldReceive('firstUseDate')->andReturn($firstUseDate)->once();
$generator->shouldReceive('multiSet')->once()->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.category.all', [1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryController
* @dataProvider dateRangeProvider
*
* @param string $range
*/
public function testFrontPage(string $range): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$repository = $this->mock(CategoryRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$noCatRepos = $this->mock(NoCategoryRepositoryInterface::class);
$category = $this->getRandomCategory();
$account = $this->getRandomAsset();
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->categorySumExpenses());
$noCatRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn($this->categorySumExpenses());
$repository->shouldReceive('getCategories')->atLeast()->once()->andReturn(new Collection([$category]));
$accountRepos->shouldReceive('getAccountsByType')->once()->withArgs([[AccountType::ASSET, AccountType::DEFAULT]])->andReturn(
new Collection([$account])
);
$generator->shouldReceive('multiSet')->andReturn([]);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.category.frontpage', [1]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryController
*/
public function testReportPeriod(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$repository = $this->mock(CategoryRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->categoryListExpenses());
$opsRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->categoryListIncome());
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiSet')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.category.period', [1, '1', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryController
*/
public function testReportPeriodNoCategory(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$repository = $this->mock(CategoryRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$noCatRepos = $this->mock(NoCategoryRepositoryInterface::class);
$date = new Carbon;
$noCatRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->noCategoryListExpenses());
$noCatRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->noCategoryListIncome());
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiSet')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.category.period.no-category', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryController
* @dataProvider dateRangeProvider
*
* @param string $range
*
* @throws Exception
*/
public function testSpecificPeriod(string $range): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$repository = $this->mock(CategoryRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$chartGen = $this->mock(WholePeriodChartGenerator::class);
$account = $this->getRandomAsset();
$date = new Carbon;
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$chartGen->shouldReceive('generate')->atLeast()->once()->andReturn([]);
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$accountRepos->shouldReceive('getAccountsByType')->andReturn(new Collection([$account]));
$generator->shouldReceive('multiSet')->andReturn([])->once();
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('chart.category.specific', ['1', '2012-01-01']));
$response->assertStatus(200);
}
}

View File

@@ -1,129 +0,0 @@
<?php
/**
* CategoryReportControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use Log;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class CategoryReportControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CategoryReportControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryReportController
*/
public function testCategoryExpense(): void
{
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$this->mockDefaultSession();
//Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->categoryListExpenses());
$this->be($this->user());
$response = $this->get(route('chart.category.category-expense', ['1', '1', '20120101', '20120131', 0]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryReportController
*/
public function testCategoryIncome(): void
{
$generator = $this->mock(GeneratorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$this->mockDefaultSession();
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$opsRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->categoryListIncome());
$this->be($this->user());
$response = $this->get(route('chart.category.category-income', ['1', '1', '20120101', '20120131', 0]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\CategoryReportController
*/
public function testMainChart(): void
{
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$withdrawal = $this->getRandomWithdrawalAsArray();
$this->mockDefaultSession();
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiSet')->andReturn([])->once();
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->categoryListExpenses());
$opsRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->categoryListIncome());
$this->be($this->user());
$response = $this->get(route('chart.category.main', ['1', '1', '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,73 +0,0 @@
<?php
/**
* PiggyBankControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\TestCase;
/**
* Class PiggyBankControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class PiggyBankControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\PiggyBankController
*/
public function testHistory(): void
{
$generator = $this->mock(GeneratorInterface::class);
$repository = $this->mock(PiggyBankRepositoryInterface::class);
/** @var PiggyBankEvent $event */
$event = PiggyBankEvent::inRandomOrder()->first();
$piggy = $event->piggy_bank_id;
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$repository->shouldReceive('getEvents')->andReturn(new Collection([$event]));
$generator->shouldReceive('singleSet')->once()->andReturn([]);
$this->be($this->user());
$response = $this->get(route('chart.piggy-bank.history', [$piggy]));
$response->assertStatus(200);
}
}

View File

@@ -1,132 +0,0 @@
<?php
/**
* ReportControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Account\AccountTaskerInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class ReportControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ReportControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\ReportController
*/
public function testNetWorth(): void
{
$generator = $this->mock(GeneratorInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$netWorth = $this->mock(NetWorthInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$netWorth->shouldReceive('getNetWorthByCurrency')->andReturn(
[
[
'currency' => $this->getEuro(),
'balance' => '123',
],
]
);
$netWorth->shouldReceive('setUser')->atLeast()->once();
// mock calls:
$accountRepos->shouldReceive('setUser');
$accountRepos->shouldReceive('getMetaValue')->times(2)
->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1', '0');
$accountRepos->shouldReceive('getMetaValue')
->withArgs([Mockery::any(), 'currency_id'])->andReturn(1);
$accountRepos->shouldReceive('getMetaValue')
->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
Steam::shouldReceive('balancesByAccounts')->andReturn(['5', '10']);
$generator->shouldReceive('multiSet')->andReturn([]);
$this->be($this->user());
$response = $this->get(route('chart.report.net-worth', ['1,2', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\ReportController
*/
public function testOperations(): void
{
$generator = $this->mock(GeneratorInterface::class);
$tasker = $this->mock(AccountTaskerInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$income = [
'accounts' => [
1 => ['sum' => '100']]];
$expense = [
'accounts' => [
2 => ['sum' => '-100']]];
$generator->shouldReceive('multiSet')->andReturn([]);
$this->be($this->user());
$response = $this->get(route('chart.report.operations', [1, '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,217 +0,0 @@
<?php
/**
* TagReportControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Chart;
use Carbon\Carbon;
use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Tag\OperationsRepositoryInterface;
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class TagReportControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class TagReportControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\TagReportController
*/
public function testBudgetExpense(): void
{
$generator = $this->mock(GeneratorInterface::class);
$tagRepos = $this->mock(TagRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->tagListExpenses());
$tag = $this->user()->tags()->first();
$tagRepos->shouldReceive('setUser');
$tagRepos->shouldReceive('get')->andReturn(new Collection([$tag]));
$this->mockDefaultSession();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.tag.budget-expense', ['1', $tag->tag, '20120101', '20120131', 0]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\TagReportController
*/
public function testCategoryExpense(): void
{
$generator = $this->mock(GeneratorInterface::class);
$tagRepos = $this->mock(TagRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$tag = $this->user()->tags()->first();
$tagRepos->shouldReceive('setUser');
$tagRepos->shouldReceive('get')->andReturn(new Collection([$tag]));
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->tagListExpenses());
$this->mockDefaultSession();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.tag.category-expense', ['1', $tag->tag, '20120101', '20120131', 0]));
$response->assertStatus(200);
}
/**
* TODO something in this test sometimes gives a 404 but not sure yet what it is.
*
* @covers \FireflyIII\Http\Controllers\Chart\TagReportController
*/
public function testMainChart(): void
{
$this->mock(AccountRepositoryInterface::class);
$generator = $this->mock(GeneratorInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$tagRepos = $this->mock(TagRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->tagListExpenses());
$opsRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->tagListIncome());
$withdrawal = $this->getRandomWithdrawalAsArray();
$tag = $this->user()->tags()->where('tag', 'Expensive')->first();
$date = new Carbon;
$false = new Preference;
$false->data = false;
$this->mockDefaultSession();
$tagRepos->shouldReceive('setUser');
$tagRepos->shouldReceive('get')->andReturn(new Collection([$tag]));
Preferences::shouldReceive('get')->withArgs(['customFiscalYear', false])->andReturn($false);
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiSet')->andReturn([])->once()->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('chart.tag.main', ['1', $tag->id, '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\TagReportController
*/
public function testTagExpense(): void
{
$this->mockDefaultSession();
$generator = $this->mock(GeneratorInterface::class);
$tagRepos = $this->mock(TagRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->tagListExpenses());
$this->mock(AccountRepositoryInterface::class);
$tag = $this->user()->tags()->first();
$tagRepos->shouldReceive('setUser');
$tagRepos->shouldReceive('get')->andReturn(new Collection([$tag]));
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.tag.tag-expense', ['1', $tag->tag, '20120101', '20120131', 0]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Chart\TagReportController
*/
public function testTagIncome(): void
{
$this->mockDefaultSession();
$generator = $this->mock(GeneratorInterface::class);
$tagRepos = $this->mock(TagRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$opsRepos->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->tagListIncome());
$tag = $this->user()->tags()->first();
$tagRepos->shouldReceive('setUser');
$tagRepos->shouldReceive('get')->andReturn(new Collection([$tag]));
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$generator->shouldReceive('multiCurrencyPieChart')->andReturn([])->once();
$this->be($this->user());
$response = $this->get(route('chart.tag.tag-income', ['1', $tag->tag, '20120101', '20120131', 0]));
$response->assertStatus(200);
}
}

View File

@@ -1,533 +0,0 @@
<?php
/**
* CurrencyControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class CurrencyControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CurrencyControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testCannotCreate(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_currencies_create');
// mock stuff
$this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('currencies.create'));
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testCannotDelete(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$repository->shouldReceive('currencyInUse')->andReturn(true);
$repository->shouldReceive('currencyInUseAt')->andReturn('something');
$userRepos->shouldReceive('hasRole')->once()->andReturn(true);
$this->be($this->user());
$response = $this->get(route('currencies.delete', [$euro->id]));
$response->assertStatus(302);
// has bread crumb
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testCannotDestroy(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$repository->shouldReceive('currencyInUse')->andReturn(true);
$userRepos->shouldReceive('hasRole')->once()->andReturn(true);
$this->session(['currencies.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('currencies.destroy', [$euro->id]));
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testCreate(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_currencies_create');
// mock stuff
$this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$this->be($this->user());
$response = $this->get(route('currencies.create'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDefaultCurrency(): void
{
$this->mockDefaultSession();
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$currencyRepos->shouldReceive('enable')->once();
Preferences::shouldReceive('mark')->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['currencyPreference', $euro->code])->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('currencies.default', [$euro->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDelete(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$repository->shouldReceive('currencyInUse')->andReturn(false);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$this->be($this->user());
$response = $this->get(route('currencies.delete', [$euro->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDestroy(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$repository->shouldReceive('currencyInUse')->andReturn(false);
$repository->shouldReceive('destroy')->andReturn(true)->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(1)->andReturn(true);
$this->session(['currencies.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('currencies.destroy', [$euro->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDisable(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
Preferences::shouldReceive('mark')->atLeast()->once();
$userRepos->shouldReceive('hasRole')->atLeast()->once()->andReturn(true);
$repository->shouldReceive('currencyInuse')->atLeast()->once()->andReturn(false);
$repository->shouldReceive('disable')->atLeast()->once()->andReturn(false);
$repository->shouldReceive('get')->atLeast()->once()->andReturn(new Collection([$euro]));
$this->be($this->user());
$response = $this->get(route('currencies.disable', [$euro->id]));
$response->assertStatus(302);
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDisableEnableFirst(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$userRepos->shouldReceive('hasRole')->atLeast()->once()->andReturn(true);
$repository->shouldReceive('currencyInuse')->atLeast()->once()->andReturn(false);
$repository->shouldReceive('disable')->atLeast()->once()->andReturn(false);
$repository->shouldReceive('get')->atLeast()->once()->andReturn(new Collection);
$repository->shouldReceive('getAll')->atLeast()->once()->andReturn(new Collection([$euro]));
$repository->shouldReceive('enable')->atLeast()->once()->andReturn(true);
Preferences::shouldReceive('mark')->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['currencyPreference', $euro->code])->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('currencies.disable', [$euro->id]));
$response->assertStatus(302);
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDisableInUse(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$userRepos->shouldReceive('hasRole')->atLeast()->once()->andReturn(true);
$repository->shouldReceive('currencyInuse')->atLeast()->once()->andReturn(true);
$repository->shouldReceive('currencyInUseAt')->atLeast()->once()->andReturn('accounts');
$repository->shouldNotReceive('disable');
Preferences::shouldReceive('mark')->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('currencies.disable', [$euro->id]));
$response->assertStatus(302);
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testDisableNothingLeft(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$userRepos->shouldReceive('hasRole')->atLeast()->once()->andReturn(true);
$repository->shouldReceive('currencyInuse')->atLeast()->once()->andReturn(false);
$repository->shouldReceive('disable')->atLeast()->once()->andReturn(false);
$repository->shouldReceive('get')->atLeast()->once()->andReturn(new Collection);
$repository->shouldReceive('getAll')->atLeast()->once()->andReturn(new Collection);
Preferences::shouldReceive('mark')->atLeast()->once();
Log::warning('The following error is part of a test.');
$this->be($this->user());
$response = $this->get(route('currencies.disable', [$euro->id]));
$response->assertStatus(500);
$response->assertSee('No currencies found.');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testEdit(): void
{
$this->mockDefaultSession();
// mock stuff
$this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$this->be($this->user());
$response = $this->get(route('currencies.edit', [$euro->id]));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testEnable(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$repository->shouldReceive('enable')->atLeast()->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('currencies.enable', [$euro->id]));
$response->assertStatus(302);
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_currencies_index');
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$currencies = TransactionCurrency::get();
$repository->shouldReceive('getCurrencyByPreference')->andReturn($currencies->first());
$repository->shouldReceive('getAll')->andReturn($currencies);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(true);
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$pref = new Preference;
$pref->data = 'EUR';
Preferences::shouldReceive('get')->withArgs(['currencyPreference', 'EUR'])->atLeast()->once()->andReturn($pref);
$this->be($this->user());
$response = $this->get(route('currencies.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
*/
public function testIndexNoRights(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_currencies_index');
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('getCurrencyByPreference')->andReturn(new TransactionCurrency);
$repository->shouldReceive('getAll')->andReturn(new Collection);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->times(2)->andReturn(false);
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$pref = new Preference;
$pref->data = 'EUR';
Preferences::shouldReceive('get')->withArgs(['currencyPreference', 'EUR'])->atLeast()->once()->andReturn($pref);
$this->be($this->user());
$response = $this->get(route('currencies.index'));
$response->assertStatus(200);
// has bread crumb
$response->assertSee('<ol class="breadcrumb">');
$response->assertSessionHas('info');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
* @covers \FireflyIII\Http\Requests\CurrencyFormRequest
*/
public function testStore(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('store')->andReturn(new TransactionCurrency);
$userRepos->shouldReceive('hasRole')->once()->andReturn(true);
$this->session(['currencies.create.uri' => 'http://localhost']);
$data = [
'name' => 'XX',
'code' => 'XXX',
'symbol' => 'x',
'decimal_places' => 2,
];
$this->be($this->user());
$response = $this->post(route('currencies.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
* @covers \FireflyIII\Http\Requests\CurrencyFormRequest
*/
public function testStoreError(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('store')->andThrow(new FireflyException('Could not store'));
$userRepos->shouldReceive('hasRole')->once()->andReturn(true);
$this->session(['currencies.create.uri' => 'http://localhost']);
$data = [
'name' => 'XX',
'code' => 'XXX',
'symbol' => 'x',
'decimal_places' => 2,
];
$this->be($this->user());
$response = $this->post(route('currencies.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('error', 'Could not store the new currency.');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
* @covers \FireflyIII\Http\Requests\CurrencyFormRequest
*/
public function testStoreNoRights(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('store')->andReturn(new TransactionCurrency);
$userRepos->shouldReceive('hasRole')->once()->andReturn(true);
$this->session(['currencies.create.uri' => 'http://localhost']);
$data = [
'name' => 'XX',
'code' => 'XXX',
'symbol' => 'x',
'decimal_places' => 2,
];
$this->be($this->user());
$response = $this->post(route('currencies.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\CurrencyController
* @covers \FireflyIII\Http\Requests\CurrencyFormRequest
*/
public function testUpdate(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('update')->andReturn(new TransactionCurrency);
$userRepos->shouldReceive('hasRole')->once()->andReturn(true);
$repository->shouldReceive('currencyInUse')->atLeast()->once()->andReturn(true);
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['currencies.edit.uri' => 'http://localhost']);
$data = [
'id' => 2,
'name' => 'XA',
'code' => 'XAX',
'symbol' => 'a',
'decimal_places' => 2,
];
$this->be($this->user());
$response = $this->post(route('currencies.update', [2]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,131 +0,0 @@
<?php
/**
* DebugControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class HomeControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class DebugControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\DebugController
*/
public function testDisplayError(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('error'));
$response->assertStatus(500);
$response->assertSee('A very simple test error');
}
/**
* @covers \FireflyIII\Http\Controllers\DebugController
*/
public function testFlush(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
Preferences::shouldReceive('mark')->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('flush'));
$response->assertStatus(302);
}
/**
* @covers \FireflyIII\Http\Controllers\DebugController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('debug'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\DebugController
*/
public function testRoutes(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('routes'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\DebugController
*/
public function testTestFlash(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('test-flash'));
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertSessionHas('info');
$response->assertSessionHas('warning');
$response->assertSessionHas('error');
}
}

View File

@@ -1,156 +0,0 @@
<?php
/**
* HelpControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use FireflyIII\Helpers\Help\HelpInterface;
use FireflyIII\Models\Preference;
use Log;
use Tests\TestCase;
/**
* Class HelpControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class HelpControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\HelpController
*/
public function testShow(): void
{
$this->mockDefaultSession();
$help = $this->mock(HelpInterface::class);
$help->shouldReceive('hasRoute')->andReturn(true)->once();
$help->shouldReceive('inCache')->andReturn(false)->once();
$help->shouldReceive('getFromGithub')->andReturn('Recent new content here.')->once();
$help->shouldReceive('putInCache')->once();
$this->be($this->user());
$response = $this->get(route('help.show', ['index']));
$response->assertStatus(200);
$response->assertSee('Recent new content here.');
}
/**
* @covers \FireflyIII\Http\Controllers\HelpController
*/
public function testShowBackupFromCache(): void
{
$this->mockDefaultSession();
$help = $this->mock(HelpInterface::class);
$help->shouldReceive('hasRoute')->withArgs(['index'])->andReturn(true)->once();
$help->shouldReceive('inCache')->withArgs(['index', 'en_US'])->andReturn(false)->once();
$help->shouldReceive('getFromGithub')->withArgs(['index', 'en_US'])->andReturn('')->once();
// is US in cache?
$help->shouldReceive('inCache')->withArgs(['index', 'en_US'])->andReturn(true)->once();
$help->shouldReceive('getFromCache')->withArgs(['index', 'en_US'])->andReturn('US from cache.')->once();
$this->be($this->user());
$response = $this->get(route('help.show', ['index']));
$response->assertStatus(200);
$response->assertSee('US from cache.');
// put English back:
Preference::where('user_id', $this->user()->id)->where('name', 'language')->delete();
Preference::create(['user_id' => $this->user()->id, 'name' => 'language', 'data' => 'en_US']);
}
/**
* @covers \FireflyIII\Http\Controllers\HelpController
*/
public function testShowBackupFromGithub(): void
{
$this->mockDefaultSession();
$help = $this->mock(HelpInterface::class);
$help->shouldReceive('hasRoute')->withArgs(['index'])->andReturn(true)->once();
$help->shouldReceive('inCache')->withArgs(['index', 'en_US'])->andReturn(false)->once();
$help->shouldReceive('getFromGithub')->withArgs(['index', 'en_US'])->andReturn('')->once();
// is US in cache?
$help->shouldReceive('inCache')->withArgs(['index', 'en_US'])->andReturn(false)->once();
$help->shouldReceive('getFromGithub')->withArgs(['index', 'en_US'])->andReturn('')->once();
$help->shouldReceive('putInCache')->once();
$this->be($this->user());
$response = $this->get(route('help.show', ['index']));
$response->assertStatus(200);
$response->assertSee('This help text is not yet available in your language');
// put English back:
Preference::where('user_id', $this->user()->id)->where('name', 'language')->delete();
Preference::create(['user_id' => $this->user()->id, 'name' => 'language', 'data' => 'en_US']);
}
/**
* @covers \FireflyIII\Http\Controllers\HelpController
*/
public function testShowCached(): void
{
$this->mockDefaultSession();
$help = $this->mock(HelpInterface::class);
$help->shouldReceive('hasRoute')->andReturn(true)->once();
$help->shouldReceive('inCache')->andReturn(true)->once();
$help->shouldReceive('getFromCache')->andReturn('Cached help content here.')->once();
$this->be($this->user());
$response = $this->get(route('help.show', ['index']));
$response->assertStatus(200);
$response->assertSee('Cached help content here.');
}
/**
* @covers \FireflyIII\Http\Controllers\HelpController
*/
public function testShowNoRoute(): void
{
$this->mockDefaultSession();
$help = $this->mock(HelpInterface::class);
$help->shouldReceive('hasRoute')->andReturn(false)->once();
$this->be($this->user());
$response = $this->get(route('help.show', ['index']));
$response->assertStatus(200);
$response->assertSee('There is no help for this route.');
}
}

View File

@@ -1,174 +0,0 @@
<?php
/**
* HomeControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use Amount;
use Event;
use FireflyIII\Events\RequestedVersionCheckStatus;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class HomeControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class HomeControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\HomeController
*/
public function testDateRange(): void
{
$this->mockDefaultSession();
$this->be($this->user());
$args = [
'start' => '2012-01-01',
'end' => '2012-04-01',
];
$response = $this->post(route('daterange'), $args);
$response->assertStatus(200);
$response->assertSessionHas('warning', '91 days of data may take a while to load.');
}
/**
* @covers \FireflyIII\Http\Controllers\HomeController
*/
public function testDateRangeCustom(): void
{
$this->mockDefaultSession();
$this->be($this->user());
$args = [
'start' => '2012-01-01',
'end' => '2012-04-01',
'label' => 'Custom range',
];
$response = $this->post(route('daterange'), $args);
$response->assertStatus(200);
$response->assertSessionHas('warning', '91 days of data may take a while to load.');
}
/**
* @covers \FireflyIII\Http\Controllers\HomeController
* @covers \FireflyIII\Http\Controllers\Controller
* @dataProvider dateRangeProvider
*
* @param $range
*/
public function testIndex(string $range): void
{
Event::fake();
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_index');
$account = $this->getRandomAsset();
$pref = new Preference;
$pref->data = [$account->id];
Preferences::shouldReceive('get')->withArgs(['frontPageAccounts', [$account->id]])->atLeast()->once()->andReturn($pref);
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
Steam::shouldReceive('balance')->atLeast()->once()->andReturn('5');
// mock stuff
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$billRepos = $this->mock(BillRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$accountRepos->shouldReceive('count')->andReturn(1)->atLeast()->once();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getAccountsByType')->withArgs([[AccountType::DEFAULT, AccountType::ASSET]])->andReturn(new Collection([$account]))->atLeast()->once();
$accountRepos->shouldReceive('getAccountsById')->andReturn(new Collection([$account]))->atLeast()->once();
$accountRepos->shouldReceive('getAccountCurrency')->andReturn($euro)->atLeast()->once();
$billRepos->shouldReceive('getBills')->andReturn(new Collection)->atLeast()->once();
// $currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($euro);
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setLimit')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withAccountInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setPage')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getGroups')->atLeast()->once()->andReturn(new Collection);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('index'));
$response->assertStatus(200);
Event::assertDispatched(RequestedVersionCheckStatus::class);
}
/**
* @covers \FireflyIII\Http\Controllers\HomeController
* @covers \FireflyIII\Http\Controllers\Controller
* @dataProvider dateRangeProvider
*
* @param $range
*/
public function testIndexEmpty(string $range): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_index');
// mock stuff
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('count')->andReturn(0);
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('index'));
$response->assertStatus(302);
}
}

View File

@@ -1,172 +0,0 @@
<?php
/**
* JavascriptControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use Amount;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class JavascriptControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class JavascriptControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\JavascriptController
*/
public function testAccounts(): void
{
$this->mockDefaultSession();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$account = $this->getRandomAsset();
$euro = $this->getEuro();
$pref = new Preference;
$pref->data = 'EUR';
Preferences::shouldReceive('get')->withArgs(['currencyPreference', 'EUR'])->atLeast()->once()->andReturn($pref);
$accountRepos->shouldReceive('getAccountsByType')->andReturn(new Collection([$account]))->withArgs([[AccountType::DEFAULT, AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD]])->once();
$currencyRepos->shouldReceive('findByCodeNull')->withArgs(['EUR'])->andReturn($euro);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$this->be($this->user());
$response = $this->get(route('javascript.accounts'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\JavascriptController
*/
public function testCurrencies(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$euro = $this->getEuro();
$repository->shouldReceive('get')->andReturn(new Collection([$euro]));
$this->be($this->user());
$response = $this->get(route('javascript.currencies'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\JavascriptController
*
* @param string $range
*
* @dataProvider dateRangeProvider
*/
public function testVariables(string $range): void
{
$this->mockDefaultSession();
$account = $this->getRandomAsset();
$euro = $this->getEuro();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos->shouldReceive('findNull')->andReturn($account);
$currencyRepos->shouldReceive('findNull')->andReturn($euro);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('javascript.variables'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\JavascriptController
*
* @param string $range
*
* @dataProvider dateRangeProvider
*/
public function testVariablesCustom(string $range): void
{
$this->mockDefaultSession();
$account = $this->getRandomAsset();
$euro = $this->getEuro();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos->shouldReceive('findNull')->andReturn($account);
$currencyRepos->shouldReceive('findNull')->andReturn($euro);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$this->session(['is_custom_range' => true]);
$response = $this->get(route('javascript.variables'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\JavascriptController
*
* @param string $range
*
* @dataProvider dateRangeProvider
*/
public function testVariablesNull(string $range): void
{
$this->mockDefaultSession();
$account = $this->getRandomAsset();
$euro = $this->getEuro();
//Amount::shouldReceive('getDefaultCurrency')->andReturn($euro)->times(2);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos->shouldReceive('findNull')->andReturn($account);
$currencyRepos->shouldReceive('findNull')->andReturn(null);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$this->be($this->user());
$this->changeDateRange($this->user(), $range);
$response = $this->get(route('javascript.variables'));
$response->assertStatus(200);
}
}

View File

@@ -1,180 +0,0 @@
<?php
/**
* AutoCompleteControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use FireflyIII\Models\AccountType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Tests\TestCase;
/**
* Class AutoCompleteControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class AutoCompleteControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Request a list of asset accounts
*
* @covers \FireflyIII\Http\Controllers\Json\AutoCompleteController
*/
public function testAccounts(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$account = $this->getRandomAsset();
$euro = $this->getEuro();
$accountRepos->shouldReceive('searchAccount')->atLeast()->once()->andReturn(new Collection([$account]));
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$this->mockDefaultSession();
$this->be($this->user());
$httpQuery = http_build_query(['types' => AccountType::ASSET]);
$response = $this->get(route('json.autocomplete.accounts') . '?' . $httpQuery);
$response->assertStatus(200);
$response->assertSee($account->name);
}
/**
* Request a list of revenue accounts
*
* @covers \FireflyIII\Http\Controllers\Json\AutoCompleteController
*/
public function testRevenueAccounts(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$account = $this->getRandomAsset();
$accountRepos->shouldReceive('searchAccount')->atLeast()->once()->andReturn(new Collection([$account]));
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('json.autocomplete.revenue-accounts'));
$response->assertStatus(200);
$response->assertSee($account->name);
}
/**
* Request a list of expense accounts
*
* @covers \FireflyIII\Http\Controllers\Json\AutoCompleteController
*/
public function testExpenseAccounts(): void
{
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$account = $this->getRandomAsset();
$accountRepos->shouldReceive('searchAccount')->atLeast()->once()->andReturn(new Collection([$account]));
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('json.autocomplete.expense-accounts'));
$response->assertStatus(200);
$response->assertSee($account->name);
}
/**
* Request a list of expense accounts
*
* @covers \FireflyIII\Http\Controllers\Json\AutoCompleteController
*/
public function testAllJournals(): void
{
$groupRepos = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mockDefaultSession();
$journal = $this->getRandomWithdrawalAsArray();
$journalRepos->shouldReceive('searchJournalDescriptions')->atLeast()->once()->andReturn(new Collection([$journal]));
$this->be($this->user());
$response = $this->get(route('json.autocomplete.all-journals'));
$response->assertStatus(200);
$response->assertSee($journal['description']);
}
/**
* Request a list of expense accounts
*
* @covers \FireflyIII\Http\Controllers\Json\AutoCompleteController
*/
public function testAllJournalsWithId(): void
{
$groupRepos = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mockDefaultSession();
$journal = $this->getRandomWithdrawalAsArray();
$journalRepos->shouldReceive('searchJournalDescriptions')->atLeast()->once()->andReturn(new Collection([$journal]));
$this->be($this->user());
$response = $this->get(route('json.autocomplete.all-journals-with-id'));
$response->assertStatus(200);
$response->assertSee($journal['description']);
$response->assertSee($journal['id']);
}
/**
* Request a list of expense accounts
*
* @covers \FireflyIII\Http\Controllers\Json\AutoCompleteController
*/
public function testAllJournalsWithIdNumeric(): void
{
$groupRepos = $this->mock(TransactionGroupRepositoryInterface::class);
$journalRepos = $this->mockDefaultSession();
$journal = $this->getRandomWithdrawalAsArray();
$journalObject = $this->getRandomWithdrawalGroup();
$journalRepos->shouldReceive('searchJournalDescriptions')->atLeast()->once()->andReturn(new Collection([$journal]));
$groupRepos->shouldReceive('find')->atLeast()->once()->andReturn($journalObject);
$this->be($this->user());
$response = $this->get(route('json.autocomplete.all-journals-with-id') . '?search=' . $journal['id']);
$response->assertStatus(200);
$response->assertSee($journal['description']);
$response->assertSee($journal['id']);
}
}

View File

@@ -1,398 +0,0 @@
<?php
/**
* BoxControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use Amount;
use Carbon\Carbon;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class BoxControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class BoxControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testAvailable(): void
{
$this->mockDefaultSession();
$return = [
0 => [
'spent' => '-1200', // more than budgeted.
],
];
$repository = $this->mock(BudgetRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$opsRepository = $this->mock(OperationsRepositoryInterface::class);
$abRepository = $this->mock(AvailableBudgetRepositoryInterface::class);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('-100');
$abRepository->shouldReceive('getAvailableBudget')->andReturn('1000');
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection);
$opsRepository->shouldReceive('collectBudgetInformation')->andReturn($return);
$this->be($this->user());
$response = $this->get(route('json.box.available'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testAvailableDays(): void
{
$this->mockDefaultSession();
$return = [
0 => [
'spent' => '-800', // more than budgeted.
],
];
$repository = $this->mock(BudgetRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$opsRepository = $this->mock(OperationsRepositoryInterface::class);
$abRepository = $this->mock(AvailableBudgetRepositoryInterface::class);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('-100');
$abRepository->shouldReceive('getAvailableBudget')->andReturn('1000');
$repository->shouldReceive('getActiveBudgets')->andReturn(new Collection);
$opsRepository->shouldReceive('collectBudgetInformation')->andReturn($return);
$this->be($this->user());
$response = $this->get(route('json.box.available'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testBalance(): void
{
$this->mockDefaultSession();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('-100');
// try a collector for income:
//$collector->shouldReceive('setAllAssetAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
//$collector->shouldReceive('withOpposingAccount')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([])->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('json.box.balance'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testBalanceTransactions(): void
{
$withdrawal = $this->getRandomWithdrawalAsArray();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$euro = $this->getEuro();
$this->mockDefaultSession();
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('-100');
// try a collector for income:
//$collector->shouldReceive('setAllAssetAccounts')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setRange')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('setTypes')->andReturnSelf()->atLeast()->once();
//$collector->shouldReceive('withOpposingAccount')->andReturnSelf()->atLeast()->once();
$collector->shouldReceive('getExtractedJournals')->andReturn([$withdrawal])->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($euro);
$this->be($this->user());
$response = $this->get(route('json.box.balance'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testBills(): void
{
$this->mockDefaultSession();
$billRepos = $this->mock(BillRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->andReturn('-100');
$billRepos->shouldReceive('getBillsPaidInRange')->andReturn('0');
$billRepos->shouldReceive('getBillsUnpaidInRange')->andReturn('0');
$this->be($this->user());
$response = $this->get(route('json.box.bills'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testNetWorth(): void
{
$this->mockDefaultSession();
$result = [
[
'currency' => $this->getEuro(),
'balance' => '3',
],
];
$netWorthHelper = $this->mock(NetWorthInterface::class);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$netWorthHelper->shouldReceive('setUser')->once();
$netWorthHelper->shouldReceive('getNetWorthByCurrency')->once()->andReturn($result);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$this->user()->accounts()->first()]));
$currencyRepos->shouldReceive('findNull')->andReturn($this->getEuro());
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$this->be($this->user());
$response = $this->get(route('json.box.net-worth'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testNetWorthFuture(): void
{
$this->mockDefaultSession();
$result = [
[
'currency' => $this->getEuro(),
'balance' => '3',
],
];
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$netWorthHelper = $this->mock(NetWorthInterface::class);
$netWorthHelper->shouldReceive('setUser')->once();
$netWorthHelper->shouldReceive('getNetWorthByCurrency')->once()->andReturn($result);
$accountRepos->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$this->user()->accounts()->first()]));
$currencyRepos->shouldReceive('findNull')->andReturn($this->getEuro());
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$start = new Carbon;
$start->addMonths(6)->startOfMonth();
$end = clone $start;
$end->endOfMonth();
$this->session(['start' => $start, 'end' => $end]);
$this->be($this->user());
$response = $this->get(route('json.box.net-worth'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testNetWorthPast(): void
{
$this->mockDefaultSession();
$result = [
[
'currency' => $this->getEuro(),
'balance' => '3',
],
];
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$netWorthHelper = $this->mock(NetWorthInterface::class);
$netWorthHelper->shouldReceive('setUser')->once();
$netWorthHelper->shouldReceive('getNetWorthByCurrency')->once()->andReturn($result);
$accountRepos->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$this->user()->accounts()->first()]));
$currencyRepos->shouldReceive('findNull')->andReturn($this->getEuro());
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$start = new Carbon;
$start->subMonths(6)->startOfMonth();
$end = clone $start;
$end->endOfMonth();
$this->session(['start' => $start, 'end' => $end]);
$this->be($this->user());
$response = $this->get(route('json.box.net-worth'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testNetWorthNoCurrency(): void
{
$this->mockDefaultSession();
$result = [
[
'currency' => $this->getEuro(),
'balance' => '3',
],
];
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$netWorthHelper = $this->mock(NetWorthInterface::class);
$netWorthHelper->shouldReceive('setUser')->once();
$netWorthHelper->shouldReceive('getNetWorthByCurrency')->once()->andReturn($result);
$accountRepos->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$this->user()->accounts()->first()]));
$currencyRepos->shouldReceive('findNull')->andReturn(null);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$this->be($this->user());
$response = $this->get(route('json.box.net-worth'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testNetWorthNoInclude(): void
{
$this->mockDefaultSession();
$result = [
[
'currency' => $this->getEuro(),
'balance' => '3',
],
];
$netWorthHelper = $this->mock(NetWorthInterface::class);
$netWorthHelper->shouldReceive('setUser')->once();
$netWorthHelper->shouldReceive('getNetWorthByCurrency')->once()->andReturn($result);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$this->user()->accounts()->first()]));
$currencyRepos->shouldReceive('findNull')->andReturn($this->getEuro());
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('0');
$this->be($this->user());
$response = $this->get(route('json.box.net-worth'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\BoxController
*/
public function testNetWorthVirtual(): void
{
$this->mockDefaultSession();
$result = [
[
'currency' => $this->getEuro(),
'balance' => '3',
],
];
$account = $this->user()->accounts()->first();
$account->virtual_balance = '1000';
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
Amount::shouldReceive('formatAnything')->andReturn('-100');
$netWorthHelper = $this->mock(NetWorthInterface::class);
$netWorthHelper->shouldReceive('setUser')->once();
$netWorthHelper->shouldReceive('getNetWorthByCurrency')->once()->andReturn($result);
$accountRepos->shouldReceive('getActiveAccountsByType')->andReturn(new Collection([$account]));
$currencyRepos->shouldReceive('findNull')->andReturn($this->getEuro());
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'accountRole'])->andReturn('ccAsset');
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'include_net_worth'])->andReturn('1');
$this->be($this->user());
$response = $this->get(route('json.box.net-worth'));
$response->assertStatus(200);
}
}

View File

@@ -1,115 +0,0 @@
<?php
/**
* ExchangeControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use Carbon\Carbon;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Services\Currency\ExchangeRateInterface;
use Log;
use Tests\TestCase;
/**
* Class ExchangeControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ExchangeControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Json\ExchangeController
*/
public function testGetRate(): void
{
$repository = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$this->mockDefaultSession();
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$rate = $this->getRandomCer();
$repository->shouldReceive('getExchangeRate')->andReturn($rate);
$this->be($this->user());
$response = $this->get(route('json.rate', ['EUR', 'USD', '20170101']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\ExchangeController
*/
public function testGetRateAmount(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$rate = $this->getRandomCer();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$repository->shouldReceive('getExchangeRate')->andReturn($rate);
$this->be($this->user());
$response = $this->get(route('json.rate', ['EUR', 'USD', '20170101']) . '?amount=10');
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\ExchangeController
*/
public function testGetRateNull(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$rate = $this->getRandomCer();
$repository->shouldReceive('getExchangeRate')->andReturnNull();
$interface = $this->mock(ExchangeRateInterface::class);
$interface->shouldReceive('setUser')->once();
$interface->shouldReceive('getRate')->andReturn($rate);
$this->be($this->user());
$response = $this->get(route('json.rate', ['EUR', 'USD', '20170101']));
$response->assertStatus(200);
}
}

View File

@@ -1,69 +0,0 @@
<?php
/**
* FrontpageControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Tests\TestCase;
use Amount;
/**
* Class FrontpageControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class FrontpageControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Json\FrontpageController
*/
public function testPiggyBanks(): void
{
$this->mockDefaultSession();
$piggy = $this->user()->piggyBanks()->first();
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$repository->shouldReceive('getPiggyBanks')->andReturn(new Collection([$piggy]));
$repository->shouldReceive('getCurrentAmount')->andReturn('10');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$this->be($this->user());
$response = $this->get(route('json.fp.piggy-banks'));
$response->assertStatus(200);
}
}

View File

@@ -1,110 +0,0 @@
<?php
/**
* IntroControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use Log;
use Preferences;
use Tests\TestCase;
/**
* Class IntroControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class IntroControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Json\IntroController
*/
public function testGetIntroSteps(): void
{
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('json.intro', ['index']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\IntroController
*/
public function testGetIntroStepsAsset(): void
{
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('json.intro', ['accounts_create', 'asset']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\IntroController
*/
public function testGetIntroStepsOutro(): void
{
$this->mockDefaultSession();
$this->be($this->user());
$response = $this->get(route('json.intro', ['reports_report', 'category']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\IntroController
*/
public function testPostEnable(): void
{
$this->mockDefaultSession();
Preferences::shouldReceive('set')->withArgs(['shown_demo_accounts_create_asset', false])->atLeast()->once();
$this->be($this->user());
$response = $this->post(route('json.intro.enable', ['accounts_create', 'asset']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\IntroController
*/
public function testPostFinished(): void
{
$this->mockDefaultSession();
Preferences::shouldReceive('set')->withArgs(['shown_demo_accounts_create_asset', true])->atLeast()->once();
$this->be($this->user());
$response = $this->post(route('json.intro.finished', ['accounts_create', 'asset']));
$response->assertStatus(200);
}
}

View File

@@ -1,148 +0,0 @@
<?php
/**
* ReconcileControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use Amount;
use Carbon\Carbon;
use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
use Steam;
/**
*
* Class ReconcileControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class ReconcileControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Test overview of reconciliation.
*
* @covers \FireflyIII\Http\Controllers\Json\ReconcileController
*/
public function testOverview(): void
{
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$euro = $this->getEuro();
$withdrawal = $this->getRandomWithdrawalAsArray();
$date = new Carbon;
$account = $this->user()->accounts()->where('id', $withdrawal['source_account_id'])->first();
// make sure it falls into the current range
$withdrawal['date'] = new Carbon('2017-01-30');
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$collector->shouldReceive('setJournalIds')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([$withdrawal]);
Amount::shouldReceive('formatAnything')->andReturn('-100');
Amount::shouldReceive('getDefaultCurrency')->andReturn($euro);
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$parameters = [
'startBalance' => '0',
'endBalance' => '10',
'journals' => [1, 2, 3],
'cleared' => [4, 5, 6],
];
$this->be($this->user());
$response = $this->get(route('accounts.reconcile.overview', [$account->id, '20170101', '20170131']) . '?' . http_build_query($parameters));
$response->assertStatus(200);
$response->assertSee('-100');
}
/**
* List transactions for reconciliation view.
*
* @covers \FireflyIII\Http\Controllers\Json\ReconcileController
*/
public function testTransactions(): void
{
$this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
$repository = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$collector = $this->mock(GroupCollectorInterface::class);
$date = new Carbon;
$euro = $this->getEuro();
$withdrawal = $this->getRandomWithdrawalAsArray();
Steam::shouldReceive('balance')->atLeast()->once()->andReturn('20');
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
//Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->andReturn('-100');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
//$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$collector->shouldReceive('setAccounts')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('setRange')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withBudgetInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withAccountInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('withCategoryInformation')->atLeast()->once()->andReturnSelf();
$collector->shouldReceive('getExtractedJournals')->atLeast()->once()->andReturn([$withdrawal]);
$this->be($this->user());
$response = $this->get(route('accounts.reconcile.transactions', [1, '20170101', '20170131']));
$response->assertStatus(200);
$response->assertSee('-100');
}
}

View File

@@ -1,375 +0,0 @@
<?php
/**
* RecurrenceControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use Carbon\Carbon;
use FireflyIII\Models\RecurrenceRepetition;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use Log;
use Tests\TestCase;
/**
*
* Class RecurrenceControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class RecurrenceControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* Ndom test
*
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testEventsNdom(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
// collection of dates:
$dates = [new Carbon('2018-01-01'), new Carbon('2018-01-07')];
$repository->shouldReceive('getOccurrencesInRange')->withAnyArgs()->once()
->andReturn($dates);
$parameters = [
'start' => '2018-01-01',
'end' => '2018-01-31',
'first_date' => '2018-01-01',
'ends' => 'forever',
'type' => 'ndom,1,1', // weekly on Monday
'reps' => 0,
'weekend' => RecurrenceRepetition::WEEKEND_DO_NOTHING,
'skip' => 0,
];
$this->be($this->user());
$response = $this->get(route('recurring.events') . '?' . http_build_query($parameters));
$response->assertStatus(200);
// expected data:
$expected = [
[
'id' => 'ndom20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-01',
'end' => '2018-01-01',
'editable' => false,
'rendering' => 'background',
],
[
'id' => 'ndom20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-07',
'end' => '2018-01-07',
'editable' => false,
'rendering' => 'background',
],
];
$response->assertExactJson($expected);
}
/**
* yearly, until date
*
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testEventsNumberOfEvents(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
// collection of dates:
$dates = [new Carbon('2018-01-01'), new Carbon('2018-01-07')];
$repository->shouldReceive('getXOccurrences')->withAnyArgs()->once()
->andReturn($dates);
$parameters = [
'start' => '2018-01-01',
'end' => '2018-01-31',
'first_date' => '2018-01-01',
'ends' => 'times',
'type' => 'yearly,1,1', // weekly on Monday
'reps' => 0,
'weekend' => RecurrenceRepetition::WEEKEND_DO_NOTHING,
'skip' => 0,
];
$this->be($this->user());
$response = $this->get(route('recurring.events') . '?' . http_build_query($parameters));
$response->assertStatus(200);
// expected data:
$expected = [
[
'id' => 'yearly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-01',
'end' => '2018-01-01',
'editable' => false,
'rendering' => 'background',
],
[
'id' => 'yearly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-07',
'end' => '2018-01-07',
'editable' => false,
'rendering' => 'background',
],
];
$response->assertExactJson($expected);
}
/**
* First date is after range, so nothing happens.
*
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testEventsStartAfterEnd(): void
{
$this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
$parameters = [
'start' => '2018-01-01',
'end' => '2018-01-31',
'first_date' => '2018-02-01',
'ends' => '',
'type' => 'daily,',
'reps' => 1,
];
$this->be($this->user());
$response = $this->get(route('recurring.events') . '?' . http_build_query($parameters));
$response->assertStatus(200);
$response->assertExactJson([]);
}
/**
* yearly, until date
*
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testEventsUntilDate(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
// collection of dates:
$dates = [new Carbon('2018-01-01'), new Carbon('2018-01-07')];
$repository->shouldReceive('getOccurrencesInRange')->withAnyArgs()->once()
->andReturn($dates);
$parameters = [
'start' => '2018-01-01',
'end' => '2018-01-31',
'first_date' => '2018-01-01',
'ends' => 'until_date',
'type' => 'yearly,1,1', // weekly on Monday
'reps' => 0,
'weekend' => RecurrenceRepetition::WEEKEND_DO_NOTHING,
'skip' => 0,
];
$this->be($this->user());
$response = $this->get(route('recurring.events') . '?' . http_build_query($parameters));
$response->assertStatus(200);
// expected data:
$expected = [
[
'id' => 'yearly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-01',
'end' => '2018-01-01',
'editable' => false,
'rendering' => 'background',
],
[
'id' => 'yearly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-07',
'end' => '2018-01-07',
'editable' => false,
'rendering' => 'background',
],
];
$response->assertExactJson($expected);
}
/**
* Every week on Monday.
*
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testEventsWeeklyMonday(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
// collection of dates:
$dates = [new Carbon('2018-01-01'), new Carbon('2018-01-07')];
$repository->shouldReceive('getOccurrencesInRange')->withAnyArgs()->once()
->andReturn($dates);
$parameters = [
'start' => '2018-01-01',
'end' => '2018-01-31',
'first_date' => '2018-01-01',
'ends' => 'forever',
'type' => 'weekly,1', // weekly on Monday
'reps' => 0,
'weekend' => RecurrenceRepetition::WEEKEND_DO_NOTHING,
'skip' => 0,
];
$this->be($this->user());
$response = $this->get(route('recurring.events') . '?' . http_build_query($parameters));
$response->assertStatus(200);
// expected data:
$expected = [
[
'id' => 'weekly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-01',
'end' => '2018-01-01',
'editable' => false,
'rendering' => 'background',
],
[
'id' => 'weekly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-07',
'end' => '2018-01-07',
'editable' => false,
'rendering' => 'background',
],
];
$response->assertExactJson($expected);
}
/**
* yearly
*
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testEventsYearly(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
// collection of dates:
$dates = [new Carbon('2018-01-01'), new Carbon('2018-01-07')];
$repository->shouldReceive('getOccurrencesInRange')->withAnyArgs()->once()
->andReturn($dates);
$parameters = [
'start' => '2018-01-01',
'end' => '2018-01-31',
'first_date' => '2018-01-01',
'ends' => 'forever',
'type' => 'yearly,1,1', // weekly on Monday
'reps' => 0,
'weekend' => RecurrenceRepetition::WEEKEND_DO_NOTHING,
'skip' => 0,
];
$this->be($this->user());
$response = $this->get(route('recurring.events') . '?' . http_build_query($parameters));
$response->assertStatus(200);
// expected data:
$expected = [
[
'id' => 'yearly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-01',
'end' => '2018-01-01',
'editable' => false,
'rendering' => 'background',
],
[
'id' => 'yearly20180101',
'title' => 'X',
'allDay' => true,
'start' => '2018-01-07',
'end' => '2018-01-07',
'editable' => false,
'rendering' => 'background',
],
];
$response->assertExactJson($expected);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\RecurrenceController
*/
public function testSuggest(): void
{
$this->mock(RecurringRepositoryInterface::class);
$this->mockDefaultSession();
$this->be($this->user());
$parameters = [
'past' => 'true',
'pre_select' => 'daily',
'date' => '2018-01-01',
];
$response = $this->get(route('recurring.suggest') . '?' . http_build_query($parameters));
$response->assertStatus(200);
$expected = [
'daily' => ['label' => 'Every day', 'selected' => true],
'monthly,1' => ['label' => 'Every month on the 1(st/nd/rd/th) day', 'selected' => false],
'ndom,1,1' => ['label' => 'Every month on the 1(st/nd/rd/th) Monday', 'selected' => false],
'weekly,1' => ['label' => 'Every week on Monday', 'selected' => false],
'yearly,2018-01-01' => ['label' => 'Every year on January 1', 'selected' => false],
];
$response->assertExactJson($expected);
}
}

View File

@@ -1,73 +0,0 @@
<?php
/**
* RuleControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Json;
use Log;
use Tests\TestCase;
/**
* Class RuleControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class RuleControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Json\RuleController
*/
public function testAction(): void
{
$this->mockDefaultSession();
// mock stuff
$this->be($this->user());
$response = $this->get(route('json.action'));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Json\RuleController
*/
public function testTrigger(): void
{
$this->mockDefaultSession();
// mock stuff
$this->be($this->user());
$response = $this->get(route('json.trigger'));
$response->assertStatus(200);
}
}

View File

@@ -1,186 +0,0 @@
<?php
/**
* NewUserControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class NewUserControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class NewUserControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\NewUserController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
// mock stuff
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$accountRepos->shouldReceive('count')->andReturn(0);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->be($this->emptyUser());
$response = $this->get(route('new-user.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\NewUserController
*/
public function testIndexExisting(): void
{
$this->mockDefaultSession();
// mock stuff
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('count')->andReturn(1);
$this->be($this->user());
$response = $this->get(route('new-user.index'));
$response->assertStatus(302);
$response->assertRedirect(route('index'));
}
/**
* @covers \FireflyIII\Http\Controllers\NewUserController
*/
public function testSubmit(): void
{
$this->mockDefaultSession();
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$euro = $this->getEuro();
$accountRepos->shouldReceive('store')->times(3);
$currencyRepos->shouldReceive('findNull')->andReturn($euro);
$currencyRepos->shouldReceive('enable')->once();
Preferences::shouldReceive('set')->withArgs(['language', 'en_US'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['currencyPreference', 'EUR'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['transaction_journal_optional_fields', Mockery::any()])->atLeast()->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'bank_name' => 'New bank',
'savings_balance' => '1000',
'bank_balance' => '100',
'language' => 'en_US',
'amount_currency_id_bank_balance' => 1,
];
$this->be($this->emptyUser());
$response = $this->post(route('new-user.submit'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\NewUserController
*/
public function testSubmitNull(): void
{
$euro = $this->getEuro();
$this->mockDefaultSession();
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('store')->times(3);
$currencyRepos->shouldReceive('findNull')->andReturn(null);
$currencyRepos->shouldReceive('findByCodeNull')->withArgs(['EUR'])->andReturn($euro)->once();
$currencyRepos->shouldReceive('enable')->once();
Preferences::shouldReceive('set')->withArgs(['language', 'en_US'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['currencyPreference', 'EUR'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['transaction_journal_optional_fields', Mockery::any()])->atLeast()->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'bank_name' => 'New bank',
'savings_balance' => '1000',
'bank_balance' => '100',
'language' => 'en_US',
'amount_currency_id_bank_balance' => 1,
];
$this->be($this->emptyUser());
$response = $this->post(route('new-user.submit'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\NewUserController
*/
public function testSubmitSingle(): void
{
$this->mockDefaultSession();
$euro = $this->getEuro();
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$accountRepos->shouldReceive('store')->times(3);
$currencyRepos->shouldReceive('findNull')->andReturn($euro);
$currencyRepos->shouldReceive('enable')->once();
Preferences::shouldReceive('set')->withArgs(['language', 'en_US'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['currencyPreference', 'EUR'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['transaction_journal_optional_fields', Mockery::any()])->atLeast()->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$data = [
'bank_name' => 'New bank',
'bank_balance' => '100',
'amount_currency_id_bank_balance' => 1,
];
$this->be($this->emptyUser());
$response = $this->post(route('new-user.submit'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,563 +0,0 @@
<?php
/**
* PiggyBankControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use Amount;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\AccountTransformer;
use FireflyIII\Transformers\PiggyBankTransformer;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
* Class PiggyBankControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PiggyBankControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testAdd(): void
{
$this->mockDefaultSession();
// mock stuff
$piggyRepos = $this->mock(PiggyBankRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
$piggyRepos->shouldReceive('getCurrentAmount')->andReturn('0');
$piggyRepos->shouldReceive('leftOnAccount')->andReturn('0');
$this->be($this->user());
$response = $this->get(route('piggy-banks.add', [$piggyBank->id]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testAddMobile(): void
{
$this->mockDefaultSession();
// mock stuff
$piggyRepos = $this->mock(PiggyBankRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
$piggyRepos->shouldReceive('getCurrentAmount')->andReturn('0');
$piggyRepos->shouldReceive('leftOnAccount')->andReturn('0');
$this->be($this->user());
$response = $this->get(route('piggy-banks.add-money-mobile', [$piggyBank->id]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testCreate(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_piggy-banks_create');
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mock(PiggyBankRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
// new account list thing.
$currency = $this->getEuro();
$currencyRepos->shouldReceive('findNull')->andReturn($currency);
Amount::shouldReceive('getDefaultCurrency')->andReturn($currency);
Amount::shouldReceive('balance')->andReturn('0');
$this->be($this->user());
$response = $this->get(route('piggy-banks.create'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testDelete(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$this->mock(PiggyBankRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->be($this->user());
$response = $this->get(route('piggy-banks.delete', [$piggyBank->id]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testDestroy(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$this->mock(AccountRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$repository->shouldReceive('destroy')->andReturn(true);
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['piggy-banks.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('piggy-banks.destroy', [$piggyBank->id]));
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('index'));
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testEdit(): void
{
$this->mockDefaultSession();
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$this->mock(PiggyBankRepositoryInterface::class);
Steam::shouldReceive('balance')->atLeast()->once()->andReturn('123');
// mock stuff
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
// mock stuff for new account list thing.
$currency = $this->getEuro();
$account = $this->getRandomAsset();
$currencyRepos->shouldReceive('findNull')->andReturn($currency);
$accountRepos->shouldReceive('getAccountsByType')
->withArgs([[AccountType::ASSET, AccountType::DEFAULT]])->andReturn(new Collection([$account]))->once();
Amount::shouldReceive('getDefaultCurrency')->andReturn($currency);
Amount::shouldReceive('balance')->andReturn('0');
$this->be($this->user());
$response = $this->get(route('piggy-banks.edit', [$piggyBank->id]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_piggy-banks_index');
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$transformer = $this->mock(PiggyBankTransformer::class);
$accountTransformer = $this->mock(AccountTransformer::class);
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
['id' => 5, 'current_amount' => '10', 'target_amount' => '10', 'currency_symbol' => 'x']
);
// mock transformer again
$accountTransformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$accountTransformer->shouldReceive('transform')->atLeast()->once()->andReturn(
['id' => 5, 'current_balance' => '10', 'name' => 'Account', 'current_amount' => '5', 'currency_symbol' => 'x']
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$first = $this->user()->transactionJournals()->inRandomOrder()->first();
$piggies = $this->user()->piggyBanks()->take(2)->get();
$journalRepos->shouldReceive('firstNull')->once()->andReturn($first);
$repository->shouldReceive('getPiggyBanks')->andReturn($piggies);
$repository->shouldReceive('getCurrentAmount')->andReturn('10');
$repository->shouldReceive('setUser');
$repository->shouldReceive('correctOrder');
$repository->shouldReceive('getSuggestedMonthlyAmount')->andReturn('1');
$this->be($this->user());
$response = $this->get(route('piggy-banks.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testPostAdd(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
Preferences::shouldReceive('mark')->atLeast()->once();
$repository->shouldReceive('canAddAmount')->once()->andReturn(true);
$repository->shouldReceive('addAmount')->once()->andReturn(true);
$data = ['amount' => '1.123'];
$this->be($this->user());
$response = $this->post(route('piggy-banks.add', [$piggyBank]), $data);
$response->assertStatus(302);
$response->assertRedirect(route('piggy-banks.index'));
$response->assertSessionHas('success');
}
/**
* Add way too much
*
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testPostAddTooMuch(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$repository->shouldReceive('canAddAmount')->once()->andReturn(false);
$data = ['amount' => '1000'];
$this->be($this->user());
$response = $this->post(route('piggy-banks.add', [$piggyBank->id]), $data);
$response->assertStatus(302);
$response->assertRedirect(route('piggy-banks.index'));
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testPostRemove(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
Preferences::shouldReceive('mark')->atLeast()->once();
$repository->shouldReceive('canRemoveAmount')->once()->andReturn(true);
$repository->shouldReceive('removeAmount')->once()->andReturn(true);
$data = ['amount' => '1.123'];
$this->be($this->user());
$response = $this->post(route('piggy-banks.remove', [$piggyBank->id]), $data);
$response->assertStatus(302);
$response->assertRedirect(route('piggy-banks.index'));
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testPostRemoveTooMuch(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$repository->shouldReceive('canRemoveAmount')->once()->andReturn(false);
$data = ['amount' => '1.123'];
$this->be($this->user());
$response = $this->post(route('piggy-banks.remove', [$piggyBank->id]), $data);
$response->assertStatus(302);
$response->assertRedirect(route('piggy-banks.index'));
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testRemove(): void
{
$this->mockDefaultSession();
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$piggyRepos = $this->mock(PiggyBankRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$repetition = PiggyBankRepetition::first();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
$piggyRepos->shouldReceive('getRepetition')->once()->andReturn($repetition);
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$this->be($this->user());
$response = $this->get(route('piggy-banks.remove', [$piggyBank->id]));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testRemoveMobile(): void
{
$this->mockDefaultSession();
// mock stuff
$currencyRepos = $this->mock(CurrencyRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$piggyRepos = $this->mock(PiggyBankRepositoryInterface::class);
$repetition = PiggyBankRepetition::first();
$piggyBank = $this->getRandomPiggyBank();
$accountRepos->shouldReceive('getMetaValue')->withArgs([Mockery::any(), 'currency_id'])->andReturn('1')->atLeast()->once();
$currencyRepos->shouldReceive('findNull')->withArgs([1])->andReturn($this->getEuro())->atLeast()->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$piggyRepos->shouldReceive('getRepetition')->once()->andReturn($repetition);
$this->be($this->user());
$response = $this->get(route('piggy-banks.remove-money-mobile', [$piggyBank->id]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* Test setting of order/
*
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testSetOrder(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$repository->shouldReceive('setOrder')->once()->withArgs([Mockery::any(), 3])->andReturn(false);
$data = ['order' => '3'];
$this->be($this->user());
$response = $this->post(route('piggy-banks.set-order', [$piggyBank->id]), $data);
$response->assertStatus(200);
$response->assertExactJson(['data' => 'OK']);
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
*/
public function testShow(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_piggy-banks_show');
// mock stuff
$first = $this->user()->transactionJournals()->inRandomOrder()->first();
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$transformer = $this->mock(PiggyBankTransformer::class);
$piggyBank = $this->getRandomPiggyBank();
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
// mock transformer
$transformer->shouldReceive('setParameters')->withAnyArgs()->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
['id' => 5, 'current_amount' => '5', 'currency_symbol' => 'x', 'target_amount' => '5', 'left_to_save' => '5', 'save_per_month' => '5']
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$journalRepos->shouldReceive('firstNull')->andReturn($first)->atLeast()->once();
$repository->shouldReceive('getEvents')->andReturn(new Collection)->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$this->be($this->user());
$response = $this->get(route('piggy-banks.show', [$piggyBank->id]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
* @covers \FireflyIII\Http\Requests\PiggyBankFormRequest
*/
public function testStore(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$repository->shouldReceive('store')->andReturn(new PiggyBank);
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['piggy-banks.create.uri' => 'http://localhost']);
$data = [
'name' => 'Piggy ' . $this->randomInt(),
'targetamount' => '100.123',
'account_id' => 2,
'amount_currency_id_targetamount' => 1,
];
$this->be($this->user());
$response = $this->post(route('piggy-banks.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('index'));
}
/**
* @covers \FireflyIII\Http\Controllers\PiggyBankController
* @covers \FireflyIII\Http\Requests\PiggyBankFormRequest
*/
public function testUpdate(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(PiggyBankRepositoryInterface::class);
$piggyBank = $this->getRandomPiggyBank();
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$repository->shouldReceive('update')->andReturn(new PiggyBank);
Preferences::shouldReceive('mark')->atLeast()->once();
$this->session(['piggy-banks.edit.uri' => 'http://localhost']);
$data = [
'id' => 3,
'name' => 'Updated Piggy ' . $this->randomInt(),
'targetamount' => '100.123',
'account_id' => 2,
'amount_currency_id_targetamount' => 1,
];
$this->be($this->user());
$response = $this->post(route('piggy-banks.update', [$piggyBank->id]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('index'));
}
}

View File

@@ -1,418 +0,0 @@
<?php
/**
* ReportControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Popup;
use Amount;
use Carbon\Carbon;
use FireflyIII\Helpers\Report\PopupReportInterface;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use Log;
use Tests\TestCase;
/**
* Class ReportControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ReportControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testBadEndDate(): void
{
$this->mock(PopupReportInterface::class);
$this->mockDefaultSession();
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'bla-bla',
'startDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'endDate' => 'bla-bla',
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertSee('Firefly III cannot handle');
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testBadStartDate(): void
{
$this->mock(PopupReportInterface::class);
$this->be($this->user());
$this->mockDefaultSession();
$arguments = [
'attributes' => [
'location' => 'bla-bla',
'startDate' => 'bla-bla',
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertSee('Firefly III cannot handle');
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testBudgetSpentAmount(): void
{
$this->mock(AccountRepositoryInterface::class);
$this->mock(CategoryRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$budget = $this->getRandomBudget();
$this->mockDefaultSession();
$budgetRepos->shouldReceive('findNull')->andReturn($budget)->once()->withArgs([1]);
$popupHelper->shouldReceive('byBudget')->andReturn([]);
//Amount::shouldReceive('formatAnything')->andReturn('-100')->atLeast()->once();
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'budget-spent-amount',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'currencyId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testBudgetSpentAmountNoBudget(): void
{
$this->mock(AccountRepositoryInterface::class);
$this->mock(CategoryRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
//Amount::shouldReceive('formatAnything')->andReturn('-100')->atLeast()->once();
$this->mockDefaultSession();
$budgetRepos->shouldReceive('findNull')->andReturnNull()->once()->withArgs([1]);
$popupHelper->shouldReceive('byBudget')->andReturn([]);
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'budget-spent-amount',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testCategoryEntry(): void
{
$this->mock(BudgetRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$category = $this->getRandomCategory();
$this->mockDefaultSession();
$categoryRepos->shouldReceive('findNull')->andReturn($category)->once()->withArgs([1]);
$popupHelper->shouldReceive('byCategory')->andReturn([]);
//Amount::shouldReceive('formatAnything')->andReturn('-100')->atLeast()->once();
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'category-entry',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testCategoryEntryUnknown(): void
{
$this->mock(BudgetRepositoryInterface::class);
$this->mock(AccountRepositoryInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$this->mockDefaultSession();
$categoryRepos->shouldReceive('findNull')->andReturn(null)->once()->withArgs([1]);
$popupHelper->shouldReceive('byCategory')->andReturn([]);
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'category-entry',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
$response->assertSee('This is an unknown category. Apologies.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testExpenseEntry(): void
{
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$account = $this->getRandomAsset();
//Amount::shouldReceive('formatAnything')->andReturn('-100')->atLeast()->once();
$this->mockDefaultSession();
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($account)->once();
$popupHelper->shouldReceive('byExpenses')->andReturn([]);
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'expense-entry',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testExpenseEntryUnknown(): void
{
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$this->mockDefaultSession();
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn(null)->once();
$popupHelper->shouldReceive('byExpenses')->andReturn([]);
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'expense-entry',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
$response->assertSee('This is an unknown account. Apologies.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testIncomeEntry(): void
{
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$account = $this->getRandomAsset();
$this->mockDefaultSession();
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn($account)->once();
$popupHelper->shouldReceive('byIncome')->andReturn([]);
//Amount::shouldReceive('formatAnything')->andReturn('-100')->atLeast()->once();
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'income-entry',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
*/
public function testIncomeEntryUnknown(): void
{
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$categoryRepos = $this->mock(CategoryRepositoryInterface::class);
$popupHelper = $this->mock(PopupReportInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$this->mockDefaultSession();
$accountRepos->shouldReceive('findNull')->withArgs([1])->andReturn(null)->once();
$popupHelper->shouldReceive('byIncome')->andReturn([]);
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'income-entry',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
/**
* @covers \FireflyIII\Http\Controllers\Popup\ReportController
* @expectedExceptionMessage Firefly cannot handle
*/
public function testWrongLocation(): void
{
$popupReport = $this->mock(PopupReportInterface::class);
$this->mockDefaultSession();
$this->be($this->user());
$arguments = [
'attributes' => [
'location' => 'bla-bla',
'startDate' => Carbon::now()->startOfMonth()->format('Ymd'),
'endDate' => Carbon::now()->endOfMonth()->format('Ymd'),
'accounts' => 1,
'accountId' => 1,
'categoryId' => 1,
'budgetId' => 1,
],
];
$uri = route('popup.general') . '?' . http_build_query($arguments);
$response = $this->get($uri);
$response->assertStatus(200);
$response->assertDontSee('Firefly III could not render the view. Please see the log files.');
}
}

View File

@@ -1,138 +0,0 @@
<?php
/**
* PreferencesControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
* Class PreferencesControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PreferencesControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\PreferencesController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
$this->mockIntroPreference('shown_demo_preferences_index');
// mock stuff
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$accountRepos->shouldReceive('getAccountsByType')->withArgs([[AccountType::DEFAULT, AccountType::ASSET]])->andReturn(new Collection)->once();
// mock get preferences:
$frontPage = new Preference;
$frontPage->data = [];
Preferences::shouldReceive('get')->withArgs(['frontPageAccounts', []])->andReturn($frontPage)->atLeast()->once();
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$pref = new Preference;
$pref->data = 0;
Preferences::shouldReceive('get')->withArgs(['customFiscalYear', 0])->atLeast()->once()->andReturn($pref);
$pref = new Preference;
$pref->data = '01-01';
Preferences::shouldReceive('get')->withArgs(['fiscalYearStart', '01-01'])->atLeast()->once()->andReturn($pref);
$pref = new Preference;
$pref->data = [];
Preferences::shouldReceive('get')->withArgs(['transaction_journal_optional_fields', []])->atLeast()->once()->andReturn($pref);
$this->be($this->user());
$response = $this->get(route('preferences.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\PreferencesController
*/
public function testPostIndex(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->andReturn(false);
$data = [
'fiscalYearStart' => '2016-01-01',
'frontPageAccounts' => [1],
'viewRange' => '1M',
'customFiscalYear' => 0,
'showDepositsFrontpage' => 0,
'listPageSize' => 100,
'language' => 'en_US',
'tj' => [],
];
Preferences::shouldReceive('set')->withArgs(['frontPageAccounts', [1]])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['viewRange', '1M'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['customFiscalYear', false])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['fiscalYearStart', '01-01'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['listPageSize', 100])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['listPageSize', 50])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['language', 'en_US'])->atLeast()->once();
Preferences::shouldReceive('set')->withArgs(['transaction_journal_optional_fields', Mockery::any()])->atLeast()->once();
Preferences::shouldReceive('mark')->atLeast()->once();
$this->be($this->user());
$response = $this->post(route('preferences.update'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('preferences.index'));
}
}

View File

@@ -1,609 +0,0 @@
<?php
/**
* ProfileControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers;
use Amount;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Google2FA;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use stdClass;
use Tests\TestCase;
/**
* Class ProfileControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProfileControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testChangeEmail(): void
{
$this->mockDefaultSession();
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('profile.change-email'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testChangePassword(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->be($this->user());
$response = $this->get(route('profile.change-password'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testCode(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
Google2FA::shouldReceive('generateSecretKey')->andReturn('secret');
Google2FA::shouldReceive('getQRCodeInline')->andReturn('long-data-url');
$this->be($this->user());
$response = $this->get(route('profile.code'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testConfirmEmailChangeNoToken(): void
{
$this->mockDefaultSession();
$this->mock(UserRepositoryInterface::class);
Preferences::shouldReceive('findByName')->withArgs(['email_change_confirm_token'])->andReturn(new Collection());
Log::warning('The following error is part of a test.');
$response = $this->get(route('profile.confirm-email-change', ['some-fake-token']));
$response->assertStatus(500);
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testConfirmEmailWithToken(): void
{
$this->mockDefaultSession();
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('unblockUser');
$preference = new Preference;
$preference->data = 'existing-token';
/** @var stdClass $preference */
$preference->user = $this->user();
Preferences::shouldReceive('findByName')->withArgs(['email_change_confirm_token'])->andReturn(new Collection([$preference]));
// email_change_confirm_token
$response = $this->get(route('profile.confirm-email-change', ['existing-token']));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testDeleteAccount(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$this->be($this->user());
$response = $this->get(route('profile.delete-account'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testDeleteCode(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->atLeast()->once()->andReturn(false);
$userRepos->shouldReceive('setMFACode')->withArgs([Mockery::any(), null])->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('profile.delete-code'));
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertSessionHas('info');
$response->assertRedirect(route('profile.index'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testEnable2FANoSecret(): void
{
$this->mockDefaultSession();
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->times(1)->andReturn(false);
$this->be($this->user());
$response = $this->post(route('profile.enable2FA'));
$response->assertStatus(302);
$response->assertRedirect(route('profile.code'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testEnable2FASecret(): void
{
//$this->mockDefaultSession(); // DISABLED ON PURPOSE
$this->mockDefaultConfiguration();
$repository = $this->mock(UserRepositoryInterface::class);
$journalRepos = $this->mock(JournalRepositoryInterface::class);
$journalRepos->shouldReceive('firstNull')->andReturnNull();
$euro = $this->getEuro();
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->times(1)->andReturn(false);
$view = new Preference;
$view->data = '1M';
Preferences::shouldReceive('get')->withArgs(['viewRange', Mockery::any()])->andReturn($view)->atLeast()->once();
$lang = new Preference;
$lang->data = 'en_US';
Preferences::shouldReceive('get')->withArgs(['language', 'en_US'])->andReturn($lang)->atLeast()->once();
$list = new Preference;
$list->data = 50;
Preferences::shouldReceive('get')->withArgs(['list-length', 10])->andReturn($list)->atLeast()->once();
Amount::shouldReceive('getDefaultCurrency')->atLeast()->once()->andReturn($euro);
$this->session(['rule-groups.delete.uri' => 'http://localhost']);
$this->be($this->user());
$response = $this->post(route('profile.enable2FA'));
$response->assertStatus(302);
$response->assertRedirect(route('profile.code'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testIndex(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$userRepos->shouldReceive('findNull')->atLeast()->once()->andReturn($this->user());
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('get')->withArgs(['access_token', null])->atLeast()->once()->andReturn($pref);
$arrayPref = new Preference;
$arrayPref->data = [];
Preferences::shouldReceive('get')->withArgs(['mfa_recovery', []])->atLeast()->once()->andReturn($arrayPref);
Preferences::shouldReceive('getForUser')->withArgs(['xxx'])->andReturn($pref);
$this->be($this->user());
$response = $this->get(route('profile.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testIndexEmptyToken(): void
{
$this->mockDefaultSession();
// mock stuff
$userRepos = $this->mock(UserRepositoryInterface::class);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$pref = new Preference;
$pref->data = 'token';
Preferences::shouldReceive('get')->withArgs(['access_token', null])->atLeast()->once()->andReturnNull();
Preferences::shouldReceive('set')->withArgs(['access_token', Mockery::any()])->atLeast()->once()->andReturn($pref);
$arrayPref = new Preference;
$arrayPref->data = [];
Preferences::shouldReceive('get')->withArgs(['mfa_recovery', []])->atLeast()->once()->andReturn($arrayPref);
Preferences::shouldReceive('getForUser')->withArgs(['xxx'])->andReturn($pref);
$this->be($this->user());
$response = $this->get(route('profile.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostChangeEmail(): void
{
$this->mockDefaultSession();
$data = [
'email' => 'new@example.com',
];
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('findByEmail')->once()->andReturn(null);
$repository->shouldReceive('changeEmail')->once()->andReturn(true);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$pref = new Preference;
$pref->data = 'invalid';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'email_change_confirm_token', 'invalid'])->andReturn($pref);
$pref = new Preference;
$pref->data = 'invalid';
Preferences::shouldReceive('getForUser')->withArgs([Mockery::any(), 'email_change_undo_token', 'invalid'])->andReturn($pref);
$this->be($this->user());
$response = $this->post(route('profile.change-email.post'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('index'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostChangeEmailExisting(): void
{
$this->mockDefaultSession();
$data = [
'email' => 'existing@example.com',
];
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('findByEmail')->once()->andReturn(new User);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$this->be($this->user());
$response = $this->post(route('profile.change-email.post'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('index'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostChangeEmailSame(): void
{
$this->mockDefaultSession();
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$data = [
'email' => $this->user()->email,
];
$this->be($this->user());
$response = $this->post(route('profile.change-email.post'), $data);
$response->assertStatus(302);
$response->assertSessionHas('error');
$response->assertRedirect(route('profile.change-email'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostChangePassword(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('changePassword');
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$data = [
'current_password' => 'james',
'new_password' => 'james2',
'new_password_confirmation' => 'james2',
];
$this->be($this->user());
$response = $this->post(route('profile.change-password.post'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostChangePasswordNotCorrect(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('changePassword');
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$data = [
'current_password' => 'james3',
'new_password' => 'james2',
'new_password_confirmation' => 'james2',
];
$this->be($this->user());
$response = $this->post(route('profile.change-password.post'), $data);
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostChangePasswordSameNew(): void
{
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('changePassword');
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$data = [
'current_password' => 'james',
'new_password' => 'james',
'new_password_confirmation' => 'james',
];
$this->be($this->user());
$response = $this->post(route('profile.change-password.post'), $data);
$response->assertStatus(302);
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostCode(): void
{
$userRepos = $this->mock(UserRepositoryInterface::class);
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
$secret = '0123456789abcde';
$key = '123456';
$this->withoutMiddleware();
$this->session(['two-factor-secret' => $secret]);
$userRepos->shouldReceive('setMFACode')->withArgs([Mockery::any(), $secret])->atLeast()->once();
// set recovery history
Preferences::shouldReceive('set')->withArgs(['mfa_history', Mockery::any()])->atLeast()->once();
// set recovery codes.
Preferences::shouldReceive('set')->withArgs(['mfa_recovery', null])->atLeast()->once();
$pref = new Preference;
$pref->data= [];
Preferences::shouldReceive('get')->withArgs(['mfa_history', []])->atLeast()->once()->andReturn($pref);
Preferences::shouldReceive('mark')->once();
Google2FA::shouldReceive('verifyKey')->withArgs([$secret, $key])->andReturn(true);
$data = [
'code' => $key,
];
$this->be($this->user());
$response = $this->post(route('profile.code.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostDeleteAccount(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('destroy')->once();
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$data = [
'password' => 'james',
];
$this->be($this->user());
$response = $this->post(route('profile.delete-account.post'), $data);
$response->assertStatus(302);
$response->assertRedirect(route('index'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testPostDeleteAccountWrong(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
// mock stuff
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
$data = [
'password' => 'james2',
];
$this->be($this->user());
$response = $this->post(route('profile.delete-account.post'), $data);
$response->assertStatus(302);
$response->assertRedirect(route('profile.delete-account'));
$response->assertSessionHas('error');
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testRegenerate(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('hasRole')->withArgs([Mockery::any(), 'demo'])->once()->andReturn(false);
Preferences::shouldReceive('set')->withArgs(['access_token', Mockery::any()])->atLeast()->once();
$this->be($this->user());
$response = $this->post(route('profile.regenerate'));
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('profile.index'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testUndoEmailChange(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
$this->mock(UserRepositoryInterface::class);
$hash = hash('sha256', 'previous@example.com');
$tokenPreference = new Preference;
$tokenPreference->data = 'token';
/** @var stdClass $tokenPreference */
$tokenPreference->user = $this->user();
$hashPreference = new Preference;
$hashPreference->data = 'previous@example.com';
/** @var stdClass $hashPreference */
$hashPreference->user = $this->user();
Preferences::shouldReceive('findByName')->once()->andReturn(new Collection([$tokenPreference]));
Preferences::shouldReceive('beginsWith')->once()->andReturn(new Collection([$hashPreference]));
$repository = $this->mock(UserRepositoryInterface::class);
$repository->shouldReceive('changeEmail')->once();
$repository->shouldReceive('unblockUser')->once();
$response = $this->get(route('profile.undo-email-change', ['token', $hash]));
$response->assertStatus(302);
$response->assertSessionHas('success');
$response->assertRedirect(route('login'));
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
* @expectedExceptionMessage Invalid token
*/
public function testUndoEmailChangeBadHash(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
$this->mock(UserRepositoryInterface::class);
$hash = hash('sha256', 'previous@example.comX');
$tokenPreference = new Preference;
$tokenPreference->data = 'token';
/** @var stdClass $tokenPreference */
$tokenPreference->user = $this->user();
$hashPreference = new Preference;
$hashPreference->data = 'previous@example.com';
/** @var stdClass $hashPreference */
$hashPreference->user = $this->user();
Preferences::shouldReceive('findByName')->once()->andReturn(new Collection([$tokenPreference]));
Preferences::shouldReceive('beginsWith')->once()->andReturn(new Collection([$hashPreference]));
Log::warning('The following error is part of a test.');
$response = $this->get(route('profile.undo-email-change', ['token', $hash]));
$response->assertStatus(500);
}
/**
* @covers \FireflyIII\Http\Controllers\ProfileController
*/
public function testUndoEmailChangeBadToken(): void
{
Log::info(sprintf('Now in test %s.', __METHOD__));
$this->mockDefaultSession();
$this->mock(UserRepositoryInterface::class);
Preferences::shouldReceive('findByName')->once()->andReturn(new Collection);
$response = $this->get(route('profile.undo-email-change', ['token', 'some-hash']));
$response->assertStatus(500);
}
}

View File

@@ -1,728 +0,0 @@
<?php
/**
* CreateControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Recurring;
use Amount;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Validation\AccountValidator;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
*
* Class CreateControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class CreateControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
*/
public function testCreate(): void
{
// mock repositories, even if not used.
$this->mock(RecurringRepositoryInterface::class);
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(PiggyBankRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$euro = $this->getEuro();
$asset = $this->getRandomAsset();
$cash = $this->getRandomAsset();
$this->mockDefaultSession();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$budgetRepos->shouldReceive('getActiveBudgets')->andReturn(new Collection)->once();
// for view:
$accountRepos->shouldReceive('getActiveAccountsByType')->atLeast()->once()->andReturn(new Collection([$asset]));
Steam::shouldReceive('balance')->andReturn('100')->atLeast()->once();
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturnNull();
$accountRepos->shouldReceive('getCashAccount')->atLeast()->once()->andReturn($cash);
//Amount::shouldReceive('getDefaultCurrency')->andReturn($euro)->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('100');
$this->be($this->user());
$response = $this->get(route('recurring.create'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
$response->assertSee('source_id_holder');
$response->assertSee('deposit_source_id');
$response->assertSee('withdrawal_destination_id');
}
/**
* Stores a withdrawal. From Asset account to Expense account
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreWithdrawalExpense(): void
{
// mock repositories, even if not used.
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* Stores a withdrawal, but destination is invalid
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreWithdrawalInvalidDest(): void
{
// mock repositories, even if not used.
$this->mock(BudgetRepositoryInterface::class);
$this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
$this->mockDefaultSession();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(false);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('errors');
}
/**
* Try to store withdrawal, but the source account is invalid.
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreWithdrawalInvalidSource(): void
{
$this->mockDefaultSession();
// mock repositories, even if not used.
$this->mock(BudgetRepositoryInterface::class);
$this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
// source account is invalid.
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(false);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('errors');
}
/**
* Stores a withdrawal. But throw error.
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreError(): void
{
// mock repositories, even if not used.
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
$this->mockDefaultSession();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andThrow(new FireflyException('Some exception'));
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('error', 'Some exception');
}
/**
* Store a deposit from Revenue to Asset.
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreDepositRevenue(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomRevenue();
$destination = $this->getRandomAsset();
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['deposit'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$data = [
'title' => 'hello' . $this->randomInt(),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => 'Some descr' . $this->randomInt(),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'deposit',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'deposit_source_id' => $source->id,
'destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* Store a withdrawal but it's monthly, not daily.
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreMonthly(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'monthly,5',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* Store a withdrawal but use ndom.
*
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreNdom(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'ndom,3,5',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreTransfer(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomAsset($source->id);
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['transfer'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$data = [
'title' => 'hello' . $this->randomInt(),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => 'Some descr' . $this->randomInt(),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'transfer',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreUntilDate(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'until_date',
'repeat_until' => $tomorrow->format('Y-m-d'),
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\CreateController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testStoreYearly(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$source = $this->getRandomAsset();
$destination = $this->getRandomExpense();
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
$data = [
'title' => sprintf('hello %d', $this->randomInt()),
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'yearly,2018-01-01',
'skip' => 0,
'recurring_description' => sprintf('Some descr %d', $this->randomInt()),
'active' => '1',
'apply_rules' => '1',
'foreign_amount' => '1',
'foreign_currency_id' => '2',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => $source->id,
'withdrawal_destination_id' => $destination->id,
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$recurringRepos->shouldReceive('store')->andReturn($recurrence)->once();
$this->be($this->user());
$response = $this->post(route('recurring.store'), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,94 +0,0 @@
<?php
/**
* DeleteControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Recurring;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class DeleteControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class DeleteControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\DeleteController
*/
public function testDelete(): void
{
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
$recurringRepos->shouldReceive('getTransactions')->andReturn(new Collection)->once();
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$this->be($this->user());
$response = $this->get(route('recurring.delete', [1]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\DeleteController
*/
public function testDestroy(): void
{
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$this->mockDefaultSession();
Preferences::shouldReceive('mark')->atLeast()->once();
$recurringRepos->shouldReceive('destroy')->once();
$this->be($this->user());
$response = $this->post(route('recurring.destroy', [1]));
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,186 +0,0 @@
<?php
/**
* EditControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Recurring;
use Amount;
use Carbon\Carbon;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\RecurrenceTransformer;
use FireflyIII\Validation\AccountValidator;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Steam;
use Tests\TestCase;
/**
*
* Class EditControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class EditControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\EditController
*/
public function testEdit(): void
{
$this->mock(CurrencyRepositoryInterface::class);
$this->mock(PiggyBankRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$accountRepos = $this->mock(AccountRepositoryInterface::class);
$transformer = $this->mock(RecurrenceTransformer::class);
$asset = $this->getRandomAsset();
$euro = $this->getEuro();
$cash = $this->getRandomAsset();
$this->mockDefaultSession();
$transformed = [
'transactions' => [
[
'source_id' => 1,
'destination_id' => 1,
],
],
];
// for view:
$accountRepos->shouldReceive('getActiveAccountsByType')->atLeast()->once()->andReturn(new Collection([$asset]));
Steam::shouldReceive('balance')->andReturn('100')->atLeast()->once();
$accountRepos->shouldReceive('getAccountCurrency')->atLeast()->once()->andReturn($euro);
$accountRepos->shouldReceive('getMetaValue')->atLeast()->once()->andReturnNull();
$accountRepos->shouldReceive('getCashAccount')->atLeast()->once()->andReturn($cash);
//Amount::shouldReceive('getDefaultCurrency')->andReturn($euro)->atLeast()->once();
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('100');
// transform recurrence.
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn($transformed);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
// get stuff from recurrence.
$recurringRepos->shouldReceive('setUser');
$recurringRepos->shouldReceive('getNoteText')->andReturn('Note!');
$recurringRepos->shouldReceive('repetitionDescription')->andReturn('dunno');
$recurringRepos->shouldReceive('getXOccurrences')->andReturn([]);
$budgetRepos->shouldReceive('findNull')->andReturn($this->user()->budgets()->first());
$budgetRepos->shouldReceive('getActiveBudgets')->andReturn(new Collection)->once();
//\Amount::shouldReceive('getDefaultCurrency')->andReturn($this->getEuro());
$this->be($this->user());
$response = $this->get(route('recurring.edit', [1]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
$response->assertSee('deposit_source_id');
$response->assertSee('withdrawal_destination_id');
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\EditController
* @covers \FireflyIII\Http\Requests\RecurrenceFormRequest
*/
public function testUpdate(): void
{
$this->mock(BudgetRepositoryInterface::class);
$recurringRepos = $this->mock(RecurringRepositoryInterface::class);
$validator = $this->mock(AccountValidator::class);
$expense = $this->getRandomExpense();
$this->mockDefaultSession();
$recurringRepos->shouldReceive('update')->once();
// validator:
$validator->shouldReceive('setTransactionType')->withArgs(['withdrawal'])->atLeast()->once();
$validator->shouldReceive('validateSource')->atLeast()->once()->andReturn(true);
$validator->shouldReceive('validateDestination')->atLeast()->once()->andReturn(true);
Preferences::shouldReceive('mark')->once();
$tomorrow = Carbon::now()->addDays(2);
$recurrence = $this->user()->recurrences()->first();
$data = [
'id' => $recurrence->id,
'title' => 'hello',
'first_date' => $tomorrow->format('Y-m-d'),
'repetition_type' => 'daily',
'skip' => 0,
'recurring_description' => 'Some descr',
'active' => '1',
'apply_rules' => '1',
'return_to_edit' => '1',
// mandatory for transaction:
'transaction_description' => 'Some descr',
'transaction_type' => 'withdrawal',
'transaction_currency_id' => '1',
'amount' => '30',
// mandatory account info:
'source_id' => '1',
'source_name' => '',
'withdrawal_destination_id' => $expense->id,
'destination_id' => '',
'destination_name' => 'Some Expense',
// optional fields:
'budget_id' => '1',
'category' => 'CategoryA',
'tags' => 'A,B,C',
'create_another' => '1',
'repetition_end' => 'times',
'repetitions' => 3,
];
$this->be($this->user());
$response = $this->post(route('recurring.update', [1]), $data);
$response->assertStatus(302);
$response->assertSessionHas('success');
}
}

View File

@@ -1,172 +0,0 @@
<?php
/**
* IndexControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Recurring;
use FireflyConfig;
use FireflyIII\Factory\CategoryFactory;
use FireflyIII\Models\Configuration;
use FireflyIII\Models\Preference;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\RecurrenceTransformer;
use Illuminate\Support\Collection;
use Log;
use Mockery;
use Preferences;
use Tests\TestCase;
/**
*
* Class IndexControllerTest
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class IndexControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\IndexController
*/
public function testIndex(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$categoryFactory = $this->mock(CategoryFactory::class);
$transformer = $this->mock(RecurrenceTransformer::class);
// mock calls
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$repository->shouldReceive('getOccurrencesInRange')->atLeast()->once()->andReturn([]);
$this->mockDefaultSession();
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
[
'id' => 5,
'first_date' => '2018-01-01',
'repeat_until' => null,
'latest_date' => null,
]
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$config = new Configuration;
$config->data = 0;
$falseConfig = new Configuration;
$falseConfig->data = false;
$collection = $this->user()->recurrences()->take(2)->get();
// mock cron job config:
FireflyConfig::shouldReceive('get')->withArgs(['last_rt_job', 0])->once()->andReturn($config);
$repository->shouldReceive('get')->andReturn($collection)->once();
$this->be($this->user());
$response = $this->get(route('recurring.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
/**
* The last time the recurring job fired it was a long time ago.
*
* @covers \FireflyIII\Http\Controllers\Recurring\IndexController
*/
public function testIndexLongAgo(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$categoryFactory = $this->mock(CategoryFactory::class);
$transformer = $this->mock(RecurrenceTransformer::class);
// mock calls
$pref = new Preference;
$pref->data = 50;
Preferences::shouldReceive('get')->withArgs(['listPageSize', 50])->atLeast()->once()->andReturn($pref);
$repository->shouldReceive('getOccurrencesInRange')->atLeast()->once()->andReturn([]);
$this->mockDefaultSession();
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
[
'id' => 5,
'first_date' => '2018-01-01',
'repeat_until' => null,
'latest_date' => null,
]
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$config = new Configuration;
$config->data = 1;
$falseConfig = new Configuration;
$falseConfig->data = false;
$collection = $this->user()->recurrences()->take(2)->get();
// mock cron job config:
FireflyConfig::shouldReceive('get')->withArgs(['last_rt_job', 0])->once()->andReturn($config);
$repository->shouldReceive('get')->andReturn($collection)->once();
$this->be($this->user());
$response = $this->get(route('recurring.index'));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
$response->assertSessionHas('warning');
}
}

View File

@@ -1,98 +0,0 @@
<?php
/**
* ShowControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Recurring;
use FireflyIII\Factory\CategoryFactory;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Transformers\RecurrenceTransformer;
use Illuminate\Support\Collection;
use Tests\TestCase;
use Log;
use Mockery;
/**
*
* Class ShowControllerTest
*/
class ShowControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Recurring\IndexController
*/
public function testShow(): void
{
$repository = $this->mock(RecurringRepositoryInterface::class);
$budgetRepos = $this->mock(BudgetRepositoryInterface::class);
$userRepos = $this->mock(UserRepositoryInterface::class);
$categoryFactory = $this->mock(CategoryFactory::class);
$transformer = $this->mock(RecurrenceTransformer::class);
$this->mockDefaultSession();
$transformer->shouldReceive('setParameters')->atLeast()->once();
$transformer->shouldReceive('transform')->atLeast()->once()->andReturn(
[
'id' => 5,
'first_date' => '2018-01-01',
'repeat_until' => null,
'latest_date' => null,
'repetitions' => [
[
'occurrences' => [
'2019-01-01',
],
],
],
]
);
$userRepos->shouldReceive('hasRole')->withArgs([Mockery::any(), 'owner'])->atLeast()->once()->andReturn(true);
$recurrence = $this->user()->recurrences()->first();
$repository->shouldReceive('setUser');
$repository->shouldReceive('getTransactions')->andReturn(new Collection)->atLeast()->once();
$this->be($this->user());
$response = $this->get(route('recurring.show', [$recurrence->id]));
$response->assertStatus(200);
$response->assertSee('<ol class="breadcrumb">');
}
}

View File

@@ -1,78 +0,0 @@
<?php
/**
* AccountControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Report;
use Carbon\Carbon;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Account\AccountTaskerInterface;
use Log;
use Preferences;
use Tests\TestCase;
/**
* Class AccountControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class AccountControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Report\AccountController
*/
public function testGeneral(): void
{
$this->mockDefaultSession();
$return = [
'accounts' => [],
'start' => '0',
'end' => '0',
'difference' => '0',
];
$tasker = $this->mock(AccountTaskerInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$tasker->shouldReceive('getAccountReport')->andReturn($return);
$this->be($this->user());
$response = $this->get(route('report-data.account.general', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,74 +0,0 @@
<?php
/**
* BalanceControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Report;
use Carbon\Carbon;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\TestCase;
/**
* Class BalanceControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BalanceControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Report\BalanceController
*/
public function testGeneral(): void
{
$this->mockDefaultSession();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$date = new Carbon;
$budget = $this->getRandomBudget();
$repository->shouldReceive('getBudgets')->atLeast()->once()->andReturn(new Collection([$budget]));
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$this->be($this->user());
$response = $this->get(route('report-data.balance.general', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,121 +0,0 @@
<?php
/**
* BudgetControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Report;
use Carbon\Carbon;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\NoBudgetRepositoryInterface;
use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Amount;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class BudgetControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class BudgetControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Report\BudgetController
*/
public function testGeneral(): void
{
$this->mockDefaultSession();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$budget = $this->getRandomBudget();
$limit = $this->getRandomBudgetLimit();
$repository->shouldReceive('getBudgets')->atLeast()->once()->andReturn(new Collection([$budget]));
$blRepos->shouldReceive('getBudgetLimits')->atLeast()->once()->andReturn(new Collection([$limit]));
$opsRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn([]);
$nbRepos->shouldReceive('sumExpenses')->atLeast()->once()->andReturn([]);
$date = new Carbon;
//Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$this->be($this->user());
$response = $this->get(route('report-data.budget.general', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Report\BudgetController
*/
public function testPeriod(): void
{
$this->mockDefaultSession();
$first = [1 => ['entries' => ['1', '1']]];
$second = ['entries' => ['1', '1']];
$repository = $this->mock(BudgetRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$repository = $this->mock(BudgetRepositoryInterface::class);
$blRepos = $this->mock(BudgetLimitRepositoryInterface::class);
$nbRepos = $this->mock(NoBudgetRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$date = new Carbon;
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->budgetListExpenses());
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
//Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$repository->shouldReceive('getBudgets')->andReturn(new Collection);
$repository->shouldReceive('getBudgetPeriodReport')->andReturn($first);
$repository->shouldReceive('getNoBudgetPeriodReport')->andReturn($second);
$this->be($this->user());
$response = $this->get(route('report-data.budget.period', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
}

View File

@@ -1,154 +0,0 @@
<?php
/**
* CategoryControllerTest.php
* Copyright (c) 2019 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\Feature\Controllers\Report;
use Amount;
use Carbon\Carbon;
use FireflyIII\Helpers\Fiscal\FiscalHelperInterface;
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface;
use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
use Illuminate\Support\Collection;
use Log;
use Preferences;
use Tests\Support\TestDataTrait;
use Tests\TestCase;
/**
* Class CategoryControllerTest
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CategoryControllerTest extends TestCase
{
/**
*
*/
public function setUp(): void
{
self::markTestIncomplete('Incomplete for refactor.');
return;
parent::setUp();
Log::info(sprintf('Now in %s.', get_class($this)));
}
/**
* @covers \FireflyIII\Http\Controllers\Report\CategoryController
*/
public function testExpenses(): void
{
$this->mockDefaultSession();
$first = [1 => ['entries' => ['1', '1']]];
$second = ['entries' => ['1', '1']];
$repository = $this->mock(CategoryRepositoryInterface::class);
$opsRepos = $this->mock(OperationsRepositoryInterface::class);
$noCatRepository = $this->mock(NoCategoryRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$opsRepos->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->categoryListExpenses());
$noCatRepository->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->noCategoryListExpenses());
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$repository->shouldReceive('getCategories')->andReturn(new Collection);
$repository->shouldReceive('periodExpenses')->andReturn($first);
$repository->shouldReceive('periodExpensesNoCategory')->andReturn($second);
$this->be($this->user());
$response = $this->get(route('report-data.category.expenses', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Report\CategoryController
*/
public function testIncome(): void
{
$this->mockDefaultSession();
$first = [
1 => ['entries' => ['1', '1']],
2 => ['entries' => ['0']],
];
$second = ['entries' => ['1', '1']];
$repository = $this->mock(CategoryRepositoryInterface::class);
$opsRepository = $this->mock(OperationsRepositoryInterface::class);
$noCatRepository = $this->mock(NoCategoryRepositoryInterface::class);
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$opsRepository->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->categoryListIncome());
$noCatRepository->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->noCategoryListIncome());
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$repository->shouldReceive('getCategories')->andReturn(new Collection);
$repository->shouldReceive('periodIncome')->andReturn($first);
$repository->shouldReceive('periodIncomeNoCategory')->andReturn($second);
$this->be($this->user());
$response = $this->get(route('report-data.category.income', ['1', '20120101', '20120131']));
$response->assertStatus(200);
}
/**
* @covers \FireflyIII\Http\Controllers\Report\CategoryController
*/
public function testOperations(): void
{
$this->mockDefaultSession();
$repository = $this->mock(CategoryRepositoryInterface::class);
$opsRepository = $this->mock(OperationsRepositoryInterface::class);
$noCatRepository = $this->mock(NoCategoryRepositoryInterface::class);
$category = $this->getRandomCategory();
$fiscalHelper = $this->mock(FiscalHelperInterface::class);
$date = new Carbon;
$opsRepository->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->categoryListIncome());
$noCatRepository->shouldReceive('listIncome')->atLeast()->once()->andReturn($this->noCategoryListIncome());
$opsRepository->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->categoryListExpenses());
$noCatRepository->shouldReceive('listExpenses')->atLeast()->once()->andReturn($this->noCategoryListExpenses());
Preferences::shouldReceive('lastActivity')->atLeast()->once()->andReturn('md512345');
Amount::shouldReceive('formatAnything')->atLeast()->once()->andReturn('x');
$fiscalHelper->shouldReceive('endOfFiscalYear')->atLeast()->once()->andReturn($date);
$fiscalHelper->shouldReceive('startOfFiscalYear')->atLeast()->once()->andReturn($date);
$repository->shouldReceive('getCategories')->andReturn(new Collection([$category]));
$repository->shouldReceive('spentInPeriod')->andReturn([]);
$repository->shouldReceive('earnedInPeriod')->andReturn([]);
$this->be($this->user());
$response = $this->get(route('report-data.category.operations', ['1', '20120101', '20120131']));
$response->assertStatus(200);
$response->assertDontSee('An error prevented Firefly III from rendering: %s. Apologies.');
}
}

Some files were not shown because too many files have changed in this diff Show More