aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Wallabag/ImportBundle/Tests/Import/PocketImportTest.php
blob: 043b2114e802711e46666c8e6df42fa4e0333921 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php

namespace Wallabag\ImportBundle\Tests\Import;

use Wallabag\UserBundle\Entity\User;
use Wallabag\ImportBundle\Import\PocketImport;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Mock;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Stream\Stream;
use Monolog\Logger;
use Monolog\Handler\TestHandler;

class PocketImportMock extends PocketImport
{
    public function getAccessToken()
    {
        return $this->accessToken;
    }
}

class PocketImportTest extends \PHPUnit_Framework_TestCase
{
    protected $token;
    protected $user;
    protected $em;
    protected $contentProxy;
    protected $logHandler;

    private function getPocketImport($consumerKey = 'ConsumerKey')
    {
        $this->user = new User();

        $this->tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $this->contentProxy = $this->getMockBuilder('Wallabag\CoreBundle\Helper\ContentProxy')
            ->disableOriginalConstructor()
            ->getMock();

        $token->expects($this->once())
            ->method('getUser')
            ->willReturn($this->user);

        $this->tokenStorage->expects($this->once())
            ->method('getToken')
            ->willReturn($token);

        $this->em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $pocket = new PocketImportMock(
            $this->tokenStorage,
            $this->em,
            $this->contentProxy,
            $consumerKey
        );

        $this->logHandler = new TestHandler();
        $logger = new Logger('test', array($this->logHandler));
        $pocket->setLogger($logger);

        return $pocket;
    }

    public function testInit()
    {
        $pocketImport = $this->getPocketImport();

        $this->assertEquals('Pocket', $pocketImport->getName());
        $this->assertNotEmpty($pocketImport->getUrl());
        $this->assertContains('This importer will import all your Pocket data.', $pocketImport->getDescription());
    }

    public function testOAuthRequest()
    {
        $client = new Client();

        $mock = new Mock([
            new Response(200, ['Content-Type' => 'application/json'], Stream::factory(json_encode(['code' => 'wunderbar_code']))),
        ]);

        $client->getEmitter()->attach($mock);

        $pocketImport = $this->getPocketImport();
        $pocketImport->setClient($client);

        $code = $pocketImport->getRequestToken('http://0.0.0.0/redirect');

        $this->assertEquals('wunderbar_code', $code);
    }

    public function testOAuthRequestBadResponse()
    {
        $client = new Client();

        $mock = new Mock([
            new Response(403),
        ]);

        $client->getEmitter()->attach($mock);

        $pocketImport = $this->getPocketImport();
        $pocketImport->setClient($client);

        $code = $pocketImport->getRequestToken('http://0.0.0.0/redirect');

        $this->assertFalse($code);

        $records = $this->logHandler->getRecords();
        $this->assertContains('PocketImport: Failed to request token', $records[0]['message']);
        $this->assertEquals('ERROR', $records[0]['level_name']);
    }

    public function testOAuthAuthorize()
    {
        $client = new Client();

        $mock = new Mock([
            new Response(200, ['Content-Type' => 'application/json'], Stream::factory(json_encode(['access_token' => 'wunderbar_token']))),
        ]);

        $client->getEmitter()->attach($mock);

        $pocketImport = $this->getPocketImport();
        $pocketImport->setClient($client);

        $res = $pocketImport->authorize('wunderbar_code');

        $this->assertTrue($res);
        $this->assertEquals('wunderbar_token', $pocketImport->getAccessToken());
    }

    public function testOAuthAuthorizeBadResponse()
    {
        $client = new Client();

        $mock = new Mock([
            new Response(403),
        ]);

        $client->getEmitter()->attach($mock);

        $pocketImport = $this->getPocketImport();
        $pocketImport->setClient($client);

        $res = $pocketImport->authorize('wunderbar_code');

        $this->assertFalse($res);

        $records = $this->logHandler->getRecords();
        $this->assertContains('PocketImport: Failed to authorize client', $records[0]['message']);
        $this->assertEquals('ERROR', $records[0]['level_name']);
    }

    /**
     * Will sample results from https://getpocket.com/developer/docs/v3/retrieve.
     */
    public function testImport()
    {
        $client = new Client();

        $mock = new Mock([
            new Response(200, ['Content-Type' => 'application/json'], Stream::factory(json_encode(['access_token' => 'wunderbar_token']))),
            new Response(200, ['Content-Type' => 'application/json'], Stream::factory('
                {
                    "status": 1,
                    "list": {
                        "229279689": {
                            "item_id": "229279689",
                            "resolved_id": "229279689",
                            "given_url": "http://www.grantland.com/blog/the-triangle/post/_/id/38347/ryder-cup-preview",
                            "given_title": "The Massive Ryder Cup Preview - The Triangle Blog - Grantland",
                            "favorite": "1",
                            "status": "1",
                            "resolved_title": "The Massive Ryder Cup Preview",
                            "resolved_url": "http://www.grantland.com/blog/the-triangle/post/_/id/38347/ryder-cup-preview",
                            "excerpt": "The list of things I love about the Ryder Cup is so long that it could fill a (tedious) novel, and golf fans can probably guess most of them.",
                            "is_article": "1",
                            "has_video": "1",
                            "has_image": "1",
                            "word_count": "3197",
                            "images": {
                                "1": {
                                    "item_id": "229279689",
                                    "image_id": "1",
                                    "src": "http://a.espncdn.com/combiner/i?img=/photo/2012/0927/grant_g_ryder_cr_640.jpg&w=640&h=360",
                                    "width": "0",
                                    "height": "0",
                                    "credit": "Jamie Squire/Getty Images",
                                    "caption": ""
                                }
                            },
                            "videos": {
                                "1": {
                                    "item_id": "229279689",
                                    "video_id": "1",
                                    "src": "http://www.youtube.com/v/Er34PbFkVGk?version=3&hl=en_US&rel=0",
                                    "width": "420",
                                    "height": "315",
                                    "type": "1",
                                    "vid": "Er34PbFkVGk"
                                }
                            },
                            "tags": {
                                "grantland": {
                                    "item_id": "1147652870",
                                    "tag": "grantland"
                                },
                                "Ryder Cup": {
                                    "item_id": "1147652870",
                                    "tag": "Ryder Cup"
                                }
                            }
                        },
                        "229279690": {
                            "item_id": "229279689",
                            "resolved_id": "229279689",
                            "given_url": "http://www.grantland.com/blog/the-triangle/post/_/id/38347/ryder-cup-preview",
                            "given_title": "The Massive Ryder Cup Preview - The Triangle Blog - Grantland",
                            "favorite": "1",
                            "status": "1",
                            "resolved_title": "The Massive Ryder Cup Preview",
                            "resolved_url": "http://www.grantland.com/blog/the-triangle/post/_/id/38347/ryder-cup-preview",
                            "excerpt": "The list of things I love about the Ryder Cup is so long that it could fill a (tedious) novel, and golf fans can probably guess most of them.",
                            "is_article": "1",
                            "has_video": "0",
                            "has_image": "0",
                            "word_count": "3197"
                        }
                    }
                }
            ')),
        ]);

        $client->getEmitter()->attach($mock);

        $pocketImport = $this->getPocketImport();

        $entryRepo = $this->getMockBuilder('Wallabag\CoreBundle\Repository\EntryRepository')
            ->disableOriginalConstructor()
            ->getMock();

        $entryRepo->expects($this->exactly(2))
            ->method('existByUrlAndUserId')
            ->will($this->onConsecutiveCalls(false, true));

        $tag = $this->getMockBuilder('Wallabag\CoreBundle\Entity\Tag')
            ->disableOriginalConstructor()
            ->getMock();

        $tagRepo = $this->getMockBuilder('Wallabag\CoreBundle\Repository\TagRepository')
            ->disableOriginalConstructor()
            ->getMock();

        $tagRepo->expects($this->exactly(2))
            // the method `findOneByLabel` doesn't exist, EntityRepository will then call `_call` method
            // to magically call the `findOneBy` with ['label' => 'foo']
            ->method('__call')
            ->will($this->onConsecutiveCalls(false, $tag));

        $this->em
            ->expects($this->any())
            ->method('getRepository')
            ->will($this->onConsecutiveCalls($entryRepo, $tagRepo, $tagRepo, $entryRepo));

        $entry = $this->getMockBuilder('Wallabag\CoreBundle\Entity\Entry')
            ->disableOriginalConstructor()
            ->getMock();

        $this->contentProxy
            ->expects($this->once())
            ->method('updateEntry')
            ->willReturn($entry);

        $pocketImport->setClient($client);
        $pocketImport->authorize('wunderbar_code');

        $res = $pocketImport->import();

        $this->assertTrue($res);
        $this->assertEquals(['skipped' => 1, 'imported' => 1], $pocketImport->getSummary());
    }

    public function testImportBadResponse()
    {
        $client = new Client();

        $mock = new Mock([
            new Response(200, ['Content-Type' => 'application/json'], Stream::factory(json_encode(['access_token' => 'wunderbar_token']))),
            new Response(403),
        ]);

        $client->getEmitter()->attach($mock);

        $pocketImport = $this->getPocketImport();
        $pocketImport->setClient($client);
        $pocketImport->authorize('wunderbar_code');

        $res = $pocketImport->import();

        $this->assertFalse($res);

        $records = $this->logHandler->getRecords();
        $this->assertContains('PocketImport: Failed to import', $records[0]['message']);
        $this->assertEquals('ERROR', $records[0]['level_name']);
    }
}