Failed Conditions
Pull Request — master (#8)
by Laurens
02:20
created

ClientTest::testSetApiDetails()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 28
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 28
rs 8.8571
cc 1
eloc 21
nc 1
nop 0
1
<?php
2
namespace Test\Werkspot\BingAdsApiBundle\Api;
3
4
use BingAds\Bulk\ReportTimePeriod;
5
use BingAds\Proxy\ClientProxy;
6
use Mockery;
7
use Mockery\MockInterface;
8
use PHPUnit_Framework_TestCase;
9
use SoapFault;
10
use stdClass;
11
use Symfony\Component\Filesystem\Filesystem;
12
use Werkspot\BingAdsApiBundle\Api\Client;
13
use Werkspot\BingAdsApiBundle\Api\Exceptions;
14
use Werkspot\BingAdsApiBundle\Api\Helper;
15
use Werkspot\BingAdsApiBundle\Guzzle\OauthTokenService;
16
use Werkspot\BingAdsApiBundle\Model\AccessToken;
17
use Werkspot\BingAdsApiBundle\Model\ApiDetails;
18
19
class ClientTest extends PHPUnit_Framework_TestCase
20
{
21
    const ACCESS_TOKEN = '2ec09aeccaf634d982eec793037e37fe';
22
    const REFRESH_TOKEN = '0c59f7e609b0cc467067e39d523116ce';
23
24
    public function testSetApiDetails()
25
    {
26
        $newApiDetails = new ApiDetails('1', '2', '3', '4', '5');
27
28
        $expected = $this->getApiClient(
29
            new OauthTokenService(new \GuzzleHttp\Client()),
30
            $newApiDetails,
31
            new ClientProxy('example.com'),
32
            new Helper\File(),
33
            new Helper\Csv(),
34
            $this->getTimeHelperMock(),
35
            new Filesystem()
36
        );
37
38
        $api = $this->getApiClient(
39
            new OauthTokenService(new \GuzzleHttp\Client()),
40
            new ApiDetails(null, null, null, null, null),
41
            new ClientProxy('example.com'),
42
            new Helper\File(),
43
            new Helper\Csv(),
44
            $this->getTimeHelperMock(),
45
            new Filesystem()
46
        );
47
48
        $this->assertNotEquals($expected, $api);
49
        $api->setApiDetails($newApiDetails);
50
        $this->assertEquals($expected, $api);
51
    }
52
53
    /**
54
     * @dataProvider getTestSoapExceptionData
55
     *
56
     * @param int $code
57
     * @param string $exceptionClassName
58
     */
59
    public function testSoapExceptions($code, $exceptionClassName)
60
    {
61
        $this->expectException($exceptionClassName);
62
        $this->runClientSoapException($code);
63
    }
64
65
    /**
66
     * @dataProvider getTestSoapExceptionData
67
     *
68
     * @param int $code
69
     * @param string $exceptionClassName
70
     */
71
    public function testSoapOperationErrorExceptions($code, $exceptionClassName)
72
    {
73
        $this->expectException($exceptionClassName);
74
        $this->runClientSoapException($code, 'OperationError');
75
    }
76
77
    /**
78
     * @dataProvider getTestSoapExceptionData
79
     *
80
     * @param int $code
81
     * @param string $exceptionClassName
82
     */
83
    public function testSoapBatchErrorExceptions($code, $exceptionClassName)
84
    {
85
        $this->expectException($exceptionClassName);
86
        $this->runClientSoapException($code, 'BatchErrors');
87
    }
88
89
    public function getTestSoapExceptionData()
90
    {
91
        return [
92
            0 => [
93
                'errorCode' => 0,
94
                'exceptionClassName' => Exceptions\SoapInternalErrorException::class
95
            ],
96
            105 => [
97
                'errorCode' => 105,
98
                'exceptionClassName' => Exceptions\SoapInvalidCredentialsException::class,
99
            ],
100
            106 => [
101
                'errorCode' => 106,
102
                'exceptionClassName' => Exceptions\SoapUserIsNotAuthorizedException::class,
103
            ],
104
            2004 => [
105
                'errorCode' => 2004,
106
                'exceptionClassName' => Exceptions\SoapNoCompleteDataAvailableException::class,
107
            ],
108
            2100 => [
109
                'errorCode' => 2100,
110
                'exceptionClassName' => Exceptions\SoapReportingServiceInvalidReportIdException::class,
111
            ],
112
            9999 => [
113
                'errorCode' => 9999,
114
                'exceptionClassName' => Exceptions\SoapUnknownErrorException::class,
115
            ],
116
        ];
117
    }
118
119
    /**
120
     * @param int $code
121
     * @param null|string $type
122
     *
123
     * @return MockInterface
124
     */
125
    private function runClientSoapException($code, $type = null)
126
    {
127
        $clientProxyMock = $this->getClientProxyMock();
128
        $clientProxyMock
129
            ->shouldReceive('GetService')
130
            ->andThrow($this->generateSoapFault($code, $type));
131
132
        $apiClient = $this->getApiClient(
133
            $this->getOauthTokenServiceMock(),
134
            new ApiDetails('refreshToken', 'clientId', 'clientSecret', 'redirectUri', 'devToken'),
135
            $clientProxyMock,
136
            new Helper\File(),
137
            new Helper\Csv(),
138
            $this->getTimeHelperMock(),
139
            new Filesystem()
140
        );
141
142
        $apiClient->getReport('GeoLocationPerformanceReport', [], ReportTimePeriod::LastWeek, 'test.csv');
143
    }
144
145
    /**
146
     * @return Mockery\MockInterface
147
     */
148
    private function getOauthTokenServiceMock()
149
    {
150
        $oauthTokenServiceMock = Mockery::mock(OauthTokenService::class);
151
        $oauthTokenServiceMock
152
            ->shouldReceive('refreshToken')
153
            ->with('clientId', 'clientSecret', 'redirectUri', AccessToken::class)
154
            ->once()
155
            ->andReturn(new AccessToken(self::ACCESS_TOKEN, self::REFRESH_TOKEN));
156
157
        return $oauthTokenServiceMock;
158
    }
159
160
    private function getTimeHelperMock()
161
    {
162
        $timeHelperMock = Mockery::mock(Helper\Time::class);
163
        $timeHelperMock->shouldReceive('sleep')->andReturnNull();
164
165
        return $timeHelperMock;
166
    }
167
168
    /**
169
     * @param OauthTokenService $oauthTokenService
170
     * @param ApiDetails $apiDetails
171
     * @param ClientProxy $clientProxy
172
     * @param Helper\File $fileHelper
173
     * @param Helper\Csv $csvHelper
174
     * @param Helper\Time $timeHelper
175
     * @param Filesystem $filesystem
176
     *
177
     * @return Client
178
     */
179
    private function getApiClient(OauthTokenService $oauthTokenService, ApiDetails $apiDetails, ClientProxy $clientProxy, Helper\File $fileHelper, Helper\Csv $csvHelper, Helper\Time $timeHelper, Filesystem $filesystem)
180
    {
181
        $apiClient = new Client($oauthTokenService, $apiDetails, $clientProxy, $fileHelper, $csvHelper, $timeHelper, $filesystem);
182
        $apiClient->setConfig(['cache_dir' => '/tmp']);
183
184
        return $apiClient;
185
    }
186
187
    /**
188
     * @param int $code
189
     * @param null|string $type
190
     *
191
     * @return \SoapFault
192
     */
193
    private function generateSoapFault($code, $type = null)
194
    {
195
        $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...
196
        $error = new stdClass();
197
        $error->Code = $code;
198
        $error->Message = $message;
199
        $exception = new SoapFault('Server', '');
200
        $exception->detail = new stdClass();
201
        if ($type === 'BatchErrors') {
202
            $exception->detail->ApiFaultDetail = new stdClass();
203
            $exception->detail->ApiFaultDetail->BatchErrors = new stdClass();
204
            $exception->detail->ApiFaultDetail->BatchErrors->BatchError = [$error];
205
        } elseif ($type === 'OperationError') {
206
            $exception->detail->ApiFaultDetail = new stdClass();
207
            $exception->detail->ApiFaultDetail->OperationErrors = new stdClass();
208
            $exception->detail->ApiFaultDetail->OperationErrors->OperationError = [$error];
209
        } else {
210
            $exception->detail->AdApiFaultDetail = new stdClass();
211
            $exception->detail->AdApiFaultDetail->Errors = new stdClass();
212
            $exception->detail->AdApiFaultDetail->Errors->AdApiError = [$error];
213
        }
214
215
        return $exception;
216
    }
217
218
    private function getClientProxyMock()
219
    {
220
        $clientProxyMock = Mockery::mock(ClientProxy::class);
221
        $clientProxyMock
222
            ->shouldReceive('ConstructWithCredentials')
223
            ->andReturnSelf()
224
            ->once()
225
            ->shouldReceive('GetNamespace')
226
            ->andReturn('Namespace');
227
228
        return $clientProxyMock;
229
    }
230
}
231