refactor: replace custom CRM with Monica fork
Some checks failed
Build & Push Monica Image to Gitea Registry / build-and-push (push) Failing after 9s

This commit is contained in:
Kroonk
2026-05-22 16:19:55 +02:00
parent 38cc4c09ca
commit a213a1dba0
2215 changed files with 242567 additions and 6015 deletions

View File

@@ -0,0 +1,21 @@
<?php
namespace Tests\Unit\Controllers\Account\LifeEvent;
use Tests\FeatureTestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LifeEventCategoriesControllerTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_the_list_of_life_event_categories()
{
$user = $this->signin();
$response = $this->get('settings/personalization/lifeeventcategories');
$response->assertStatus(200);
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Tests\Unit\Controllers\Auth;
use Tests\TestCase;
use App\Models\User\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Notification as NotificationFacade;
class PasswordResetTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_sends_password_reset_email()
{
NotificationFacade::fake();
$user = factory(User::class)->create();
$this->post('/password/email', ['email' => $user->email]);
NotificationFacade::assertSentTo($user, ResetPassword::class);
$notifications = NotificationFacade::sent($user, ResetPassword::class);
$message = $notifications[0]->toMail($user);
$this->assertStringContainsString('You are receiving this email because we received a password reset request for your account.', implode('', $message->introLines));
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Tests\Unit\Controllers\Contact;
use Tests\FeatureTestCase;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ContactAuditLogControllerTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_the_list_of_audit_logs_for_the_contact()
{
$user = $this->signin();
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
]);
$response = $this->get("/people/{$contact->hashID()}/auditlogs");
$response->assertStatus(200);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Tests\Unit\Controllers\Contact;
use Tests\FeatureTestCase;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LifeEventsControllerTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_the_list_of_life_events_for_the_contact()
{
$user = $this->signin();
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
]);
$response = $this->get("/people/{$contact->hashID()}/lifeevents");
$response->assertStatus(200);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Tests\Unit\Controllers\Settings;
use Tests\FeatureTestCase;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AuditLogControllerTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_the_list_of_audit_logs_for_the_account()
{
$user = $this->signin();
factory(Contact::class)->create([
'account_id' => $user->account_id,
]);
$response = $this->get('/settings/auditlogs');
$response->assertStatus(200);
}
}

View File

@@ -0,0 +1,202 @@
<?php
namespace Tests\Unit\Controllers\Settings;
use Tests\FeatureTestCase;
use App\Models\Contact\Gender;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class GendersControllerTest extends FeatureTestCase
{
use DatabaseTransactions;
protected $jsonStructure = [
'id',
'name',
'type',
'isDefault',
'numberOfContacts',
];
protected $typesJsonStructure = [
'id',
'name',
];
/** @test */
public function it_gets_the_list_of_genders()
{
$user = $this->signin();
$response = $this->json('GET', '/settings/personalization/genders');
$response->assertStatus(200);
$response->assertJsonStructure([
'*' => $this->jsonStructure,
]);
$this->assertCount(
3,
$response->decodeResponseJson()
);
}
/** @test */
public function it_gets_the_list_of_genderTypes()
{
$user = $this->signin();
$response = $this->json('GET', '/settings/personalization/genderTypes');
$response->assertStatus(200);
$response->assertJsonStructure([
'*' => $this->typesJsonStructure,
]);
$this->assertCount(
5,
$response->decodeResponseJson()
);
}
/** @test */
public function it_stores_a_new_gender()
{
$user = $this->signin();
$response = $this->json('POST', '/settings/personalization/genders', [
'name' => 'gender',
'type' => 'O',
]);
$response->assertStatus(200);
$response->assertJsonStructure($this->jsonStructure);
$this->assertDataBaseHas('genders', [
'account_id' => $user->account_id,
'name' => 'gender',
'type' => 'O',
]);
}
/** @test */
public function it_stores_a_new_default_gender()
{
$user = $this->signin();
$this->assertNull($user->account->default_gender_id);
$response = $this->json('POST', '/settings/personalization/genders', [
'name' => 'new-default-gender',
'type' => 'O',
'isDefault' => 'true',
]);
$this->assertEquals($response->getData()->id, $user->account->default_gender_id);
}
/** @test */
public function it_updates_a_gender()
{
$user = $this->signin();
$gender = $user->account->genders()->first();
$response = $this->json('PUT', '/settings/personalization/genders/'.$gender->id, [
'name' => 'gender',
'type' => 'U',
]);
$response->assertStatus(200);
$response->assertJsonStructure($this->jsonStructure);
$this->assertDataBaseHas('genders', [
'account_id' => $user->account_id,
'id' => $gender->id,
'name' => 'gender',
]);
}
/** @test */
public function it_replaces_a_gender()
{
$user = $this->signin();
$genders = $user->account->genders()->get();
$gender1 = $genders[0]->id;
$gender2 = $genders[1]->id;
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
'gender_id' => $gender1,
]);
$response = $this->json('DELETE', '/settings/personalization/genders/'.$gender1.'/replaceby/'.$gender2);
$this->expectObjectDeleted($response, $genders[0]->id);
$this->assertDataBaseMissing('genders', [
'account_id' => $user->account_id,
'id' => $genders[0]->id,
]);
$this->assertDataBaseHas('contacts', [
'account_id' => $user->account_id,
'id' => $contact->id,
'gender_id' => $gender2,
]);
}
/** @test */
public function it_replaces_a_gender_with_error()
{
$user = $this->signin();
$gender1 = factory(Gender::class)->create([
'account_id' => $user->account_id,
]);
$gender2 = factory(Gender::class)->create();
$response = $this->json('DELETE', '/settings/personalization/genders/'.$gender1->id.'/replaceby/'.$gender2->id);
$response->assertStatus(403);
$response->assertJson([
'message' => 'Please choose a gender from the list.',
]);
}
/** @test */
public function it_destroys_a_gender()
{
$user = $this->signin();
$gender = $user->account->genders()->first();
$response = $this->json('DELETE', '/settings/personalization/genders/'.$gender->id);
$this->expectObjectDeleted($response, $gender->id);
$this->assertDataBaseMissing('genders', [
'account_id' => $user->account_id,
'id' => $gender->id,
]);
}
/** @test */
public function it_updates_the_default_gender()
{
$user = $this->signin();
$gender = $user->account->genders()->first();
$this->assertNull($user->account->default_gender_id);
$response = $this->json('PUT', '/settings/personalization/genders/default/'.$gender->id);
$response->assertStatus(200);
$response->assertJsonStructure($this->jsonStructure);
$this->assertEquals($gender->id, $user->account->default_gender_id);
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Tests\Unit\Events;
use Tests\FeatureTestCase;
use App\Events\RecoveryLogin;
use Illuminate\Auth\AuthManager;
use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Event;
use PragmaRX\Google2FALaravel\Facade as Google2FA;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class Google2faEventListenerTest extends FeatureTestCase
{
use DatabaseTransactions;
public function setUp(): void
{
parent::setUp();
$this->startSession();
$request = new FakeRequest();
$request->session = $this->app['session'];
Google2FA::setRequest($request);
app('pragmarx.google2fa')->setStateless(false);
}
/** @test */
public function it_listens_recovery_event()
{
$user = $this->signIn();
$user->google2fa_secret = 'x';
Event::dispatch(new RecoveryLogin($user));
$this->assertTrue($this->app['session']->get('google2fa.auth_passed'));
}
/** @test */
public function it_listens_login_remember_event()
{
$user = $this->signIn();
$user->google2fa_secret = 'x';
$guard = app(AuthManager::class)->guard();
$this->setPrivateValue($guard, 'viaRemember', true);
Event::dispatch(new Login('guard', $user, true));
$this->assertTrue($this->app['session']->get('google2fa.auth_passed'));
}
}
class FakeRequest
{
public $session;
public function session()
{
return $this->session;
}
}

View File

@@ -0,0 +1,264 @@
<?php
namespace Tests\Unit\Helpers;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Contact\Call;
use App\Helpers\AccountHelper;
use App\Models\Contact\Gender;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\Activity;
use App\Models\Contact\Reminder;
use App\Models\Account\Invitation;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AccountHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function user_has_limitations_if_not_subscribed_or_exempted_of_subscriptions(): void
{
$account = factory(Account::class)->make([
'has_access_to_paid_version_for_free' => true,
]);
$this->assertFalse(AccountHelper::hasLimitations($account));
// Check that if the ENV variable REQUIRES_SUBSCRIPTION has an effect
$account = factory(Account::class)->make([
'has_access_to_paid_version_for_free' => false,
]);
config(['monica.requires_subscription' => false]);
$this->assertFalse(AccountHelper::hasLimitations($account));
}
/** @test */
public function account_has_reached_contact_limit_on_free_plan(): void
{
$account = factory(Account::class)->create();
factory(Contact::class, 2)->create([
'account_id' => $account->id,
]);
config(['monica.number_of_allowed_contacts_free_account' => 1]);
$this->assertTrue(AccountHelper::hasReachedContactLimit($account));
$this->assertFalse(AccountHelper::isBelowContactLimit($account));
factory(Contact::class)->state('partial')->create([
'account_id' => $account->id,
]);
config(['monica.number_of_allowed_contacts_free_account' => 3]);
$this->assertFalse(AccountHelper::hasReachedContactLimit($account));
$this->assertTrue(AccountHelper::isBelowContactLimit($account));
config(['monica.number_of_allowed_contacts_free_account' => 100]);
$this->assertFalse(AccountHelper::hasReachedContactLimit($account));
$this->assertTrue(AccountHelper::isBelowContactLimit($account));
$account = factory(Account::class)->create();
factory(Contact::class, 2)->create([
'account_id' => $account->id,
'is_active' => false,
]);
factory(Contact::class, 3)->create([
'account_id' => $account->id,
'is_active' => true,
]);
config(['monica.number_of_allowed_contacts_free_account' => 3]);
$this->assertTrue(AccountHelper::hasReachedContactLimit($account));
$this->assertTrue(AccountHelper::isBelowContactLimit($account));
}
/** @test */
public function user_can_downgrade_with_only_one_user_and_no_pending_invitations_and_under_contact_limit(): void
{
config(['monica.number_of_allowed_contacts_free_account' => 1]);
$contact = factory(Contact::class)->create();
factory(User::class)->create([
'account_id' => $contact->account_id,
]);
$this->assertTrue(AccountHelper::canDowngrade($contact->account));
}
/** @test */
public function user_cant_downgrade_with_two_users(): void
{
$contact = factory(Contact::class)->create();
factory(User::class, 3)->create([
'account_id' => $contact->account_id,
]);
$this->assertFalse(AccountHelper::canDowngrade($contact->account));
}
/** @test */
public function user_cant_downgrade_with_pending_invitations(): void
{
$account = factory(Account::class)->create();
factory(Invitation::class)->create([
'account_id' => $account->id,
]);
$this->assertFalse(AccountHelper::canDowngrade($account));
}
/** @test */
public function user_cant_downgrade_with_too_many_contacts(): void
{
config(['monica.number_of_allowed_contacts_free_account' => 1]);
$account = factory(Account::class)->create();
factory(Contact::class, 2)->create([
'account_id' => $account->id,
]);
$this->assertFalse(AccountHelper::canDowngrade($account));
}
/** @test */
public function it_gets_the_default_gender_for_the_account(): void
{
$account = factory(Account::class)->create();
$this->assertEquals(Gender::UNKNOWN, AccountHelper::getDefaultGender($account));
$gender = factory(Gender::class)->create([
'account_id' => $account->id,
]);
$account->default_gender_id = $gender->id;
$account->save();
$this->assertEquals($gender->type, AccountHelper::getDefaultGender($account));
}
/** @test */
public function get_reminders_for_month_returns_no_reminders(): void
{
$account = factory(Account::class)->create();
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
factory(Reminder::class, 3)->create([
'account_id' => $account->id,
]);
// check if there are reminders for the month of March
$this->actingAs($user)->assertCount(0, AccountHelper::getUpcomingRemindersForMonth($account, 3));
}
/** @test */
public function get_reminders_for_month_returns_reminders_for_given_month(): void
{
$account = factory(Account::class)->create();
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
// add 3 reminders for the month of March
for ($i = 0; $i < 3; $i++) {
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'initial_date' => '2017-03-03 00:00:00',
]);
$reminder->schedule($user);
}
$this->actingAs($user)->assertCount(3, AccountHelper::getUpcomingRemindersForMonth($account, 2));
}
/** @test */
public function get_reminders_for_month_returns_reminders_for_current_user_only(): void
{
$account = factory(Account::class)->create();
$user1 = factory(User::class)->create([
'account_id' => $account->id,
]);
$user2 = factory(User::class)->create([
'account_id' => $account->id,
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
// add 3 reminders for the month of March
for ($i = 0; $i < 3; $i++) {
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'initial_date' => '2017-03-03 00:00:00',
]);
$reminder->schedule($user1);
$reminder->schedule($user2);
}
$this->actingAs($user1)->assertCount(3, AccountHelper::getUpcomingRemindersForMonth($account, 2));
}
/** @test */
public function it_retrieves_yearly_activities_statistics(): void
{
$account = factory(Account::class)->create();
factory(Activity::class, 4)->create([
'account_id' => $account->id,
'happened_at' => '2018-03-02',
]);
factory(Activity::class, 2)->create([
'account_id' => $account->id,
'happened_at' => '1992-03-02',
]);
$statistics = AccountHelper::getYearlyActivitiesStatistics($account);
$this->assertEquals(
[
1992 => 2,
2018 => 4,
],
$statistics->toArray()
);
}
/** @test */
public function it_retrieves_yearly_call_statistics(): void
{
$contact = factory(Contact::class)->create();
factory(Call::class, 4)->create([
'account_id' => $contact->account_id,
'contact_id' => $contact->id,
'called_at' => '2018-03-02',
]);
factory(Call::class, 2)->create([
'account_id' => $contact->account_id,
'contact_id' => $contact->id,
'called_at' => '1992-03-02',
]);
$statistics = AccountHelper::getYearlyCallStatistics($contact->account);
$this->assertEquals(
[
1992 => 2,
2018 => 4,
],
$statistics->toArray()
);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use App\Models\User\User;
use App\Helpers\AuditLogHelper;
use App\Models\Contact\Contact;
use App\Models\Instance\AuditLog;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AuditLogHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_prepares_a_collection_of_audit_logs_for_the_settings_page()
{
$user = factory(User::class)->create([]);
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
'first_name' => 'roger',
'last_name' => 'moore',
]);
factory(AuditLog::class, 2)->create([
'account_id' => $user->account_id,
'about_contact_id' => $contact->id,
'objects' => '{"contact_name":"'.$contact->name.'","contact_id":'.$contact->id.'}',
]);
$logs = $user->account->auditLogs;
$collection = AuditLogHelper::getCollectionOfAudits($logs);
$this->assertEquals(
2,
$collection->count()
);
}
/** @test */
public function it_prepares_a_collection_of_audit_logs_without_likns_for_the_settings_page()
{
$user = factory(User::class)->create([]);
factory(AuditLog::class, 2)->create([
'account_id' => $user->account_id,
'about_contact_id' => null,
'objects' => '{"contact_name":"roger moore","contact_id":123456789}',
]);
$logs = $user->account->auditLogs;
$collection = AuditLogHelper::getCollectionOfAudits($logs);
$this->assertEquals(
2,
$collection->count()
);
$this->assertEquals(
'logs.settings_log_account_created_with_name',
$collection[0]['description']
);
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Helpers\CollectionHelper;
use Illuminate\Support\Facades\App;
class CollectionHelperTest extends FeatureTestCase
{
/** @test */
public function sortByCollator_base()
{
$collection = collect([
['name' => 'a'],
['name' => 'c'],
['name' => 'b'],
]);
$collection = CollectionHelper::sortByCollator($collection, 'name');
$this->assertEquals(
[
['name' => 'a'],
['name' => 'b'],
['name' => 'c'],
],
array_values($collection->toArray())
);
}
/** @test */
public function sortByCollator_macro()
{
$collection = collect([
['name' => 'a'],
['name' => 'c'],
['name' => 'b'],
]);
$collection = $collection->sortByCollator('name');
$this->assertEquals(
[
['name' => 'a'],
['name' => 'b'],
['name' => 'c'],
],
array_values($collection->toArray())
);
}
/** @test */
public function sortByCollator_callback()
{
$collection = collect([
['name' => 'a'],
['name' => 'c'],
['name' => 'b'],
]);
$collection = $collection->sortByCollator(function ($item) {
return $item['name'];
});
$this->assertEquals(
[
['name' => 'a'],
['name' => 'b'],
['name' => 'c'],
],
array_values($collection->toArray())
);
}
/** @test */
public function sortByCollator_default_collation()
{
App::setLocale('en');
$collection = collect([
['name' => 'cote'],
['name' => 'côté'],
['name' => 'coté'],
['name' => 'côte'],
]);
$collection = CollectionHelper::sortByCollator($collection, 'name');
$this->assertEquals(
[
['name' => 'cote'],
['name' => 'coté'],
['name' => 'côte'],
['name' => 'côté'],
],
array_values($collection->toArray())
);
}
/** @test */
public function sortByCollator_french_collation()
{
App::setLocale('fr');
$collection = collect([
['name' => 'cote'],
['name' => 'côté'],
['name' => 'coté'],
['name' => 'côte'],
]);
$collection = CollectionHelper::sortByCollator($collection, 'name');
$this->assertEquals(
[
['name' => 'cote'],
['name' => 'côte'],
['name' => 'coté'],
['name' => 'côté'],
],
array_values($collection->toArray())
);
}
/** @test */
public function getCollator_french_collation()
{
$collator = CollectionHelper::getCollator('fr');
$this->assertEquals($collator->getAttribute(\Collator::FRENCH_COLLATION), \Collator::ON);
$this->assertEquals($collator->getLocale(\Locale::VALID_LOCALE), 'fr');
}
/** @test */
public function group_by_items_property()
{
$object1 = (object) ['name' => 'John'];
$object2 = (object) ['name' => 'Jack'];
$object3 = (object) ['name' => 'John'];
$collection = collect([
$object1,
$object2,
$object3,
]);
$collection = CollectionHelper::groupByItemsProperty($collection, 'name');
$this->assertEquals(
[
'John' => [$object1, $object3],
'Jack' => [$object2],
],
$collection->toArray()
);
}
/** @test */
public function it_maps_uuid()
{
$collection = collect();
for ($i = 1; $i <= 3; $i++) {
$uuid = new \stdClass();
$uuid->uuid = $i;
$collection->push($uuid);
}
$uuids = $collection->mapUuid();
$this->assertEquals([1, 2, 3], $uuids);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Settings\Term;
use App\Helpers\ComplianceHelper;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ComplianceHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_checks_if_the_user_has_signed_the_given_term()
{
$user = factory(User::class)->create([]);
$term = factory(Term::class)->create([]);
$this->assertFalse(ComplianceHelper::hasSignedGivenTerm($user, $term));
$term = factory(Term::class)->create([]);
$user->terms()->sync([$term->id => ['account_id' => $user->account_id]]);
$this->assertTrue(ComplianceHelper::hasSignedGivenTerm($user, $term));
}
/** @test */
public function it_checks_if_the_user_has_signed_the_latest_term()
{
$user = factory(User::class)->create([]);
$term = factory(Term::class)->create([
'created_at' => '1990-02-07 02:26:07',
]);
$this->assertFalse(ComplianceHelper::isCompliantWithCurrentTerm($user));
$term = factory(Term::class)->create([
'created_at' => '2020-02-07 02:26:07',
]);
$user->terms()->syncWithoutDetaching([$term->id => ['account_id' => $user->account_id]]);
$this->assertTrue(ComplianceHelper::isCompliantWithCurrentTerm($user));
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Helpers\CountriesHelper;
class CountryHelperTest extends FeatureTestCase
{
/**
* @dataProvider countryDefaultCountryFromLocaleProvider
*/
public function test_country_getDefaultCountryFromLocale($locale, $expect)
{
$reflection = new \ReflectionClass(CountriesHelper::class);
$method = $reflection->getMethod('getDefaultCountryFromLocale');
$method->setAccessible(true);
$country = $method->invokeArgs(null, [$locale]);
$this->assertEquals(
$expect,
$country
);
}
public function countryDefaultCountryFromLocaleProvider()
{
return [
['en', 'US'],
['En', 'US'],
['EN', 'US'],
['cs', 'CZ'],
['he', 'IL'],
['zh', 'CN'],
['de', 'DE'],
['es', 'ES'],
['fr', 'FR'],
['hr', 'HR'],
['it', 'IT'],
['nl', 'NL'],
['pt', 'PT'],
['ru', 'RU'],
['tr', 'TR'],
['ja', null],
];
}
/**
* @dataProvider countryCountryFromLocaleProvider
*/
public function test_country_getCountryFromLocale($locale, $expect)
{
$country = CountriesHelper::getCountryFromLocale($locale);
$this->assertNotNull($country);
$this->assertEquals(
$expect,
$country->getIsoAlpha2()
);
}
public function countryCountryFromLocaleProvider()
{
return [
['en', 'US'],
['En', 'US'],
['EN', 'US'],
['en-US', 'US'],
['cs', 'CZ'],
['he', 'IL'],
['zh', 'CN'],
['de', 'DE'],
['es', 'ES'],
['fr', 'FR'],
['hr', 'HR'],
['id', 'ID'],
['it', 'IT'],
['nl', 'NL'],
['pt', 'PT'],
['ru', 'RU'],
['tr', 'TR'],
['ja', 'JP'],
['pt-BR', 'BR'],
['fr-BE', 'BE'],
];
}
/**
* @dataProvider timezoneFromLocaleProvider
* @test
*/
public function it_get_default_timezone($locale, $expect)
{
$country = CountriesHelper::getCountryFromLocale($locale);
$timezone = CountriesHelper::getDefaultTimezone($country);
$this->assertNotNull($timezone);
$this->assertEquals(
$expect,
$timezone
);
}
public function timezoneFromLocaleProvider()
{
return [
['en', 'America/Chicago'],
['cs', 'Europe/Prague'],
['he', 'Asia/Jerusalem'],
['zh', 'Asia/Shanghai'],
['de', 'Europe/Berlin'],
['es', 'Europe/Madrid'],
['fr', 'Europe/Paris'],
['hr', 'Europe/Zagreb'],
['id', 'Asia/Jakarta'],
['it', 'Europe/Rome'],
['nl', 'Europe/Amsterdam'],
['pt', 'Europe/Lisbon'],
['ru', 'Europe/Moscow'],
['tr', 'Europe/Istanbul'],
['ja', 'Asia/Tokyo'],
];
}
}

View File

@@ -0,0 +1,761 @@
<?php
namespace Tests\Unit\Helpers;
use Carbon\Carbon;
use Tests\FeatureTestCase;
use App\Helpers\DateHelper;
use App\Helpers\TimezoneHelper;
use Illuminate\Support\Facades\App;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DateHelperTest extends FeatureTestCase
{
use DatabaseTransactions;
public function testGetShortDateWithEnglishLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'Jan 22, 2017',
DateHelper::getShortDate($date)
);
}
public function testGetShortDateWithFrenchLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('fr');
$this->assertEquals(
'22 janv. 2017',
DateHelper::getShortDate($date)
);
}
public function testGetShortDateWithUnknownLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('jp');
$this->assertEquals(
'Jan 22, 2017',
DateHelper::getShortDate($date)
);
}
public function testGetFullDateWithEnglishLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'January 22, 2017',
DateHelper::getFullDate($date)
);
}
public function testGetFullDateWithFrenchLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('fr');
$this->assertEquals(
'22 janvier 2017',
DateHelper::getFullDate($date)
);
}
public function testGetFullDateWithUnknownLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('jp');
$this->assertEquals(
'January 22, 2017',
DateHelper::getFullDate($date)
);
}
public function testGetShortDateWithTimeWithEnglishLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'Jan 22, 2017 17:56',
DateHelper::getShortDateWithTime($date)
);
}
public function testGetShortDateWithTimeWithFrenchLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('fr');
$this->assertEquals(
'22 janv. 2017 17:56',
DateHelper::getShortDateWithTime($date)
);
}
public function testGetShortDateWithTimeWithUnknownLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('jp');
$this->assertEquals(
'Jan 22, 2017 17:56',
DateHelper::getShortDateWithTime($date)
);
}
public function test_get_short_date_without_year_returns_a_date()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'Jan 22',
DateHelper::getShortDateWithoutYear($date)
);
App::setLocale('fr');
$this->assertEquals(
'22 janv.',
DateHelper::getShortDateWithoutYear($date)
);
}
public function test_it_returns_the_default_short_date()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale(null);
$this->assertEquals(
'Jan 22',
DateHelper::getShortDateWithoutYear($date)
);
}
public function test_add_time_according_to_frequency_type_returns_the_right_value()
{
$date = '2017-01-22 17:56:03';
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(
'2017-01-29',
DateHelper::addTimeAccordingToFrequencyType($testDate, 'week', 1)->toDateString()
);
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(
'2017-02-22',
DateHelper::addTimeAccordingToFrequencyType($testDate, 'month', 1)->toDateString()
);
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(
'2018-01-22',
DateHelper::addTimeAccordingToFrequencyType($testDate, 'year', 1)->toDateString()
);
}
public function test_parse_dateTime()
{
$testDate = DateHelper::parseDateTime(null);
$this->assertNull($testDate);
$date = '2017-01-22 17:56:03';
$testDate = DateHelper::parseDateTime($date);
$this->assertInstanceOf(Carbon::class, $testDate);
}
public function test_parse_dateTime_bad()
{
$date = 'xF 2017';
$testDate = DateHelper::parseDateTime($date);
$this->assertNull($testDate);
}
public function test_parse_parseDate_bad()
{
$date = 'xF 2017';
$testDate = DateHelper::parseDate($date);
$this->assertNull($testDate);
}
public function test_parse_dateTime_format()
{
$date = '20190120T232144Z';
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(2019, $testDate->year);
$this->assertEquals(1, $testDate->month);
$this->assertEquals(20, $testDate->day);
$this->assertEquals(23, $testDate->hour);
$this->assertEquals(21, $testDate->minute);
$this->assertEquals(44, $testDate->second);
$this->assertEquals('UTC', $testDate->timezone->getName());
$this->assertEquals(
'2019-01-20',
$testDate->toDateString()
);
$this->assertEquals(
'2019-01-20T23:21:44Z',
DateHelper::getTimestamp($testDate)
);
}
public function test_parse_dateTime_utc()
{
$date = '2017-01-22 17:56:03';
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(2017, $testDate->year);
$this->assertEquals(1, $testDate->month);
$this->assertEquals(22, $testDate->day);
$this->assertEquals(17, $testDate->hour);
$this->assertEquals(56, $testDate->minute);
$this->assertEquals(03, $testDate->second);
$this->assertEquals('UTC', $testDate->timezone->getName());
$this->assertEquals(
'2017-01-22',
$testDate->toDateString()
);
$this->assertEquals(
'2017-01-22T17:56:03Z',
DateHelper::getTimestamp($testDate)
);
}
public function test_parse_dateTime_new_york()
{
$date = '2017-01-22 17:56:03';
$timezone = 'America/New_York';
$testDate = DateHelper::parseDateTime($date, $timezone);
$this->assertEquals(2017, $testDate->year);
$this->assertEquals(1, $testDate->month);
$this->assertEquals(22, $testDate->day);
$this->assertEquals(22, $testDate->hour);
$this->assertEquals(56, $testDate->minute);
$this->assertEquals(03, $testDate->second);
$this->assertEquals('UTC', $testDate->timezone->getName());
$this->assertEquals(
'2017-01-22',
$testDate->toDateString()
);
$this->assertEquals(
'2017-01-22T22:56:03Z',
DateHelper::getTimestamp($testDate)
);
}
public function test_parse_dateTime_paris()
{
$date = '2019-01-01 00:56:03';
$timezone = 'Europe/Paris';
$testDate = DateHelper::parseDateTime($date, $timezone);
$this->assertEquals(2018, $testDate->year);
$this->assertEquals(12, $testDate->month);
$this->assertEquals(31, $testDate->day);
$this->assertEquals(23, $testDate->hour);
$this->assertEquals(56, $testDate->minute);
$this->assertEquals(03, $testDate->second);
$this->assertEquals('UTC', $testDate->timezone->getName());
$this->assertEquals(
'2018-12-31',
$testDate->toDateString()
);
$this->assertEquals(
'2018-12-31T23:56:03Z',
DateHelper::getTimestamp($testDate)
);
}
public function test_parse_dateTime_carbon()
{
$date = new Carbon('2019-01-01 00:56:03', 'Europe/Paris');
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(2018, $testDate->year);
$this->assertEquals(12, $testDate->month);
$this->assertEquals(31, $testDate->day);
$this->assertEquals(23, $testDate->hour);
$this->assertEquals(56, $testDate->minute);
$this->assertEquals(03, $testDate->second);
$this->assertEquals('UTC', $testDate->timezone->getName());
$this->assertEquals(
'2018-12-31',
$testDate->toDateString()
);
$this->assertEquals(
'2018-12-31T23:56:03Z',
DateHelper::getTimestamp($testDate)
);
}
public function test_parse_dateTime_dateTimeObject()
{
$date = new \DateTime('2019-01-01 00:56:03', new \DateTimeZone('Europe/Paris'));
$testDate = DateHelper::parseDateTime($date);
$this->assertEquals(2018, $testDate->year);
$this->assertEquals(12, $testDate->month);
$this->assertEquals(31, $testDate->day);
$this->assertEquals(23, $testDate->hour);
$this->assertEquals(56, $testDate->minute);
$this->assertEquals(03, $testDate->second);
$this->assertEquals('UTC', $testDate->timezone->getName());
$this->assertEquals(
'2018-12-31',
$testDate->toDateString()
);
$this->assertEquals(
'2018-12-31T23:56:03Z',
DateHelper::getTimestamp($testDate)
);
}
public function testGetShortMonthWithEnglishLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'Jan',
DateHelper::getShortMonth($date)
);
}
public function testGetShortMonthWithFrenchLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('fr');
$this->assertEquals(
'janv.',
DateHelper::getShortMonth($date)
);
}
public function testGetShortMonthWithUnknownLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('jp');
$this->assertEquals(
'Jan',
DateHelper::getShortMonth($date)
);
}
public function testGetFullMonthAndDateWithEnglishLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'January 2017',
DateHelper::getFullMonthAndDate($date)
);
}
public function testGetFullMonthAndDateWithFrenchLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('fr');
$this->assertEquals(
'janvier 2017',
DateHelper::getFullMonthAndDate($date)
);
}
public function testGetFullMonthAndDateWithUnknownLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('jp');
$this->assertEquals(
'January 2017',
DateHelper::getFullMonthAndDate($date)
);
}
public function testGetShortDayWithEnglishLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('en');
$this->assertEquals(
'Sun',
DateHelper::getShortDay($date)
);
}
public function testGetShortDayWithFrenchLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('fr');
$this->assertEquals(
'dim.',
DateHelper::getShortDay($date)
);
}
public function testGetShortDayWithUnknownLocale()
{
$date = Carbon::parse('2017-01-22 17:56:03');
App::setLocale('jp');
$this->assertEquals(
'Sun',
DateHelper::getShortDay($date)
);
}
public function test_get_month_and_year()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1));
$this->assertEquals(
'Jul 2017',
DateHelper::getMonthAndYear(6)
);
}
public function test_it_gets_date_one_month_from_now()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1));
$this->assertEquals(
'2017-02-01',
DateHelper::getNextTheoriticalBillingDate('monthly')->toDateString()
);
}
public function test_it_gets_date_one_year_from_now()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1));
$this->assertEquals(
'2018-01-01',
DateHelper::getNextTheoriticalBillingDate('yearly')->toDateString()
);
}
public function test_it_returns_a_list_with_years()
{
$user = $this->signIn();
$user->locale = 'en';
$user->save();
$this->assertCount(
3,
DateHelper::getListOfYears(2)
);
$this->assertEquals(
now()->year,
DateHelper::getListOfYears(2)->first()['name']
);
$this->assertEquals(
now()->subYears(2)->year,
DateHelper::getListOfYears(2)->last()['name']
);
$this->assertEquals(
now()->subYears(-2)->year,
DateHelper::getListOfYears(2, -2)->first()['name']
);
$this->assertEquals(
now()->year,
DateHelper::getListOfYears(2, -2)[2]['name']
);
}
public function test_it_returns_a_list_with_twelve_months()
{
$user = $this->signIn();
$user->locale = 'en';
$user->save();
$this->assertCount(
12,
DateHelper::getListOfMonths()
);
}
public function test_it_returns_a_list_of_months_in_english()
{
$user = $this->signIn();
$user->locale = 'en';
$user->save();
$months = DateHelper::getListOfMonths();
$this->assertEquals(
'January',
$months[0]['name']
);
}
public function test_it_returns_a_list_with_thirty_one_days()
{
$user = $this->signIn();
$user->locale = 'en';
$user->save();
$this->assertCount(
31,
DateHelper::getListOfDays()
);
}
public function test_it_returns_a_list_with_twenty_four_hours()
{
$this->assertCount(
24,
DateHelper::getListOfHours()
);
}
public function test_it_returns_a_list_of_hours()
{
$hours = DateHelper::getListOfHours();
$this->assertEquals(
'01.00 AM',
$hours[0]['name']
);
$this->assertEquals(
'01:00',
$hours[0]['id']
);
$this->assertEquals(
'02.00 PM',
$hours[13]['name']
);
$this->assertEquals(
'14:00',
$hours[13]['id']
);
}
public function test_it_returns_a_list_of_hours_French()
{
App::setLocale('fr');
$hours = DateHelper::getListOfHours();
$this->assertEquals(
'01:00',
$hours[0]['name']
);
$this->assertEquals(
'01:00',
$hours[0]['id']
);
$this->assertEquals(
'14:00',
$hours[13]['name']
);
$this->assertEquals(
'14:00',
$hours[13]['id']
);
}
public function test_old_timezones_exists()
{
// These are all currently used timezone in monica
$oldTimezones = [
'US/Eastern',
'US/Central',
'America/Los_Angeles',
'Pacific/Midway',
'Pacific/Samoa',
'Pacific/Honolulu',
'US/Alaska',
'America/Tijuana',
'US/Arizona',
'America/Chihuahua',
'America/Chihuahua',
'America/Mazatlan',
'US/Mountain',
'America/Managua',
'US/Central',
'America/Mexico_City',
'America/Mexico_City',
'America/Monterrey',
'Canada/Saskatchewan',
'America/Bogota',
'US/Eastern',
'US/East-Indiana',
'America/Lima',
'America/Bogota',
'Canada/Atlantic',
'America/Caracas',
'America/La_Paz',
'America/Santiago',
'Canada/Newfoundland',
'America/Sao_Paulo',
'America/Argentina/Buenos_Aires',
'America/Noronha',
'Atlantic/Azores',
'Atlantic/Cape_Verde',
'Africa/Casablanca',
'Europe/London',
'Etc/Greenwich',
'Europe/Lisbon',
'Europe/London',
'Africa/Monrovia',
'UTC',
'Europe/Amsterdam',
'Europe/Belgrade',
'Europe/Berlin',
'Europe/Bratislava',
'Europe/Brussels',
'Europe/Budapest',
'Europe/Copenhagen',
'Europe/Ljubljana',
'Europe/Madrid',
'Europe/Paris',
'Europe/Prague',
'Europe/Rome',
'Europe/Sarajevo',
'Europe/Skopje',
'Europe/Stockholm',
'Europe/Vienna',
'Europe/Warsaw',
'Africa/Lagos',
'Europe/Zagreb',
'Europe/Zurich',
'Europe/Athens',
'Europe/Bucharest',
'Africa/Cairo',
'Africa/Harare',
'Europe/Helsinki',
'Europe/Istanbul',
'Asia/Jerusalem',
'Europe/Helsinki',
'Africa/Johannesburg',
'Europe/Riga',
'Europe/Sofia',
'Europe/Tallinn',
'Europe/Vilnius',
'Asia/Baghdad',
'Asia/Kuwait',
'Europe/Minsk',
'Africa/Nairobi',
'Asia/Riyadh',
'Europe/Volgograd',
'Asia/Tehran',
'Asia/Muscat',
'Asia/Baku',
'Europe/Moscow',
'Asia/Muscat',
'Europe/Moscow',
'Asia/Tbilisi',
'Asia/Yerevan',
'Asia/Kabul',
'Asia/Karachi',
'Asia/Karachi',
'Asia/Tashkent',
'Asia/Calcutta',
'Asia/Kolkata',
'Asia/Calcutta',
'Asia/Calcutta',
'Asia/Calcutta',
'Asia/Katmandu',
'Asia/Almaty',
'Asia/Dhaka',
'Asia/Dhaka',
'Asia/Yekaterinburg',
'Asia/Rangoon',
'Asia/Bangkok',
'Asia/Bangkok',
'Asia/Jakarta',
'Asia/Novosibirsk',
'Asia/Hong_Kong',
'Asia/Chongqing',
'Asia/Hong_Kong',
'Asia/Krasnoyarsk',
'Asia/Kuala_Lumpur',
'Australia/Perth',
'Asia/Singapore',
'Asia/Taipei',
'Asia/Ulan_Bator',
'Asia/Urumqi',
'Asia/Irkutsk',
'Asia/Tokyo',
'Asia/Tokyo',
'Asia/Seoul',
'Asia/Tokyo',
'Australia/Adelaide',
'Australia/Darwin',
'Australia/Brisbane',
'Australia/Canberra',
'Pacific/Guam',
'Australia/Hobart',
'Australia/Melbourne',
'Pacific/Port_Moresby',
'Australia/Sydney',
'Asia/Yakutsk',
'Asia/Vladivostok',
'Pacific/Auckland',
'Pacific/Fiji',
'Pacific/Kwajalein',
'Asia/Kamchatka',
'Asia/Magadan',
'Pacific/Fiji',
'Asia/Magadan',
'Asia/Magadan',
'Pacific/Auckland',
'Pacific/Tongatapu',
];
$list = TimezoneHelper::getListOfTimezones();
$list = collect($list);
$missed = '';
foreach ($oldTimezones as $timezone) {
$timezone = TimezoneHelper::adjustEquivalentTimezone($timezone);
if ($list->firstWhere('timezone', $timezone) == null) {
$missed .= $timezone.',';
}
}
$this->assertTrue(empty($missed), 'Missed timezones : '.$missed);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use App\Models\User\User;
use App\Helpers\FormHelper;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class FormHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_name_order_for_a_form()
{
$user = factory(User::class)->create([]);
$user->name_order = 'firstname_lastname';
$this->assertEquals(
'firstname',
FormHelper::getNameOrderForForms($user)
);
$user->name_order = 'firstname_lastname_nickname';
$this->assertEquals(
'firstname',
FormHelper::getNameOrderForForms($user)
);
$user->name_order = 'firstname_nickname_lastname';
$this->assertEquals(
'firstname',
FormHelper::getNameOrderForForms($user)
);
$user->name_order = 'lastname_firstname';
$this->assertEquals(
'lastname',
FormHelper::getNameOrderForForms($user)
);
$user->name_order = 'lastname_firstname_nickname';
$this->assertEquals(
'lastname',
FormHelper::getNameOrderForForms($user)
);
$user->name_order = 'lastname_nickname_firstname';
$this->assertEquals(
'lastname',
FormHelper::getNameOrderForForms($user)
);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Helpers\GenderHelper;
use App\Models\Contact\Gender;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
class GenderHelperTest extends FeatureTestCase
{
/** @test */
public function it_gets_all_the_gender_inputs()
{
$this->signIn();
$genders = GenderHelper::getGendersInput();
$this->assertCount(4, $genders);
$this->assertEquals([
'id' => '',
'name' => 'No gender',
], $genders[0]);
}
/** @test */
public function it_replaces_gender_with_another_gender()
{
$account = factory(Account::class)->create();
$male = factory(Gender::class)->create([
'account_id' => $account->id,
]);
$female = factory(Gender::class)->create([
'account_id' => $account->id,
]);
factory(Contact::class, 2)->create([
'account_id' => $account->id,
'gender_id' => $male,
]);
factory(Contact::class)->create([
'account_id' => $account->id,
'gender_id' => $female,
]);
GenderHelper::replace($account, $male, $female);
$this->assertEquals(
3,
$female->contacts->count()
);
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace Tests\Unit\Helpers;
use Mockery;
use Tests\TestCase;
use function Safe\json_decode;
use App\Helpers\InstanceHelper;
use App\Models\Account\Account;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class InstanceHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_the_number_of_paid_subscribers()
{
factory(Account::class)->create(['stripe_id' => 'id292839']);
factory(Account::class)->create();
factory(Account::class)->create(['stripe_id' => 'id2sdf92839']);
$this->assertEquals(
2,
InstanceHelper::getNumberOfPaidSubscribers()
);
}
/** @test */
public function it_fetches_the_monthly_plan_information()
{
config(['monica.paid_plan_monthly_friendly_name' => 'Monthly']);
config(['monica.paid_plan_monthly_id' => 'monthly']);
config(['monica.paid_plan_monthly_price' => 1000]);
$this->assertEquals(
'monthly',
InstanceHelper::getPlanInformationFromConfig('monthly')['type']
);
$this->assertEquals(
'Monthly',
InstanceHelper::getPlanInformationFromConfig('monthly')['name']
);
$this->assertEquals(
'monthly',
InstanceHelper::getPlanInformationFromConfig('monthly')['id']
);
$this->assertEquals(
1000,
InstanceHelper::getPlanInformationFromConfig('monthly')['price']
);
$this->assertEquals(
'$10.00',
InstanceHelper::getPlanInformationFromConfig('monthly')['friendlyPrice']
);
}
/** @test */
public function it_fetches_the_annually_plan_information()
{
config(['monica.paid_plan_annual_friendly_name' => 'Annual']);
config(['monica.paid_plan_annual_id' => 'annual']);
config(['monica.paid_plan_annual_price' => 1000]);
$this->assertEquals(
'annual',
InstanceHelper::getPlanInformationFromConfig('annual')['type']
);
$this->assertEquals(
'Annual',
InstanceHelper::getPlanInformationFromConfig('annual')['name']
);
$this->assertEquals(
'annual',
InstanceHelper::getPlanInformationFromConfig('annual')['id']
);
$this->assertEquals(
1000,
InstanceHelper::getPlanInformationFromConfig('annual')['price']
);
$this->assertEquals(
'$10.00',
InstanceHelper::getPlanInformationFromConfig('annual')['friendlyPrice']
);
}
/** @test */
public function it_fetches_subscription_information()
{
$stripeSubscription = (object) [
'plan' => (object) [
'currency' => 'USD',
'amount' => 500,
'interval' => 'month',
'id' => 'monthly',
],
'current_period_end' => 1629976560,
];
$subscription = Mockery::mock('\Laravel\Cashier\Subscription');
$subscription->shouldReceive('asStripeSubscription')
->andReturn($stripeSubscription);
$subscription->shouldReceive('getAttribute')
->with('name')
->andReturn('Monthly');
$this->assertEquals(
'monthly',
InstanceHelper::getPlanInformationFromSubscription($subscription)['type']
);
$this->assertEquals(
'Monthly',
InstanceHelper::getPlanInformationFromSubscription($subscription)['name']
);
$this->assertEquals(
'monthly',
InstanceHelper::getPlanInformationFromSubscription($subscription)['id']
);
$this->assertEquals(
500,
InstanceHelper::getPlanInformationFromSubscription($subscription)['price']
);
$this->assertEquals(
'$5.00',
InstanceHelper::getPlanInformationFromSubscription($subscription)['friendlyPrice']
);
}
/** @test */
public function it_returns_null_when_fetching_an_unknown_plan_information()
{
$account = new Account;
$this->assertNull(
InstanceHelper::getPlanInformationFromConfig('unknown_plan')
);
}
/** @test */
public function it_gets_latest_changelog_entries()
{
$json = public_path('changelog.json');
$changelogs = json_decode(file_get_contents($json), true)['entries'];
$count = count($changelogs);
$this->assertCount(
$count,
InstanceHelper::getChangelogEntries()
);
$this->assertCount(
3,
InstanceHelper::getChangelogEntries(3)
);
}
/** @test */
public function it_checks_if_the_instance_has_at_least_one_account()
{
DB::table('accounts')->delete();
$this->assertFalse(
InstanceHelper::hasAtLeastOneAccount()
);
factory(Account::class)->create();
$this->assertTrue(
InstanceHelper::hasAtLeastOneAccount()
);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Journal\Day;
use App\Helpers\JournalHelper;
use App\Models\Account\Account;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class JournalHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function you_can_vote_if_you_havent_voted_yet_today()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$this->assertFalse(JournalHelper::hasAlreadyRatedToday($user));
}
/** @test */
public function you_cant_vote_if_you_have_already_voted_today()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create(['account_id' => $account->id]);
factory(Day::class)->create([
'account_id' => $account->id,
'date' => now(),
]);
$this->assertTrue(JournalHelper::hasAlreadyRatedToday($user));
}
}

View File

@@ -0,0 +1,162 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Helpers\LocaleHelper;
use Illuminate\Support\Facades\App;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LocaleHelperTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function get_locale_returns_english_by_default()
{
$this->assertEquals(
'en',
LocaleHelper::getLocale()
);
}
/** @test */
public function get_locale_returns_right_locale_if_user_logged()
{
$user = $this->signIn();
$user->locale = 'fr';
$user->save();
$this->assertEquals(
'fr',
LocaleHelper::getLocale()
);
}
/** @test */
public function get_direction_default()
{
$this->assertEquals(
'ltr',
LocaleHelper::getDirection()
);
}
/** @test */
public function get_direction_french()
{
App::setLocale('fr');
$this->assertEquals(
'ltr',
LocaleHelper::getDirection()
);
}
/** @test */
public function get_direction_hebrew()
{
App::setLocale('he');
$this->assertEquals(
'rtl',
LocaleHelper::getDirection()
);
}
/** @test */
public function format_telephone_by_iso()
{
$tel = LocaleHelper::formatTelephoneNumberByISO('202-555-0191', 'gb');
$this->assertEquals(
'+44 20 2555 0191',
$tel
);
}
/**
* @dataProvider localeHelperGetLangProvider
*/
public function test_locale_get_lang($locale, $expect)
{
$lang = LocaleHelper::getLang($locale);
$this->assertEquals(
$expect,
$lang
);
}
public function localeHelperGetLangProvider()
{
return [
['en', 'en'],
['En', 'en'],
['EN', 'en'],
['en-US', 'en'],
['en-us', 'en'],
['en_US', 'en'],
['pt-BR', 'pt'],
['xx-YY', 'xx'],
];
}
/**
* @dataProvider localeHelperGetCountryProvider
*/
public function test_locale_get_country($locale, $expect)
{
$country = LocaleHelper::getCountry($locale);
$this->assertEquals(
$expect,
$country
);
}
public function localeHelperGetCountryProvider()
{
return [
['en', 'US'],
['en-us', 'US'],
['en-US', 'US'],
['en_US', 'US'],
['pt-BR', 'BR'],
['xx-YY', 'YY'],
];
}
/**
* @dataProvider localeHelperExtractCountryProvider
*/
public function test_locale_extract_country($locale, $expect)
{
$country = LocaleHelper::extractCountry($locale);
$this->assertEquals(
$expect,
$country
);
App::setLocale($locale);
$country = LocaleHelper::extractCountry();
$this->assertEquals(
$expect,
$country
);
}
public function localeHelperExtractCountryProvider()
{
return [
['en', null],
['fr', null],
['en-US', 'US'],
['pt-BR', 'BR'],
['xx-YY', 'YY'],
];
}
}

View File

@@ -0,0 +1,114 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use App\Models\User\User;
use App\Helpers\MoneyHelper;
use App\Models\Settings\Currency;
use Illuminate\Support\Facades\App;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class MoneyHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_returns_the_amount_with_the_currency_symbol()
{
$currency = new Currency();
$currency->iso = 'EUR';
$this->assertEquals('€500.00', MoneyHelper::format(50000, $currency));
$this->assertEquals('€5,038.29', MoneyHelper::format(503829, $currency));
$this->assertEquals('500.00', MoneyHelper::getValue(50000, $currency));
$this->assertEquals('5038.29', MoneyHelper::getValue(503829, $currency));
$this->assertEquals(500, MoneyHelper::exchangeValue(50000, $currency));
$this->assertEquals(5038.29, MoneyHelper::exchangeValue(503829, $currency));
}
/** @test */
public function it_returns_the_amount_with_the_currency_symbol_in_the_right_locale()
{
App::setLocale('fr');
$currency = new Currency();
$currency->iso = 'EUR';
$this->assertEquals('500,00 €', MoneyHelper::format(50000, $currency));
$this->assertEquals('5038,29 €', MoneyHelper::format(503829, $currency));
$this->assertEquals('500,00', MoneyHelper::getValue(50000, $currency));
$this->assertEquals('5038,29', MoneyHelper::getValue(503829, $currency));
$this->assertEquals(500, MoneyHelper::exchangeValue(50000, $currency));
$this->assertEquals(5038.29, MoneyHelper::exchangeValue(503829, $currency));
}
/** @test */
public function it_returns_the_amount_with_the_currency_symbol_with_the_right_punctuation()
{
$currency = new Currency();
$currency->iso = 'JPY'; // minorUnit value is zero "0"
$this->assertEquals('¥500', MoneyHelper::format(500, $currency));
$this->assertEquals('¥5,038', MoneyHelper::format(5038, $currency));
$this->assertEquals('500', MoneyHelper::getValue(500, $currency));
$this->assertEquals('5038', MoneyHelper::getValue(5038, $currency));
$this->assertEquals(500, MoneyHelper::exchangeValue(500, $currency));
$this->assertEquals(5038, MoneyHelper::exchangeValue(5038, $currency));
}
/** @test */
public function it_formats_the_currency_with_the_right_locale()
{
$currency = Currency::where('iso', 'GBP')->first();
$user = factory(User::class)->create([
'currency_id' => $currency->id,
]);
$this->actingAs($user);
$this->assertEquals('£75.00', MoneyHelper::format(7500, $currency));
$this->assertEquals('£2,734.12', MoneyHelper::format(273412, $currency));
$this->assertEquals('75.00', MoneyHelper::getValue(7500, $currency));
$this->assertEquals('2734.12', MoneyHelper::getValue(273412, $currency));
$this->assertEquals(75, MoneyHelper::exchangeValue(7500, $currency));
$this->assertEquals(2734.12, MoneyHelper::exchangeValue(273412, $currency));
}
/** @test */
public function it_returns_the_amount_without_the_currency_symbol_if_not_provided()
{
$this->assertEquals('500', MoneyHelper::format(500));
$this->assertEquals('5,000', MoneyHelper::format(5000));
}
/** @test */
public function it_returns_zero_if_amount_is_null()
{
$this->assertEquals('0', MoneyHelper::format(null));
}
/** @test */
public function it_covers_brazilian_currency()
{
$currency = Currency::where('iso', 'BRL')->first();
$user = factory(User::class)->create([
'currency_id' => $currency->id,
]);
$this->actingAs($user);
$this->assertEquals('R$12,345.67', MoneyHelper::format(1234567, $currency));
$this->assertEquals('12345.67', MoneyHelper::getValue(1234567, $currency));
$this->assertEquals(12345.67, MoneyHelper::exchangeValue(1234567, $currency));
}
/** @test */
public function it_parse_an_input_value()
{
$currency = new Currency();
$currency->iso = 'EUR';
$this->assertEquals(50000, MoneyHelper::parseInput('500.00', $currency));
$this->assertEquals(503829, MoneyHelper::parseInput('5038.29', $currency));
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use Mockery\MockInterface;
use App\Helpers\RequestHelper;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Request;
use Stevebauman\Location\Facades\Location;
class RequestHelperTest extends TestCase
{
/** @test */
public function get_cf_ip()
{
Request::instance()->headers->set('Cf-Connecting-Ip', '1.2.3.4');
$this->assertEquals(
'1.2.3.4',
RequestHelper::ip()
);
}
/** @test */
public function get_server_ip()
{
Request::instance()->server->set('REMOTE_ADDR', '1.2.3.4');
$this->assertEquals(
'1.2.3.4',
RequestHelper::ip()
);
}
/** @test */
public function get_country_from_cf()
{
Request::instance()->headers->set('Cf-Ipcountry', 'XX');
$this->assertEquals(
'XX',
RequestHelper::country('1.2.3.4')
);
}
/** @test */
public function get_country_from_ip()
{
$driver = $this->mock(\Stevebauman\Location\Drivers\Driver::class, function (MockInterface $mock) {
$mock->shouldReceive('get')
->with('123.45.67.89')
->andReturn(tap(new \Stevebauman\Location\Position(), function ($position) {
$position->countryCode = 'TEST';
}));
});
Location::setDriver($driver);
Request::instance()->server->set('REMOTE_ADDR', '123.45.67.89');
$this->assertEquals(
'TEST',
RequestHelper::country(null)
);
}
/** @test */
public function get_infos_from_ip()
{
config(['location.ipdata.token' => 'test']);
$body = file_get_contents(base_path('tests/Fixtures/Helpers/ipdata.json'));
Http::fake([
'https://api.ipdata.co/*' => Http::response($body, 200),
]);
$this->assertEquals(
[
'country' => 'FR',
'currency' => 'EUR',
'timezone' => 'Europe/Paris',
],
RequestHelper::infos('test')
);
}
/** @test */
public function get_infos_from_ip_fail()
{
config(['location.ipdata.token' => 'test']);
Http::fake([
'https://api.ipdata.co/*' => Http::response(null, 500),
]);
Request::instance()->headers->set('Cf-Ipcountry', 'XX');
$this->assertEquals(
[
'country' => 'XX',
'currency' => null,
'timezone' => null,
],
RequestHelper::infos('test')
);
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Models\Contact\Note;
use App\Helpers\SearchHelper;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class SearchHelperTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function searching_for_contacts_returns_a_collection_with_pagination()
{
$user = $this->signin();
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
]);
$searchResults = SearchHelper::searchContacts($contact->first_name, 'created_at')
->paginate(1);
$this->assertNotNull($searchResults);
$this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $searchResults);
$this->assertCount(1, $searchResults);
}
/** disabled for now */
public function searching_with_notes()
{
$user = $this->signin();
$note = factory(Note::class)->create([
'account_id' => $user->account_id,
'body' => 'we met on github and talked about monica',
]);
$searchResults = SearchHelper::searchContacts('monica', 'created_at')
->paginate(1);
$this->assertNotNull($searchResults);
$this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $searchResults);
$this->assertCount(1, $searchResults);
}
/** disabled for now */
public function searching_with_introduction_information()
{
$user = $this->signin();
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
'first_met_additional_info' => 'github',
]);
$searchResults = SearchHelper::searchContacts($contact->first_met_additional_info, 'created_at')
->paginate(1);
$this->assertNotNull($searchResults);
$this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $searchResults);
$this->assertCount(1, $searchResults);
}
/** @test */
public function searching_with_wrong_search_field()
{
$user = $this->signin();
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
]);
$searchResults = SearchHelper::searchContacts('wrongsearchfield:1', 'created_at')
->paginate(1);
$this->assertNotNull($searchResults);
$this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $searchResults);
$this->assertCount(0, $searchResults);
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\TestCase;
use App\Models\Account\Photo;
use App\Helpers\StorageHelper;
use App\Models\Account\Account;
use App\Models\Contact\Document;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class StorageHelperTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_calculates_the_account_storage_size(): void
{
$account = factory(Account::class)->create([]);
factory(Document::class)->create([
'filesize' => 1000000,
'account_id' => $account->id,
]);
factory(Photo::class)->create([
'filesize' => 1000000,
'account_id' => $account->id,
]);
$this->assertEquals(
2000000,
StorageHelper::getAccountStorageSize($account)
);
}
/** @test */
public function it_tests_account_storage_limit(): void
{
config(['monica.requires_subscription' => true]);
$account = factory(Account::class)->create([]);
factory(Document::class)->create([
'filesize' => 1000000,
'account_id' => $account->id,
]);
config(['monica.max_storage_size' => 0.1]);
$this->assertTrue(StorageHelper::hasReachedAccountStorageLimit($account));
config(['monica.max_storage_size' => 1]);
$this->assertFalse(StorageHelper::hasReachedAccountStorageLimit($account));
factory(Photo::class)->create([
'filesize' => 1000000,
'account_id' => $account->id,
]);
config(['monica.max_storage_size' => 2]);
$this->assertFalse(StorageHelper::hasReachedAccountStorageLimit($account));
config(['monica.max_storage_size' => 1]);
$this->assertTrue(StorageHelper::hasReachedAccountStorageLimit($account));
config(['monica.requires_subscription' => false]);
$this->assertFalse(StorageHelper::hasReachedAccountStorageLimit($account));
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Helpers\VCardHelper;
use Sabre\VObject\Component\VCard;
class VCardHelperTest extends FeatureTestCase
{
/** @test */
public function it_get_country_by_sabre_vcard()
{
$vcard = new VCard([
'TEL' => '202-555-0191',
'ADR' => ['', '', '17 Shakespeare Ave.', 'Southampton', '', 'SO17 2HB', 'United Kingdom'],
]);
$iso = VCardHelper::getCountryISOFromSabreVCard($vcard);
$this->assertEquals(
'GB',
$iso
);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Tests\Unit\Helpers;
use Tests\FeatureTestCase;
use App\Helpers\WeatherHelper;
use App\Jobs\GetGPSCoordinate;
use App\Models\Contact\Address;
use App\Models\Contact\Contact;
use Illuminate\Bus\PendingBatch;
use App\Jobs\GetWeatherInformation;
use Illuminate\Support\Facades\Bus;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class WeatherHelperTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_returns_null_if_address_is_not_set()
{
$contact = factory(Contact::class)->create([]);
$this->assertNull(WeatherHelper::getWeatherForAddress($contact->addresses()->first()));
}
/** @test */
public function it_dispatch_batch_with_get_coordinates()
{
config(['monica.enable_geolocation' => true]);
config(['monica.location_iq_api_key' => 'test']);
config(['monica.enable_weather' => true]);
config(['monica.weatherapi_key' => 'test']);
$fake = Bus::fake();
$address = factory(Address::class)->create();
WeatherHelper::getWeatherForAddress($address);
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(2, $pendingBatch->jobs);
$this->assertInstanceOf(GetGPSCoordinate::class, $pendingBatch->jobs[0]);
$this->assertInstanceOf(GetWeatherInformation::class, $pendingBatch->jobs[1]);
return true;
});
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Tests\Unit\Jobs;
use Tests\TestCase;
use App\Models\Contact\Contact;
use Illuminate\Support\Facades\Queue;
use App\Jobs\Avatars\GenerateDefaultAvatar;
use App\Jobs\Avatars\GetAvatarsFromInternet;
use App\Jobs\Avatars\CreateAvatarsForExistingContacts;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CreateAvatarsForExistingContactsTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_creates_jobs_for_avatars_migration()
{
Queue::fake();
$contact = factory(Contact::class)->create([
'avatar_adorable_url' => null,
]);
(new CreateAvatarsForExistingContacts)->handle();
Queue::assertPushed(GenerateDefaultAvatar::class, function ($job) use ($contact) {
return $job->contact->id === $contact->id;
});
Queue::assertPushed(GetAvatarsFromInternet::class, function ($job) use ($contact) {
return $job->contact->id === $contact->id;
});
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Tests\Unit\Jobs\Dav;
use Tests\TestCase;
use App\Models\User\User;
use App\Jobs\Dav\DeleteVCard;
use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Facades\Bus;
use App\Jobs\Dav\DeleteMultipleVCard;
use Illuminate\Bus\DatabaseBatchRepository;
use App\Models\Account\AddressBookSubscription;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DeleteMultipleVCardTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_delete_cards()
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
]);
$pendingBatch = $fake->batch([
$job = new DeleteMultipleVCard($addressBookSubscription, ['https://test/dav/uri']),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(DeleteMultipleVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
$fake->assertDispatched(function (DeleteVCard $updateVCard) {
$uri = $this->getPrivateValue($updateVCard, 'uri');
$this->assertEquals('https://test/dav/uri', $uri);
return true;
});
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Tests\Unit\Jobs\Dav;
use Tests\TestCase;
use App\Models\User\User;
use App\Jobs\Dav\DeleteVCard;
use Illuminate\Bus\PendingBatch;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Http;
use Illuminate\Bus\DatabaseBatchRepository;
use App\Models\Account\AddressBookSubscription;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DeleteVCardTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_delete_card()
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
]);
Http::fake(function (Request $request) {
$this->assertEquals('https://test/dav/uri', $request->url());
$this->assertEquals('DELETE', $request->method());
return Http::response(null, 204);
});
$pendingBatch = $fake->batch([
$job = new DeleteVCard($addressBookSubscription, 'https://test/dav/uri'),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(DeleteVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
}
}

View File

@@ -0,0 +1,176 @@
<?php
namespace Tests\Unit\Jobs\Dav;
use Tests\TestCase;
use App\Models\User\User;
use Mockery\MockInterface;
use Tests\Api\DAV\CardEtag;
use App\Jobs\Dav\UpdateVCard;
use App\Models\Contact\Contact;
use Illuminate\Bus\PendingBatch;
use App\Jobs\Dav\GetMultipleVCard;
use Illuminate\Support\Facades\Bus;
use Sabre\CardDAV\Plugin as CardDAVPlugin;
use Illuminate\Bus\DatabaseBatchRepository;
use App\Models\Account\AddressBookSubscription;
use App\Services\DavClient\Utils\Dav\DavClient;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class GetMultipleVCardTest extends TestCase
{
use DatabaseTransactions;
use CardEtag;
/** @test */
public function it_get_cards()
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
]);
$contact = new Contact();
$contact->forceFill([
'first_name' => 'Test',
'uuid' => 'affacde9-b2fe-4371-9acb-6612aaee6971',
'updated_at' => now(),
]);
$card = $this->getCard($contact);
$etag = $this->getEtag($contact, true);
$this->mock(DavClient::class, function (MockInterface $mock) use ($card, $etag) {
$mock->shouldReceive('setBaseUri')->once()->andReturn($mock);
$mock->shouldReceive('setCredentials')->once()->andReturn($mock);
$mock->shouldReceive('addressbookMultiget')
->once()
->withArgs(function ($properties, $contacts) {
$this->assertEquals([
'{DAV:}getetag',
[
'name' => '{'.CardDAVPlugin::NS_CARDDAV.'}address-data',
'value' => null,
'attributes' => [
'content-type' => 'text/vcard',
'version' => '4.0',
],
],
], $properties);
$this->assertEquals(['https://test/dav/uri'], $contacts);
return true;
})
->andReturn([
'https://test/dav/uri' => [
200 => [
'{'.CardDAVPlugin::NS_CARDDAV.'}address-data' => $card,
'{DAV:}getetag' => $etag,
],
],
]);
});
$pendingBatch = $fake->batch([
$job = new GetMultipleVCard($addressBookSubscription, ['https://test/dav/uri']),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(GetMultipleVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
$fake->assertDispatched(function (UpdateVCard $updateVCard) use ($etag, $card) {
$dto = $this->getPrivateValue($updateVCard, 'contact');
$this->assertEquals('https://test/dav/uri', $dto->uri);
$this->assertEquals($etag, $dto->etag);
$this->assertEquals($card, $dto->card);
return true;
});
}
/** @test */
public function it_get_cards_mock_http()
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
]);
$contact = new Contact();
$contact->forceFill([
'first_name' => 'Test',
'uuid' => 'affacde9-b2fe-4371-9acb-6612aaee6971',
'updated_at' => now(),
]);
$card = $this->getCard($contact);
$etag = $this->getEtag($contact, true);
$this->mock(DavClient::class, function (MockInterface $mock) use ($card, $etag) {
$mock->shouldReceive('setBaseUri')->once()->andReturn($mock);
$mock->shouldReceive('setCredentials')->once()->andReturn($mock);
$mock->shouldReceive('addressbookMultiget')
->once()
->withArgs(function ($properties, $contacts) {
$this->assertEquals([
'{DAV:}getetag',
[
'name' => '{'.CardDAVPlugin::NS_CARDDAV.'}address-data',
'value' => null,
'attributes' => [
'content-type' => 'text/vcard',
'version' => '4.0',
],
],
], $properties);
$this->assertEquals(['https://test/dav/uri'], $contacts);
return true;
})
->andReturn([
'https://test/dav/uri' => [
200 => [
'{'.CardDAVPlugin::NS_CARDDAV.'}address-data' => $card,
'{DAV:}getetag' => $etag,
],
],
]);
});
$pendingBatch = $fake->batch([
$job = new GetMultipleVCard($addressBookSubscription, ['https://test/dav/uri']),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(GetMultipleVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
$fake->assertDispatched(function (UpdateVCard $updateVCard) use ($etag, $card) {
$dto = $this->getPrivateValue($updateVCard, 'contact');
$this->assertEquals('https://test/dav/uri', $dto->uri);
$this->assertEquals($etag, $dto->etag);
$this->assertEquals($card, $dto->card);
return true;
});
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace Tests\Unit\Jobs\Dav;
use Tests\TestCase;
use App\Models\User\User;
use App\Jobs\Dav\GetVCard;
use Tests\Api\DAV\CardEtag;
use App\Jobs\Dav\UpdateVCard;
use App\Models\Contact\Contact;
use Illuminate\Bus\PendingBatch;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Http;
use Illuminate\Bus\DatabaseBatchRepository;
use App\Models\Account\AddressBookSubscription;
use App\Services\DavClient\Utils\Model\ContactDto;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class GetVCardTest extends TestCase
{
use DatabaseTransactions;
use CardEtag;
/** @test */
public function it_get_card()
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
]);
$contact = new Contact();
$contact->forceFill([
'first_name' => 'Test',
'uuid' => 'affacde9-b2fe-4371-9acb-6612aaee6971',
'updated_at' => now(),
]);
$card = $this->getCard($contact);
$etag = $this->getEtag($contact, true);
Http::fake([
'https://test/dav/uri' => Http::response($card, 200),
]);
$pendingBatch = $fake->batch([
$job = new GetVCard($addressBookSubscription, new ContactDto('https://test/dav/uri', $etag)),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(GetVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
$fake->assertDispatched(function (UpdateVCard $updateVCard) use ($etag, $card) {
$dto = $this->getPrivateValue($updateVCard, 'contact');
$this->assertEquals('https://test/dav/uri', $dto->uri);
$this->assertEquals($etag, $dto->etag);
$this->assertEquals($card, $dto->card);
return true;
});
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace Tests\Unit\Jobs\Dav;
use Tests\TestCase;
use App\Models\User\User;
use App\Jobs\Dav\PushVCard;
use Tests\Api\DAV\CardEtag;
use App\Models\Contact\Contact;
use Illuminate\Bus\PendingBatch;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Http;
use Illuminate\Bus\DatabaseBatchRepository;
use App\Models\Account\AddressBookSubscription;
use App\Services\DavClient\Utils\Model\ContactPushDto;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PushVCardTest extends TestCase
{
use DatabaseTransactions;
use CardEtag;
/**
* @test
* @dataProvider modes
*/
public function it_push_card($mode, $ifmatch)
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
'uri' => 'https://test/dav',
]);
$contact = factory(Contact::class)->create([
'account_id' => $user->account_id,
'first_name' => 'John',
'last_name' => 'Doe',
'uuid' => 'affacde9-b2fe-4371-9acb-6612aaee6971',
'updated_at' => '2021-09-01',
]);
$card = $this->getCard($contact);
$etag = $this->getEtag($contact, true);
if ($ifmatch == ['etag']) {
$ifmatch = [$etag];
}
Http::fake(function (Request $request, $options) use ($card, $ifmatch) {
$this->assertEquals('https://test/dav/uri', $request->url());
$this->assertEquals('PUT', $request->method());
$this->assertEquals($ifmatch, $request->header('If-Match'));
return Http::response($card, 200);
});
$pendingBatch = $fake->batch([
$job = new PushVCard($addressBookSubscription, new ContactPushDto('https://test/dav/uri', $etag, $card, $contact->id, $mode)),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(PushVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
}
public function modes(): array
{
return [
[0, []],
[1, ['etag']],
[2, ['*']],
];
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace Tests\Unit\Jobs\Dav;
use Tests\TestCase;
use App\Models\User\User;
use Tests\Api\DAV\CardEtag;
use App\Jobs\Dav\UpdateVCard;
use App\Models\Contact\Contact;
use Illuminate\Bus\PendingBatch;
use App\Models\Account\AddressBook;
use Illuminate\Support\Facades\Bus;
use Illuminate\Bus\DatabaseBatchRepository;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Services\DavClient\Utils\Model\ContactUpdateDto;
class UpdateVCardTest extends TestCase
{
use DatabaseTransactions;
use CardEtag;
/** @test */
public function it_create_a_contact()
{
$fake = Bus::fake();
$user = factory(User::class)->create();
$addressBook = AddressBook::factory()->create([
'account_id' => $user->account_id,
'user_id' => $user->id,
]);
$contact = new Contact();
$contact->forceFill([
'first_name' => 'Test',
'uuid' => 'affacde9-b2fe-4371-9acb-6612aaee6971',
'updated_at' => now(),
]);
$card = $this->getCard($contact);
$etag = $this->getEtag($contact, true);
$pendingBatch = $fake->batch([
$job = new UpdateVCard($user, $addressBook->name, new ContactUpdateDto('https://test/dav/uricontact1', $etag, $card)),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(UpdateVCard::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
$this->assertDatabaseHas('contacts', [
'first_name' => 'Test',
'uuid' => 'affacde9-b2fe-4371-9acb-6612aaee6971',
]);
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace Tests\Unit\Jobs;
use Tests\TestCase;
use Mockery\MockInterface;
use App\Models\Account\Place;
use Illuminate\Bus\PendingBatch;
use App\Jobs\GetWeatherInformation;
use Illuminate\Support\Facades\Bus;
use Illuminate\Bus\DatabaseBatchRepository;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Services\Instance\Weather\GetWeatherInformation as GetWeatherInformationService;
class GetWeatherInformationTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_run_job_weather_information()
{
$fake = Bus::fake();
$place = factory(Place::class)->create([
'latitude' => '34.112456',
'longitude' => '-118.4270732',
]);
$this->mock(GetWeatherInformationService::class, function (MockInterface $mock) use ($place) {
$mock->shouldReceive('execute')
->once()
->withArgs(function ($data) use ($place) {
$this->assertEquals([
'account_id' => $place->account_id,
'place_id' => $place->id,
], $data);
return true;
});
});
$pendingBatch = $fake->batch([
$job = new GetWeatherInformation($place),
]);
$batch = $pendingBatch->dispatch();
$fake->assertBatched(function (PendingBatch $pendingBatch) {
$this->assertCount(1, $pendingBatch->jobs);
$this->assertInstanceOf(GetWeatherInformation::class, $pendingBatch->jobs->first());
return true;
});
$batch = app(DatabaseBatchRepository::class)->store($pendingBatch);
$job->withBatchId($batch->id)->handle();
}
}

View File

@@ -0,0 +1,274 @@
<?php
namespace Tests\Unit\Jobs\Reminder;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\Reminder;
use App\Notifications\UserNotified;
use App\Notifications\UserReminded;
use App\Models\Contact\ReminderOutbox;
use Illuminate\Support\Facades\Notification;
use App\Jobs\Reminder\NotifyUserAboutReminder;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class NotifyUserAboutReminderTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_sends_a_reminder_to_a_user()
{
Notification::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'initial_date' => '2017-01-01',
'title' => 'fake text saying nothing',
'frequency_type' => 'year',
'frequency_number' => 1,
]);
$reminderOutbox = factory(ReminderOutbox::class)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
'planned_date' => '2017-01-01',
'nature' => 'reminder',
]);
NotifyUserAboutReminder::dispatch($reminderOutbox);
// Assert the notification has been sent to the user with the right
// reminderoutbox id and the right email content
Notification::assertSentTo(
$user,
UserReminded::class,
function ($notification, $channels) use ($reminderOutbox, $reminder, $user, $contact) {
$mailData = $notification->toMail($user)->toArray();
$this->assertEquals("Reminder for {$contact->name}", $mailData['subject']);
$this->assertEquals("Hi {$user->first_name}", $mailData['greeting']);
$this->assertStringContainsString("You wanted to be reminded of {$reminderOutbox->reminder->title}", $mailData['introLines'][0]);
return $notification->reminder->id === $reminder->id;
}
);
}
/** @test */
public function it_sends_a_notification_to_a_user()
{
Notification::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'initial_date' => '2017-01-01',
'title' => 'fake text saying nothing',
'frequency_type' => 'year',
'frequency_number' => '1',
]);
$reminderOutbox = factory(ReminderOutbox::class)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
'planned_date' => '2017-01-01',
'nature' => 'notification',
]);
NotifyUserAboutReminder::dispatch($reminderOutbox);
// Assert the notification has been sent to the user with the right
// reminderoutbox id and the right email content
Notification::assertSentTo(
$user,
UserNotified::class,
function ($notification, $channels) use ($reminder, $user, $contact) {
$mailData = $notification->toMail($user)->toArray();
$this->assertEquals("Reminder for {$contact->name}", $mailData['subject']);
$this->assertEquals("Hi {$user->first_name}", $mailData['greeting']);
$this->assertStringContainsString('In days (on Jan 01, 2018), the following event will happen:', $mailData['introLines'][0]);
return $notification->reminder->id === $reminder->id;
}
);
}
/** @test */
public function it_doesnt_notify_a_user_if_he_is_on_the_free_plan()
{
Notification::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
config(['monica.requires_subscription' => true]);
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
'has_access_to_paid_version_for_free' => false,
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'initial_date' => '2017-01-01',
'title' => 'fake text saying nothing',
'frequency_type' => 'year',
'frequency_number' => 1,
]);
$reminderOutbox = factory(ReminderOutbox::class)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
'planned_date' => '2017-01-01',
]);
NotifyUserAboutReminder::dispatch($reminderOutbox);
Notification::assertNotSentTo(
$user,
UserReminded::class
);
}
/** @test */
public function it_doesnt_notify_a_user_if_contact_deleted()
{
Notification::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'initial_date' => '2017-01-01',
'title' => 'fake text saying nothing',
'frequency_type' => 'year',
'frequency_number' => '1',
]);
$reminderOutbox = factory(ReminderOutbox::class)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
'planned_date' => '2017-01-01',
'nature' => 'notification',
]);
$contact->delete();
NotifyUserAboutReminder::dispatch($reminderOutbox);
Notification::assertNotSentTo(
$user,
UserReminded::class
);
}
/** @test */
public function it_marks_the_one_time_reminder_has_inactive_once_it_is_sent()
{
Notification::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'initial_date' => '2017-01-01',
'title' => 'fake text saying nothing',
'frequency_type' => 'one_time',
]);
$reminderOutbox = factory(ReminderOutbox::class)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
'planned_date' => '2017-01-01',
]);
NotifyUserAboutReminder::dispatch($reminderOutbox);
$this->assertDatabaseMissing('reminder_outbox', [
'account_id' => $user->account_id,
'id' => $reminderOutbox->id,
]);
$this->assertDatabaseHas('reminders', [
'account_id' => $user->account_id,
'id' => $reminder->id,
'inactive' => true,
]);
}
/** @test */
public function it_reschedule_a_recurring_reminder_once_it_is_sent()
{
Notification::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'initial_date' => '2017-01-01',
'title' => 'fake text saying nothing',
'frequency_type' => 'year',
'frequency_number' => 1,
]);
$reminderOutbox = factory(ReminderOutbox::class)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
'planned_date' => '2017-01-01',
]);
NotifyUserAboutReminder::dispatch($reminderOutbox);
$this->assertDatabaseMissing('reminder_outbox', [
'account_id' => $user->account_id,
'id' => $reminderOutbox->id,
]);
$this->assertDatabaseHas('reminders', [
'account_id' => $user->account_id,
'id' => $reminder->id,
'inactive' => false,
]);
$this->assertDatabaseHas('reminder_outbox', [
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
]);
}
}

View File

@@ -0,0 +1,125 @@
<?php
namespace Tests\Unit\Jobs;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Notifications\StayInTouchEmail;
use App\Jobs\StayInTouch\ScheduleStayInTouch;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Notification as NotificationFacade;
class ScheduleStayInTouchTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_dispatches_an_email()
{
NotificationFacade::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 12, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
'has_access_to_paid_version_for_free' => 1,
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'stay_in_touch_trigger_date' => '2017-01-01 07:00:00',
'stay_in_touch_frequency' => 5,
]);
$user = factory(User::class)->create([
'account_id' => $account->id,
'email' => 'john@doe.com',
'timezone' => 'America/New_York',
]);
ScheduleStayInTouch::dispatch($contact);
NotificationFacade::assertSentTo($user, StayInTouchEmail::class,
function ($notification, $channels) use ($contact) {
return $channels[0] == 'mail'
&& $notification->assertSentFor($contact);
}
);
$notifications = NotificationFacade::sent($user, StayInTouchEmail::class);
$message = $notifications[0]->toMail($user);
$this->assertStringContainsString('You asked to be reminded to stay in touch with John Doe every 5 days.', implode('', $message->introLines));
$this->assertDatabaseHas('contacts', [
'stay_in_touch_trigger_date' => '2017-01-06 07:00:00',
]);
}
/** @test */
public function it_doesnt_dispatches_an_email_if_free_account()
{
NotificationFacade::fake();
Carbon::setTestNow(Carbon::create(2017, 1, 1, 5, 0, 0));
config(['monica.requires_subscription' => true]);
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
'has_access_to_paid_version_for_free' => 0,
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'stay_in_touch_trigger_date' => '2017-01-01 07:00:00',
'stay_in_touch_frequency' => 5,
]);
$user = factory(User::class)->create([
'account_id' => $account->id,
'email' => 'john@doe.com',
'timezone' => 'America/New_York',
]);
ScheduleStayInTouch::dispatch($contact);
NotificationFacade::assertNotSentTo($user, StayInTouchEmail::class);
NotificationFacade::assertNothingSent();
$this->assertDatabaseHas('contacts', [
'stay_in_touch_trigger_date' => '2017-01-01 07:00:00',
]);
}
/** @test */
public function it_reschedule_missed_stayintouch()
{
NotificationFacade::fake();
Carbon::setTestNow(Carbon::create(2019, 1, 1, 5, 0, 0));
$account = factory(Account::class)->create([
'default_time_reminder_is_sent' => '07:00',
'has_access_to_paid_version_for_free' => 0,
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'stay_in_touch_trigger_date' => '2018-01-01 07:00:00',
'stay_in_touch_frequency' => 30,
]);
$user = factory(User::class)->create([
'account_id' => $account->id,
'email' => 'john@doe.com',
'timezone' => 'America/New_York',
]);
ScheduleStayInTouch::dispatch($contact);
NotificationFacade::assertNotSentTo($user, StayInTouchEmail::class);
NotificationFacade::assertNothingSent();
$this->assertDatabaseHas('contacts', [
'stay_in_touch_trigger_date' => '2019-01-26 07:00:00',
]);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Tests\Unit\Jobs;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ServiceQueueTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_run_a_service_ok(): void
{
config(['queue.default' => 'sync']);
ServiceQueueTester::dispatch();
$this->assertTrue(ServiceQueueTester::$executed);
$this->assertFalse(ServiceQueueTester::$failed);
}
/** @test */
public function it_run_a_service_sync(): void
{
ServiceQueueTester::dispatchSync();
$this->assertTrue(ServiceQueueTester::$executed);
$this->assertFalse(ServiceQueueTester::$failed);
}
/** @test */
public function it_run_a_service_which_failed(): void
{
$this->expectException(\Exception::class);
try {
ServiceQueueTester::dispatchSync(['throw' => true]);
} finally {
$this->assertTrue(ServiceQueueTester::$executed);
$this->assertTrue(ServiceQueueTester::$failed);
}
}
/** @test */
public function service_is_not_run_if_queue_set(): void
{
config(['queue.default' => 'database']);
ServiceQueueTester::dispatch(['throw' => true]);
$this->assertFalse(ServiceQueueTester::$executed);
$this->assertFalse(ServiceQueueTester::$failed);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Tests\Unit\Jobs;
use Throwable;
use App\Services\BaseService;
use App\Services\QueuableService;
use App\Services\DispatchableService;
class ServiceQueueTester extends BaseService implements QueuableService
{
use DispatchableService;
public static bool $executed = false;
public static bool $failed = false;
public bool $object;
/**
* Initialize the service.
*
* @param array $data
*/
public function __construct()
{
self::$executed = false;
self::$failed = false;
}
/**
* Execute the service.
*/
public function handle($data): void
{
self::$executed = true;
if ($data && $data['throw'] === true) {
throw new \Exception();
}
}
/**
* Handle a job failure.
*
* @param \Throwable $exception
*/
public function failed(Throwable $exception): void
{
self::$failed = true;
if (isset($this->obj)) {
// variable can be touch
}
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Tests\Unit\Jobs;
use Carbon\Carbon;
use Tests\TestCase;
use App\Jobs\SynchronizeAddressBooks;
use App\Models\Account\AddressBookSubscription;
use App\Services\DavClient\SynchronizeAddressBook;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class SynchronizeAddressBooksTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_run_synchronize()
{
Carbon::setTestNow(Carbon::create(2021, 9, 1, 10, 0, 0));
$subscription = AddressBookSubscription::factory()->create();
$this->mock(SynchronizeAddressBook::class, function ($mock) use ($subscription) {
$mock->shouldReceive('execute')
->once()
->with([
'account_id' => $subscription->account_id,
'addressbook_subscription_id' => $subscription->id,
'force' => false,
]);
});
(new SynchronizeAddressBooks($subscription))
->handle();
$subscription->refresh();
$this->assertEquals(Carbon::create(2021, 9, 1, 10, 0, 0), $subscription->last_synchronized_at);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Tests\Unit\Jobs;
use Tests\TestCase;
use App\Models\Contact\Contact;
use App\Jobs\Avatars\UpdateGravatar;
use Illuminate\Support\Facades\Queue;
use App\Jobs\Avatars\UpdateAllGravatars;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UpdateAllGravatarsTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_creates_jobs_for_update_gravatars()
{
Queue::fake();
$contacts = factory(Contact::class, 10)->create([
'avatar_source' => 'gravatar',
]);
(new UpdateAllGravatars)->handle();
foreach ($contacts as $contact) {
Queue::assertPushed(UpdateGravatar::class, function ($job) use ($contact) {
return $job->contact->id === $contact->id;
});
}
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Tests\Unit\Jobs;
use Tests\TestCase;
use App\Models\Contact\Contact;
use App\Models\Contact\ContactField;
use App\Models\Contact\ContactFieldType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Jobs\Avatars\UpdateGravatar as UpdateGravatarJob;
class UpdateGravatarTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_update_gravatar()
{
$contact = factory(Contact::class)->create();
$contactFieldType = factory(ContactFieldType::class)->create([
'account_id' => $contact->account->id,
]);
factory(ContactField::class)->create([
'contact_id' => $contact->id,
'account_id' => $contact->account->id,
'contact_field_type_id' => $contactFieldType->id,
'data' => 'matt@wordpress.com',
]);
(new UpdateGravatarJob($contact))->handle();
$contact->refresh();
$this->assertNotNull(
$contact->avatar_gravatar_url
);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Tests\Unit\Jobs;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Contact\Contact;
use App\Jobs\UpdateLastConsultedDate;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UpdateLastConsultedDateTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_updates_the_last_consulted_at_field_for_the_given_contact()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$contact = factory(Contact::class)->create([
'number_of_views' => 1,
]);
UpdateLastConsultedDate::dispatch($contact);
$this->assertDatabaseHas('contacts', [
'id' => $contact->id,
'last_consulted_at' => '2017-01-01 07:00:00',
'number_of_views' => 2,
]);
}
}

View File

@@ -0,0 +1,669 @@
<?php
namespace Tests\Unit\Models;
use App\Models\User\User;
use Tests\FeatureTestCase;
use App\Models\User\Module;
use App\Models\Account\Photo;
use App\Models\Account\Place;
use App\Models\Contact\Gender;
use App\Models\Account\Account;
use App\Models\Account\Company;
use App\Models\Account\Weather;
use App\Models\Contact\Address;
use App\Models\Contact\Contact;
use App\Models\Contact\Message;
use App\Models\Contact\Document;
use App\Models\Contact\LifeEvent;
use App\Models\Instance\AuditLog;
use App\Models\Contact\Occupation;
use Illuminate\Support\Facades\DB;
use App\Models\Account\ActivityType;
use App\Models\Contact\Conversation;
use App\Models\Contact\LifeEventType;
use App\Models\Contact\ReminderOutbox;
use App\Models\Contact\LifeEventCategory;
use App\Models\Account\ActivityTypeCategory;
use App\Models\Relationship\RelationshipType;
use App\Models\Relationship\RelationshipTypeGroup;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AccountTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_has_many_genders()
{
$account = factory(Account::class)->create();
$gender = factory(Gender::class)->create([
'account_id' => $account->id,
'name' => 'test',
]);
$gender = factory(Gender::class)->create([
'account_id' => $account->id,
'name' => 'test',
]);
$this->assertTrue($account->genders()->exists());
}
/** @test */
public function it_has_many_relationship_types()
{
$account = factory(Account::class)->create();
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->relationshipTypes()->exists());
}
/** @test */
public function it_has_many_relationship_type_groups()
{
$contact = factory(Contact::class)->create();
$account = $contact->account;
$relationshipTypeGroup = factory(RelationshipTypeGroup::class)->create([
'account_id' => $account->id,
]);
$relationshipTypeGroup = factory(RelationshipTypeGroup::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->relationshipTypeGroups()->exists());
}
/** @test */
public function it_has_many_modules()
{
$contact = factory(Contact::class)->create();
$account = $contact->account;
$module = factory(Module::class)->create([
'account_id' => $account->id,
]);
$module = factory(Module::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->modules()->exists());
}
/** @test */
public function it_has_many_activity_types()
{
$account = factory(Account::class)->create();
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->activityTypes()->exists());
}
/** @test */
public function it_has_many_activity_type_categories()
{
$account = factory(Account::class)->create();
$ActivityTypeCategory = factory(ActivityTypeCategory::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->activityTypeCategories()->exists());
}
/** @test */
public function it_has_many_conversations()
{
$account = factory(Account::class)->create([]);
$conversation = factory(Conversation::class, 2)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->conversations()->exists());
}
/** @test */
public function it_has_many_messages()
{
$account = factory(Account::class)->create([]);
$conversation = factory(Conversation::class)->create([
'account_id' => $account->id,
]);
$message = factory(Message::class, 2)->create([
'account_id' => $account->id,
'conversation_id' => $conversation->id,
]);
$this->assertTrue($account->messages()->exists());
}
/** @test */
public function it_has_many_life_event_categories()
{
$account = factory(Account::class)->create([]);
$lifeEventCategory = factory(LifeEventCategory::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->lifeEventCategories()->exists());
}
/** @test */
public function it_has_many_reminder_outboxes()
{
$reminderOutbox = factory(ReminderOutbox::class)->create([]);
$this->assertTrue($reminderOutbox->account->reminderOutboxes()->exists());
}
/** @test */
public function it_has_many_life_event_types()
{
$account = factory(Account::class)->create([]);
$lifeEventType = factory(LifeEventType::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->lifeEventTypes()->exists());
}
/** @test */
public function it_has_many_life_events()
{
$account = factory(Account::class)->create([]);
$lifeEvent = factory(LifeEvent::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->lifeEvents()->exists());
}
/** @test */
public function it_has_many_documents()
{
$account = factory(Account::class)->create([]);
$document = factory(Document::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->documents()->exists());
}
/** @test */
public function it_has_many_photos()
{
$account = factory(Account::class)->create([]);
$photo = factory(Photo::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->photos()->exists());
}
/** @test */
public function it_has_many_weathers()
{
$weather = factory(Weather::class)->create([]);
$this->assertTrue($weather->account->weathers()->exists());
}
/** @test */
public function it_has_many_places()
{
$account = factory(Account::class)->create([]);
$places = factory(Place::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->places()->exists());
}
/** @test */
public function it_has_many_addresses()
{
$account = factory(Account::class)->create([]);
$addresses = factory(Address::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->addresses()->exists());
}
/** @test */
public function it_has_many_companies()
{
$account = factory(Account::class)->create([]);
$companies = factory(Company::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->companies()->exists());
}
/** @test */
public function it_has_many_occupations()
{
$account = factory(Account::class)->create([]);
$occupations = factory(Occupation::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->occupations()->exists());
}
/** @test */
public function it_has_many_logs()
{
$account = factory(Account::class)->create([]);
factory(AuditLog::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($account->auditLogs()->exists());
}
/** @test */
public function user_is_subscribed_if_user_can_access_to_paid_version_for_free()
{
$account = factory(Account::class)->make([
'has_access_to_paid_version_for_free' => true,
]);
$this->assertTrue(
$account->isSubscribed()
);
}
/** @test */
public function user_is_subscribed_returns_false_if_not_subcribed()
{
$account = factory(Account::class)->make([
'has_access_to_paid_version_for_free' => false,
]);
$this->assertFalse(
$account->isSubscribed()
);
}
/** @test */
public function user_is_subscribed_returns_true_if_monthly_plan_is_set()
{
$account = factory(Account::class)->create();
$plan = factory(\Laravel\Cashier\Subscription::class)->create([
'account_id' => $account->id,
'stripe_price' => 'chandler_5',
'stripe_id' => 'sub_C0R444pbxddhW7',
'name' => 'fakePlan',
]);
config(['monica.paid_plan_monthly_friendly_name' => 'fakePlan']);
$this->assertTrue(
$account->isSubscribed()
);
}
/** @test */
public function user_is_subscribed_returns_true_if_annual_plan_is_set()
{
$account = factory(Account::class)->create();
$plan = factory(\Laravel\Cashier\Subscription::class)->create([
'account_id' => $account->id,
'stripe_price' => 'chandler_annual',
'stripe_id' => 'sub_C0R444pbxddhW7',
'name' => 'annualPlan',
]);
config(['monica.paid_plan_annual_friendly_name' => 'annualPlan']);
$this->assertTrue(
$account->isSubscribed()
);
}
/** @test */
public function user_is_subscribed_returns_false_if_no_plan_is_set()
{
$account = factory(Account::class)->create();
$this->assertFalse(
$account->isSubscribed()
);
}
/** @test */
public function has_invoices_returns_true_if_a_plan_exists()
{
$account = factory(Account::class)->create();
$plan = factory(\Laravel\Cashier\Subscription::class)->create([
'account_id' => $account->id,
'stripe_price' => 'chandler_5',
'stripe_id' => 'sub_C0R444pbxddhW7',
'name' => 'fakePlan',
]);
$this->assertTrue($account->hasInvoices());
}
/** @test */
public function has_invoices_returns_false_if_a_plan_does_not_exist()
{
$account = factory(Account::class)->create();
$this->assertFalse($account->hasInvoices());
}
/** @test */
public function it_gets_the_id_of_the_subscribed_plan()
{
config([
'monica.paid_plan_annual_friendly_name' => 'fakePlan',
'monica.paid_plan_annual_id' => 'chandler_5',
]);
$user = $this->signIn();
$account = $user->account;
$plan = factory(\Laravel\Cashier\Subscription::class)->create([
'account_id' => $account->id,
'stripe_price' => 'chandler_5',
'stripe_id' => 'sub_C0R444pbxddhW7',
'name' => 'fakePlan',
]);
$this->assertEquals(
'chandler_5',
$account->getSubscribedPlanId()
);
}
/** @test */
public function it_gets_the_friendly_name_of_the_subscribed_plan()
{
config([
'monica.paid_plan_annual_friendly_name' => 'fakePlan',
'monica.paid_plan_annual_id' => 'chandler_5',
]);
$user = $this->signIn();
$account = $user->account;
$plan = factory(\Laravel\Cashier\Subscription::class)->create([
'account_id' => $account->id,
'stripe_price' => 'chandler_5',
'stripe_id' => 'sub_C0R444pbxddhW7',
'name' => 'fakePlan',
]);
$this->assertEquals(
'fakePlan',
$account->getSubscribedPlanName()
);
}
/** @test */
public function it_populates_the_account_with_three_default_genders()
{
$account = factory(Account::class)->create();
$account->populateDefaultGendersTable();
$this->assertEquals(
3,
$account->genders->count()
);
}
/** @test */
public function it_populates_the_account_with_the_right_default_genders()
{
$account = factory(Account::class)->create();
$account->populateDefaultGendersTable();
$this->assertDatabaseHas(
'genders',
['name' => 'Man']
);
$this->assertDatabaseHas(
'genders',
['name' => 'Woman']
);
$this->assertDatabaseHas(
'genders',
['name' => 'Rather not say']
);
}
/** @test */
public function it_gets_default_time_reminder_is_sent_attribute()
{
$account = factory(Account::class)->create(['default_time_reminder_is_sent' => '14:00']);
$this->assertEquals(
'14:00',
$account->default_time_reminder_is_sent
);
}
/** @test */
public function it_sets_default_time_reminder_is_sent_attribute()
{
$account = new Account;
$account->default_time_reminder_is_sent = '14:00';
$this->assertEquals(
'14:00',
$account->default_time_reminder_is_sent
);
}
/** @test */
public function it_populates_the_account_with_two_default_reminder_rules()
{
$account = factory(Account::class)->create();
$account->populateDefaultReminderRulesTable();
$this->assertEquals(
2,
$account->reminderRules->count()
);
}
/** @test */
public function it_populates_the_account_with_the_right_default_reminder_rules()
{
$account = factory(Account::class)->create();
$account->populateDefaultReminderRulesTable();
$this->assertDatabaseHas(
'reminder_rules',
['number_of_days_before' => 7]
);
$this->assertDatabaseHas(
'reminder_rules',
['number_of_days_before' => 30]
);
}
/** @test */
public function it_gets_the_relationship_type_object_matching_a_given_name()
{
$account = factory(Account::class)->create();
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'partner',
]);
$this->assertInstanceOf(RelationshipType::class, $account->getRelationshipTypeByType('partner'));
}
/** @test */
public function it_gets_the_relationship_type_group_object_matching_a_given_name()
{
$account = factory(Account::class)->create();
$relationshipTypeGroup = factory(RelationshipTypeGroup::class)->create([
'account_id' => $account->id,
'name' => 'love',
]);
$this->assertInstanceOf(RelationshipTypeGroup::class, $account->getRelationshipTypeGroupByType('love'));
}
/** @test */
public function it_populates_default_relationship_type_groups_table_if_tables_havent_been_migrated_yet()
{
$account = factory(Account::class)->create();
// Love type
$id = DB::table('default_relationship_type_groups')->insertGetId([
'name' => 'friend_and_family',
]);
$account->populateRelationshipTypeGroupsTable();
$this->assertDatabaseHas('relationship_type_groups', [
'name' => 'friend_and_family',
]);
}
/** @test */
public function it_skips_default_relationship_type_groups_table_for_types_already_migrated()
{
$account = factory(Account::class)->create();
$id = DB::table('default_relationship_type_groups')->insertGetId([
'name' => 'friend_and_family',
'migrated' => 1,
]);
$account->populateRelationshipTypeGroupsTable(true);
$this->assertDatabaseMissing('relationship_type_groups', [
'name' => 'friend_and_family',
]);
}
/** @test */
public function it_populates_default_relationship_types_table_if_tables_havent_been_migrated_yet()
{
$account = factory(Account::class)->create();
$id = DB::table('default_relationship_type_groups')->insertGetId([
'name' => 'friend_and_family',
]);
DB::table('default_relationship_types')->insert([
'name' => 'fuckfriend',
'relationship_type_group_id' => $id,
]);
$account->populateRelationshipTypeGroupsTable();
$account->populateRelationshipTypesTable();
$this->assertDatabaseHas('relationship_types', [
'name' => 'fuckfriend',
]);
}
/** @test */
public function it_skips_default_relationship_types_table_for_types_already_migrated()
{
$account = factory(Account::class)->create();
$id = DB::table('default_relationship_type_groups')->insertGetId([
'name' => 'friend_and_family',
]);
DB::table('default_relationship_types')->insert([
'name' => 'fuckfriend',
'relationship_type_group_id' => $id,
'migrated' => 1,
]);
$account->populateRelationshipTypeGroupsTable();
$account->populateRelationshipTypesTable(true);
$this->assertDatabaseMissing('relationship_types', [
'name' => 'fuckfriend',
]);
}
/** @test */
public function it_create_default_account()
{
$account = Account::createDefault('John', 'Doe', 'john@doe.com', 'password');
$this->assertDatabaseHas('accounts', [
'id' => $account->id,
]);
$this->assertDatabaseHas('users', [
'account_id' => $account->id,
]);
}
/** @test */
public function it_throw_an_exception_if_user_already_exist()
{
$account = Account::createDefault('John', 'Doe', 'john@doe.com', 'password');
$this->assertDatabaseHas('accounts', [
'id' => $account->id,
]);
$this->assertDatabaseHas('users', [
'account_id' => $account->id,
]);
$this->expectException(\Illuminate\Validation\ValidationException::class);
$account = Account::createDefault('John', 'Doe', 'john@doe.com', 'password');
}
/** @test */
public function it_gets_first_user_locale()
{
$account = factory(Account::class)->create();
$user = factory(User::class)->create([
'account_id' => $account->id,
'locale' => 'fr',
]);
$user = factory(User::class)->create([
'account_id' => $account->id,
'locale' => 'en',
]);
$this->assertEquals(
'fr',
$account->getFirstLocale()
);
}
/** @test */
public function getting_first_locale_returns_null_if_user_doesnt_exist()
{
$account = factory(Account::class)->create();
$this->assertNull($account->getFirstLocale());
}
/** @test */
public function it_populates_default_life_event_tables_upon_creation()
{
$account = factory(Account::class)->create();
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
$account->populateDefaultFields();
$this->assertEquals(
5,
DB::table('life_event_categories')->where('account_id', $account->id)->get()->count()
);
$this->assertEquals(
43,
DB::table('life_event_types')->where('account_id', $account->id)->get()->count()
);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Tests\Unit\Models;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Account\Activity;
use App\Models\Account\ActivityType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ActivityTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_returns_the_happened_at()
{
$activity = factory(Activity::class)->make();
$this->assertInstanceOf(
Carbon::class,
$activity->happened_at
);
}
/** @test */
public function it_returns_a_title()
{
$type = factory(ActivityType::class)->create();
$activity = factory(Activity::class)->create([
'activity_type_id' => $type->id,
]);
$this->assertEquals(
$type->translation_key,
$activity->getTitle()
);
}
/** @test */
public function it_gets_info_for_journal_entry()
{
$activity = factory(Activity::class)->create();
$data = [
'type' => 'activity',
'id' => $activity->id,
'activity_type' => (! is_null($activity->type) ? $activity->type->name : null),
'summary' => $activity->summary,
'description' => $activity->description,
'day' => $activity->happened_at->day,
'day_name' => $activity->happened_at->format('D'),
'month' => $activity->happened_at->month,
'month_name' => strtoupper($activity->happened_at->format('M')),
'year' => $activity->happened_at->year,
'attendees' => $activity->getContactsForAPI(),
];
$this->assertEquals(
$data,
$activity->getInfoForJournalEntry()
);
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\ActivityType;
use App\Models\Account\ActivityTypeCategory;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ActivityTypeCategoryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$this->assertTrue($activityTypeCategory->account()->exists());
}
/** @test */
public function it_has_many_activity_types()
{
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$activityType = factory(ActivityType::class, 10)->create([
'activity_type_category_id' => $activityTypeCategory->id,
]);
$this->assertTrue($activityTypeCategory->activityTypes()->exists());
}
/** @test */
public function it_gets_the_name_attribute()
{
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([
'translation_key' => 'awesome_key',
'name' => null,
]);
$this->assertEquals(
'people.activity_type_category_awesome_key',
$activityTypeCategory->name
);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([
'translation_key' => null,
'name' => 'awesome_name',
]);
$this->assertEquals(
'awesome_name',
$activityTypeCategory->name
);
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\Activity;
use App\Models\Account\ActivityType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ActivityTypeTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$activityType = factory(ActivityType::class)->create([]);
$this->assertTrue($activityType->account()->exists());
}
/** @test */
public function it_belongs_to_a_category()
{
$activityType = factory(ActivityType::class)->create([]);
$this->assertTrue($activityType->category()->exists());
}
/** @test */
public function it_has_many_activities()
{
$account = factory(Account::class)->create();
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
$activity = factory(Activity::class, 2)->create([
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
]);
$this->assertTrue($account->activities()->exists());
}
/** @test */
public function it_gets_the_name_attribute()
{
$activityType = factory(ActivityType::class)->create([
'translation_key' => 'awesome_key',
'name' => null,
]);
$this->assertEquals(
'people.activity_type_awesome_key',
$activityType->name
);
$activityType = factory(ActivityType::class)->create([
'translation_key' => null,
'name' => 'awesome_name',
]);
$this->assertEquals(
'awesome_name',
$activityType->name
);
}
/** @test */
public function it_resets_the_associated_activities()
{
$activityType = factory(ActivityType::class)->create([]);
$activity = factory(Activity::class, 10)->create([
'activity_type_id' => $activityType->id,
]);
$this->assertEquals(
10,
$activityType->activities()->count()
);
$this->assertDatabaseHas('activities', [
'activity_type_id' => $activityType->id,
]);
$activityType->resetAssociationWithActivities();
$this->assertDatabaseMissing('activities', [
'activity_type_id' => $activityType->id,
]);
$this->assertEquals(
0,
$activityType->activities()->count()
);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Account\Account;
use App\Models\Account\AddressBook;
use App\Models\Account\AddressBookSubscription;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AddressBookSubscriptionTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create();
$user = factory(User::class)->create(['account_id' => $account->id]);
$addressBookSubscription = AddressBookSubscription::factory()->create([
'account_id' => $account->id,
'user_id' => $user->id,
]);
$this->assertTrue($addressBookSubscription->account()->exists());
}
/** @test */
public function it_belongs_to_a_user()
{
$user = factory(User::class)->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'user_id' => $user->id,
]);
$this->assertTrue($addressBookSubscription->user()->exists());
}
/** @test */
public function it_belongs_to_an_addressbook()
{
$addressBook = AddressBook::factory()->create();
$addressBookSubscription = AddressBookSubscription::factory()->create([
'address_book_id' => $addressBook->id,
]);
$this->assertTrue($addressBookSubscription->addressBook()->exists());
}
/** @test */
public function it_saves_capabilities()
{
$addressBookSubscription = new AddressBookSubscription();
$addressBookSubscription->capabilities = [
'test' => true,
];
$this->assertIsArray($addressBookSubscription->capabilities);
$this->assertEquals([
'test' => true,
], $addressBookSubscription->capabilities);
}
/** @test */
public function it_saves_password()
{
$addressBookSubscription = new AddressBookSubscription();
$addressBookSubscription->password = 'test';
$this->assertEquals('test', $addressBookSubscription->password);
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Account\Account;
use App\Models\Account\AddressBook;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AddressBookTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create();
$user = factory(User::class)->create(['account_id' => $account->id]);
$addressBook = AddressBook::factory()->create([
'account_id' => $account->id,
'user_id' => $user->id,
]);
$this->assertTrue($addressBook->account()->exists());
}
/** @test */
public function it_belongs_to_a_user()
{
$user = factory(User::class)->create();
$addressBook = AddressBook::factory()->create([
'user_id' => $user->id,
]);
$this->assertTrue($addressBook->user()->exists());
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Address;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AddressTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$address = factory(Address::class)->create([]);
$this->assertTrue($address->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$address = factory(Address::class)->create([]);
$this->assertTrue($address->contact()->exists());
}
/** @test */
public function it_belongs_to_a_place()
{
$address = factory(Address::class)->create([]);
$this->assertTrue($address->place()->exists());
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Tests\Unit\Models;
use Tests\ApiTestCase;
use App\Models\Contact\Contact;
use App\Models\Instance\AuditLog;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class AuditLogTest extends ApiTestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account(): void
{
$auditLog = factory(AuditLog::class)->create([]);
$this->assertTrue($auditLog->account()->exists());
}
/** @test */
public function it_belongs_to_a_user(): void
{
$auditLog = factory(AuditLog::class)->create([]);
$this->assertTrue($auditLog->author()->exists());
}
/** @test */
public function it_belongs_to_a_contact(): void
{
$contact = factory(Contact::class)->create([]);
$auditLog = factory(AuditLog::class)->create([
'about_contact_id' => $contact->id,
]);
$this->assertTrue($auditLog->contact()->exists());
}
/** @test */
public function it_returns_the_object_attribute(): void
{
$auditLog = factory(AuditLog::class)->create([]);
$this->assertEquals(
1,
$auditLog->object->{'user'}
);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\Company;
use App\Models\Contact\Occupation;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CompanyTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$company = factory(Company::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($company->account()->exists());
}
/** @test */
public function it_has_many_occupations()
{
$company = factory(Company::class)->create([]);
$occupations = factory(Occupation::class)->create([
'company_id' => $company->id,
]);
$this->assertTrue($company->occupations()->exists());
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\ContactField;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ContactFieldTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_fetches_data_field()
{
$contactField = new ContactField;
$contactField->data = 'this is a test';
$this->assertEquals(
'this is a test',
$contactField->data
);
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Tests\Unit\Models;
use Tests\FeatureTestCase;
use App\Models\Account\Account;
use App\Models\Contact\Conversation;
use App\Models\Contact\ContactFieldType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ContactFieldTypeTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_has_many_conversations()
{
$contactFieldType = factory(ContactFieldType::class)->create([]);
$conversation = factory(Conversation::class, 3)->create([
'account_id' => $contactFieldType->account_id,
'contact_field_type_id' => $contactFieldType->id,
]);
$this->assertTrue($contactFieldType->conversations()->exists());
}
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$contactFieldType = factory(ContactFieldType::class)->create([]);
$conversation = factory(Conversation::class, 3)->create([
'account_id' => $account->id,
'contact_field_type_id' => $contactFieldType->id,
]);
$this->assertTrue($contactFieldType->account()->exists());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,64 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\Message;
use App\Models\Contact\Conversation;
use App\Models\Contact\ContactFieldType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ConversationTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$conversation = factory(Conversation::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($conversation->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create();
$conversation = factory(Conversation::class)->create([
'contact_id' => $contact->id,
]);
$this->assertTrue($conversation->contact()->exists());
}
/** @test */
public function it_belongs_to_a_contact_field_type()
{
$account = factory(Account::class)->create([]);
$contactFieldType = factory(ContactFieldType::class)->create([
'account_id' => $account->id,
]);
$conversation = factory(Conversation::class)->create([
'contact_field_type_id' => $contactFieldType->id,
'account_id' => $account->id,
]);
$this->assertTrue($conversation->contactFieldType()->exists());
}
/** @test */
public function it_has_many_messages()
{
$conversation = factory(Conversation::class)->create();
$message = factory(Message::class)->create([
'conversation_id' => $conversation->id,
]);
$this->assertTrue($conversation->messages()->exists());
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Journal\Day;
use Illuminate\Support\Carbon;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DayTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function get_info_for_journal_entry_that_doesnt_happen_today()
{
$day = factory(Day::class)->make();
$day->id = 1;
$day->rate = 1;
$day->comment = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.';
$day->date = '2017-01-01 00:00:00';
$day->created_at = '2017-01-01 00:00:00';
$day->save();
$data = [
'type' => 'day',
'id' => 1,
'rate' => 1,
'comment' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.',
'day' => 1,
'day_name' => 'Sun',
'month' => 1,
'month_name' => 'JAN',
'year' => 2017,
'happens_today' => false,
'date' => Carbon::parse('2017-01-01 00:00:00'),
];
$this->assertEquals(
$data,
$day->getInfoForJournalEntry()
);
}
/** @test */
public function get_info_for_journal_entry_that_happen_today()
{
$date = now();
$day = factory(Day::class)->make();
$day->id = 1;
$day->rate = 1;
$day->comment = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.';
$day->date = $date;
$day->created_at = '2017-01-01 00:00:00';
$day->save();
$data = [
'type' => 'day',
'id' => 1,
'rate' => 1,
'comment' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor.',
'day' => $date->day,
'day_name' => $date->format('D'),
'month' => $date->month,
'month_name' => strtoupper($date->format('M')),
'year' => $date->year,
'happens_today' => true,
'date' => $date->addMicroseconds(-1 * $date->microsecond),
];
$this->assertEquals(
$data,
$day->getInfoForJournalEntry()
);
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\Document;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DocumentTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$document = factory(Document::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($document->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create();
$document = factory(Document::class)->create([
'contact_id' => $contact->id,
]);
$this->assertTrue($document->contact()->exists());
}
/** @test */
public function it_gets_the_download_link()
{
$document = factory(Document::class)->create();
$this->assertEquals(
config('app.url').'/store/'.$document->new_filename,
$document->getDownloadLink()
);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Instance\Emotion\Emotion;
use App\Models\Instance\Emotion\PrimaryEmotion;
use App\Models\Instance\Emotion\SecondaryEmotion;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class EmotionTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function emotion_belongs_to_a_primary_emotion()
{
$emotion = factory(Emotion::class)->create([]);
$this->assertTrue($emotion->primary->exists());
$this->assertTrue($emotion->secondary->exists());
}
/** @test */
public function secondary_emotion_belongs_to_a_primary_emotion()
{
$secondaryEmotion = factory(SecondaryEmotion::class)->create([]);
$this->assertTrue($secondaryEmotion->primary->exists());
}
/** @test */
public function a_primary_emotion_has_multiple_emotions()
{
$primaryEmotion = factory(PrimaryEmotion::class)->create([]);
$secondaryEmotion = factory(SecondaryEmotion::class)->create([
'emotion_primary_id' => $primaryEmotion->id,
]);
factory(Emotion::class, 3)->create([
'emotion_primary_id' => $primaryEmotion->id,
'emotion_secondary_id' => $secondaryEmotion->id,
]);
$this->assertTrue($primaryEmotion->secondaries()->exists());
$this->assertTrue($primaryEmotion->emotions()->exists());
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Journal\Entry;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class EntryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function get_info_for_journal_entry()
{
$entry = factory(Entry::class)->make([
'id' => 1,
'title' => 'This is the title',
'post' => 'this is a post',
'created_at' => '2017-01-01 00:00:00',
]);
$data = [
'type' => 'entry',
'id' => 1,
'title' => 'This is the title',
'post' => 'this is a post',
'day' => 1,
'day_name' => 'Sun',
'month' => 1,
'month_name' => 'JAN',
'year' => 2017,
'date' => '2017-01-01 00:00:00',
'created_at' => 'Jan 01, 2017 00:00',
];
$this->assertEquals(
$data,
$entry->getInfoForJournalEntry()
);
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Gender;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class GenderTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$gender = factory(Gender::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($gender->account()->exists());
}
/** @test */
public function it_belongs_to_many_contacts()
{
$account = factory(Account::class)->create([]);
$gender = factory(Gender::class)->create([
'account_id' => $account->id,
]);
$contact = factory(Contact::class)->create(['account_id' => $account->id, 'gender_id' => $gender->id]);
$contact = factory(Contact::class)->create(['account_id' => $account->id, 'gender_id' => $gender->id]);
$this->assertTrue($gender->contacts()->exists());
}
/** @test */
public function it_gets_the_gender_name()
{
$gender = new Gender;
$gender->name = 'Woman';
$this->assertEquals(
'Woman',
$gender->name
);
}
/** @test */
public function it_gets_the_default_gender()
{
$account = factory(Account::class)->create();
$gender = Gender::create([
'account_id' => $account->id,
'name' => 'Woman',
]);
$this->assertFalse($gender->isDefault());
$account->default_gender_id = $gender->id;
$account->save();
$gender->refresh();
$this->assertTrue($gender->isDefault());
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Contact\Gift;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class GiftTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function has_particular_recipient_returns_false_if_it_s_for_no_specific_recipient()
{
$gift = factory(Gift::class)->make();
$this->assertFalse(
$gift->hasParticularRecipient()
);
}
/** @test */
public function has_particular_recipient_returns_true_if_it_s_for_a_specific_recipient()
{
$gift = factory(Gift::class)->make([
'is_for' => 1,
]);
$this->assertTrue(
$gift->hasParticularRecipient()
);
}
/** @test */
public function it_sets_is_for_attribute()
{
$gift = factory(Gift::class)->make([
'is_for' => 1,
]);
$this->assertEquals(
1,
$gift->is_for
);
}
/** @test */
public function it_gets_the_recipient_name()
{
$contact = factory(Contact::class)->create(['first_name' => 'Regis']);
$gift = factory(Gift::class)->make([
'account_id' => $contact->account_id,
'is_for' => $contact->id,
'contact_id' => $contact->id,
]);
$this->assertEquals(
'Regis',
$gift->recipient_name
);
}
/** @test */
public function it_gets_the_gift_name()
{
$gift = factory(Gift::class)->make([
'name' => 'Maison de folie',
]);
$this->assertEquals(
'Maison de folie',
$gift->name
);
}
/** @test */
public function it_gets_the_gift_url()
{
$gift = factory(Gift::class)->make([
'url' => 'https://facebook.com',
]);
$this->assertEquals(
'https://facebook.com',
$gift->url
);
}
/** @test */
public function it_gets_the_comment()
{
$gift = factory(Gift::class)->make([
'comment' => 'This is just a comment',
]);
$this->assertEquals(
'This is just a comment',
$gift->comment
);
}
/** @test */
public function it_gets_the_value()
{
$user = factory(User::class)->create();
$this->be($user);
$gift = factory(Gift::class)->make([
'account_id' => $user->account_id,
'amount' => 100,
]);
$this->assertEquals(
'100.00',
$gift->amount
);
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\User\User;
use Illuminate\Session\Store;
use App\Http\Requests\Request;
use Illuminate\Session\NullSessionHandler;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class Google2FATest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_tests_a_wrong_key_for_Google2fa()
{
$google2fa = app('pragmarx.google2fa');
$secret = $google2fa->generateSecretKey(32);
$result = $google2fa->verifyGoogle2FA($secret, 'aaaaaa');
$this->assertFalse($result);
}
/** @test */
public function it_tests_a_correct_key_for_Google2fa()
{
$google2fa = app('pragmarx.google2fa');
$secret = $google2fa->generateSecretKey(32);
$one_time_password = $google2fa->getCurrentOtp($secret);
$result = $google2fa->verifyGoogle2FA($secret, $one_time_password);
$this->assertTrue($result);
}
/** @test */
public function it_logs_in_with_Google2Fa()
{
config(['google2fa.enabled' => true]);
$google2fa = app('pragmarx.google2fa')->setStateless(false);
$secret = $google2fa->generateSecretKey(32);
$user = factory(User::class)->create();
$user->google2fa_secret = $secret;
$this->actingAs($user);
$request = $this->app['request'];
// Avoid "Session store not set on request." - Exception!
$request->setLaravelSession(new Store('test', new NullSessionHandler));
$request->getSession()->start();
$authenticator = new \PragmaRX\Google2FALaravel\Support\Authenticator($request);
$this->assertFalse($authenticator->isAuthenticated());
$this->assertTrue($google2fa->isActivated());
$google2fa->login();
$this->assertTrue($authenticator->isAuthenticated());
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Contact;
use App\Services\Instance\IdHasher;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class IdHasherTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_prepends_the_id_with_the_letter_h()
{
$idHasher = new IdHasher();
$test_id = rand();
$test_hash = $idHasher->encodeId($test_id);
$value = substr($test_hash, 0, 1);
$this->assertEquals('h', $value);
}
/** @test */
public function it_returns_the_id_back()
{
$idHasher = new IdHasher();
$test_id = rand();
$test_hash = $idHasher->encodeId($test_id);
$result_id = $idHasher->decodeId($test_hash);
$this->assertEquals($test_id, $result_id);
}
/** @test */
public function it_gets_an_exception_when_the_id_is_not_valid()
{
$idHasher = new IdHasher();
$test_id = rand();
$this->expectException(\App\Exceptions\WrongIdException::class);
$idHasher->decodeId($test_id);
}
/** @test */
public function it_decodes_the_hash_and_returns_the_right_id()
{
$idHasher = new IdHasher();
$contact = factory(Contact::class)->create();
$value = $idHasher->decodeId($contact->hashID());
$this->assertEquals($contact->id, $value);
}
}

View File

@@ -0,0 +1,347 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\ImportJob;
use Sabre\VObject\Component\VCard;
use App\Models\Contact\ContactField;
use App\Models\Account\ImportJobReport;
use Illuminate\Support\Facades\Storage;
use App\Models\Contact\ContactFieldType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ImportJobTest extends TestCase
{
use DatabaseTransactions;
public $vcfContent = 'BEGIN:VCARD
VERSION:3.0
FN:Bono
N:;Bono;;;
EMAIL;TYPE=INTERNET:bono@example.com
TEL:+1 202-555-0191
ORG:U2
TITLE:Lead vocalist
BDAY:1960-05-10
NOTE:Lorem ipsum dolor sit amet
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:John Doe
N:Doe;John;;;
EMAIL;TYPE=INTERNET:john.doe@example.com
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:
N:;;;;
NICKNAME:Johnny
ADR:;;17 Shakespeare Ave.;Southampton;;SO17 2HB;United Kingdom
END:VCARD
';
/** @test */
public function it_belongs_to_a_user()
{
$importJob = factory(ImportJob::class)->create();
$this->assertTrue($importJob->user()->exists());
}
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
$importJob = factory(ImportJob::class)->create([
'account_id' => $account->id,
'user_id' => $user->id,
]);
$this->assertTrue($importJob->account()->exists());
}
/** @test */
public function it_belongs_to_many_reports()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
$importJob = factory(ImportJob::class)->create([
'account_id' => $account->id,
'user_id' => $user->id,
]);
factory(ImportJobReport::class, 100)->create([
'import_job_id' => $importJob->id,
'account_id' => $account->id,
'user_id' => $user->id,
]);
$this->assertTrue($importJob->importJobReports()->exists());
}
/** @test */
public function it_initiates_the_job()
{
$importJob = factory(ImportJob::class)->make([]);
$this->assertNull($importJob->started_at);
$this->invokePrivateMethod($importJob, 'initJob');
$this->assertNotNull($importJob->started_at);
}
/** @test */
public function it_finalizes_the_job()
{
$importJob = factory(ImportJob::class)->make([]);
$this->assertNull($importJob->ended_at);
$this->invokePrivateMethod($importJob, 'endJob');
$this->assertNotNull($importJob->ended_at);
}
/** @test */
public function it_fails_and_throws_an_exception()
{
$importJob = factory(ImportJob::class)->create([]);
$this->invokePrivateMethod($importJob, 'fail', [
'reason',
]);
$this->assertTrue($importJob->failed);
$this->assertEquals(
'reason',
$importJob->failed_reason
);
}
/** @test */
public function it_gets_the_physical_file()
{
Storage::fake('public');
$importJob = factory(ImportJob::class)->create([
'filename' => 'testfile.vcf',
]);
Storage::disk('public')->put(
'testfile.vcf',
'fakeContent'
);
Storage::disk('public')->assertExists($importJob->filename);
$this->assertNull($importJob->physicalFile);
$this->invokePrivateMethod($importJob, 'getPhysicalFile');
$this->assertIsResource($importJob->physicalFile);
}
/** @test */
public function it_throws_an_exception_if_file_doesnt_exist()
{
Storage::fake('public', [
'throw' => true,
]);
$importJob = factory(ImportJob::class)->create([
'filename' => 'testfile.vcf',
]);
$this->invokePrivateMethod($importJob, 'getPhysicalFile');
$this->assertEquals(
trans('settings.import_vcard_file_not_found'),
$importJob->failed_reason
);
}
/** @test */
public function it_deletes_the_file()
{
Storage::fake('public');
$importJob = factory(ImportJob::class)->create([
'filename' => 'testfile.vcf',
]);
Storage::disk('public')->put(
'testfile.vcf',
'fakeContent'
);
$this->invokePrivateMethod($importJob, 'deletePhysicalFile');
Storage::disk('public')->assertMissing($importJob->filename);
}
/** @test */
public function it_calculates_how_many_entries_there_are_and_populate_the_entries_array()
{
Storage::fake('public');
$importJob = $this->createImportJob();
$importJob->filename = 'testfile.vcf';
Storage::disk('public')->put(
'testfile.vcf',
$this->vcfContent
);
$this->invokePrivateMethod($importJob, 'getPhysicalFile');
$this->invokePrivateMethod($importJob, 'getEntries');
$this->invokePrivateMethod($importJob, 'processEntries');
$this->assertJobSuccess($importJob);
$this->assertEquals(
3,
$importJob->contacts_found
);
}
/** @test */
public function it_doesnt_process_an_entry_if_import_is_not_feasible()
{
$importJob = $this->createImportJob();
$vcard = new VCard([
'TEL' => '+1 555 34567 455',
'N' => ['', '', '', '', ''],
]);
$this->invokePrivateMethod($importJob, 'processSingleEntry', [
$vcard->serialize(),
]);
$this->assertJobSuccess($importJob);
$this->assertEquals(
1,
$importJob->contacts_skipped
);
}
/** @test */
public function it_doesnt_process_an_entry_if_contact_already_exists()
{
$importJob = $this->createImportJob();
$contact = factory(Contact::class)->create([
'account_id' => $importJob->account_id,
]);
$contactFieldType = factory(ContactFieldType::class)->create([
'account_id' => $importJob->account_id,
'type' => 'email',
]);
$contactField = factory(ContactField::class)->create([
'account_id' => $importJob->account_id,
'contact_id' => $contact->id,
'contact_field_type_id' => $contactFieldType->id,
'data' => 'john@doe.com',
]);
$vcard = new VCard([
'N' => ['John', 'Doe', '', '', ''],
'EMAIL' => 'john@doe.com',
]);
$this->invokePrivateMethod($importJob, 'processSingleEntry', [$vcard]);
$this->assertJobSuccess($importJob);
$this->assertEquals(
1,
$importJob->contacts_skipped
);
}
/** @test */
public function skipping_entries_increments_counter_and_file_job_report()
{
$importJob = $this->createImportJob();
$this->invokePrivateMethod($importJob, 'skipEntry', [
'John Doe',
]);
$this->assertEquals(
1,
$importJob->contacts_skipped
);
$this->assertDatabaseHas('import_job_reports', [
'account_id' => $importJob->account_id,
'import_job_id' => $importJob->id,
]);
}
/** @test */
public function it_files_an_import_job_report()
{
$importJob = $this->createImportJob();
$vcard = new VCard([
'N' => ['John', 'Doe', '', '', ''],
'EMAIL' => 'john@doe.com',
]);
$this->invokePrivateMethod($importJob, 'fileImportJobReport', [
'Doe John john@doe.com',
$importJob::VCARD_SKIPPED,
]);
$this->assertDatabaseHas('import_job_reports', [
'account_id' => $importJob->account_id,
'user_id' => $importJob->user_id,
'import_job_id' => $importJob->id,
'contact_information' => 'Doe John john@doe.com',
'skipped' => 1,
'skip_reason' => null,
]);
$this->invokePrivateMethod($importJob, 'fileImportJobReport', [
'Doe John john@doe.com',
$importJob::VCARD_IMPORTED,
]);
$this->assertDatabaseHas('import_job_reports', [
'account_id' => $importJob->account_id,
'user_id' => $importJob->user_id,
'import_job_id' => $importJob->id,
'contact_information' => 'Doe John john@doe.com',
'skipped' => 0,
'skip_reason' => null,
]);
$this->invokePrivateMethod($importJob, 'fileImportJobReport', [
'Doe John john@doe.com',
$importJob::VCARD_SKIPPED,
'the reason why',
]);
$this->assertDatabaseHas('import_job_reports', [
'account_id' => $importJob->account_id,
'user_id' => $importJob->user_id,
'import_job_id' => $importJob->id,
'contact_information' => 'Doe John john@doe.com',
'skipped' => 1,
'skip_reason' => 'the reason why',
]);
}
private function createImportJob()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
return factory(ImportJob::class)->create([
'account_id' => $account->id,
'user_id' => $user->id,
'failed' => false,
]);
}
private function assertJobSuccess($importJob)
{
$this->assertFalse($importJob->failed, 'Job has failed, reason: '.$importJob->failed_reason);
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Tests\Unit\Models;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Journal\Entry;
use App\Models\Account\Account;
use App\Models\Account\Activity;
use App\Models\Journal\JournalEntry;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class JournalEntryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$task = factory(JournalEntry::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($task->account()->exists());
}
/** @test */
public function it_has_polymorphic_relations()
{
$activity = factory(Activity::class)->create();
$journalEntry = JournalEntry::add($activity);
$activity->refresh();
$this->assertNotNull($journalEntry->journalable);
$this->assertEquals($activity->id, $journalEntry->journalable_id);
$this->assertNotNull($activity->journalEntry);
$this->assertEquals($journalEntry->id, $activity->journalEntry->id);
}
/** @test */
public function it_has_polymorphic_relations2()
{
$entry = factory(Entry::class)->create();
$entry->date = '2018-01-01';
$journalEntry = JournalEntry::add($entry);
$entry->refresh();
$this->assertNotNull($journalEntry->journalable);
$this->assertEquals($entry->id, $journalEntry->journalable_id);
$this->assertNotNull($entry->journalEntry);
$this->assertEquals($journalEntry->id, $entry->journalEntry->id);
}
/** @test */
public function get_add_adds_data_of_the_right_type()
{
$activity = factory(Activity::class)->create();
$date = $activity->happened_at;
$journalEntry = JournalEntry::add($activity);
$this->assertDatabaseHas('journal_entries', [
'account_id' => $activity->account_id,
'date' => $date,
'journalable_id' => $activity->id,
'journalable_type' => 'App\Models\Account\Activity',
]);
}
/** @test */
public function get_object_data_returns_an_object()
{
$activity = factory(Activity::class)->create();
$journalEntry = JournalEntry::add($activity);
$data = [
'type' => 'activity',
'id' => $activity->id,
'activity_type' => (! is_null($activity->type) ? $activity->type->name : null),
'summary' => $activity->summary,
'description' => $activity->description,
'day' => $activity->happened_at->day,
'day_name' => $activity->happened_at->format('D'),
'month' => $activity->happened_at->month,
'month_name' => strtoupper($activity->happened_at->format('M')),
'year' => $activity->happened_at->year,
'attendees' => $activity->getContactsForAPI(),
];
$this->assertEquals(
$data,
$journalEntry->getObjectData()
);
}
/** @test */
public function get_edit_journal_entry()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1, 0, 0, 0));
$entry = factory(Entry::class)->create([
'title' => 'This is the title',
'post' => 'this is a post',
]);
$entry->date = '2017-01-01';
$journalEntry = JournalEntry::add($entry);
$this->assertDatabaseHas('journal_entries', [
'account_id' => $entry->account_id,
'date' => '2017-01-01 00:00:00',
'journalable_id' => $entry->id,
'journalable_type' => 'App\Models\Journal\Entry',
]);
$entry->date = '2018-01-01';
$journalEntry->edit($entry);
$this->assertDatabaseHas('journal_entries', [
'account_id' => $entry->account_id,
'date' => '2018-01-01 00:00:00',
'journalable_id' => $entry->id,
'journalable_type' => 'App\Models\Journal\Entry',
]);
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\LifeEvent;
use App\Models\Contact\LifeEventType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LIfeEventTypeTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$lifeEventType = factory(LifeEventType::class)->create([]);
$this->assertTrue($lifeEventType->account()->exists());
}
/** @test */
public function it_belongs_to_a_category()
{
$lifeEventType = factory(LifeEventType::class)->create([]);
$this->assertTrue($lifeEventType->lifeEventCategory()->exists());
}
/** @test */
public function it_has_many_life_events()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$lifeEventType = factory(LifeEventType::class)->create([]);
$lifeEvents = factory(LifeEvent::class, 2)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
'life_event_type_id' => $lifeEventType->id,
]);
$this->assertTrue($lifeEventType->lifeEvents()->exists());
}
/** @test */
public function it_gets_the_name_attribute()
{
$lifeEventType = factory(LifeEventType::class)->create([
'name' => 'Fake name',
]);
$this->assertEquals(
'Fake name',
$lifeEventType->name
);
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\LifeEventType;
use App\Models\Contact\LifeEventCategory;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LifeEventCategoryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$lifeEventCategory = factory(LifeEventCategory::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($lifeEventCategory->account()->exists());
}
/** @test */
public function it_has_many_life_event_types()
{
$lifeEventCategory = factory(LifeEventCategory::class)->create();
factory(LifeEventType::class)->create([
'life_event_category_id' => $lifeEventCategory->id,
]);
$this->assertTrue($lifeEventCategory->lifeEventTypes()->exists());
}
/** @test */
public function it_gets_name_attribute()
{
$lifeEventCategory = factory(LifeEventCategory::class)->create([
'name' => 'Fake name',
]);
$this->assertEquals(
'Fake name',
$lifeEventCategory->name
);
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Reminder;
use App\Models\Contact\LifeEvent;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class LifeEventTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$lifeEvent = factory(LifeEvent::class)->create([]);
$this->assertTrue($lifeEvent->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$lifeEvent = factory(LifeEvent::class)->create([]);
$this->assertTrue($lifeEvent->contact()->exists());
}
/** @test */
public function it_belongs_to_a_type()
{
$lifeEvent = factory(LifeEvent::class)->create([]);
$this->assertTrue($lifeEvent->lifeEventType()->exists());
}
/** @test */
public function it_has_a_reminder()
{
$lifeEvent = factory(LifeEvent::class)->create([]);
$reminder = factory(Reminder::class)->create([
'account_id' => $lifeEvent->account_id,
]);
$lifeEvent->reminder_id = $reminder->id;
$lifeEvent->save();
$this->assertTrue($lifeEvent->reminder()->exists());
}
/** @test */
public function it_gets_the_name_attribute()
{
$lifeEvent = factory(LifeEvent::class)->create([
'name' => 'Fake name',
]);
$this->assertEquals(
'Fake name',
$lifeEvent->name
);
}
/** @test */
public function it_gets_the_note_attribute()
{
$lifeEvent = factory(LifeEvent::class)->create([
'note' => 'Fake note',
]);
$this->assertEquals(
'Fake note',
$lifeEvent->note
);
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\Message;
use App\Models\Contact\Conversation;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class MessageTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$message = factory(Message::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($message->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create();
$message = factory(Message::class)->create([
'contact_id' => $contact->id,
]);
$this->assertTrue($message->contact()->exists());
}
/** @test */
public function it_belongs_to_a_conversation()
{
$conversation = factory(Conversation::class)->create();
$message = factory(Message::class)->create([
'conversation_id' => $conversation->id,
]);
$this->assertTrue($message->conversation()->exists());
}
/** @test */
public function it_gets_the_content_attribute()
{
$message = factory(Message::class)->create([
'content' => 'This is a text',
]);
$this->assertEquals(
'This is a text',
$message->content
);
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Note;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class NoteTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$note = factory(Note::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
]);
$this->assertTrue($note->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create([]);
$note = factory(Note::class)->create([
'contact_id' => $contact->id,
]);
$this->assertTrue($note->contact()->exists());
}
/** @test */
public function it_filters_by_favorited_notes()
{
$note = factory(Note::class)->create(['is_favorited' => true]);
$note = factory(Note::class)->create(['is_favorited' => true]);
$note = factory(Note::class)->create(['is_favorited' => false]);
$note = factory(Note::class)->create(['is_favorited' => true]);
$this->assertEquals(
3,
Note::favorited()->count()
);
}
public function testGetBodyReturnsNullIfUndefined()
{
$note = new Note;
$this->assertNull($note->getBody());
}
public function testGetBodyReturnsTextIfDefined()
{
$note = new Note;
$note->body = 'This is a text';
$this->assertEquals(
'This is a text',
$note->getBody()
);
}
public function testGetCreatedAtReturnsAFormattedDate()
{
$note = new Note;
$note->created_at = '2017-01-22 17:56:03';
$this->assertEquals(
'Jan 22, 2017',
$note->getCreatedAt()
);
}
public function testGetCreatedAtReturnsAString()
{
$note = new Note;
$note->created_at = '2017-01-22 17:56:03';
$this->assertIsString($note->getCreatedAt());
}
public function testGetContentReturnsAString()
{
$note = factory(Note::class)->make();
$this->assertIsString($note->getContent());
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\Company;
use App\Models\Contact\Contact;
use App\Models\Contact\Occupation;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class OccupationTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$occupation = factory(Occupation::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($occupation->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create([]);
$occupation = factory(Occupation::class)->create([
'contact_id' => $contact->id,
]);
$this->assertTrue($occupation->contact()->exists());
}
/** @test */
public function it_belongs_to_a_company()
{
$company = factory(Company::class)->create([]);
$occupation = factory(Occupation::class)->create([
'company_id' => $company->id,
]);
$this->assertTrue($occupation->company()->exists());
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\PetCategory;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PetCategoryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_only_common_pets()
{
$petCategory = new PetCategory;
$this->assertEquals(
3,
$petCategory->common()->count()
);
}
/** @test */
public function it_gets_pet_category_name()
{
$petCategory = new PetCategory;
$petCategory->name = 'Rgis';
$this->assertEquals(
'Rgis',
$petCategory->name
);
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Pet;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\PetCategory;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PetTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$pet = factory(Pet::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
]);
$this->assertTrue($pet->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create([]);
$pet = factory(Pet::class)->create([
'account_id' => $contact->account_id,
'contact_id' => $contact->id,
]);
$this->assertTrue($pet->contact()->exists());
}
/** @test */
public function it_belongs_to_a_pet_category()
{
$petCategory = factory(PetCategory::class)->create([]);
$pet = factory(Pet::class)->create([
'pet_category_id' => $petCategory->id,
]);
$this->assertTrue($pet->petCategory()->exists());
}
/** @test */
public function it_sets_name()
{
$pet = new Pet;
$this->assertNull($pet->name);
$pet->name = 'henri';
$this->assertEquals(
'henri',
$pet->name
);
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Photo;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PhotoTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$photo = factory(Photo::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($photo->account()->exists());
}
/** @test */
public function it_belongs_to_many_contacts()
{
$contact = factory(Contact::class)->create();
$photo = factory(Photo::class)->create();
$contact->photos()->sync([$photo->id]);
$photo = factory(Photo::class)->create();
$contact->photos()->sync([$photo->id]);
$this->assertTrue($photo->contacts()->exists());
}
/** @test */
public function it_gets_the_url()
{
$photo = factory(Photo::class)->create();
$this->assertEquals(
config('app.url').'/store/'.$photo->new_filename,
$photo->url()
);
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Place;
use App\Models\Account\Weather;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class PlaceTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$place = factory(Place::class)->create([]);
$this->assertTrue($place->account()->exists());
}
/** @test */
public function it_has_many_weathers()
{
$weather = factory(Weather::class)->create([]);
$this->assertTrue($weather->place->weathers()->exists());
}
/** @test */
public function it_returns_the_full_address_as_a_string()
{
$place = factory(Place::class)->create([]);
$this->assertEquals(
'12 beverly hills 90210 United States',
$place->getAddressAsString()
);
}
/** @test */
public function it_returns_country_name()
{
$place = factory(Place::class)->create([]);
$this->assertEquals(
'United States',
$place->getCountryName()
);
}
/** @test */
public function it_returns_a_link_to_google_maps()
{
$place = factory(Place::class)->create([]);
$this->assertEquals(
'https://www.google.com/maps/place/'.urlencode($place->getAddressAsString()),
$place->getGoogleMapAddress()
);
}
/** @test */
public function it_returns_a_google_map_url_with_latitude_longitude()
{
$place = new Place;
$place->latitude = 24.197611;
$place->longitude = 120.780512;
$this->assertEquals(
'http://maps.google.com/maps?q=24.197611,120.780512',
$place->getGoogleMapsAddressWithLatitude()
);
}
}

View File

@@ -0,0 +1,146 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Relationship\Relationship;
use App\Models\Relationship\RelationshipType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class RelationshipTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$relationship = factory(Relationship::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($relationship->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create([]);
$relationship = factory(Relationship::class)->create([
'contact_is' => $contact->id,
]);
$this->assertTrue($relationship->contactIs()->exists());
}
/** @test */
public function it_belongs_to_another_contact()
{
$contact = factory(Contact::class)->create([]);
$relationship = factory(Relationship::class)->create([
'of_contact' => $contact->id,
]);
$this->assertTrue($relationship->ofContact()->exists());
}
/** @test */
public function it_belongs_to_a_relationship_type()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
]);
$relationship = factory(Relationship::class)->create([
'account_id' => $account->id,
'relationship_type_id' => $relationshipType->id,
]);
$this->assertTrue($relationship->relationshipType()->exists());
}
/** @test */
public function it_belongs_to_a_contact_through_with_contact_field()
{
$contact = factory(Contact::class)->create([]);
$relationship = factory(Relationship::class)->create([
'of_contact' => $contact->id,
]);
$this->assertTrue($relationship->ofContact()->exists());
}
/** @test */
public function it_gets_the_reverse_relationship()
{
$account = factory(Account::class)->create();
$contactA = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$contactB = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$relationshipTypeA = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$relationshipA = factory(Relationship::class)->create([
'account_id' => $account->id,
'relationship_type_id' => $relationshipTypeA->id,
'contact_is' => $contactA->id,
'of_contact' => $contactB->id,
]);
$relationshipTypeB = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'nephew',
'name_reverse_relationship' => 'uncle',
]);
$relationshipB = factory(Relationship::class)->create([
'account_id' => $account->id,
'relationship_type_id' => $relationshipTypeB->id,
'contact_is' => $contactB->id,
'of_contact' => $contactA->id,
]);
$reverseRelationship = $relationshipA->reverseRelationship();
$this->assertEquals(
$relationshipB->id,
$reverseRelationship->id
);
$reverseReverseRelationship = $reverseRelationship->reverseRelationship();
$this->assertEquals(
$relationshipA->id,
$reverseReverseRelationship->id
);
}
/** @test */
public function it_not_gets_the_reverse_relationship()
{
$account = factory(Account::class)->create();
$contactA = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$contactB = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$relationshipTypeA = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
]);
$relationshipA = factory(Relationship::class)->create([
'account_id' => $account->id,
'relationship_type_id' => $relationshipTypeA->id,
'contact_is' => $contactA->id,
'of_contact' => $contactB->id,
]);
$reverseRelationship = $relationshipA->reverseRelationship();
$this->assertNull($reverseRelationship);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Relationship\RelationshipType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class RelationshipTypeGroupTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($relationshipType->account()->exists());
}
}

View File

@@ -0,0 +1,182 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Relationship\RelationshipType;
use App\Models\Relationship\RelationshipTypeGroup;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class RelationshipTypeTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($relationshipType->account()->exists());
}
/** @test */
public function it_belongs_to_an_relationship_type_group()
{
$account = factory(Account::class)->create([]);
$relationshipTypeGroup = factory(RelationshipTypeGroup::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($relationshipTypeGroup->account()->exists());
}
/** @test */
public function it_gets_the_masculine_short_name_of_the_relationship_type()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$this->assertEquals(
'uncle',
$relationshipType->getLocalizedName()
);
}
/** @test */
public function it_gets_the_feminine_short_name_of_the_relationship_type()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$this->assertEquals(
'aunt',
$relationshipType->getLocalizedName(null, false, 'F')
);
}
/** @test */
public function it_gets_the_masculine_name_of_the_relationship_type_with_the_name_of_the_contact()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'first_name' => 'Mark',
'last_name' => 'Twain',
]);
$this->assertEquals(
'Mark Twains uncle',
$relationshipType->getLocalizedName($contact, false, 'M')
);
}
/** @test */
public function it_gets_the_feminine_name_of_the_relationship_type_with_the_name_of_the_contact()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'first_name' => 'Mark',
'last_name' => 'Twain',
]);
$this->assertEquals(
'Mark Twains aunt',
$relationshipType->getLocalizedName($contact, false, 'F')
);
}
/** @test */
public function it_gets_both_names_of_the_relationship_type_with_the_name_of_the_contact_and_the_opposite_version()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'first_name' => 'Mark',
'last_name' => 'Twain',
]);
$this->assertEquals(
'Mark Twains uncle/aunt',
$relationshipType->getLocalizedName($contact, true)
);
}
/** @test */
public function it_gets_only_one_name_of_the_relationship_type_if_name_and_name_reverse_are_similar()
{
$account = factory(Account::class)->create([]);
$relationshipType = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'partner',
'name_reverse_relationship' => 'partner',
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
'first_name' => 'Mark',
'last_name' => 'Twain',
]);
$this->assertEquals(
'Mark Twains significant other',
$relationshipType->getLocalizedName($contact, true)
);
}
/** @test */
public function it_gets_the_reverse_relationship_type()
{
$account = factory(Account::class)->create([]);
$relationshipTypeA = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'uncle',
'name_reverse_relationship' => 'nephew',
]);
$relationshipTypeB = factory(RelationshipType::class)->create([
'account_id' => $account->id,
'name' => 'nephew',
'name_reverse_relationship' => 'uncle',
]);
$reverseRelationshipType = $relationshipTypeA->reverseRelationshipType();
$this->assertEquals(
$relationshipTypeB->id,
$reverseRelationshipType->id
);
$reverseReverseRelationshipType = $reverseRelationshipType->reverseRelationshipType();
$this->assertEquals(
$relationshipTypeA->id,
$reverseReverseRelationshipType->id
);
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\ReminderOutbox;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ReminderOutboxTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$reminderOutbox = factory(ReminderOutbox::class)->create([]);
$this->assertTrue($reminderOutbox->account()->exists());
}
/** @test */
public function it_belongs_to_a_reminder()
{
$reminderOutbox = factory(ReminderOutbox::class)->create([]);
$this->assertTrue($reminderOutbox->reminder()->exists());
}
/** @test */
public function it_belongs_to_a_user()
{
$reminderOutbox = factory(ReminderOutbox::class)->create([]);
$this->assertTrue($reminderOutbox->user()->exists());
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\ReminderRule;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ReminderRuleTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$reminderRule = factory(ReminderRule::class)->create(['account_id' => $account->id]);
$this->assertTrue($reminderRule->account()->exists());
}
/** @test */
public function it_gets_number_of_days_before_attribute()
{
$reminderRule = factory(ReminderRule::class)->create(['number_of_days_before' => '14']);
$this->assertEquals(
14,
$reminderRule->number_of_days_before
);
}
/** @test */
public function it_sets_number_of_days_before_attribute()
{
$reminderRule = new ReminderRule;
$reminderRule->number_of_days_before = '14';
$this->assertEquals(
14,
$reminderRule->number_of_days_before
);
}
}

View File

@@ -0,0 +1,254 @@
<?php
namespace Tests\Unit\Models;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Contact\Reminder;
use App\Models\Contact\ReminderRule;
use App\Models\Contact\ReminderOutbox;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ReminderTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($reminder->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$contact = factory(Contact::class)->create([]);
$reminder = factory(Reminder::class)->create([
'contact_id' => $contact->id,
]);
$this->assertTrue($reminder->contact()->exists());
}
/** @test */
public function it_has_many_reminder_outbox()
{
$user = factory(User::class)->create([]);
$reminder = factory(Reminder::class)->create(['account_id' => $user->account_id]);
factory(ReminderOutbox::class, 3)->create([
'account_id' => $user->account_id,
'reminder_id' => $reminder->id,
'user_id' => $user->id,
]);
$this->assertTrue($reminder->reminderOutboxes()->exists());
}
/** @test */
public function it_gets_the_title_attribute()
{
$reminder = factory(Reminder::class)->create([
'title' => 'Fake name',
]);
$this->assertEquals(
'Fake name',
$reminder->title
);
}
/** @test */
public function it_gets_the_description_attribute()
{
$reminder = factory(Reminder::class)->create([
'description' => 'Fake name',
]);
$this->assertEquals(
'Fake name',
$reminder->description
);
}
/** @test */
public function it_calculates_next_expected_date()
{
$timezone = 'UTC';
$reminder = new Reminder;
$reminder->initial_date = '1980-01-01 10:10:10';
$reminder->frequency_number = 1;
Carbon::setTestNow(Carbon::create(1980, 1, 1));
$reminder->frequency_type = 'week';
$this->assertEquals(
'1980-01-08',
$reminder->calculateNextExpectedDate()->toDateString()
);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
// from 1980, incrementing one week will lead to Jan 03, 2017
$reminder->frequency_type = 'week';
$this->assertEquals(
'2017-01-03',
$reminder->calculateNextExpectedDate()->toDateString()
);
$reminder->frequency_type = 'month';
$reminder->initial_date = '1980-01-01 10:10:10';
$this->assertEquals(
'2017-02-01',
$reminder->calculateNextExpectedDate()->toDateString()
);
$reminder->frequency_type = 'year';
$reminder->initial_date = '1980-01-01 10:10:10';
$this->assertEquals(
'2018-01-01',
$reminder->calculateNextExpectedDate()->toDateString()
);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
$reminder->initial_date = '2016-12-25 10:10:10';
$reminder->frequency_type = 'week';
$this->assertEquals(
'2017-01-08',
$reminder->calculateNextExpectedDate()->toDateString()
);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
$reminder->initial_date = '2017-02-02 10:10:10';
$reminder->frequency_type = 'week';
$this->assertEquals(
'2017-02-02',
$reminder->calculateNextExpectedDate()->toDateString()
);
}
/** @test */
public function it_calculates_next_expected_date_in_timezone()
{
config(['app.timezone' => 'Europe/Paris']);
$reminder = new Reminder;
$reminder->initial_date = '1980-05-01';
$reminder->frequency_type = 'year';
$reminder->frequency_number = 1;
Carbon::setTestNow(Carbon::create(2000, 4, 30, 21, 59, 59));
$this->assertEquals(
'2000-05-01',
$reminder->calculateNextExpectedDateOnTimezone()->toDateString()
);
Carbon::setTestNow(Carbon::create(2000, 4, 30, 22, 00, 00));
$this->assertEquals(
'2001-05-01',
$reminder->calculateNextExpectedDateOnTimezone()->toDateString()
);
}
/** @test */
public function it_schedules_a_reminder_for_one_user()
{
Carbon::setTestNow(Carbon::create(2017, 2, 1));
$user = factory(User::class)->create([]);
$reminder = factory(Reminder::class)->create([
'account_id' => $user->account_id,
'initial_date' => '2017-01-01',
'frequency_type' => 'year',
'frequency_number' => 1,
]);
$reminder->schedule($user);
$this->assertDatabaseHas('reminder_outbox', [
'reminder_id' => $reminder->id,
'planned_date' => '2018-01-01',
'nature' => 'reminder',
'user_id' => $user->id,
]);
}
/** @test */
public function scheduling_a_reminder_also_schedules_notifications_for_one_user()
{
Carbon::setTestNow(Carbon::create(2017, 2, 1));
$user = factory(User::class)->create([]);
$reminder = factory(Reminder::class)->create([
'account_id' => $user->account_id,
'initial_date' => '2017-01-01',
'frequency_type' => 'year',
'frequency_number' => 1,
]);
$reminderRule = factory(ReminderRule::class)->create([
'account_id' => $reminder->account_id,
'number_of_days_before' => 30,
'active' => 1,
]);
$reminderRule = factory(ReminderRule::class)->create([
'account_id' => $reminder->account_id,
'number_of_days_before' => 7,
'active' => 1,
]);
$reminder->schedule($user);
$this->assertDatabaseHas('reminder_outbox', [
'reminder_id' => $reminder->id,
'planned_date' => '2017-12-02',
'nature' => 'notification',
'notification_number_days_before' => 30,
]);
$this->assertDatabaseHas('reminder_outbox', [
'reminder_id' => $reminder->id,
'planned_date' => '2017-12-25',
'nature' => 'notification',
'notification_number_days_before' => 7,
'user_id' => $user->id,
]);
$this->assertEquals(
3,
$reminder->reminderOutboxes()->count()
);
}
/** @test */
public function it_doesnt_schedule_a_notification_if_date_is_too_close_to_present_date()
{
Carbon::setTestNow(Carbon::create(2017, 2, 1));
$user = factory(User::class)->create([]);
$reminder = factory(Reminder::class)->create([
'account_id' => $user->account_id,
'initial_date' => '2017-01-01',
'frequency_type' => 'week',
'frequency_number' => 1,
]);
$reminderRule = factory(ReminderRule::class)->create([
'account_id' => $reminder->account_id,
'number_of_days_before' => 7,
'active' => 1,
]);
$reminder->schedule($user);
$this->assertDatabaseMissing('reminder_outbox', [
'reminder_id' => $reminder->id,
'nature' => 'notification',
]);
$this->assertEquals(
1,
$reminder->reminderOutboxes()->count()
);
}
}

View File

@@ -0,0 +1,196 @@
<?php
namespace Tests\Unit\Models;
use Carbon\Carbon;
use Tests\FeatureTestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Instance\SpecialDate;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class SpecialDateTest extends FeatureTestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$specialDate = factory(SpecialDate::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($specialDate->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$specialDate = factory(SpecialDate::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
]);
$this->assertTrue($specialDate->contact()->exists());
}
/** @test */
public function get_age_returns_null_if_no_date_is_set()
{
$specialDate = new SpecialDate;
$this->assertNull($specialDate->getAge());
}
/** @test */
public function get_age_returns_null_if_year_is_unknown()
{
$specialDate = factory(SpecialDate::class)->make();
$specialDate->is_year_unknown = 1;
$specialDate->save();
$this->assertNull($specialDate->getAge());
}
/** @test */
public function get_age_returns_age()
{
Carbon::setTestNow(Carbon::create(2020, 2, 17, 17, 0, 0));
$specialDate = factory(SpecialDate::class)->make();
$specialDate->is_year_unknown = 0;
$specialDate->date = now()->subYears(5);
$specialDate->save();
$this->assertEquals(
5,
$specialDate->getAge()
);
}
/** @test */
public function create_from_age_sets_the_right_date()
{
$specialDate = factory(SpecialDate::class)->make();
$specialDate->createFromAge(100);
$this->assertTrue(
$specialDate->is_age_based
);
$this->assertEquals(
1,
$specialDate->date->day
);
$this->assertEquals(
1,
$specialDate->date->month
);
}
/** @test */
public function create_from_date_creates_an_approximate_date()
{
$specialDate = factory(SpecialDate::class)->make();
$specialDate->createFromDate(0, 10, 10);
$this->assertTrue(
$specialDate->is_year_unknown
);
$this->assertEquals(
10,
$specialDate->date->day
);
$this->assertEquals(
10,
$specialDate->date->month
);
$this->assertEquals(
now()->year,
$specialDate->date->year
);
}
/** @test */
public function create_from_date_creates_an_exact_date()
{
$specialDate = factory(SpecialDate::class)->make();
$specialDate->createFromDate(2019, 10, 10);
$this->assertFalse(
$specialDate->is_year_unknown
);
$this->assertEquals(
10,
$specialDate->date->day
);
$this->assertEquals(
10,
$specialDate->date->month
);
$this->assertEquals(
2019,
$specialDate->date->year
);
}
/** @test */
public function set_contact_sets_the_contact_information()
{
$specialDate = factory(SpecialDate::class)->make();
$contact = factory(Contact::class)->create();
$specialDate->setToContact($contact);
$this->assertEquals(
$contact->account_id,
$specialDate->account_id
);
$this->assertEquals(
$contact->id,
$specialDate->contact_id
);
}
/** @test */
public function to_short_string_returns_date_with_year()
{
$specialDate = new SpecialDate;
$specialDate->is_year_unknown = false;
$specialDate->date = Carbon::create(2001, 5, 21);
$this->assertEquals(
'May 21, 2001',
$specialDate->toShortString()
);
}
/** @test */
public function to_short_string_returns_date_without_year()
{
$specialDate = new SpecialDate;
$specialDate->is_year_unknown = true;
$specialDate->date = Carbon::create(2001, 5, 21);
$this->assertEquals(
'May 21',
$specialDate->toShortString()
);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Tag;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TagTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$tag = factory(Tag::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($tag->account()->exists());
}
/** @test */
public function it_belongs_to_many_contacts()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$tag = factory(Tag::class)->create(['account_id' => $account->id]);
$contact->tags()->sync([$tag->id => ['account_id' => $account->id]]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$tag = factory(Tag::class)->create(['account_id' => $account->id]);
$contact->tags()->sync([$tag->id => ['account_id' => $account->id]]);
$this->assertTrue($tag->contacts()->exists());
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Contact\Task;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TaskTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$task = factory(Task::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
]);
$this->assertTrue($task->account()->exists());
}
/** @test */
public function it_belongs_to_a_contact()
{
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create(['account_id' => $account->id]);
$task = factory(Task::class)->create([
'account_id' => $account->id,
'contact_id' => $contact->id,
]);
$this->assertTrue($task->contact()->exists());
}
/** @test */
public function it_filters_by_completed_items()
{
$task = factory(Task::class)->create(['completed' => true]);
$task = factory(Task::class)->create(['completed' => true]);
$task = factory(Task::class)->create(['completed' => false]);
$task = factory(Task::class)->create(['completed' => true]);
$this->assertEquals(
3,
Task::completed()->count()
);
}
/** @test */
public function it_filters_by_incomplete_items()
{
$task = factory(Task::class)->create(['completed' => false]);
$task = factory(Task::class)->create(['completed' => true]);
$task = factory(Task::class)->create(['completed' => true]);
$task = factory(Task::class)->create(['completed' => true]);
$this->assertEquals(
1,
Task::inProgress()->count()
);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Settings\Term;
use App\Models\Account\Account;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TermTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_many_users()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$term = factory(Term::class)->create([]);
$term->users()->sync([$user->id => ['account_id' => $account->id]]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$term = factory(Term::class)->create([]);
$term->users()->sync([$user->id => ['account_id' => $account->id]]);
$this->assertTrue($term->users()->exists());
}
}

View File

@@ -0,0 +1,453 @@
<?php
namespace Tests\Unit\Models;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\User\User;
use App\Models\Settings\Term;
use App\Models\Account\Account;
use App\Models\Contact\Reminder;
use App\Models\Settings\Currency;
use App\Services\User\CreateUser;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Notification;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserTest extends TestCase
{
use DatabaseTransactions;
private function createUser($account_id, $first_name, $last_name, $email, $password)
{
return app(CreateUser::class)->execute([
'account_id' => $account_id,
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $password,
]);
}
/** @test */
public function it_belongs_to_account()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$this->assertTrue($user->account()->exists());
}
/** @test */
public function it_belongs_to_many_terms()
{
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$term = factory(Term::class)->create();
$user->terms()->sync([$term->id => ['account_id' => $account->id]]);
$user = factory(User::class)->create(['account_id' => $account->id]);
$term = factory(Term::class)->create();
$user->terms()->sync([$term->id => ['account_id' => $account->id]]);
$this->assertTrue($user->terms()->exists());
}
/** @test */
public function name_accessor_returns_name_in_the_user_preferred_way()
{
$user = new User;
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->name_order = 'firstname_lastname';
$this->assertEquals(
$user->name,
'John Doe'
);
$user->name_order = 'lastname_firstname';
$this->assertEquals(
$user->name,
'Doe John'
);
}
/** @test */
public function it_gets_2fa_secret_attribute()
{
$user = new User;
$this->assertNull($user->getGoogle2faSecretAttribute(null));
$string = 'pass1234';
$this->assertEquals(
$string,
$user->getGoogle2faSecretAttribute(encrypt($string))
);
}
/** @test */
public function it_gets_fluid_layout()
{
$user = new User;
$user->fluid_container = true;
$this->assertEquals(
'container-fluid',
$user->getFluidLayout()
);
$user->fluid_container = false;
$this->assertEquals(
'container',
$user->getFluidLayout()
);
}
/** @test */
public function it_gets_the_locale()
{
$user = new User;
$user->locale = 'en';
$this->assertEquals(
'en',
$user->locale
);
}
/** @test */
public function user_should_not_be_reminded_because_dates_are_different()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1));
$account = factory(Account::class)->create();
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'initial_date' => '2018-02-01',
]);
$this->assertFalse($user->isTheRightTimeToBeReminded($reminder->initial_date));
}
/** @test */
public function user_should_not_be_reminded_because_hours_are_different()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create(['default_time_reminder_is_sent' => '08:00']);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'initial_date' => '2017-01-01',
]);
$this->assertFalse($user->isTheRightTimeToBeReminded($reminder->initial_date));
}
/** @test */
public function user_should_not_be_reminded_because_timezone_is_different()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 0, 0));
$account = factory(Account::class)->create(['default_time_reminder_is_sent' => '07:00']);
$user = factory(User::class)->create([
'account_id' => $account->id,
'timezone' => 'Europe/Paris',
]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'initial_date' => '2017-01-01',
]);
$this->assertFalse($user->isTheRightTimeToBeReminded($reminder->initial_date));
}
/** @test */
public function user_should_be_reminded()
{
Carbon::setTestNow(Carbon::create(2017, 1, 1, 7, 32, 12));
$account = factory(Account::class)->create(['default_time_reminder_is_sent' => '07:00']);
$user = factory(User::class)->create(['account_id' => $account->id]);
$reminder = factory(Reminder::class)->create([
'account_id' => $account->id,
'initial_date' => '2017-01-01',
]);
$this->assertTrue($user->isTheRightTimeToBeReminded($reminder->initial_date));
}
/** @test */
public function it_creates_default_user_en()
{
App::setLocale('en');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'USD')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'en',
'timezone' => 'America/Chicago',
'currency_id' => $currency->id,
'temperature_scale' => 'fahrenheit',
]);
}
/** @test */
public function it_creates_default_user_fr()
{
App::setLocale('fr');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'EUR')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'fr',
'timezone' => 'Europe/Paris',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_cs()
{
App::setLocale('cs');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'CZK')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'cs',
'timezone' => 'Europe/Prague',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_de()
{
App::setLocale('de');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'EUR')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'de',
'timezone' => 'Europe/Berlin',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_es()
{
App::setLocale('es');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'EUR')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'es',
'timezone' => 'Europe/Madrid',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_he()
{
App::setLocale('he');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'ILS')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'he',
'timezone' => 'Asia/Jerusalem',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_it()
{
App::setLocale('it');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'EUR')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'it',
'timezone' => 'Europe/Rome',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_nl()
{
App::setLocale('nl');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'EUR')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'nl',
'timezone' => 'Europe/Amsterdam',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_pt()
{
App::setLocale('pt');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'EUR')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'pt',
'timezone' => 'Europe/Lisbon',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_ru()
{
App::setLocale('ru');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'RUB')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'ru',
'timezone' => 'Europe/Moscow',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_creates_default_user_zh()
{
App::setLocale('zh');
$account = factory(Account::class)->create([]);
$user = $this->createUser($account->id, 'John', 'Doe', 'john@doe.com', 'password');
$currency = Currency::where('iso', 'CNY')->first();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'account_id' => $account->id,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@doe.com',
'locale' => 'zh',
'timezone' => 'Asia/Shanghai',
'currency_id' => $currency->id,
'temperature_scale' => 'celsius',
]);
}
/** @test */
public function it_sends_a_verification_email()
{
config(['monica.signup_double_optin' => true]);
Notification::fake();
// Creating a fake account
factory(Account::class)->create();
$user = factory(User::class)->create([]);
$user->sendEmailVerificationNotification();
Notification::assertSentTo(
[$user], VerifyEmail::class
);
}
/** @test */
public function it_doesnt_send_a_verification_email_if_the_double_optin_is_disabled_at_the_instance_level()
{
config(['monica.signup_double_optin' => false]);
Notification::fake();
$user = factory(User::class)->create([]);
$user->sendEmailVerificationNotification();
Notification::assertNothingSent();
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace Tests\Unit\Models;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\Weather;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class WeatherTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_belongs_to_an_account()
{
$account = factory(Account::class)->create([]);
$weather = factory(Weather::class)->create([
'account_id' => $account->id,
]);
$this->assertTrue($weather->account()->exists());
}
/** @test */
public function it_belongs_to_a_place()
{
$weather = factory(Weather::class)->create([]);
$this->assertTrue($weather->place()->exists());
}
/** @test */
public function it_gets_current_temperature()
{
$weather = factory(Weather::class)->create();
$this->assertEquals(
13,
$weather->temperature()
);
}
/** @test */
public function it_gets_current_temperature_in_celsius()
{
$weather = factory(Weather::class)->create();
$this->assertEquals(
13,
$weather->temperature('celsius')
);
}
/** @test */
public function it_gets_current_temperature_in_fahrenheit()
{
$weather = factory(Weather::class)->create();
$this->assertEquals(
55.4,
$weather->temperature('fahrenheit')
);
}
/** @test */
public function it_gets_current_summary()
{
$weather = factory(Weather::class)->create();
$this->assertEquals(
'Partly cloudy',
$weather->summary
);
}
/** @test */
public function it_gets_current_code()
{
$weather = factory(Weather::class)->create();
$this->assertEquals(
'partly-cloudy-night',
$weather->summary_code
);
}
/** @test */
public function it_gets_weather_emoji()
{
$weather = factory(Weather::class)->create();
$this->assertEquals(
'🎑',
$weather->emoji
);
}
}

View File

@@ -0,0 +1,249 @@
<?php
namespace Tests\Unit\Services\Account\Activity;
use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\Activity;
use App\Models\Account\ActivityType;
use App\Models\Account\ActivityStatistic;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Services\Account\Activity\ActivityStatisticService;
class ActivityStatisticServiceTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_gets_a_list_of_activities_since_a_given_number_of_months()
{
$service = new ActivityStatisticService;
$contact = factory(Contact::class)->create();
for ($i = 0; $i <= 2; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => now()->subMonth(),
'account_id' => $contact->account_id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
$this->assertCount(
3,
$service->activitiesWithContactInTimeRange($contact, now()->subMonths(2), now())
);
$this->assertInstanceOf(
Activity::class,
$service->activitiesWithContactInTimeRange($contact, now()->subMonths(2), now())[1]
);
}
/** @test */
public function it_gets_an_empty_list_of_activities()
{
$service = new ActivityStatisticService;
$contact = factory(Contact::class)->create();
for ($i = 0; $i <= 2; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => now()->subYears(2),
'account_id' => $contact->account_id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
$this->assertCount(
0,
$service->activitiesWithContactInTimeRange($contact, now()->subMonths(2), now())
);
}
/** @test */
public function it_gets_a_list_of_unique_activity_types()
{
$service = new ActivityStatisticService;
$account = factory(Account::class)->create();
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
// creation of 3 activities with a given activity type
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
for ($i = 0; $i <= 2; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => now(),
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
// creation of 1 activity with a given activity type
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
$activity = factory(Activity::class)->create([
'happened_at' => now(),
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
// here we should have 2 uniques activity types, one with 3 and the other with 1 occurence
$response = $service->uniqueActivityTypesInTimeRange($contact, now()->subMonths(2), now());
$this->assertCount(
2,
$response
);
$this->assertInstanceOf(
ActivityType::class,
$response[0]['object']
);
$this->assertEquals(
3,
$response[0]['occurences']
);
$this->assertInstanceOf(
ActivityType::class,
$response[1]['object']
);
$this->assertEquals(
1,
$response[1]['occurences']
);
}
/** @test */
public function it_gets_the_breakdown_of_activities_per_year()
{
$service = new ActivityStatisticService;
$account = factory(Account::class)->create();
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
for ($i = 0; $i <= 2; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => now()->subYears(2),
'account_id' => $account->id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
for ($i = 0; $i <= 5; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => now(),
'account_id' => $account->id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
$activityStatistic = $contact->activityStatistics()->make();
$activityStatistic->account_id = $contact->account_id;
$activityStatistic->contact_id = $contact->id;
$activityStatistic->year = now()->year;
$activityStatistic->count = 6;
$activityStatistic->save();
$activityStatistic = $contact->activityStatistics()->make();
$activityStatistic->account_id = $contact->account_id;
$activityStatistic->contact_id = $contact->id;
$activityStatistic->year = now()->subYears(2)->year;
$activityStatistic->count = 3;
$activityStatistic->save();
$response = $service->activitiesPerYearWithContact($contact);
$this->assertCount(
2,
$response
);
$this->assertEquals(
6,
$response[0]->count
);
$this->assertEquals(
3,
$response[1]->count
);
$this->assertInstanceOf(
ActivityStatistic::class,
$response[0]
);
}
/** @test */
public function it_gets_a_list_of_activities_per_month_for_given_year()
{
$service = new ActivityStatisticService;
$account = factory(Account::class)->create();
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
Carbon::setTestNow(Carbon::create(2017, 1, 1));
for ($i = 0; $i <= 2; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => '2017-01-02',
'account_id' => $account->id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
for ($i = 0; $i <= 5; $i++) {
$activity = factory(Activity::class)->create([
'happened_at' => '2017-02-01',
'account_id' => $account->id,
]);
$contact->activities()->attach($activity, ['account_id' => $contact->account_id]);
}
$response = $service->activitiesPerMonthForYear($contact, 2017);
$this->assertCount(
12,
$response
);
$this->assertEquals(
1,
$response[0]['month']
);
$this->assertEquals(
3,
$response[0]['occurences']
);
$this->assertEquals(
2,
$response[1]['month']
);
$this->assertEquals(
6,
$response[1]['occurences']
);
$this->assertInstanceOf(
Activity::class,
$response[1]['activities'][0]
);
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Tests\Unit\Services\Account\Activity\ActivityType;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\ActivityType;
use App\Models\Account\ActivityTypeCategory;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\ActivityType\CreateActivityType;
class CreateActivityTypeTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_stores_an_activity_type()
{
$account = factory(Account::class)->create([]);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([
'account_id' => $account->id,
]);
$request = [
'account_id' => $account->id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'central perk',
'translation_key' => 'central_perk',
];
$activityType = app(CreateActivityType::class)->execute($request);
$this->assertDatabaseHas('activity_types', [
'id' => $activityType->id,
'account_id' => $account->id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'central perk',
'translation_key' => 'central_perk',
]);
$this->assertInstanceOf(
ActivityType::class,
$activityType
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$request = [
'name' => '199 Lafayette Street',
];
$this->expectException(ValidationException::class);
app(CreateActivityType::class)->execute($request);
}
/** @test */
public function it_fails_if_activity_type_category_is_not_linked_to_account()
{
$account = factory(Account::class)->create([]);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$request = [
'account_id' => $account->id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'central perk',
'translation_key' => 'central_perk',
];
$this->expectException(ModelNotFoundException::class);
app(CreateActivityType::class)->execute($request);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Tests\Unit\Services\Account\Activity\ActivityType;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\ActivityType;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\ActivityType\DestroyActivityType;
class DestroyActivityTypeTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_destroys_a_activity_type()
{
$activityType = factory(ActivityType::class)->create([]);
$request = [
'account_id' => $activityType->account_id,
'activity_type_id' => $activityType->id,
];
app(DestroyActivityType::class)->execute($request);
$this->assertDatabaseMissing('activity_types', [
'id' => $activityType->id,
]);
}
/** @test */
public function it_throws_an_exception_if_account_is_not_linked_to_activity_type()
{
$account = factory(Account::class)->create([]);
$activityType = factory(ActivityType::class)->create([]);
$request = [
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
];
$this->expectException(ModelNotFoundException::class);
app(DestroyActivityType::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_ids_do_not_exist()
{
$request = [
'account_id' => 11111111,
'activity_type_id' => 11111111,
];
$this->expectException(ValidationException::class);
app(DestroyActivityType::class)->execute($request);
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Tests\Unit\Services\Account\Activity\ActivityType;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\ActivityType;
use App\Models\Account\ActivityTypeCategory;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\ActivityType\UpdateActivityType;
class UpdateActivityTypeTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_updates_an_activity_type()
{
$activityType = factory(ActivityType::class)->create([]);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([
'account_id' => $activityType->account_id,
]);
$request = [
'account_id' => $activityType->account_id,
'activity_type_id' => $activityType->id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'Chandler House',
'translation_key' => 'https://centralperk.com',
];
$activityType = app(UpdateActivityType::class)->execute($request);
$this->assertDatabaseHas('activity_types', [
'id' => $activityType->id,
'account_id' => $activityType->account_id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'Chandler House',
'translation_key' => 'https://centralperk.com',
]);
$this->assertInstanceOf(
ActivityType::class,
$activityType
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$activityType = factory(ActivityType::class)->create([]);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([
'account_id' => $activityType->account_id,
]);
$request = [
'account_id' => $activityType->account_id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'Chandler House',
'translation_key' => 'https://centralperk.com',
];
$this->expectException(ValidationException::class);
app(UpdateActivityType::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_activity_is_not_linked_to_account()
{
$account = factory(Account::class)->create([]);
$activityType = factory(ActivityType::class)->create([]);
$request = [
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
'activity_type_category_id' => $activityType->activity_type_category_id,
'name' => 'Chandler House',
'translation_key' => 'https://centralperk.com',
];
$this->expectException(ModelNotFoundException::class);
app(UpdateActivityType::class)->execute($request);
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Tests\Unit\Services\Account\Activity\ActivityTypeCategory;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\ActivityTypeCategory;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Services\Account\Activity\ActivityTypeCategory\CreateActivityTypeCategory;
class CreateActivityTypeCategoryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_stores_an_activity_type_category()
{
$account = factory(Account::class)->create([]);
$request = [
'account_id' => $account->id,
'name' => 'central perk',
'translation_key' => 'central_perk',
];
$activityTypeCategory = app(CreateActivityTypeCategory::class)->execute($request);
$this->assertDatabaseHas('activity_type_categories', [
'id' => $activityTypeCategory->id,
'account_id' => $account->id,
'name' => 'central perk',
'translation_key' => 'central_perk',
]);
$this->assertInstanceOf(
ActivityTypeCategory::class,
$activityTypeCategory
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$request = [
'name' => '199 Lafayette Street',
];
$this->expectException(ValidationException::class);
app(CreateActivityTypeCategory::class)->execute($request);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Tests\Unit\Services\Account\Activity\ActivityTypeCategory;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\ActivityTypeCategory;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\ActivityTypeCategory\DestroyActivityTypeCategory;
class DestroyActivityTypeCategoryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_destroys_a_activity_type_category()
{
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$request = [
'account_id' => $activityTypeCategory->account_id,
'activity_type_category_id' => $activityTypeCategory->id,
];
app(DestroyActivityTypeCategory::class)->execute($request);
$this->assertDatabaseMissing('activity_type_categories', [
'id' => $activityTypeCategory->id,
]);
}
/** @test */
public function it_throws_an_exception_if_account_is_not_linked_to_activity_type_category()
{
$account = factory(Account::class)->create([]);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$request = [
'account_id' => $account->id,
'activity_type_category_id' => $activityTypeCategory->id,
];
$this->expectException(ModelNotFoundException::class);
app(DestroyActivityTypeCategory::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_ids_do_not_exist()
{
$request = [
'account_id' => 11111111,
'activity_type_category_id' => 11111111,
];
$this->expectException(ValidationException::class);
app(DestroyActivityTypeCategory::class)->execute($request);
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace Tests\Unit\Services\Account\Activity\ActivityTypeCategory;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\ActivityTypeCategory;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\ActivityTypeCategory\UpdateActivityTypeCategory;
class UpdateActivityTypeCategoryTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_updates_a_activity_type_category()
{
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$request = [
'account_id' => $activityTypeCategory->account_id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => 'Chandler House',
'translation_key' => 'https://centralperk.com',
];
$activityTypeCategory = app(UpdateActivityTypeCategory::class)->execute($request);
$this->assertDatabaseHas('activity_type_categories', [
'id' => $activityTypeCategory->id,
'account_id' => $activityTypeCategory->account_id,
'name' => 'Chandler House',
'translation_key' => 'https://centralperk.com',
]);
$this->assertInstanceOf(
ActivityTypeCategory::class,
$activityTypeCategory
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$request = [
'name' => '199 Lafayette Street',
];
$this->expectException(ValidationException::class);
app(UpdateActivityTypeCategory::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_activity_is_not_linked_to_account()
{
$account = factory(Account::class)->create([]);
$activityTypeCategory = factory(ActivityTypeCategory::class)->create([]);
$request = [
'account_id' => $account->id,
'activity_type_category_id' => $activityTypeCategory->id,
'name' => '199 Lafayette Street',
];
$this->expectException(ModelNotFoundException::class);
app(UpdateActivityTypeCategory::class)->execute($request);
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Tests\Unit\Services\Account\Activity;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\Activity;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\Activity\AttachContactToActivity;
class AttachContactToActivityTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_attaches_contacts()
{
$activity = factory(Activity::class)->create([]);
$contactA = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$contactB = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$contactC = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$request = [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contacts' => [$contactA->id, $contactB->id, $contactC->id],
];
$activity = app(AttachContactToActivity::class)->execute($request);
$this->assertDatabaseHas('activity_contact', [
'activity_id' => $activity->id,
'contact_id' => $contactA->id,
'account_id' => $activity->account_id,
]);
$this->assertDatabaseHas('activity_contact', [
'activity_id' => $activity->id,
'contact_id' => $contactB->id,
'account_id' => $activity->account_id,
]);
$this->assertDatabaseHas('activity_contact', [
'activity_id' => $activity->id,
'contact_id' => $contactC->id,
'account_id' => $activity->account_id,
]);
$this->assertInstanceOf(
Activity::class,
$activity
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$activity = factory(Activity::class)->create([]);
$contactA = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$request = [
'activity_id' => $activity->id,
'contacts' => [$contactA->id],
];
$this->expectException(ValidationException::class);
app(AttachContactToActivity::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_contact_is_not_linked_to_account()
{
$activity = factory(Activity::class)->create([]);
$account = factory(Account::class)->create([]);
$contactA = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$request = [
'activity_id' => $activity->id,
'account_id' => $account->id,
'contacts' => [$contactA->id],
];
$this->expectException(ModelNotFoundException::class);
app(AttachContactToActivity::class)->execute($request);
}
}

View File

@@ -0,0 +1,149 @@
<?php
namespace Tests\Unit\Services\Account\Activity;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\Activity;
use App\Models\Account\ActivityType;
use App\Models\Instance\Emotion\Emotion;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\Activity\CreateActivity;
class CreateActivityTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_stores_an_activity_and_creates_an_entry_in_the_journal()
{
$account = factory(Account::class)->create();
$contacts = factory(Contact::class, 3)->create([
'account_id' => $account->id,
]);
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
$request = [
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => $contacts->map(function ($contact) {
return $contact->id;
})->toArray(),
];
$activity = app(CreateActivity::class)->execute($request);
$this->assertDatabaseHas('activities', [
'id' => $activity->id,
'account_id' => $account->id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
]);
foreach ($contacts as $contact) {
$this->assertDatabaseHas('activity_contact', [
'account_id' => $account->id,
'activity_id' => $activity->id,
'contact_id' => $contact->id,
]);
}
$this->assertInstanceOf(
Activity::class,
$activity
);
$this->assertDatabaseHas('journal_entries', [
'account_id' => $account->id,
'journalable_id' => $activity->id,
'journalable_type' => get_class($activity),
]);
}
/** @test */
public function it_adds_emotions()
{
$account = factory(Account::class)->create();
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$emotion = factory(Emotion::class)->create([]);
$emotion2 = factory(Emotion::class)->create([]);
$emotionArray = [];
$emotionArray[] = $emotion->id;
$emotionArray[] = $emotion2->id;
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
$request = [
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'emotions' => $emotionArray,
'contacts' => [$contact->id],
];
$activity = app(CreateActivity::class)->execute($request);
$this->assertDatabaseHas('emotion_activity', [
'account_id' => $account->id,
'activity_id' => $activity->id,
'emotion_id' => $emotion->id,
]);
$this->assertDatabaseHas('emotion_activity', [
'account_id' => $account->id,
'activity_id' => $activity->id,
'emotion_id' => $emotion2->id,
]);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$account = factory(Account::class)->create([]);
$request = [
'account_id' => $account->id,
];
$this->expectException(ValidationException::class);
app(CreateActivity::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_activity_type_is_not_linked_to_account()
{
$account = factory(Account::class)->create([]);
$activityType = factory(ActivityType::class)->create([]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$request = [
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => [$contact->id],
];
$this->expectException(ModelNotFoundException::class);
app(CreateActivity::class)->execute($request);
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace Tests\Unit\Services\Account\Activity;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\Activity;
use App\Models\Account\ActivityType;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Services\Account\Activity\Activity\CreateActivity;
use App\Services\Account\Activity\Activity\DestroyActivity;
class DestroyActivityTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_destroys_a_activity()
{
$activity = factory(Activity::class)->create([]);
$request = [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
];
$this->assertDatabaseHas('activities', [
'id' => $activity->id,
]);
app(DestroyActivity::class)->execute($request);
$this->assertDatabaseMissing('activities', [
'id' => $activity->id,
]);
}
/** @test */
public function it_removes_the_journal_entry_when_destroying_the_activity()
{
$account = factory(Account::class)->create([]);
$activityType = factory(ActivityType::class)->create([
'account_id' => $account->id,
]);
$contact = factory(Contact::class)->create([
'account_id' => $account->id,
]);
$request = [
'account_id' => $account->id,
'activity_type_id' => $activityType->id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => [$contact->id],
];
$activity = app(CreateActivity::class)->execute($request);
$this->assertDatabaseHas('activities', [
'id' => $activity->id,
]);
$this->assertDatabaseHas('activity_contact', [
'activity_id' => $activity->id,
'contact_id' => $contact->id,
]);
$this->assertDatabaseHas('journal_entries', [
'account_id' => $account->id,
'journalable_id' => $activity->id,
'journalable_type' => get_class($activity),
]);
$request = [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
];
app(DestroyActivity::class)->execute($request);
$this->assertDatabaseMissing('activities', [
'id' => $activity->id,
]);
$this->assertDatabaseMissing('activity_contact', [
'activity_id' => $activity->id,
]);
$this->assertDatabaseMissing('journal_entries', [
'account_id' => $account->id,
'journalable_id' => $activity->id,
'journalable_type' => get_class($activity),
]);
}
}

View File

@@ -0,0 +1,191 @@
<?php
namespace Tests\Unit\Services\Account\Activity;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Contact\Contact;
use App\Models\Account\Activity;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use App\Services\Account\Activity\Activity\UpdateActivity;
class UpdateActivityTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_updates_an_activity()
{
$activity = factory(Activity::class)->create([]);
$contact = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$request = [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'activity_type_id' => $activity->activity_type_id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => [$contact->id],
];
app(UpdateActivity::class)->execute($request);
$this->assertDatabaseHas('activities', [
'id' => $activity->id,
'account_id' => $activity->account_id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
]);
$this->assertInstanceOf(
Activity::class,
$activity
);
}
/** @test */
public function it_removes_old_associated_contacts()
{
$activity = factory(Activity::class)->create();
$contacts = factory(Contact::class, 3)->create([
'account_id' => $activity->account_id,
]);
foreach ($contacts as $contact) {
$activity->contacts()->syncWithoutDetaching([$contact->id => [
'account_id' => $activity->account_id,
]]);
}
foreach ($contacts as $contact) {
$this->assertDatabaseHas('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $contact->id,
]);
}
$newContact = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$request = [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'activity_type_id' => $activity->activity_type_id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => [$newContact->id],
];
app(UpdateActivity::class)->execute($request);
$this->assertDatabaseHas('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $newContact->id,
]);
foreach ($contacts as $contact) {
$this->assertDatabaseMissing('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $contact->id,
]);
}
}
/** @test */
public function it_removes_old_associated_contacts_and_keep_previous_one()
{
$activity = factory(Activity::class)->create();
$contacts = factory(Contact::class, 3)->create([
'account_id' => $activity->account_id,
]);
foreach ($contacts as $contact) {
$activity->contacts()->syncWithoutDetaching([$contact->id => [
'account_id' => $activity->account_id,
]]);
}
foreach ($contacts as $contact) {
$this->assertDatabaseHas('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $contact->id,
]);
}
$request = [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'activity_type_id' => $activity->activity_type_id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => [$contacts[0]->id, $contacts[1]->id],
];
app(UpdateActivity::class)->execute($request);
$this->assertDatabaseHas('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $contacts[0]->id,
]);
$this->assertDatabaseHas('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $contacts[1]->id,
]);
$this->assertDatabaseMissing('activity_contact', [
'account_id' => $activity->account_id,
'activity_id' => $activity->id,
'contact_id' => $contacts[2]->id,
]);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$activity = factory(Activity::class)->create([]);
$request = [
'activity_id' => $activity->id,
'activity_type_id' => $activity->activity_type_id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
];
$this->expectException(ValidationException::class);
app(UpdateActivity::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_contact_is_not_linked_to_account()
{
$activity = factory(Activity::class)->create([]);
$account = factory(Account::class)->create([]);
$contact = factory(Contact::class)->create([
'account_id' => $activity->account_id,
]);
$request = [
'account_id' => $account->id,
'activity_id' => $activity->id,
'activity_type_id' => $activity->activity_type_id,
'summary' => 'we went to central perk',
'description' => 'it was awesome',
'happened_at' => '2009-09-09',
'contacts' => [$contact->id],
];
$this->expectException(ModelNotFoundException::class);
app(UpdateActivity::class)->execute($request);
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace Tests\Unit\Services\Account\Company;
use Tests\TestCase;
use App\Models\User\User;
use function Safe\json_encode;
use App\Models\Account\Account;
use App\Models\Account\Company;
use Illuminate\Support\Facades\Queue;
use App\Jobs\AuditLog\LogAccountAudit;
use Illuminate\Validation\ValidationException;
use App\Services\Account\Company\CreateCompany;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CreateCompanyTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_stores_a_company()
{
Queue::fake();
$account = factory(Account::class)->create([]);
$user = factory(User::class)->create([
'account_id' => $account->id,
]);
$request = [
'account_id' => $account->id,
'author_id' => $user->id,
'name' => 'central perk',
'website' => 'https://centralperk.com',
'number_of_employees' => 3,
];
$company = app(CreateCompany::class)->execute($request);
$this->assertDatabaseHas('companies', [
'id' => $company->id,
'account_id' => $account->id,
'name' => 'central perk',
'website' => 'https://centralperk.com',
'number_of_employees' => 3,
]);
$this->assertInstanceOf(
Company::class,
$company
);
Queue::assertPushed(LogAccountAudit::class, function ($job) use ($user) {
return $job->auditLog['action'] === 'company_created' &&
$job->auditLog['author_id'] === $user->id &&
$job->auditLog['about_contact_id'] === null &&
$job->auditLog['should_appear_on_dashboard'] === true &&
$job->auditLog['objects'] === json_encode([
'name' => 'central perk',
]);
});
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$account = factory(Account::class)->create([]);
$request = [
'street' => '199 Lafayette Street',
];
$this->expectException(ValidationException::class);
app(CreateCompany::class)->execute($request);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Tests\Unit\Services\Account\Company;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\Company;
use Illuminate\Validation\ValidationException;
use App\Services\Account\Company\DestroyCompany;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class DestroyCompanyTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_destroys_a_company()
{
$company = factory(Company::class)->create([]);
$request = [
'account_id' => $company->account_id,
'company_id' => $company->id,
];
app(DestroyCompany::class)->execute($request);
$this->assertDatabaseMissing('companies', [
'id' => $company->id,
]);
}
/** @test */
public function it_throws_an_exception_if_account_is_not_linked_to_company()
{
$account = factory(Account::class)->create([]);
$company = factory(Company::class)->create([]);
$request = [
'account_id' => $account->id,
'company_id' => $company->id,
];
$this->expectException(ModelNotFoundException::class);
app(DestroyCompany::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_ids_do_not_exist()
{
$request = [
'account_id' => 11111111,
'company_id' => 11111111,
];
$this->expectException(ValidationException::class);
app(DestroyCompany::class)->execute($request);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Tests\Unit\Services\Account\Company;
use Tests\TestCase;
use App\Models\Account\Account;
use App\Models\Account\Company;
use Illuminate\Validation\ValidationException;
use App\Services\Account\Company\UpdateCompany;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class UpdateCompanyTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_updates_a_company()
{
$company = factory(Company::class)->create([]);
$request = [
'account_id' => $company->account_id,
'company_id' => $company->id,
'name' => 'Chandler House',
'website' => 'https://centralperk.com',
'number_of_employees' => 300,
];
app(UpdateCompany::class)->execute($request);
$this->assertDatabaseHas('companies', [
'id' => $company->id,
'account_id' => $company->account_id,
'name' => 'Chandler House',
'website' => 'https://centralperk.com',
'number_of_employees' => 300,
]);
$this->assertInstanceOf(
Company::class,
$company
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$company = factory(Company::class)->create([]);
$request = [
'name' => '199 Lafayette Street',
];
$this->expectException(ValidationException::class);
app(UpdateCompany::class)->execute($request);
}
/** @test */
public function it_throws_an_exception_if_place_is_not_linked_to_account()
{
$account = factory(Account::class)->create([]);
$company = factory(Company::class)->create([]);
$request = [
'account_id' => $account->id,
'company_id' => $company->id,
'name' => '199 Lafayette Street',
];
$this->expectException(ModelNotFoundException::class);
app(UpdateCompany::class)->execute($request);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Tests\Unit\Services\Account\Gender;
use Tests\TestCase;
use App\Models\Contact\Gender;
use App\Models\Account\Account;
use App\Services\Account\Gender\CreateGender;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CreateGenderTest extends TestCase
{
use DatabaseTransactions;
/** @test */
public function it_stores_a_gender()
{
$account = factory(Account::class)->create([]);
$request = [
'account_id' => $account->id,
'name' => 'man',
'type' => 'M',
];
$gender = app(CreateGender::class)->execute($request);
$this->assertDatabaseHas('genders', [
'id' => $gender->id,
'account_id' => $account->id,
'name' => 'man',
'type' => 'M',
]);
$this->assertInstanceOf(
Gender::class,
$gender
);
}
/** @test */
public function it_fails_if_wrong_parameters_are_given()
{
$account = factory(Account::class)->create([]);
$request = [
'name' => 'man',
'type' => 'X',
];
$this->expectException(ValidationException::class);
app(CreateGender::class)->execute($request);
}
}

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