integration_test.py revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
1#!/usr/bin/env python
2# Copyright 2013 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6# Run build_server so that files needed by tests are copied to the local
7# third_party directory.
8import build_server
9build_server.main()
10
11import logging
12import optparse
13import os
14import sys
15import time
16import unittest
17
18from local_renderer import LocalRenderer
19from fake_fetchers import ConfigureFakeFetchers
20from handler import Handler
21from servlet import Request
22from test_util import EnableLogging, DisableLogging
23
24# Arguments set up if __main__ specifies them.
25_EXPLICIT_TEST_FILES = None
26
27def _GetPublicFiles():
28  '''Gets all public files mapped to their contents.
29  '''
30  public_path = os.path.join(sys.path[0], os.pardir, 'templates', 'public')
31  public_files = {}
32  for path, dirs, files in os.walk(public_path, topdown=True):
33    dirs[:] = [d for d in dirs if d != '.svn']
34    relative_path = path[len(public_path):]
35    for filename in files:
36      with open(os.path.join(path, filename), 'r') as f:
37        public_files[os.path.join(relative_path, filename)] = f.read()
38  return public_files
39
40class IntegrationTest(unittest.TestCase):
41  def setUp(self):
42    ConfigureFakeFetchers()
43
44  @EnableLogging('info')
45  def testCronAndPublicFiles(self):
46    '''Runs cron then requests every public file. Cron needs to be run first
47    because the public file requests are offline.
48    '''
49    if _EXPLICIT_TEST_FILES is not None:
50      return
51
52    print('Running cron...')
53    start_time = time.time()
54    try:
55      response = Handler(Request.ForTest('/_cron/stable')).Get()
56      self.assertEqual(200, response.status)
57      self.assertEqual('Success', response.content.ToString())
58    finally:
59      print('Took %s seconds' % (time.time() - start_time))
60
61    public_files = _GetPublicFiles()
62
63    print('Rendering %s public files...' % len(public_files.keys()))
64    start_time = time.time()
65    try:
66      for path, content in _GetPublicFiles().iteritems():
67        def check_result(response):
68          self.assertEqual(200, response.status,
69              'Got %s when rendering %s' % (response.status, path))
70          # This is reaaaaally rough since usually these will be tiny templates
71          # that render large files. At least it'll catch zero-length responses.
72          self.assertTrue(len(response.content) >= len(content),
73              'Content was "%s" when rendering %s' % (response.content, path))
74        check_result(Handler(Request.ForTest(path)).Get())
75        # Samples are internationalized, test some locales.
76        if path.endswith('/samples.html'):
77          for lang in ['en-US', 'es', 'ar']:
78            check_result(Handler(Request.ForTest(
79                path,
80                headers={'Accept-Language': '%s;q=0.8' % lang})).Get())
81    finally:
82      print('Took %s seconds' % (time.time() - start_time))
83
84  # TODO(kalman): Move this test elsewhere, it's not an integration test.
85  # Perhaps like "presubmit_tests" or something.
86  def testExplicitFiles(self):
87    '''Tests just the files in _EXPLICIT_TEST_FILES.
88    '''
89    if _EXPLICIT_TEST_FILES is None:
90      return
91    for filename in _EXPLICIT_TEST_FILES:
92      print('Rendering %s...' % filename)
93      start_time = time.time()
94      try:
95        response = LocalRenderer.Render(filename)
96        self.assertEqual(200, response.status)
97        self.assertTrue(response.content != '')
98      finally:
99        print('Took %s seconds' % (time.time() - start_time))
100
101  @DisableLogging('warning')
102  def testFileNotFound(self):
103    response = Handler(Request.ForTest('/extensions/notfound.html')).Get()
104    self.assertEqual(404, response.status)
105
106if __name__ == '__main__':
107  parser = optparse.OptionParser()
108  parser.add_option('-a', '--all', action='store_true', default=False)
109  (opts, args) = parser.parse_args()
110  if not opts.all:
111    _EXPLICIT_TEST_FILES = args
112  # Kill sys.argv because we have our own flags.
113  sys.argv = [sys.argv[0]]
114  unittest.main()
115