testing.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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_SETTINGS_PATH'] = abspath(
  36. dirname(__file__) + '/settings_robot.yml')
  37. # run the server
  38. self.server = subprocess.Popen(
  39. [exe, webapp],
  40. stdout=subprocess.PIPE,
  41. stderr=subprocess.STDOUT
  42. )
  43. def tearDown(self):
  44. os.kill(self.server.pid, 9)
  45. # remove previously set environment variable
  46. del os.environ['SEARX_SETTINGS_PATH']
  47. # SEARXROBOTLAYER = SearxRobotLayer()
  48. def run_robot_tests(tests):
  49. print('Running {0} tests'.format(len(tests)))
  50. for test in tests:
  51. with Browser() as browser:
  52. test(browser)
  53. class SearxTestCase(TestCase):
  54. """Base test case for non-robot tests."""
  55. layer = SearxTestLayer
  56. if __name__ == '__main__':
  57. import sys
  58. # test cases
  59. from tests import robot
  60. base_dir = abspath(join(dirname(__file__), '../tests'))
  61. if sys.argv[1] == 'robot':
  62. test_layer = SearxRobotLayer()
  63. errors = False
  64. try:
  65. test_layer.setUp()
  66. run_robot_tests([getattr(robot, x) for x in dir(robot) if x.startswith('test_')])
  67. except Exception:
  68. errors = True
  69. print('Error occured: {0}'.format(traceback.format_exc()))
  70. test_layer.tearDown()
  71. sys.exit(1 if errors else 0)