testing.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # -*- coding: utf-8 -*-
  2. """Shared testing code."""
  3. import os
  4. import subprocess
  5. import traceback
  6. from os.path import dirname, join, abspath
  7. from splinter import Browser
  8. from unittest2 import TestCase
  9. class SearxTestLayer:
  10. """Base layer for non-robot tests."""
  11. __name__ = u'SearxTestLayer'
  12. def setUp(cls):
  13. pass
  14. setUp = classmethod(setUp)
  15. def tearDown(cls):
  16. pass
  17. tearDown = classmethod(tearDown)
  18. def testSetUp(cls):
  19. pass
  20. testSetUp = classmethod(testSetUp)
  21. def testTearDown(cls):
  22. pass
  23. testTearDown = classmethod(testTearDown)
  24. class SearxRobotLayer():
  25. """Searx Robot Test Layer"""
  26. def setUp(self):
  27. os.setpgrp() # create new process group, become its leader
  28. # get program paths
  29. webapp = os.path.join(
  30. os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
  31. 'webapp.py'
  32. )
  33. exe = 'python'
  34. # set robot settings path
  35. os.environ['SEARX_DEBUG'] = '1'
  36. os.environ['SEARX_SETTINGS_PATH'] = abspath(
  37. dirname(__file__) + '/settings_robot.yml')
  38. # run the server
  39. self.server = subprocess.Popen(
  40. [exe, webapp],
  41. stdout=subprocess.PIPE,
  42. stderr=subprocess.STDOUT
  43. )
  44. if hasattr(self.server.stdout, 'read1'):
  45. print(self.server.stdout.read1(1024).decode('utf-8'))
  46. def tearDown(self):
  47. os.kill(self.server.pid, 9)
  48. # remove previously set environment variable
  49. del os.environ['SEARX_SETTINGS_PATH']
  50. # SEARXROBOTLAYER = SearxRobotLayer()
  51. def run_robot_tests(tests):
  52. print('Running {0} tests'.format(len(tests)))
  53. for test in tests:
  54. with Browser() as browser:
  55. test(browser)
  56. class SearxTestCase(TestCase):
  57. """Base test case for non-robot tests."""
  58. layer = SearxTestLayer
  59. if __name__ == '__main__':
  60. import sys
  61. # test cases
  62. from tests import robot
  63. base_dir = abspath(join(dirname(__file__), '../tests'))
  64. if sys.argv[1] == 'robot':
  65. test_layer = SearxRobotLayer()
  66. errors = False
  67. try:
  68. test_layer.setUp()
  69. run_robot_tests([getattr(robot, x) for x in dir(robot) if x.startswith('test_')])
  70. except Exception:
  71. errors = True
  72. print('Error occured: {0}'.format(traceback.format_exc()))
  73. test_layer.tearDown()
  74. sys.exit(1 if errors else 0)