Skip to content

Commit

Permalink
Working Unit Test
Browse files Browse the repository at this point in the history
  • Loading branch information
Karl DeBisschop committed Nov 26, 2020
1 parent 9eb060a commit 0297768
Show file tree
Hide file tree
Showing 3 changed files with 169 additions and 84 deletions.
38 changes: 6 additions & 32 deletions src/Extractors/GoogleAnalytics.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,9 @@ public function extract(): \Generator
}

$request = $this->reportRequest($profileSummary->getId());
$reports = $this->reportingService->reports->batchGet($request);

$response = $this->reportingService->reports->batchGet($request);
/** @var \Google_Service_AnalyticsReporting_Report $report */
foreach ($reports as $report) {
foreach ($response as $report) {
$this->setHeaders($report);
$rows = $report->getData()->getRows();
foreach ($rows as $row) {
Expand Down Expand Up @@ -315,36 +314,11 @@ public function reportRequest(string $viewId): \Google_Service_AnalyticsReportin
public function reportRequestSetup(array $dimensions, array $metrics, string $start, string $end): void
{
$this->reportRequest = new \Google_Service_AnalyticsReporting_ReportRequest();

$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($start);
$dateRange->setEndDate($end);
$this->reportRequest->setDateRanges($dateRange);

// Max 7 dimensions.
$array = [];
foreach ($dimensions as $dimension) {
$reportDimension = new \Google_Service_AnalyticsReporting_Dimension();
$reportDimension->setName($dimension);
$array[] = $reportDimension;
}
$this->reportRequest->setDimensions($array);

$this->reportRequest->setDateRanges(Helper::dateRange($start, $end));
$this->reportRequest->setDimensions(Helper::dimensions($dimensions));
$this->reportRequest->setDimensionFilterClauses([]);

// At least one metric required, max 10.
$array = [];
foreach ($metrics as $metric) {
$reportingMetric = new \Google_Service_AnalyticsReporting_Metric();
$reportingMetric->setExpression($metric['name']);
$reportingMetric->setAlias(str_replace('ga:', '', $metric['name']));
$reportingMetric->setFormattingType($metric['type']);
$array[] = $reportingMetric;
}
$this->reportRequest->setMetrics($array);

$this->reportRequest->setPageSize(self::REPORT_PAGE_SIZE);

$this->reportRequest->setMetrics(Helper::metrics($metrics));
$this->reportRequest->setPageSize(Helper::REPORT_PAGE_SIZE);
$this->reportRequest->setIncludeEmptyRows(true);
}

Expand Down
56 changes: 56 additions & 0 deletions src/Extractors/Helper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/**
* @author Karl DeBisschop <kdebisschop@gmail.com>
* @copyright Copyright (c) Karl DeBisschop
* @license MIT
*/

declare(strict_types=1);

namespace PhpEtl\GoogleAnalytics\Extractors;

/**
* Provides some static methods that can be used to in Extractor code and in tests.
*/
class Helper
{
public const REPORT_PAGE_SIZE = 1000;

public static function metrics(array $metrics): array
{
// At least one metric required, max 10.
$array = [];
foreach ($metrics as $metric) {
$reportingMetric = new \Google_Service_AnalyticsReporting_Metric();
$reportingMetric->setExpression($metric['name']);
$reportingMetric->setAlias(str_replace('ga:', '', $metric['name']));
$reportingMetric->setFormattingType($metric['type']);
$array[] = $reportingMetric;
}

return $array;
}

public static function dateRange(string $start, string $end): \Google_Service_AnalyticsReporting_DateRange
{
$dateRange = new \Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($start);
$dateRange->setEndDate($end);

return $dateRange;
}

public static function dimensions(array $dimensions): array
{
// Max 7 dimensions.
$array = [];
foreach ($dimensions as $dimension) {
$reportDimension = new \Google_Service_AnalyticsReporting_Dimension();
$reportDimension->setName($dimension);
$array[] = $reportDimension;
}

return $array;
}
}
159 changes: 107 additions & 52 deletions tests/Extractors/GoogleAnalyticsTest.php
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
<?php

/**
* @author Wizacha DevTeam <dev@wizacha.com>
* @copyright Copyright (c) Wizacha
* @copyright Copyright (c) Leonardo Marquine
* @author Karl DeBisschop <kdebisschop@gmail.com>
* @copyright Copyright (c) Karl DeBisschop
* @license MIT
*/

declare(strict_types=1);

namespace PhpEtl\GoogleAnalytics\Tests\Extractors;

use Google_Service_AnalyticsReporting_GetReportsResponse as GetReportsResponse;
use PhpEtl\GoogleAnalytics\Extractors\GoogleAnalytics;
use PhpEtl\GoogleAnalytics\Tests\TestCase;
use Wizaplace\Etl\Row;

/**
* Tests GoogleAnalytics.
Expand All @@ -25,17 +24,104 @@ class GoogleAnalyticsTest extends TestCase
protected array $options = [
'startDate' => '2010-11-11',
'dimensions' => ['ga:date'],
'metrics' => [['name' => 'ga:pageviews', 'type' => 'INTEGER']],
'metrics' => [
['name' => 'ga:pageviews', 'type' => 'INTEGER'],
['name' => 'ga:avgPageLoadTime', 'type' => 'FLOAT'],
['name' => 'ga:avgSessionDuration', 'type' => 'TIME'],
],
];

private array $dimensionHeaders;

protected function setUp(): void
{
parent::setUp();
$this->dimensionHeaders = $this->options['dimensions'];
}

/** @test */
public function defaultOptions(): void
{
$expected = [
new Row(['id' => '1', 'name' => 'John Doe', 'email' => 'johndoe@email.com']),
new Row(['id' => '2', 'name' => 'Jane Doe', 'email' => 'janedoe@email.com']),
[
'ga:date' => '2020-11-11',
'ga:pageviews' => 2,
'ga:avgPageLoadTime' => 2.2,
'ga:avgSessionDuration' => 2200,
'property' => 'www.example.com',
'summary' => 'All Data',
],
[
'ga:date' => '2020-11-12',
'ga:pageviews' => 3,
'ga:avgPageLoadTime' => 3.3,
'ga:avgSessionDuration' => 3300,
'property' => 'www.example.com',
'summary' => 'All Data',
],
[
'ga:date' => '2020-11-13',
'ga:pageviews' => 5,
'ga:avgPageLoadTime' => 5.5,
'ga:avgSessionDuration' => 5500,
'property' => 'www.example.com',
'summary' => 'All Data',
],
];
$extractor = new GoogleAnalytics();
$extractor->input($this->input);
$extractor->options($this->options);
$extractor->setAnalyticsSvc($this->mockAnalyticsService())
->setReportingSvc($this->mockReportingService($this->mockReportResponse()));

$i = 0;
/** @var \Wizaplace\Etl\Row $row */
foreach ($extractor->extract() as $row) {
static::assertEquals($expected[$i++], ($row->toArray()));
}
}

private function mockReportRow(array $dimensions, array $values): \Google_Service_AnalyticsReporting_ReportRow
{
$row = new \Google_Service_AnalyticsReporting_ReportRow();
$row->setDimensions($dimensions);
$metrics = new \Google_Service_AnalyticsReporting_DateRangeValues();
$metrics->setValues($values);
$row->setMetrics([$metrics]);

return $row;
}

private function mockReport(): \Google_Service_AnalyticsReporting_Report
{
$report = new \Google_Service_AnalyticsReporting_Report();
$reportData = new \Google_Service_AnalyticsReporting_ReportData();
$rows = [
$this->mockReportRow(['2020-11-11'], [2, 2.2, 2200]),
$this->mockReportRow(['2020-11-12'], [3, 3.3, 3300]),
$this->mockReportRow(['2020-11-13'], [5, 5.5, 5500]),
];
$reportData->setRows($rows);
$report->setData($reportData);
$columnHeader = new \Google_Service_AnalyticsReporting_ColumnHeader();
$columnHeader->setDimensions($this->dimensionHeaders);
$metricHeader = new \Google_Service_AnalyticsReporting_MetricHeader();
$metricHeaderEntries = [];
foreach ($this->options['metrics'] as $metric) {
$metricHeaderEntry = new \Google_Service_AnalyticsReporting_MetricHeaderEntry();
$metricHeaderEntry->setName($metric['name']);
$metricHeaderEntry->setType($metric['type']);
$metricHeaderEntries[] = $metricHeaderEntry;
}
$metricHeader->setMetricHeaderEntries($metricHeaderEntries);
$columnHeader->setMetricHeader($metricHeader);
$report->setColumnHeader($columnHeader);

return $report;
}

private function mockAnalyticsService(): \Google_Service_Analytics
{
$profile = $this->prophesize(\Google_Service_Analytics_ProfileSummary::class);
$profile->getId()->willReturn('12345');
$profile->getName()->willReturn('All Data');
Expand All @@ -56,57 +142,26 @@ public function defaultOptions(): void
$analyticsService = $this->prophesize(\Google_Service_Analytics::class);
$analyticsService->management_accountSummaries = $mgmtAcctSummary->reveal();

$extractor = new GoogleAnalytics();
$extractor->input($this->input);
$extractor->options($this->options);
$extractor->reportRequestSetup(
$this->options['dimensions'],
$this->options['metrics'],
$this->options['startDate'],
date('Y-m-d', strtotime('-1 day'))
);

$resourceReports = $this->prophesize(\Google_Service_AnalyticsReporting_Resource_Reports::class);
$reportRequest = $extractor->reportRequest('default');
print_r($reportRequest);
$resourceReports->batchGet($reportRequest)->shouldBeCalled()->willReturn($this->getReportsResponse());

$reportingService = $this->prophesize(\Google_Service_AnalyticsReporting::class);
$reportingService->reports = $resourceReports->reveal();

$extractor->setAnalyticsSvc($analyticsService->reveal())
->setReportingSvc($reportingService->reveal());

static::assertEquals($expected, iterator_to_array($extractor->extract()));
return $analyticsService->reveal();
}

private function getReportsResponse(): \Google_Service_AnalyticsReporting_GetReportsResponse
private function mockReportResponse(): GetReportsResponse
{
$columnHeader = new \Google_Service_AnalyticsReporting_ColumnHeader();
$columnHeader->setDimensions(['ga:date']);
$headerEntry = new \Google_Service_AnalyticsReporting_MetricHeaderEntry();
$headerEntry->setName('ga:pageviews');
$headerEntry->setType('INTEGER');
$header = new \Google_Service_AnalyticsReporting_MetricHeader();
$header->setMetricHeaderEntries([$headerEntry]);
$columnHeader->setMetricHeader($header);

$row = $this->prophesize(\Google_Service_AnalyticsReporting_ReportRow::class);
$row->getDimensions()->willReturn(['2020-11-11']);
$metrics = new \Google_Service_AnalyticsReporting_DateRangeValues();
$metrics->setValues(100);
$row->getMetrics()->willReturn([$metrics]);
$response = new GetReportsResponse();
$response->setReports([$this->mockReport()]);

$reportData = $this->prophesize(\Google_Service_AnalyticsReporting_ReportData::class);
$reportData->getRows()->willReturn([$row->reveal()]);
return $response;
}

$report = $this->prophesize(\Google_Service_AnalyticsReporting_Report::class);
$report->getColumnHeader()->willReturn();
$report->getData()->willReturn();
private function mockReportingService(GetReportsResponse $response): \Google_Service_AnalyticsReporting
{
$mock = $this->createMock(\Google_Service_AnalyticsReporting_Resource_Reports::class);
$mock->method('batchGet')->willReturn($response);

$getRptsResponse = $this->prophesize(\Google_Service_AnalyticsReporting_GetReportsResponse::class);
$getRptsResponse->getReports()->willReturn([$report->reveal()]);
$client = $this->prophesize(\Google_Client::class);
$reportingService = new \Google_Service_AnalyticsReporting($client->reveal());
$reportingService->reports = $mock;

return $getRptsResponse->reveal();
return $reportingService;
}
}

0 comments on commit 0297768

Please sign in to comment.