/tests/test_pyppeteer.py

https://github.com/miyakogi/pyppeteer · Python · 80 lines · 59 code · 13 blank · 8 comment · 6 complexity · 5fba190f8264f3a90c2fcc65a435d7e9 MD5 · raw file

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. test_pyppeteer
  5. ----------------------------------
  6. Tests for `pyppeteer` module.
  7. """
  8. import asyncio
  9. import logging
  10. from pathlib import Path
  11. from syncer import sync
  12. from .base import BaseTestCase
  13. class TestPyppeteer(BaseTestCase):
  14. @sync
  15. async def test_get_https(self):
  16. await self.page.goto('https://example.com/')
  17. self.assertEqual(self.page.url, 'https://example.com/')
  18. @sync
  19. async def test_get_facebook(self):
  20. await self.page.goto('https://www.facebook.com/')
  21. self.assertEqual(self.page.url, 'https://www.facebook.com/')
  22. @sync
  23. async def test_plain_text_depr(self):
  24. await self.page.goto(self.url)
  25. with self.assertLogs('pyppeteer', logging.WARN) as log:
  26. text = await self.page.plainText()
  27. self.assertIn('deprecated', log.records[0].msg)
  28. self.assertEqual(text.split(), ['Hello', 'link1', 'link2'])
  29. @sync
  30. async def test_inject_file(self): # deprecated
  31. tmp_file = Path('tmp.js')
  32. with tmp_file.open('w') as f:
  33. f.write('''
  34. () => document.body.appendChild(document.createElement("section"))
  35. '''.strip())
  36. with self.assertLogs('pyppeteer', logging.WARN) as log:
  37. await self.page.injectFile(str(tmp_file))
  38. self.assertIn('deprecated', log.records[0].msg)
  39. await self.page.waitForSelector('section')
  40. self.assertIsNotNone(await self.page.J('section'))
  41. tmp_file.unlink()
  42. class TestScreenshot(BaseTestCase):
  43. def setUp(self):
  44. super().setUp()
  45. self.target_path = Path(__file__).resolve().parent / 'test.png'
  46. if self.target_path.exists():
  47. self.target_path.unlink()
  48. def tearDown(self):
  49. if self.target_path.exists():
  50. self.target_path.unlink()
  51. super().tearDown()
  52. @sync
  53. async def test_screenshot_large(self):
  54. page = await self.context.newPage()
  55. await page.setViewport({
  56. 'width': 2000,
  57. 'height': 2000,
  58. })
  59. await page.goto(self.url + 'static/huge-page.html')
  60. options = {'path': str(self.target_path)}
  61. self.assertFalse(self.target_path.exists())
  62. await asyncio.wait_for(page.screenshot(options), 30)
  63. self.assertTrue(self.target_path.exists())
  64. with self.target_path.open('rb') as fh:
  65. bytes = fh.read()
  66. self.assertGreater(len(bytes), 2**20)