integration_test.py revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
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 _ToPosixPath(os_path):
28  return os_path.replace(os.sep, '/')
29
30def _GetPublicFiles():
31  '''Gets all public files mapped to their contents.
32  '''
33  public_path = os.path.join(sys.path[0], os.pardir, 'templates', 'public')
34  public_files = {}
35  for path, dirs, files in os.walk(public_path, topdown=True):
36    dirs[:] = [d for d in dirs if d != '.svn']
37    relative_posix_path = _ToPosixPath(path[len(public_path):])
38    for filename in files:
39      with open(os.path.join(path, filename), 'r') as f:
40        public_files['/'.join((relative_posix_path, filename))] = f.read()
41  return public_files
42
43class IntegrationTest(unittest.TestCase):
44  def setUp(self):
45    ConfigureFakeFetchers()
46
47  @EnableLogging('info')
48  def testCronAndPublicFiles(self):
49    '''Runs cron then requests every public file. Cron needs to be run first
50    because the public file requests are offline.
51    '''
52    if _EXPLICIT_TEST_FILES is not None:
53      return
54
55    print('Running cron...')
56    start_time = time.time()
57    try:
58      response = Handler(Request.ForTest('/_cron/stable')).Get()
59      self.assertEqual(200, response.status)
60      self.assertEqual('Success', response.content.ToString())
61    finally:
62      print('Took %s seconds' % (time.time() - start_time))
63
64    public_files = _GetPublicFiles()
65
66    print('Rendering %s public files...' % len(public_files.keys()))
67    start_time = time.time()
68    try:
69      for path, content in public_files.iteritems():
70        if path.endswith('redirects.json'):
71          continue
72        def check_result(response):
73          self.assertEqual(200, response.status,
74              'Got %s when rendering %s' % (response.status, path))
75          # This is reaaaaally rough since usually these will be tiny templates
76          # that render large files. At least it'll catch zero-length responses.
77          self.assertTrue(len(response.content) >= len(content),
78              'Content was "%s" when rendering %s' % (response.content, path))
79        check_result(Handler(Request.ForTest(path)).Get())
80        # Samples are internationalized, test some locales.
81        if path.endswith('/samples.html'):
82          for lang in ['en-US', 'es', 'ar']:
83            check_result(Handler(Request.ForTest(
84                path,
85                headers={'Accept-Language': '%s;q=0.8' % lang})).Get())
86    finally:
87      print('Took %s seconds' % (time.time() - start_time))
88
89  # TODO(kalman): Move this test elsewhere, it's not an integration test.
90  # Perhaps like "presubmit_tests" or something.
91  def testExplicitFiles(self):
92    '''Tests just the files in _EXPLICIT_TEST_FILES.
93    '''
94    if _EXPLICIT_TEST_FILES is None:
95      return
96    for filename in _EXPLICIT_TEST_FILES:
97      print('Rendering %s...' % filename)
98      start_time = time.time()
99      try:
100        response = LocalRenderer.Render(_ToPosixPath(filename))
101        self.assertEqual(200, response.status)
102        self.assertTrue(response.content != '')
103      finally:
104        print('Took %s seconds' % (time.time() - start_time))
105
106  @DisableLogging('warning')
107  def testFileNotFound(self):
108    response = Handler(Request.ForTest('/extensions/notfound.html')).Get()
109    self.assertEqual(404, response.status)
110
111if __name__ == '__main__':
112  parser = optparse.OptionParser()
113  parser.add_option('-a', '--all', action='store_true', default=False)
114  (opts, args) = parser.parse_args()
115  if not opts.all:
116    _EXPLICIT_TEST_FILES = args
117  # Kill sys.argv because we have our own flags.
118  sys.argv = [sys.argv[0]]
119  unittest.main()
120