/** * @return JsonResponse */ public function collect() { $toSave = array(); $count = 0; $currentPageIndex = 0; while ($count < self::NB_POSTS) { $url = self::getUrl($currentPageIndex++); try { $html = $this->curlUtils->getResource($url); $posts = $this->postParserUtils->getPosts($html); foreach ($posts as $post) { if ($count === self::NB_POSTS) { break; } $postContent = $this->postParserUtils->parse($post); $toSave[$count++] = $postContent; } } catch (\Exception $exception) { return new JsonResponse($exception); } } for ($i = 0; $i < count($toSave); $i++) { $this->dbal->insert(self::MODEL, $toSave[$i]); } $toReturn = count($toSave) . " posts have been added"; return new JsonResponse($toReturn); }
public function testGetBadResource() { try { $html = $this->curlUtils->getResource(PostController::BASE_URL . '/bad'); } catch (\Exception $e) { $this->assertEquals(0, $e->getCode()); $this->assertContains("Curl : last received HTTP code is 404", $e->getMessage()); return; } $this->fail(); }
public function testCollect() { // getPosts returns an array of size 10 => 20 loops => 20 getUrl $this->curlUtils->expects($this->exactly(20))->method('getResource')->will($this->returnValue('whatever')); $this->postParserUtils->expects($this->exactly(20))->method('getPosts')->will($this->returnValue(array(0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9))); $this->postParserUtils->expects($this->exactly(200))->method('parse')->will($this->returnValue(array("content" => "this is a content", "author" => "FOO", "created" => "2014-01-01 00:00:00"))); // insert in Db should be called 200 times $this->conn->expects($this->exactly(200))->method('insert'); $response = $this->postController->collect(); $this->assertInstanceOf("Symfony\\Component\\HttpFoundation\\JsonResponse", $response); $this->assertEquals(200, $response->getStatusCode()); $this->assertContains("200 posts have been added", $response->getContent()); }