def test_link_embed_data_from_cache(self) -> None: url = 'http://test.org/' link_embed_data = 'test data' with self.assertRaises(NotFoundInCache): link_embed_data_from_cache(url) with self.settings(CACHES=TEST_CACHES): cache_set(url, link_embed_data, 'database') self.assertEqual(link_embed_data, link_embed_data_from_cache(url))
def test_link_preview_no_content_type_header(self) -> None: user = self.example_user('hamlet') self.login_user(user) url = 'http://test.org/' with mock.patch('zerver.lib.actions.queue_json_publish') as patched: msg_id = self.send_stream_message(user, "Scotland", topic_name="foo", content=url) patched.assert_called_once() queue = patched.call_args[0][0] self.assertEqual(queue, "embed_links") event = patched.call_args[0][1] headers = {'content-type': ''} # No content type header mocked_response = mock.Mock(side_effect=self.create_mock_response(url, headers=headers)) with self.settings(TEST_SUITE=False, CACHES=TEST_CACHES): with mock.patch('requests.get', mocked_response): FetchLinksEmbedData().consume(event) data = link_embed_data_from_cache(url) self.assertIn('title', data) self.assertIn('image', data) msg = Message.objects.select_related("sender").get(id=msg_id) self.assertIn(data['title'], msg.rendered_content) self.assertIn(data['image'], msg.rendered_content)
def test_link_preview_open_graph_image_missing_content(self) -> None: user = self.example_user("hamlet") self.login_user(user) url = "http://test.org/foo.html" with mock_queue_publish( "zerver.lib.actions.queue_json_publish") as patched: msg_id = self.send_stream_message(user, "Scotland", topic_name="foo", content=url) patched.assert_called_once() queue = patched.call_args[0][0] self.assertEqual(queue, "embed_links") event = patched.call_args[0][1] # HTML without the og:image metadata html = "\n".join( line if "og:image" not in line else '<meta property="og:image"/>' for line in self.open_graph_html.splitlines()) self.create_mock_response(url, body=html) with self.settings(TEST_SUITE=False, CACHES=TEST_CACHES): with self.assertLogs(level="INFO") as info_logs: FetchLinksEmbedData().consume(event) cached_data = link_embed_data_from_cache(url) self.assertTrue( "INFO:root:Time spent on get_link_embed_data for http://test.org/foo.html: " in info_logs.output[0]) self.assertIn("title", cached_data) self.assertNotIn("image", cached_data) msg = Message.objects.select_related("sender").get(id=msg_id) self.assertEqual( ('<p><a href="http://test.org/foo.html">' "http://test.org/foo.html</a></p>"), msg.rendered_content, )