Skip to content

Commit

Permalink
✅ add multiple tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Rigsto committed Jul 31, 2023
1 parent 47572ec commit 404e3c5
Show file tree
Hide file tree
Showing 9 changed files with 284 additions and 35 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Dipantry

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
},
"autoload-dev": {
"psr-4": {
"Dipantry\\Rajaongkir\\Tests\\": "tests/"
"Dipantry\\Analytics\\Tests\\": "tests/"
}
},
"minimum-stability": "dev",
Expand Down
12 changes: 12 additions & 0 deletions config/analytics_testing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

use Dipantry\Analytics\RequestSessionProvider;

return [
'table_prefix' => 'analytics_',
'ignoreRobots' => false,
'mask' => [],
'session' => [
'provider' => RequestSessionProvider::class,
]
];
22 changes: 22 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
verbose="true">

<testsuites>
<testsuite name="Feature">
<directory>./tests/Feature</directory>
</testsuite>
<testsuite name="Unit">
<directory>./tests/Unit</directory>
</testsuite>
</testsuites>

<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./src</directory>
</include>
</coverage>
</phpunit>
52 changes: 38 additions & 14 deletions src/Agent.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,49 @@

use Detection\MobileDetect;
use Dipantry\Analytics\Traits\Devices;
use Jaybizzle\CrawlerDetect\CrawlerDetect;

class Agent extends MobileDetect
{
use Devices;

/**
* @var CrawlerDetect
*/
protected static CrawlerDetect $crawlerDetect;

public function __construct(array $headers = null, $userAgent = null)
{
parent::__construct($headers, $userAgent);
static::$crawlerDetect = new CrawlerDetect();
}

/**
* @inheritdoc
*/
public function __call($name, $arguments)
{
// Make sure the name starts with `is`, otherwise
if (!str_starts_with($name, 'is')) {
throw new \BadMethodCallException("No such method exists: $name");
}

$key = substr($name, 2);
$this->matchUAAgainstKey($key);
}

/**
* @return CrawlerDetect
*/
public function getCrawlerDetect(): CrawlerDetect
{
if (static::$crawlerDetect === null) {
static::$crawlerDetect = new CrawlerDetect();
}

return static::$crawlerDetect;
}

/**
* Get accept languages
*
Expand Down Expand Up @@ -227,18 +265,4 @@ public function version($propertyName, $type = self::VERSION_TYPE_STRING): float

return false;
}

/**
* @inheritdoc
*/
public function __call($name, $arguments)
{
// Make sure the name starts with `is`, otherwise
if (!str_starts_with($name, 'is')) {
throw new \BadMethodCallException("No such method exists: $name");
}

$key = substr($name, 2);
$this->matchUAAgainstKey($key);
}
}
20 changes: 0 additions & 20 deletions src/Traits/Devices.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Dipantry\Analytics\Traits;

use Jaybizzle\CrawlerDetect\CrawlerDetect;

trait Devices
{
/**
Expand Down Expand Up @@ -90,12 +88,6 @@ trait Devices
'Watch' => 'SM-V700',
);


/**
* @var CrawlerDetect
*/
protected static CrawlerDetect $crawlerDetect;

public static function getBrowsers(): array
{
return static::mergeRules(
Expand Down Expand Up @@ -181,16 +173,4 @@ public static function mergeRules(...$all): array

return $merged;
}

/**
* @return CrawlerDetect
*/
public function getCrawlerDetect(): CrawlerDetect
{
if (static::$crawlerDetect === null) {
static::$crawlerDetect = new CrawlerDetect();
}

return static::$crawlerDetect;
}
}
52 changes: 52 additions & 0 deletions tests/FakeServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace Dipantry\Analytics\Tests;

use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;

class FakeServiceProvider extends ServiceProvider
{
public function register()
{
parent::register();
}

public function boot()
{
$this->mergeConfigFrom(
__DIR__ . '/../config/analytics.php',
'analytics',
);
$this->mergeConfigFrom(
__DIR__ . '/../config/analytics_testing.php',
'analytics_testing',
);

$databasePath = __DIR__ . '/../database/migrations';
if ($this->isLumen()) {
$this->loadMigrationsFrom($databasePath);
} else {
$this->publishes(
[$databasePath => database_path('migrations')],
'migrations'
);
}

if (class_exists(Application::class)) {
$this->publishes([
__DIR__ . '/../config/analytics.php' => config_path('analytics.php'),
], 'config');
}
}

protected function isLumen(): bool
{
return !$this->isLaravel();
}

protected function isLaravel(): bool
{
return app() instanceof Application;
}
}
106 changes: 106 additions & 0 deletions tests/Feature/AnalyticsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

namespace Dipantry\Analytics\Tests\Feature;

use Dipantry\Analytics\Http\Middleware\Analytics;
use Dipantry\Analytics\Models\PageView;
use Dipantry\Analytics\Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

class AnalyticsTest extends TestCase
{
use RefreshDatabase;

/** @test */
public function a_page_view_can_be_tracked()
{
$request = Request::create('/test');
$request->setLaravelSession($this->app['session']->driver());

(new Analytics())->handle($request, function ($req) {
$this->assertEquals('test', $req->path());
$this->assertEquals('GET', $req->method());
});

$this->assertCount(1, PageView::all());
$this->assertDatabaseHas('page_views', [
'uri' => '/test',
'device' => 'desktop',
]);
}

/** @test */
public function a_page_view_can_be_masked()
{
$request = Request::create('/test/123', 'GET');
$request->setLaravelSession($this->app['session']->driver());

(new Analytics())->handle($request, function ($req) {
$this->assertEquals('test/123', $req->path());
$this->assertEquals('GET', $req->method());
});

$this->assertCount(1, PageView::all());
$this->assertDatabaseHas('page_views', [
'uri' => '/test/∗︎',
'device' => 'desktop',
]);
}

/** @test */
public function a_page_view_can_be_excluded()
{
$request = Request::create('/analytics/123', 'GET');
$request->setLaravelSession($this->app['session']->driver());

(new Analytics())->handle($request, fn($req) => null);

$this->assertCount(0, PageView::all());
$this->assertDatabaseMissing('page_views', [
'uri' => '/analytics/123',
]);
}

/** @test */
public function a_page_view_from_robot_can_be_tracked_if_enabled()
{
Config::set('analytics.ignoreRobots', false);

$request = Request::create('/test', 'GET');
$request->headers->set('User-Middleware', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
$request->setLaravelSession($this->app['session']->driver());

(new Analytics())->handle($request, function ($req) {
$this->assertEquals('test', $req->path());
$this->assertEquals('GET', $req->method());
});

$this->assertCount(1, PageView::all());
$this->assertDatabaseHas('page_views', [
'uri' => '/test',
'device' => 'robot',
]);
}

/** @test */
public function a_page_view_from_robot_is_not_tracked_if_enabled()
{
Config::set('analytics.ignoreRobots', true);

$request = Request::create('/test', 'GET');
$request->headers->set('User-Middleware', 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)');
$request->setLaravelSession($this->app['session']->driver());

(new Analytics())->handle($request, function ($req) {
$this->assertEquals('test', $req->path());
$this->assertEquals('GET', $req->method());
});

$this->assertCount(0, PageView::all());
$this->assertDatabaseMissing('page_views', [
'uri' => '/test',
]);
}
}
32 changes: 32 additions & 0 deletions tests/TestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Dipantry\Analytics\Tests;

class TestCase extends \Orchestra\Testbench\TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
}

protected function getPackageProviders($app): array
{
return [
FakeServiceProvider::class,
];
}

protected function getEnvironmentSetUp($app): void
{
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => 'analytics_',
]);
$app['config']->set('analytics.mask', [
'/test/*',
]);
}
}

0 comments on commit 404e3c5

Please sign in to comment.