Completed
Branch master (3fd795)
by Laurens
02:10
created

GeoLocationPerformanceReportTest   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 282
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
c 1
b 0
f 0
lcom 1
cbo 14
dl 0
loc 282
rs 10

15 Methods

Rating   Name   Duplication   Size   Complexity  
A generateSoapFault() 0 14 1
A testGetRequest() 0 19 1
A testSetAggregation() 0 16 1
A testGeoLocationPerformanceReportReturnsArrayWithCsv() 0 13 1
A testGeoLocationPerformanceReportMoveFile() 0 17 1
A testGetRefreshToken() 0 16 1
A testGeoLocationPerformanceReportTimeoutException() 0 13 1
A testGeoLocationPerformanceReportRequestErrorException() 0 13 1
B testPollGenerateReportSoapException() 0 30 1
B getClientProxyMock() 0 29 1
A getFileHelperMock() 0 14 1
A getCsvHelperMock() 0 17 1
A getTimeHelperMock() 0 7 1
A getRequestNewAccessTokenMock() 0 11 1
A getApiClient() 0 7 1
1
<?php
2
namespace Tests\Werkspot\BingAdsApiBundle\Api\Report;
3
4
use BingAds\Bulk\ReportTimePeriod;
5
use BingAds\Proxy\ClientProxy;
6
use BingAds\Reporting\AccountThroughAdGroupReportScope;
7
use BingAds\Reporting\GeoLocationPerformanceReportRequest;
8
use BingAds\Reporting\NonHourlyReportAggregation;
9
use BingAds\Reporting\ReportFormat;
10
use BingAds\Reporting\ReportTime;
11
use Mockery;
12
use PHPUnit_Framework_TestCase;
13
use SoapFault;
14
use stdClass;
15
use Symfony\Component\Filesystem\Filesystem;
16
use Werkspot\BingAdsApiBundle\Api\Client;
17
use Werkspot\BingAdsApiBundle\Api\Exceptions;
18
use Werkspot\BingAdsApiBundle\Api\Helper;
19
use Werkspot\BingAdsApiBundle\Api\Report\GeoLocationPerformanceReport;
20
use Werkspot\BingAdsApiBundle\Guzzle\OauthTokenService;
21
use Werkspot\BingAdsApiBundle\Model\AccessToken;
22
use Werkspot\BingAdsApiBundle\Model\ApiDetails;
23
24
class GeoLocationPerformanceReportTest extends PHPUnit_Framework_TestCase
25
{
26
    const YESTERDAY = 'Yesterday';
27
    const ACCESS_TOKEN = '2ec09aeccaf634d982eec793037e37fe';
28
    const REFRESH_TOKEN = '0c59f7e609b0cc467067e39d523116ce';
29
30
    public function testGetRequest()
31
    {
32
        $expected = new GeoLocationPerformanceReportRequest();
33
        $expected->Format = ReportFormat::Csv;
34
        $expected->ReportName = GeoLocationPerformanceReport::NAME;
35
        $expected->ReturnOnlyCompleteData = true;
36
        $expected->Aggregation = NonHourlyReportAggregation::Daily;
37
        $expected->Scope = new AccountThroughAdGroupReportScope();
38
        $expected->Time = new ReportTime();
39
        $expected->Time->PredefinedTime = self::YESTERDAY;
40
        $expected->Columns = [];
41
42
        $report = new GeoLocationPerformanceReport();
43
        $report->setTimePeriod(self::YESTERDAY);
44
        $report->setColumns([]);
45
        $result = $report->getRequest();
46
47
        $this->assertEquals($expected, $result);
48
    }
49
50
    public function testSetAggregation()
51
    {
52
        $report = new GeoLocationPerformanceReport();
53
54
        $report->setTimePeriod(self::YESTERDAY);
55
        $report->setColumns([]);
56
        $result = $report->getRequest();
57
        $this->assertEquals(NonHourlyReportAggregation::Daily, $result->Aggregation);
58
59
        $report->setAggregation(NonHourlyReportAggregation::Monthly);
60
        $report->setTimePeriod(self::YESTERDAY);
61
        $report->setColumns([]);
62
        $result = $report->getRequest();
63
64
        $this->assertEquals(NonHourlyReportAggregation::Monthly, $result->Aggregation);
65
    }
66
67
    public function testGeoLocationPerformanceReportReturnsArrayWithCsv()
68
    {
69
        $apiClient = $this->getApiClient(
70
            $this->getRequestNewAccessTokenMock(),
71
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
72
            $this->getClientProxyMock(),
73
            $this->getFileHelperMock(),
74
            $this->getCsvHelperMock(),
75
            $this->getTimeHelperMock()
76
        );
77
        $result = $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport', ReportTimePeriod::LastWeek);
78
        $this->assertEquals([ASSETS_DIR . 'report.csv'], $result);
79
    }
80
81
    public function testGeoLocationPerformanceReportMoveFile()
82
    {
83
        $apiClient = $this->getApiClient(
84
            $this->getRequestNewAccessTokenMock(),
85
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
86
            $this->getClientProxyMock(),
87
            $this->getFileHelperMock(),
88
            $this->getCsvHelperMock(),
89
            $this->getTimeHelperMock()
90
        );
91
        $result = $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport', ReportTimePeriod::LastWeek, ASSETS_DIR . 'test.csv');
92
        $this->assertEquals(ASSETS_DIR . 'test.csv', $result);
93
94
        //--Move File back
95
        $fileSystem = new Filesystem();
96
        $fileSystem->rename(ASSETS_DIR . 'test.csv', ASSETS_DIR . 'report.csv');
97
    }
98
99
    public function testGetRefreshToken()
100
    {
101
        $apiClient = $this->getApiClient(
102
            $this->getRequestNewAccessTokenMock(),
103
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
104
            $this->getClientProxyMock(),
105
            $this->getFileHelperMock(),
106
            $this->getCsvHelperMock(),
107
            $this->getTimeHelperMock()
108
        );
109
110
        $this->assertEquals('refreshToken', $apiClient->getRefreshToken());
111
112
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport', ReportTimePeriod::LastWeek);
113
        $this->assertEquals(self::REFRESH_TOKEN, $apiClient->getRefreshToken());
114
    }
115
116
    public function testGeoLocationPerformanceReportTimeoutException()
117
    {
118
        $this->expectException(Exceptions\RequestTimeoutException::class);
119
        $apiClient = $this->getApiClient(
120
            $this->getRequestNewAccessTokenMock(),
121
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
122
            $this->getClientProxyMock('Pending'),
123
            new Helper\File(),
124
            new Helper\Csv(),
125
            $this->getTimeHelperMock()
126
        );
127
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport');
128
    }
129
130
    public function testGeoLocationPerformanceReportRequestErrorException()
131
    {
132
        $this->expectException(Exceptions\ReportRequestErrorException::class);
133
        $apiClient = $this->getApiClient(
134
            $this->getRequestNewAccessTokenMock(),
135
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
136
            $this->getClientProxyMock('Error'),
137
            new Helper\File(),
138
            new Helper\Csv(),
139
            $this->getTimeHelperMock()
140
        );
141
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport');
142
    }
143
144
    public function testPollGenerateReportSoapException()
145
    {
146
        $clientProxyMock = Mockery::mock(ClientProxy::class);
147
        $clientProxyMock->ReportRequestId = 'reportID';
148
        $clientProxyMock
149
            ->shouldReceive('ConstructWithCredentials')
150
            ->andReturnSelf()
151
            ->once()
152
            ->shouldReceive('GetNamespace')
153
            ->once()
154
            ->andReturn('Namespace')
155
            ->shouldReceive('GetService')
156
            ->twice()
157
            ->andReturnSelf()
158
            ->shouldReceive('SubmitGenerateReport')
159
            ->once()
160
            ->andReturnSelf()
161
            ->shouldReceive('PollGenerateReport')
162
            ->andThrow($this->generateSoapFault(0));
163
        $this->expectException(Exceptions\SoapInternalErrorException::class);
164
        $apiClient = $this->getApiClient(
165
            $this->getRequestNewAccessTokenMock(),
166
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
167
            $clientProxyMock,
168
            new Helper\File(),
169
            new Helper\Csv(),
170
            $this->getTimeHelperMock()
171
        );
172
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport');
173
    }
174
    /**
175
     * @return Mockery\MockInterface
176
     */
177
    private function getClientProxyMock($reportStatus = 'Success')
178
    {
179
        $clientProxyMock = Mockery::mock(ClientProxy::class);
180
        $clientProxyMock
181
            ->shouldReceive('ConstructWithCredentials')
182
            ->andReturnSelf()
183
            ->once()
184
            ->shouldReceive('GetNamespace')
185
            ->between(1, 48)
186
            ->andReturn('Namespace')
187
            ->shouldReceive('GetService')
188
            ->between(2, 49)
189
            ->andReturnSelf()
190
            ->shouldReceive('SubmitGenerateReport')
191
            ->between(1, 48)
192
            ->andReturnSelf()
193
            ->shouldReceive('PollGenerateReport')
194
            ->between(1, 48)
195
            ->andReturnSelf();
196
197
        $status = new \stdClass();
198
        $status->Status = $reportStatus;
199
        $status->ReportDownloadUrl = 'http://example.com/download.zip';
200
201
        $clientProxyMock->ReportRequestId = 'reportID';
202
        $clientProxyMock->ReportRequestStatus = $status;
203
204
        return $clientProxyMock;
205
    }
206
207
    /**
208
     * @return Mockery\MockInterface
209
     */
210
    private function getRequestNewAccessTokenMock()
211
    {
212
        $oauthTokenServiceMock = Mockery::mock(OauthTokenService::class);
213
        $oauthTokenServiceMock
214
            ->shouldReceive('refreshToken')
215
            ->with('clientId', 'clientSecret', 'redirectUri', AccessToken::class)
216
            ->once()
217
            ->andReturn(new AccessToken(self::ACCESS_TOKEN, self::REFRESH_TOKEN));
218
219
        return $oauthTokenServiceMock;
220
    }
221
222
    /**
223
     * @return Mockery\MockInterface
224
     */
225
    private function getFileHelperMock()
226
    {
227
        $zipHelperMock = Mockery::mock(Helper\File::class);
228
        $zipHelperMock
229
            ->shouldReceive('getFile')
230
            ->andReturn('/tmp/report.zip')
231
            ->once()
232
            ->shouldReceive('unZip')
233
            ->with('/tmp/report.zip')
234
            ->andReturn([ASSETS_DIR . 'report.csv'])
235
            ->once();
236
237
        return $zipHelperMock;
238
    }
239
240
    /**
241
     * @return Mockery\MockInterface
242
     */
243
    private function getCsvHelperMock()
244
    {
245
        $lines = file(ASSETS_DIR . 'report.csv');
246
        $csvHelperMock = Mockery::mock(Helper\Csv::class);
247
        $csvHelperMock
248
            ->shouldReceive('removeHeaders')
249
            ->andReturn($lines)
250
            ->once()
251
            ->shouldReceive('removeLastLines')
252
            ->andReturn($lines)
253
            ->once()
254
            ->shouldReceive('convertDateMDYtoYMD')
255
            ->andReturn($lines)
256
            ->once();
257
258
        return $csvHelperMock;
259
    }
260
261
    private function getTimeHelperMock()
262
    {
263
        $timeHelperMock = Mockery::mock(Helper\Time::class);
264
        $timeHelperMock->shouldReceive('sleep')->andReturnNull();
265
266
        return $timeHelperMock;
267
    }
268
269
    /**
270
     * @param OauthTokenService $requestNewAccessToken
271
     * @param ClientProxy $clientProxy
272
     * @param Helper\File $fileHelper
273
     * @param Helper\Csv $csvHelper
274
     * @param Helper\Time $timeHelper
275
     *
276
     * @return Client
277
     */
278
    private function getApiClient(OauthTokenService $requestNewAccessToken, ApiDetails $apiDetails, ClientProxy $clientProxy, Helper\File $fileHelper, Helper\Csv $csvHelper, Helper\Time $timeHelper)
279
    {
280
        $apiClient = new Client($requestNewAccessToken, $apiDetails, $clientProxy, $fileHelper, $csvHelper, $timeHelper);
281
        $apiClient->setConfig(['cache_dir' => '/tmp']);
282
283
        return $apiClient;
284
    }
285
286
    /**
287
     * @param $code
288
     *
289
     * @return SoapFault
290
     */
291
    private function generateSoapFault($code)
292
    {
293
        $message = "an error message {$code}";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $code instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
294
        $error = new stdClass();
295
        $error->Code = $code;
296
        $error->Message = $message;
297
        $exception = new SoapFault('Server', '');
298
        $exception->detail = new stdClass();
299
        $exception->detail->AdApiFaultDetail = new stdClass();
300
        $exception->detail->AdApiFaultDetail->Errors = new stdClass();
301
        $exception->detail->AdApiFaultDetail->Errors->AdApiError = [$error];
302
303
        return $exception;
304
    }
305
}
306