Passed
Push — master ( cb5c62...93009f )
by Radosław
02:21
created

HelperTest::testGetFieldsByCategory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 54
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 9.6716
c 0
b 0
f 0
cc 1
eloc 37
nc 1
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Radowoj\Yaah;
4
5
use PHPUnit\Framework\TestCase;
6
use Radowoj\Yaah\Field;
7
use SoapClient;
8
9
class HelperTest extends TestCase
10
{
11
    protected $config = null;
12
13
    protected $soapClient = null;
14
15
    public function setUp()
16
    {
17
        $this->config = $this->getMockBuilder(Config::class)
18
            ->setMethods(['getApiKey'])
19
            ->disableOriginalConstructor()
20
            ->getMock();
21
22
        $this->config->expects($this->any())
23
            ->method('getApiKey')
24
            ->willReturn('someApiKey');
25
26
        $this->soapClient = $this->getMockBuilder(SoapClient::class)
27
            ->disableOriginalConstructor()
28
            ->setMethods(['doNewAuctionExt', 'doVerifyItem', 'doQuerySysStatus', 'doLogin', 'doSomethingNotImplementedInHelper'])
29
            ->getMock();
30
    }
31
32
33
    public function testNewAuction()
34
    {
35
        $apiClient = $this->getMockBuilder(Client::class)
36
            ->setConstructorArgs([$this->config, $this->soapClient])
37
            ->setMethods(['doNewAuctionExt', 'doVerifyItem'])
38
            ->getMock();
39
40
        $apiClient->expects($this->once())
41
            ->method('doNewAuctionExt')
42
            ->with($this->equalTo([
43
                'fields' => [
44
                    [
45
                        'fvalueString' => 'test title',
46
                        'fid' => 1,
47
                        'fvalueInt' => 0,
48
                        'fvalueFloat' => 0,
49
                        'fvalueImage' => '',
50
                        'fvalueDate' => '',
51
                        'fvalueDatetime' => 0,
52
                        'fvalueRangeInt' => [
53
                            'fvalueRangeIntMin' => 0,
54
                            'fvalueRangeIntMax' => 0,
55
                        ],
56
                        'fvalueRangeFloat' => [
57
                            'fvalueRangeFloatMin' => 0,
58
                            'fvalueRangeFloatMax' => 0,
59
                        ],
60
                        'fvalueRangeDate' => [
61
                            'fvalueRangeDateMin' => '',
62
                            'fvalueRangeDateMax' => '',
63
                        ]
64
                    ]
65
                ],
66
                'localId' => 1
67
            ]));
68
69
        $apiClient->expects($this->once())
70
            ->method('doVerifyItem')
71
            ->willReturn((object)['itemId' => 1234]);
72
73
        $helper = new Helper($apiClient);
74
75
        $result = $helper->newAuction(new Auction([1 => 'test title']), 1);
76
77
        $this->assertSame(1234, $result);
78
    }
79
80
    /**
81
     * @expectedException Radowoj\Yaah\Exception
82
     * @expectedExceptionMessage Auction has not been created
83
     */
84
    public function testExceptionOnInvalidNewAuctionResponse()
85
    {
86
        $apiClient = $this->getMockBuilder(Client::class)
87
            ->setConstructorArgs([$this->config, $this->soapClient])
88
            ->setMethods(['doNewAuctionExt', 'doVerifyItem'])
89
            ->getMock();
90
91
        $apiClient->expects($this->once())
92
            ->method('doNewAuctionExt')
93
            ->willReturn((object)['whatever' => 1]);
94
95
        $apiClient->expects($this->once())
96
            ->method('doVerifyItem')
97
            ->willReturn((object)['definitelyNotItemId' => 1234]);
98
99
        $helper = new Helper($apiClient);
100
        $helper->newAuction(new Auction([1 => 'test title']), 1);
101
    }
102
103
104
    public function testDirectWebapiCall()
105
    {
106
        $apiClient = $this->getMockBuilder(Client::class)
107
            ->setConstructorArgs([$this->config, $this->soapClient])
108
            ->setMethods(['doSomethingNotImplementedInHelper'])
109
            ->getMock();
110
111
        $apiClient->expects($this->once())
112
            ->method('doSomethingNotImplementedInHelper')
113
            ->with($this->equalTo([
114
                'param1' => 1,
115
                'param2' => 2,
116
            ]))
117
            ->willReturn(42);
118
119
        $helper = new Helper($apiClient);
120
        $result = $helper->doSomethingNotImplementedInHelper([
0 ignored issues
show
Documentation Bug introduced by
The method doSomethingNotImplementedInHelper does not exist on object<Radowoj\Yaah\Helper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
121
            'param1' => 1,
122
            'param2' => 2,
123
        ]);
124
125
        $this->assertSame(42, $result);
126
    }
127
128
129
    /**
130
     * This test checks if call of a method not implemented in helper is correctly passed via WebAPI client to soapClient
131
     * (extended by WebAPI request param - just one is tested here, as all required params are tested in ClientTest)
132
     */
133
    public function testDirectWebapiCallFromSoapClient()
134
    {
135
        $this->soapClient->expects($this->once())
136
            ->method('doQuerySysStatus')
137
            ->willReturn((object)['verKey' => 'someVersionKey']);
138
139
        $this->soapClient->expects($this->once())
140
            ->method('doLogin')
141
            ->willReturn((object)['sessionHandlePart' => 'foo', 'userId' => 'bar']);
142
143
        $this->soapClient->expects($this->once())
144
            ->method('doSomethingNotImplementedInHelper')
145
            ->with(
146
                $this->callback(function($params){
147
                    return array_key_exists('param1', $params)
148
                        && array_key_exists('webapiKey', $params)
149
                        && $params['param1'] == 1337
150
                        && $params['webapiKey'] == 'someApiKey';
151
                })
152
            )
153
            ->willReturn(42);
154
155
        $apiClient = new Client($this->config, $this->soapClient);
156
157
        $helper = new Helper($apiClient);
158
        $result = $helper->doSomethingNotImplementedInHelper([
0 ignored issues
show
Documentation Bug introduced by
The method doSomethingNotImplementedInHelper does not exist on object<Radowoj\Yaah\Helper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
159
            'param1' => 1337
160
        ]);
161
162
        $this->assertSame(42, $result);
163
    }
164
165
166
167
    public function providerFinishAuctions()
168
    {
169
        return [
170
            'do not cancel all bids, no reason' => [
171
                0,
172
                ''
173
            ],
174
            'cancel all bids, no reason' => [
175
                1,
176
                ''
177
            ],
178
            'do not cancel all bids, some reason' => [
179
                0,
180
                'some reason'
181
            ],
182
            'cancel all bids, some reason' => [
183
                1,
184
                'some reason'
185
            ],
186
187
        ];
188
    }
189
190
    /**
191
     * @dataProvider providerFinishAuctions
192
     */
193
    public function testFinishAuctions($finishCancelAllBids, $finishCancelReason)
194
    {
195
        $auctionIds = [31337, 1337, 42];
196
197
        $apiClient = $this->getMockBuilder(Client::class)
198
            ->setConstructorArgs([$this->config, $this->soapClient])
199
            ->setMethods(['getLocalVersionKey', 'login', 'doFinishItems'])
200
            ->getMock();
201
202
        $apiClient->expects($this->once())
203
            ->method('doFinishItems')
204
            ->with($this->equalTo([
205
                'finishItemsList' => [
206
                    [
207
                        'finishItemId' => 31337,
208
                        'finishCancelAllBids' => $finishCancelAllBids,
209
                        'finishCancelReason' => $finishCancelReason
210
                    ],
211
                    [
212
                        'finishItemId' => 1337,
213
                        'finishCancelAllBids' => $finishCancelAllBids,
214
                        'finishCancelReason' => $finishCancelReason
215
                    ],
216
                    [
217
                        'finishItemId' => 42,
218
                        'finishCancelAllBids' => $finishCancelAllBids,
219
                        'finishCancelReason' => $finishCancelReason
220
                    ],
221
                ]
222
            ]));
223
224
        $helper = new Helper($apiClient);
225
226
        $result = $helper->finishAuctions($auctionIds, $finishCancelAllBids, $finishCancelReason);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
227
    }
228
229
    /**
230
     * @dataProvider providerFinishAuctions
231
     */
232
    public function testFinishAuction($finishCancelAllBids, $finishCancelReason)
233
    {
234
        $apiClient = $this->getMockBuilder(Client::class)
235
            ->setConstructorArgs([$this->config, $this->soapClient])
236
            ->setMethods(['getLocalVersionKey', 'login', 'doFinishItems'])
237
            ->getMock();
238
239
        $apiClient->expects($this->once())
240
            ->method('doFinishItems')
241
            ->with($this->equalTo([
242
                'finishItemsList' => [
243
                    [
244
                        'finishItemId' => 31337,
245
                        'finishCancelAllBids' => $finishCancelAllBids,
246
                        'finishCancelReason' => $finishCancelReason
247
                    ],
248
                ]
249
            ]));
250
251
        $helper = new Helper($apiClient);
252
253
        $result = $helper->finishAuction(31337, $finishCancelAllBids, $finishCancelReason);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
254
    }
255
256
257
    public function testChangeQuantity()
258
    {
259
        $apiClient = $this->getMockBuilder(Client::class)
260
            ->setConstructorArgs([$this->config, $this->soapClient])
261
            ->setMethods(['getLocalVersionKey', 'login', 'doChangeQuantityItem'])
262
            ->getMock();
263
264
        $apiClient->expects($this->once())
265
            ->method('doChangeQuantityItem')
266
            ->with($this->equalTo([
267
                'itemId' => 1337,
268
                'newItemQuantity' => 42
269
            ]));
270
271
        $helper = new Helper($apiClient);
272
        $helper->changeQuantity(1337, 42);
273
    }
274
275
276
    /**
277
     * @expectedException Radowoj\Yaah\Exception
278
     * @expectedExceptionMessage Method nonexistentMethodWithoutWebApiDoPrefix is not implemented
279
     */
280 View Code Duplication
    public function testExceptionOnNonexistentMethodWithoutDoPrefix()
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...
281
    {
282
        $apiClient = $this->getMockBuilder(Client::class)
283
            ->setConstructorArgs([$this->config, $this->soapClient])
284
            ->setMethods(['getLocalVersionKey', 'login', 'doChangeQuantityItem'])
285
            ->getMock();
286
287
        $helper = new Helper($apiClient);
288
        $helper->nonexistentMethodWithoutWebApiDoPrefix();
0 ignored issues
show
Documentation Bug introduced by
The method nonexistentMethodWithoutWebApiDoPrefix does not exist on object<Radowoj\Yaah\Helper>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
289
    }
290
291
292
    /**
293
     * @expectedException Radowoj\Yaah\Exception
294
     * @expectedExceptionMessage Invalid WebAPI response
295
     */
296 View Code Duplication
    public function testExceptionOnInvalidApiResponseFromGetFieldsByCategory()
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...
297
    {
298
        $apiClient = $this->getMockBuilder(Client::class)
299
            ->setConstructorArgs([$this->config, $this->soapClient])
300
            ->setMethods(['getLocalVersionKey', 'login', 'doGetSellFormFieldsForCategory'])
301
            ->getMock();
302
303
        $helper = new Helper($apiClient);
304
        $helper->getFieldsByCategory(42);
305
    }
306
307
    public function testGetFieldsByCategory()
308
    {
309
        $apiClient = $this->getMockBuilder(Client::class)
310
            ->setConstructorArgs([$this->config, $this->soapClient])
311
            ->setMethods(['getLocalVersionKey', 'login', 'doGetSellFormFieldsForCategory'])
312
            ->getMock();
313
314
        $apiClient->expects($this->once())
315
            ->method('doGetSellFormFieldsForCategory')
316
            ->willReturn((object)[
317
                'sellFormFieldsForCategory' => (object)[
318
                    'sellFormFieldsList' => (object)[
319
                        'item' => [
320
                            (object)[
321
                                'sellFormId' => 1,
322
                                'sellFormTitle' => 'Some field title',
323
                                'sellFormOpt' => 1,
324
                                'sellFormOptsValues' => '0|1',
325
                                'sellFormDesc' => 'Some sell form description',
326
                            ],
327
                            (object)[
328
                                'sellFormId' => 2,
329
                                'sellFormTitle' => 'Some other field title',
330
                                'sellFormOpt' => 8,
331
                                'sellFormOptsValues' => '0|1|2',
332
                                'sellFormDesc' => 'Some other sell form description',
333
                            ]
334
                        ]
335
                    ]
336
                ]
337
            ]);
338
339
        $helper = new Helper($apiClient);
340
        $result = $helper->getFieldsByCategory(42);
341
342
        $this->assertSame([
343
            [
344
                'fid' => 1,
345
                'title' => 'Some field title',
346
                'required' => true,
347
                'options' => '0|1',
348
                'optionsDesc' => 'Some sell form description',
349
            ],
350
            [
351
                'fid' => 2,
352
                'title' => 'Some other field title',
353
                'required' => false,
354
                'options' => '0|1|2',
355
                'optionsDesc' => 'Some other sell form description',
356
            ],
357
358
        ], $result);
359
360
    }
361
362
363
364
365
}
366