Completed
Pull Request — master (#4)
by Laurens
02:47
created

testGetRefreshToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 16
rs 9.4285
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
namespace Tests\Werkspot\BingAdsApiBundle\Tests\Api\Report;
4
5
use BingAds\Bulk\ReportTimePeriod;
6
use BingAds\Proxy\ClientProxy;
7
use BingAds\Reporting\AccountThroughAdGroupReportScope;
8
use BingAds\Reporting\GeoLocationPerformanceReportRequest;
9
use BingAds\Reporting\NonHourlyReportAggregation;
10
use BingAds\Reporting\ReportFormat;
11
use BingAds\Reporting\ReportTime;
12
use Mockery;
13
use PHPUnit_Framework_TestCase;
14
use Symfony\Component\Filesystem\Filesystem;
15
use stdClass;
16
use SoapFault;
17
use Werkspot\BingAdsApiBundle\Api\Client;
18
use Werkspot\BingAdsApiBundle\Api\Exceptions;
19
use Werkspot\BingAdsApiBundle\Api\Helper;
20
use Werkspot\BingAdsApiBundle\Api\Report\GeoLocationPerformanceReport;
21
use Werkspot\BingAdsApiBundle\Guzzle\OauthTokenService;
22
use Werkspot\BingAdsApiBundle\Model\AccessToken;
23
use Werkspot\BingAdsApiBundle\Model\ApiDetails;
24
25
class GeoLocationPerformanceReportTest extends PHPUnit_Framework_TestCase
26
{
27
    const YESTERDAY = 'Yesterday';
28
    const ACCESS_TOKEN = '2ec09aeccaf634d982eec793037e37fe';
29
    const REFRESH_TOKEN = '0c59f7e609b0cc467067e39d523116ce';
30
31
    public function testGetRequest()
32
    {
33
        $expected = new GeoLocationPerformanceReportRequest();
34
        $expected->Format = ReportFormat::Csv;
35
        $expected->ReportName = GeoLocationPerformanceReport::NAME;
36
        $expected->ReturnOnlyCompleteData = true;
37
        $expected->Aggregation = NonHourlyReportAggregation::Daily;
38
        $expected->Scope = new AccountThroughAdGroupReportScope();
39
        $expected->Time = new ReportTime();
40
        $expected->Time->PredefinedTime = self::YESTERDAY;
1 ignored issue
show
Documentation Bug introduced by
It seems like self::YESTERDAY of type string is incompatible with the declared type object<BingAds\Reporting\ReportTimePeriod> of property $PredefinedTime.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
41
        $expected->Columns = [];
42
43
        $report = new GeoLocationPerformanceReport();
44
        $result = $report->getRequest([], self::YESTERDAY);
45
46
        $this->assertEquals($expected, $result);
47
    }
48
49
    public function testSetAggregation()
50
    {
51
        $report = new GeoLocationPerformanceReport();
52
53
        $result = $report->getRequest([], self::YESTERDAY);
54
        $this->assertEquals(NonHourlyReportAggregation::Daily, $result->Aggregation);
0 ignored issues
show
Bug introduced by
The property Aggregation does not seem to exist in BingAds\Reporting\ReportRequest.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
55
56
        $report->setAggregation(NonHourlyReportAggregation::Monthly);
57
        $result = $report->getRequest([], self::YESTERDAY);
58
59
        $this->assertEquals(NonHourlyReportAggregation::Monthly, $result->Aggregation);
60
    }
61
62
    public function testGeoLocationPerformanceReportReturnsArrayWithCsv()
63
    {
64
        $apiClient = $this->getApiClient(
65
            $this->getRequestNewAccessTokenMock(),
66
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
67
            $this->getClientProxyMock(),
68
            $this->getFileHelperMock(),
69
            $this->getCsvHelperMock(),
70
            $this->getTimeHelperMock()
71
        );
72
        $result = $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport', ReportTimePeriod::LastWeek);
73
        $this->assertEquals([ASSETS_DIR . 'report.csv'], $result);
74
    }
75
76
    public function testGeoLocationPerformanceReportMoveFile()
77
    {
78
        $apiClient = $this->getApiClient(
79
            $this->getRequestNewAccessTokenMock(),
80
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
81
            $this->getClientProxyMock(),
82
            $this->getFileHelperMock(),
83
            $this->getCsvHelperMock(),
84
            $this->getTimeHelperMock()
85
        );
86
        $result = $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport', ReportTimePeriod::LastWeek, ASSETS_DIR . 'test.csv');
87
        $this->assertEquals(ASSETS_DIR . 'test.csv', $result);
88
89
        //--Move File back
90
        $fileSystem = new Filesystem();
91
        $fileSystem->rename(ASSETS_DIR . 'test.csv', ASSETS_DIR . 'report.csv');
92
    }
93
94
    public function testGetRefreshToken()
95
    {
96
        $apiClient = $this->getApiClient(
97
            $this->getRequestNewAccessTokenMock(),
98
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
99
            $this->getClientProxyMock(),
100
            $this->getFileHelperMock(),
101
            $this->getCsvHelperMock(),
102
            $this->getTimeHelperMock()
103
        );
104
105
        $this->assertEquals('refreshToken', $apiClient->getRefreshToken());
106
107
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport', ReportTimePeriod::LastWeek);
108
        $this->assertEquals(self::REFRESH_TOKEN, $apiClient->getRefreshToken());
109
    }
110
111 View Code Duplication
    public function testGeoLocationPerformanceReportTimeoutException()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
    {
113
        $this->expectException(Exceptions\RequestTimeoutException::class);
114
        $apiClient = $this->getApiClient(
115
            $this->getRequestNewAccessTokenMock(),
116
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
117
            $this->getClientProxyMock('Pending'),
118
            new Helper\File(),
119
            new Helper\Csv(),
120
            $this->getTimeHelperMock()
121
        );
122
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport');
123
    }
124
125 View Code Duplication
    public function testGeoLocationPerformanceReportRequestErrorException()
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
    {
127
        $this->expectException(Exceptions\ReportRequestErrorException::class);
128
        $apiClient = $this->getApiClient(
129
            $this->getRequestNewAccessTokenMock(),
130
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
131
            $this->getClientProxyMock('Error'),
132
            new Helper\File(),
133
            new Helper\Csv(),
134
            $this->getTimeHelperMock()
135
        );
136
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport');
137
    }
138
139
    public function testPollGenerateReportSoapException()
140
    {
141
        $clientProxyMock = Mockery::mock(ClientProxy::class);
142
        $clientProxyMock->ReportRequestId = 'reportID';
1 ignored issue
show
Bug introduced by
Accessing ReportRequestId on the interface Mockery\MockInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
143
        $clientProxyMock
1 ignored issue
show
Bug introduced by
The method shouldReceive() does not seem to exist on object<Mockery\Expectation>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
144
            ->shouldReceive('ConstructWithCredentials')
145
            ->andReturnSelf()
146
            ->once()
147
            ->shouldReceive('GetNamespace')
148
            ->once()
149
            ->andReturn('Namespace')
150
            ->shouldReceive('GetService')
151
            ->twice()
152
            ->andReturnSelf()
153
            ->shouldReceive('SubmitGenerateReport')
154
            ->once()
155
            ->andReturnSelf()
156
            ->shouldReceive('PollGenerateReport')
157
            ->andThrow($this->generateSoapFault(0));
158
        $this->expectException(Exceptions\SoapInternalErrorException::class);
159
        $apiClient = $this->getApiClient(
160
            $this->getRequestNewAccessTokenMock(),
161
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
162
            $clientProxyMock,
163
            new Helper\File(),
164
            new Helper\Csv(),
165
            $this->getTimeHelperMock()
166
        );
167
        $apiClient->get(['TimePeriod', 'AccountName', 'AdGroupId'], 'GeoLocationPerformanceReport');
168
    }
169
    /**
170
     * @return Mockery\MockInterface
171
     */
172
    private function getClientProxyMock($reportStatus = 'Success')
173
    {
174
        $clientProxyMock = Mockery::mock(ClientProxy::class);
175
        $clientProxyMock
1 ignored issue
show
Bug introduced by
The method shouldReceive() does not seem to exist on object<Mockery\Expectation>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
176
            ->shouldReceive('ConstructWithCredentials')
177
            ->andReturnSelf()
178
            ->once()
179
            ->shouldReceive('GetNamespace')
180
            ->between(1, 48)
181
            ->andReturn('Namespace')
182
            ->shouldReceive('GetService')
183
            ->between(2, 49)
184
            ->andReturnSelf()
185
            ->shouldReceive('SubmitGenerateReport')
186
            ->between(1, 48)
187
            ->andReturnSelf()
188
            ->shouldReceive('PollGenerateReport')
189
            ->between(1, 48)
190
            ->andReturnSelf();
191
192
        $status = new \stdClass();
193
        $status->Status = $reportStatus;
194
        $status->ReportDownloadUrl = 'http://example.com/download.zip';
195
196
        $clientProxyMock->ReportRequestId = 'reportID';
1 ignored issue
show
Bug introduced by
Accessing ReportRequestId on the interface Mockery\MockInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
197
        $clientProxyMock->ReportRequestStatus = $status;
1 ignored issue
show
Bug introduced by
Accessing ReportRequestStatus on the interface Mockery\MockInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
198
199
        return $clientProxyMock;
200
    }
201
202
    /**
203
     * @return Mockery\MockInterface
204
     */
205 View Code Duplication
    private function getRequestNewAccessTokenMock()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
    {
207
        $requestNewAccessTokenMock = Mockery::mock(OauthTokenService::class);
208
        $requestNewAccessTokenMock
209
            ->shouldReceive('refreshToken')
210
            ->with('clientId', 'clientSecret', 'redirectUri', AccessToken::class)
211
            ->once()
212
            ->andReturn(new AccessToken(self::ACCESS_TOKEN, self::REFRESH_TOKEN));
213
214
        return $requestNewAccessTokenMock;
215
    }
216
217
    /**
218
     * @return Mockery\MockInterface
219
     */
220
    private function getFileHelperMock()
221
    {
222
        $zipHelperMock = Mockery::mock(Helper\File::class);
223
        $zipHelperMock
1 ignored issue
show
Bug introduced by
The method shouldReceive() does not seem to exist on object<Mockery\Expectation>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
224
            ->shouldReceive('getFile')
225
            ->andReturn('/tmp/report.zip')
226
            ->once()
227
            ->shouldReceive('unZip')
228
            ->with('/tmp/report.zip')
229
            ->andReturn([ASSETS_DIR . 'report.csv'])
230
            ->once();
231
232
        return $zipHelperMock;
233
    }
234
235
    /**
236
     * @return Mockery\MockInterface
237
     */
238
    private function getCsvHelperMock()
239
    {
240
        $lines = file(ASSETS_DIR . 'report.csv');
241
        $csvHelperMock = Mockery::mock(Helper\Csv::class);
242
        $csvHelperMock
1 ignored issue
show
Bug introduced by
The method shouldReceive() does not seem to exist on object<Mockery\Expectation>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
243
            ->shouldReceive('removeHeaders')
244
            ->andReturn($lines)
245
            ->once()
246
            ->shouldReceive('removeLastLines')
247
            ->andReturn($lines)
248
            ->once()
249
            ->shouldReceive('convertDateMDYtoYMD')
250
            ->andReturn($lines)
251
            ->once();
252
253
        return $csvHelperMock;
254
    }
255
256
    private function getTimeHelperMock()
257
    {
258
        $timeHelperMock = Mockery::mock(Helper\Time::class);
259
        $timeHelperMock->shouldReceive('sleep')->andReturnNull();
260
261
        return $timeHelperMock;
262
    }
263
264
    /**
265
     * @param OauthTokenService $requestNewAccessToken
266
     * @param ClientProxy $clientProxy
267
     * @param Helper\File $fileHelper
268
     * @param Helper\Csv $csvHelper
269
     * @param Helper\Time $timeHelper
270
     *
271
     * @return Client
272
     */
273 View Code Duplication
    private function getApiClient(OauthTokenService $requestNewAccessToken, ApiDetails $apiDetails, ClientProxy $clientProxy, Helper\File $fileHelper, Helper\Csv $csvHelper, Helper\Time $timeHelper)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
274
    {
275
        $apiClient = new Client($requestNewAccessToken, $apiDetails, $clientProxy, $fileHelper, $csvHelper, $timeHelper);
276
        $apiClient->setConfig(['cache_dir' => '/tmp']);
277
278
        return $apiClient;
279
    }
280
281
    /**
282
     * @param $code
283
     * @return SoapFault
284
     */
285 View Code Duplication
    private function generateSoapFault($code)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
286
    {
287
        $message = "an error message {$code}";
288
        $error = new stdClass();
289
        $error->Code = $code;
290
        $error->Message = $message;
291
        $exception = new SoapFault('Server', '');
292
        $exception->detail = new stdClass();
1 ignored issue
show
Bug introduced by
The property detail does not seem to exist in SoapFault.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
293
        $exception->detail->AdApiFaultDetail = new stdClass();
294
        $exception->detail->AdApiFaultDetail->Errors = new stdClass();
295
        $exception->detail->AdApiFaultDetail->Errors->AdApiError = [$error];
296
297
        return $exception;
298
    }
299
}
300