示例#1
0
    def testEverything(self):
        # All these tests are dependent (see above comment) so lump everything in
        # the one test.
        delegate = _TestDelegate(
            lambda _: MockFileSystem(LocalFileSystem.Create()))

        # Test that the cron runs successfully.
        response = CronServlet(Request.ForTest('trunk'),
                               delegate_for_test=delegate).Get()
        self.assertEqual(200, response.status)

        # Save the file systems created, start with a fresh set for the next run.
        first_run_file_systems = delegate.file_systems[:]
        delegate.file_systems[:] = []

        # When re-running, all file systems should be Stat()d the same number of
        # times, but the second round shouldn't have been re-Read() since the
        # Stats haven't changed.
        response = CronServlet(Request.ForTest('trunk'),
                               delegate_for_test=delegate).Get()
        self.assertEqual(200, response.status)

        self.assertEqual(len(first_run_file_systems),
                         len(delegate.file_systems))
        for i, second_run_file_system in enumerate(delegate.file_systems):
            self.assertTrue(*second_run_file_system.CheckAndReset(
                read_count=0,
                stat_count=first_run_file_systems[i].GetStatCount()))
示例#2
0
    def testCronAndPublicFiles(self):
        '''Runs cron then requests every public file. Cron needs to be run first
    because the public file requests are offline.
    '''
        if _EXPLICIT_TEST_FILES is not None:
            return

        print('Running cron...')
        start_time = time.time()
        try:
            response = Handler(Request.ForTest('/_cron/stable')).Get()
            self.assertEqual(200, response.status)
            self.assertEqual('Success', response.content.ToString())
        finally:
            print('Took %s seconds' % (time.time() - start_time))

        public_files = _GetPublicFiles()

        print('Rendering %s public files...' % len(public_files.keys()))
        start_time = time.time()
        try:
            for path, content in public_files.iteritems():
                if path.endswith('redirects.json'):
                    continue

                def check_result(response):
                    self.assertEqual(
                        200, response.status,
                        'Got %s when rendering %s' % (response.status, path))
                    # This is reaaaaally rough since usually these will be tiny templates
                    # that render large files. At least it'll catch zero-length responses.
                    self.assertTrue(
                        len(response.content) >= len(content),
                        'Content was "%s" when rendering %s' %
                        (response.content, path))

                check_result(Handler(Request.ForTest(path)).Get())
                # Samples are internationalized, test some locales.
                if path.endswith('/samples.html'):
                    for lang in ['en-US', 'es', 'ar']:
                        check_result(
                            Handler(
                                Request.ForTest(path,
                                                headers={
                                                    'Accept-Language':
                                                    '%s;q=0.8' % lang
                                                })).Get())
        finally:
            print('Took %s seconds' % (time.time() - start_time))
 def testSampleZip(self):
     sample_dir = 'extensions/talking_alarm_clock'
     request = Request.ForTest('extensions/examples/%s.zip' % sample_dir)
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(200, response.status)
     self.assertEqual('application/zip',
                      response.headers.get('content-type'))
示例#4
0
  def testWithDifferentBasePath(self):
    file_system = TestFileSystem({
      'chrome_sidenav.json': json.dumps([
        { 'href': '/H1.html' },
        { 'href': '/H2.html' },
        { 'href': '/base/path/H2.html' },
        { 'href': 'https://qualified/X1.html' },
        {
          'href': 'H3.html',
          'items': [{
            'href': 'H4.html'
          }]
        },
      ])
    }, relative_to=JSON_TEMPLATES)

    expected = [
      {'href': '/base/path/H1.html', 'level': 2, 'related': True},
      {'href': '/base/path/H2.html', 'level': 2, 'selected': True, 'related': True},
      {'href': '/base/path/base/path/H2.html', 'level': 2, 'related': True},
      {'href': 'https://qualified/X1.html', 'level': 2, 'related': True},
      {'items': [
        {'href': '/base/path/H4.html', 'level': 3}
      ],
      'href': '/base/path/H3.html', 'level': 2, 'related': True}
    ]

    server_instance = ServerInstance.ForTest(file_system,
                                             base_path='/base/path/')
    sidenav_data_source = SidenavDataSource(server_instance,
                                            Request.ForTest('/H2.html'))

    log_output = CaptureLogging(
        lambda: self.assertEqual(expected, sidenav_data_source.get('chrome')))
    self.assertEqual(2, len(log_output))
示例#5
0
 def setUp(self):
     server_instance = ServerInstance.ForTest(
         file_system=TestFileSystem(_TEST_FS))
     # Don't randomize the owners to avoid testing issues.
     self._owners_ds = OwnersDataSource(server_instance,
                                        Request.ForTest('/'),
                                        randomize=False)
 def testStaticFile(self):
     static_file = 'css/site.css'
     request = Request.ForTest('static/%s' % static_file)
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(200, response.status)
     self.assertEqual('text/css', response.headers.get('content-type'))
     self.assertEqual(ReadFile('docs/static/%s' % static_file),
                      response.content.ToString())
示例#7
0
    def testGetAPINodeAvailability(self):
        def assertEquals(node, actual):
            node_availabilities = {
                'tabs.Tab': None,
                'tabs.fakeTabsProperty1': None,
                'tabs.get': None,
                'tabs.onUpdated': None,
                'tabs.InjectDetails': 25,
                'tabs.fakeTabsProperty2': 15,
                'tabs.getCurrent': 19,
                'tabs.onActivated': 30
            }
            self.assertEquals(node_availabilities[node], actual)

        model_dict = CreateJSCView(
            self._api_models.GetContentScriptAPIs().Get(),
            self._api_models.GetModel('tabs').Get(),
            self._avail_finder, self._json_cache, _FakeTemplateCache(),
            _FakeFeaturesBundle(), None, 'extensions', [], Request.ForTest(''))

        # Test nodes that have the same availability as their parent.

        # Test type.
        assertEquals('tabs.Tab', model_dict['types'][0]['availability'])
        # Test property.
        assertEquals('tabs.fakeTabsProperty1',
                     model_dict['properties'][1]['availability'])
        # Test function.
        assertEquals('tabs.get', model_dict['functions'][1]['availability'])
        # Test event.
        assertEquals('tabs.onUpdated', model_dict['events'][1]['availability'])

        # Test nodes with varying availabilities.

        # Test type.
        assertEquals('tabs.InjectDetails',
                     model_dict['types'][1]['availability']['version'])
        # Test property.
        assertEquals('tabs.fakeTabsProperty2',
                     model_dict['properties'][3]['availability']['version'])
        # Test function.
        assertEquals('tabs.getCurrent',
                     model_dict['functions'][0]['availability']['version'])
        # Test event.
        assertEquals('tabs.onActivated',
                     model_dict['events'][0]['availability']['version'])

        # Test a node that became deprecated.
        self.assertEquals(
            {
                'scheduled':
                None,
                'version':
                26,
                'partial':
                'motemplate chrome/common/extensions/docs/templates/' +
                'private/intro_tables/deprecated_message.html'
            }, model_dict['types'][2]['availability'])
示例#8
0
 def DISABLED_testToDict(self):
     fake_avail_finder = _FakeAvailabilityFinder(self._fake_availability)
     expected_json = self._LoadJSON('expected_tester.json')
     dict_ = CreateJSCView(self._api_models.GetContentScriptAPIs().Get(),
                           self._api_models.GetModel('tester').Get(),
                           fake_avail_finder, self._json_cache,
                           _FakeTemplateCache(), self._features_bundle,
                           None, 'extensions', [], Request.ForTest(''))
     self.assertEquals(expected_json, dict_)
 def testSampleFile(self):
     sample_file = 'extensions/talking_alarm_clock/background.js'
     request = Request.ForTest('extensions/examples/%s' % sample_file)
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(200, response.status)
     content_type = response.headers.get('content-type')
     self.assertTrue(content_type == 'application/javascript'
                     or content_type == 'application/x-javascript')
     self.assertEqual(ReadFile('docs/examples/%s' % sample_file),
                      response.content.ToString())
示例#10
0
 def testHtmlTemplate(self):
     html_file = 'extensions/storage.html'
     request = Request.ForTest(html_file)
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(200, response.status)
     self.assertEqual('text/html', response.headers.get('content-type'))
     # Can't really test rendering all that well.
     self.assertTrue(
         len(response.content) > len(
             ReadFile('docs/templates/public/%s' % html_file)))
示例#11
0
    def testEverything(self):
        # All these tests are dependent (see above comment) so lump everything in
        # the one test.
        delegate = _TestDelegate(
            lambda _: MockFileSystem(LocalFileSystem.Create()))

        # Test that the cron runs successfully.
        response = CronServlet(Request.ForTest('trunk'),
                               delegate_for_test=delegate).Get()
        self.assertEqual(1, len(delegate.file_systems))
        self.assertEqual(200, response.status)

        # When re-running, all file systems should be Stat()d the same number of
        # times, but the second round shouldn't have been re-Read() since the
        # Stats haven't changed.
        response = CronServlet(Request.ForTest('trunk'),
                               delegate_for_test=delegate).Get()
        self.assertEqual(2, len(delegate.file_systems))
        self.assertTrue(*delegate.file_systems[1].CheckAndReset(
            read_count=0, stat_count=delegate.file_systems[0].GetStatCount()))
示例#12
0
 def testCreateId(self):
     fake_avail_finder = _FakeAvailabilityFinder(self._fake_availability)
     dict_ = CreateJSCView(self._api_models.GetContentScriptAPIs().Get(),
                           self._api_models.GetModel('tester').Get(),
                           fake_avail_finder, self._json_cache,
                           _FakeTemplateCache(), self._features_bundle,
                           None, 'extensions', [], Request.ForTest(''))
     self.assertEquals('type-TypeA', dict_['types'][0]['id'])
     self.assertEquals('property-TypeA-b',
                       dict_['types'][0]['properties'][0]['id'])
     self.assertEquals('method-get', dict_['functions'][0]['id'])
     self.assertEquals('event-EventA', dict_['events'][0]['id'])
示例#13
0
 def is_redirect(from_host, from_path, to_url):
     response = PatchServlet(Request.ForTest(from_path, host=from_host),
                             _PatchServletDelegate()).Get()
     redirect_url, _ = response.GetRedirect()
     if redirect_url is None:
         return (False, '%s/%s did not cause a redirect' %
                 (from_host, from_path))
     if redirect_url != to_url:
         return (False, '%s/%s redirected to %s not %s' %
                 (from_host, from_path, redirect_url, to_url))
     return (True, '%s/%s redirected to %s' %
             (from_host, from_path, redirect_url))
    def testSidenavDataSource(self):
        file_system = MockFileSystem(
            TestFileSystem(
                {
                    'chrome_sidenav.json':
                    json.dumps([{
                        'title': 'H1',
                        'href': 'H1.html',
                        'items': [{
                            'title': 'H2',
                            'href': '/H2.html'
                        }]
                    }])
                },
                relative_to=JSON_TEMPLATES))

        expected = [{
            'level':
            2,
            'child_selected':
            True,
            'title':
            'H1',
            'href':
            '/H1.html',
            'items': [{
                'level': 3,
                'selected': True,
                'related': True,
                'title': 'H2',
                'href': '/H2.html',
                'parent': {
                    'href': '/H1.html',
                    'title': 'H1'
                }
            }]
        }]

        sidenav_data_source = SidenavDataSource(
            ServerInstance.ForTest(file_system), Request.ForTest('/H2.html'))
        self.assertTrue(*file_system.CheckAndReset())

        log_output = CaptureLogging(lambda: self.assertEqual(
            expected, sidenav_data_source.get('chrome')))

        self.assertEqual(1, len(log_output))
        self.assertTrue(log_output[0].msg.startswith(
            'Paths in sidenav must be qualified.'))

        # Test that only a single file is read when creating the sidenav, so that
        # we can be confident in the compiled_file_system.SingleFile annotation.
        self.assertTrue(*file_system.CheckAndReset(
            read_count=1, stat_count=1, read_resolve_count=1))
    def testIntro(self):
        intro_data_source = IntroDataSource(self._server_instance,
                                            Request.ForTest(''))
        intro_data = intro_data_source.get('test_intro')
        article_data = intro_data_source.get('test_article')

        expected_intro = 'you<h2>first</h2><h3>inner</h3><h2>second</h2>'
        # Article still has the header.
        expected_article = '<h1>hi</h1>' + expected_intro

        self.assertEqual(expected_intro, intro_data.Render().text)
        self.assertEqual(expected_article, article_data.Render().text)
示例#16
0
 def testGetAPIAvailability(self):
     api_availabilities = {
         'bluetooth': 31,
         'contextMenus': 'master',
         'jsonStableAPI': 20,
         'idle': 5,
         'input.ime': 18,
         'tabs': 18
     }
     for api_name, availability in api_availabilities.iteritems():
         model_dict = CreateJSCView(
             self._api_models.GetContentScriptAPIs().Get(),
             self._api_models.GetModel(api_name).Get(),
             self._avail_finder, self._json_cache, _FakeTemplateCache(),
             _FakeFeaturesBundle(), None, 'extensions', [],
             Request.ForTest(''))
         self.assertEquals(
             availability,
             model_dict['introList'][1]['content'][0]['version'])
示例#17
0
    def testAddRules(self):
        fake_avail_finder = _FakeAvailabilityFinder(self._fake_availability)
        dict_ = CreateJSCView(
            self._api_models.GetContentScriptAPIs().Get(),
            self._api_models.GetModel('add_rules_tester').Get(),
            fake_avail_finder, self._json_cache,
            _FakeTemplateCache(), self._features_bundle,
            self._FakeLoadAddRulesSchema(), 'extensions', [],
            Request.ForTest(''))

        # Check that the first event has the addRulesFunction defined.
        self.assertEquals('add_rules_tester', dict_['name'])
        self.assertEquals('rules', dict_['events'][0]['name'])
        self.assertEquals(
            'notable_name_to_check_for',
            dict_['events'][0]['byName']['addRules']['parameters'][0]['name'])

        # Check that the second event has addListener defined.
        self.assertEquals('noRules', dict_['events'][1]['name'])
        self.assertEquals('add_rules_tester', dict_['name'])
        self.assertEquals('noRules', dict_['events'][1]['name'])
        self.assertEquals(
            'callback', dict_['events'][0]['byName']['addListener']
            ['parameters'][0]['name'])
示例#18
0
 def testFileNotFound(self):
     response = Handler(Request.ForTest('/extensions/notfound.html')).Get()
     self.assertEqual(404, response.status)
示例#19
0
 def testGet(self):
     api_ds = APIDataSource(self.server_instance, Request.ForTest('/'))
     jsc_view = api_ds.get('extensions').get('tester')
     funcs_arr = [{
         'availability':
         None,
         'callback': {
             'name':
             'callback',
             'optional':
             False,
             'parameters': [{
                 'array': {
                     'availability': None,
                     'description': None,
                     'events': [],
                     'functions': [],
                     'id': 'type-results-resultsType',
                     'is_object': False,
                     'link': {
                         'name': 'TypeA',
                         'ref': 'tester.TypeA',
                         'text': 'TypeA'
                     },
                     'name': 'resultsType',
                     'properties': []
                 },
                 'availability': None,
                 'description': None,
                 'functions': [],
                 'id': 'property-callback-results',
                 'is_object': False,
                 'last': True,
                 'name': 'results',
                 'optional': None,
                 'parameters': [],
                 'parentName': 'callback',
                 'properties': [],
                 'returns': None
             }],
             'simple_type': {
                 'simple_type': 'function'
             }
         },
         'description':
         'Gets stuff.',
         'id':
         'method-get',
         'name':
         'get',
         'parameters': [{
             'availability':
             None,
             'choices': [{
                 'availability': None,
                 'description': None,
                 'events': [],
                 'functions': [],
                 'id': 'type-a-string',
                 'is_object': False,
                 'name': 'string',
                 'properties': [],
                 'simple_type': 'string'
             }, {
                 'array': {
                     'availability': None,
                     'description': None,
                     'events': [],
                     'functions': [],
                     'id': 'type-strings-stringsType',
                     'is_object': False,
                     'name': 'stringsType',
                     'properties': [],
                     'simple_type': 'string'
                 },
                 'availability': None,
                 'description': None,
                 'events': [],
                 'functions': [],
                 'id': 'type-a-strings',
                 'is_object': False,
                 'last': True,
                 'name': 'strings',
                 'properties': []
             }],
             'description':
             'a param',
             'functions': [],
             'id':
             'property-get-a',
             'is_object':
             False,
             'name':
             'a',
             'optional':
             None,
             'parameters': [],
             'parentName':
             'get',
             'properties': [],
             'returns':
             None
         }, {
             'asFunction': {
                 'name':
                 'callback',
                 'optional':
                 False,
                 'parameters': [{
                     'array': {
                         'availability': None,
                         'description': None,
                         'events': [],
                         'functions': [],
                         'id': 'type-results-resultsType',
                         'is_object': False,
                         'link': {
                             'name': 'TypeA',
                             'ref': 'tester.TypeA',
                             'text': 'TypeA'
                         },
                         'name': 'resultsType',
                         'properties': []
                     },
                     'availability': None,
                     'description': None,
                     'functions': [],
                     'id': 'property-callback-results',
                     'is_object': False,
                     'last': True,
                     'name': 'results',
                     'optional': None,
                     'parameters': [],
                     'parentName': 'callback',
                     'properties': [],
                     'returns': None
                 }],
                 'simple_type': {
                     'simple_type': 'function'
                 }
             },
             'description': None,
             'id': 'property-get-callback',
             'isCallback': True,
             'last': True,
             'name': 'callback',
             'optional': False,
             'parentName': 'get',
             'simple_type': 'function'
         }],
         'returns':
         None
     }]
     self.assertEquals(funcs_arr, jsc_view['functions'])
     types_arr = [{
         'availability':
         None,
         'description':
         'A cool thing.',
         'events': [],
         'functions': [],
         'id':
         'type-TypeA',
         'is_object':
         True,
         'name':
         'TypeA',
         'properties': [{
             'array': {
                 'availability': None,
                 'description': None,
                 'events': [],
                 'functions': [],
                 'id': 'type-b-bType',
                 'is_object': False,
                 'link': {
                     'name': 'TypeA',
                     'ref': 'tester.TypeA',
                     'text': 'TypeA'
                 },
                 'name': 'bType',
                 'properties': []
             },
             'availability': None,
             'description': 'List of TypeA.',
             'functions': [],
             'id': 'property-TypeA-b',
             'is_object': False,
             'name': 'b',
             'optional': True,
             'parameters': [],
             'parentName': 'TypeA',
             'properties': [],
             'returns': None
         }],
         'simple_type':
         'object'
     }]
     self.assertEquals(types_arr, jsc_view['types'])
示例#20
0
 def testDefaultChannel(self):
     request = Request.ForTest('stable/extensions/storage.html')
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(302, response.status)
示例#21
0
 def testNotFound(self):
     request = Request.ForTest('extensions/not_found.html')
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(404, response.status)
示例#22
0
 def testExtensionAppRedirect(self):
     request = Request.ForTest('storage.html')
     response = RenderServlet(request, _RenderServletDelegate()).Get()
     self.assertEqual(302, response.status)
示例#23
0
 def test_path(path, status=404):
   response = constructor(Request.ForTest(path)).Get()
   self.assertEqual(status, response.status)
示例#24
0
    def testCronAndPublicFiles(self):
        '''Runs cron then requests every public file. Cron needs to be run first
    because the public file requests are offline.
    '''
        if _EXPLICIT_TEST_FILES is not None:
            return

        print('Running cron...')
        start_time = time.time()
        try:
            response = Handler(Request.ForTest('/_cron/stable')).Get()
            self.assertEqual(200, response.status)
            self.assertEqual('Success', response.content.ToString())
        finally:
            print('Took %s seconds' % (time.time() - start_time))

        print("Checking for broken links...")
        start_time = time.time()
        link_error_detector = LinkErrorDetector(
            LocalFileSystem(os.path.join(sys.path[0], os.pardir, os.pardir)),
            lambda path: Handler(Request.ForTest(path)).Get(),
            'templates/public',
            ('extensions/index.html', 'apps/about_apps.html'))

        broken_links = link_error_detector.GetBrokenLinks()
        if broken_links:
            # TODO(jshumway): Test should fail when broken links are detected.
            print('Warning: Found %d broken links:' % (len(broken_links)))
            print(StringifyBrokenLinks(broken_links))

        print('Took %s seconds.' % (time.time() - start_time))

        print('Searching for orphaned pages...')
        start_time = time.time()
        orphaned_pages = link_error_detector.GetOrphanedPages()
        if orphaned_pages:
            # TODO(jshumway): Test should fail when orphaned pages are detected.
            print('Warning: Found %d orphaned pages:' % len(orphaned_pages))
            for page in orphaned_pages:
                print(page)
        print('Took %s seconds.' % (time.time() - start_time))

        public_files = _GetPublicFiles()

        print('Rendering %s public files...' % len(public_files.keys()))
        start_time = time.time()
        try:
            for path, content in public_files.iteritems():
                if path.endswith('redirects.json'):
                    continue

                def check_result(response):
                    self.assertEqual(
                        200, response.status,
                        'Got %s when rendering %s' % (response.status, path))
                    # This is reaaaaally rough since usually these will be tiny templates
                    # that render large files. At least it'll catch zero-length responses.
                    self.assertTrue(
                        len(response.content) >= len(content),
                        'Content was "%s" when rendering %s' %
                        (response.content, path))

                check_result(Handler(Request.ForTest(path)).Get())

                # Make sure that leaving out the .html will temporarily redirect to the
                # path with the .html.
                if path.startswith(('apps/', 'extensions/')):
                    redirect_result = Handler(
                        Request.ForTest(posixpath.splitext(path)[0])).Get()
                    self.assertEqual((path, False),
                                     redirect_result.GetRedirect())

                # Make sure including a channel will permanently redirect to the same
                # path without a channel.
                for channel in BranchUtility.GetAllChannelNames():
                    redirect_result = Handler(
                        Request.ForTest('%s/%s' % (channel, path))).Get()
                    self.assertEqual((path, True),
                                     redirect_result.GetRedirect())

                # Samples are internationalized, test some locales.
                if path.endswith('/samples.html'):
                    for lang in ['en-US', 'es', 'ar']:
                        check_result(
                            Handler(
                                Request.ForTest(path,
                                                headers={
                                                    'Accept-Language':
                                                    '%s;q=0.8' % lang
                                                })).Get())
        finally:
            print('Took %s seconds' % (time.time() - start_time))
 def _Render(self, path, headers=None):
     return RenderServlet(Request.ForTest(path, headers=headers),
                          _RenderServletDelegate()).Get()
示例#26
0
 def _RenderWithPatch(self, path, issue):
     path_with_issue = '%s/%s' % (issue, path)
     return PatchServlet(
         Request.ForTest(path_with_issue, host=_ALLOWED_HOST),
         _PatchServletDelegate()).Get()
示例#27
0
 def _RenderWithoutPatch(self, path):
     return RenderServlet(Request.ForTest(path, host=_ALLOWED_HOST),
                          _RenderServletDelegate()).Get()
示例#28
0
    def testSafeRevision(self):
        test_data = {
            'docs': {
                'examples': {
                    'examples.txt': 'examples.txt contents'
                },
                'server2': {
                    'app.yaml': AppYamlHelper.GenerateAppYaml('2-0-8')
                },
                'static': {
                    'static.txt': 'static.txt contents'
                },
                'templates': {
                    'public': {
                        'apps': {
                            'storage.html': 'storage.html contents'
                        },
                        'extensions': {
                            'storage.html': 'storage.html contents'
                        },
                    }
                }
            }
        }

        updates = []

        def app_yaml_update(version):
            return {
                'docs': {
                    'server2': {
                        'app.yaml': AppYamlHelper.GenerateAppYaml(version)
                    }
                }
            }

        def storage_html_update(update):
            return {
                'docs': {
                    'templates': {
                        'public': {
                            'apps': {
                                'storage.html': update
                            }
                        }
                    }
                }
            }

        def static_txt_update(update):
            return {'docs': {'static': {'static.txt': update}}}

        app_yaml_path = 'docs/server2/app.yaml'
        storage_html_path = 'docs/templates/public/apps/storage.html'
        static_txt_path = 'docs/static/static.txt'

        def create_file_system(revision=None):
            '''Creates a MockFileSystem at |revision| by applying that many |updates|
      to it.
      '''
            mock_file_system = MockFileSystem(TestFileSystem(test_data))
            for update in updates[:revision]:
                mock_file_system.Update(update)
            return mock_file_system

        delegate = _TestDelegate(create_file_system)
        delegate.SetAppVersion('2-0-8')

        file_systems = delegate.file_systems

        # No updates applied yet.
        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-0-8'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('storage.html contents',
                         file_systems[-1].ReadSingle(storage_html_path))

        # Apply updates to storage.html.
        updates.append(storage_html_update('interim contents'))
        updates.append(storage_html_update('new contents'))

        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-0-8'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('new contents',
                         file_systems[-1].ReadSingle(storage_html_path))

        # Apply several updates to storage.html and app.yaml. The file system
        # should be pinned at the version before app.yaml changed.
        updates.append(storage_html_update('stuck here contents'))

        double_update = storage_html_update('newer contents')
        double_update.update(app_yaml_update('2-0-10'))
        updates.append(double_update)

        updates.append(storage_html_update('never gonna reach here'))

        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-0-8'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('stuck here contents',
                         file_systems[-1].ReadSingle(storage_html_path))

        # Further pushes to storage.html will keep it pinned.
        updates.append(storage_html_update('y u not update!'))

        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-0-8'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('stuck here contents',
                         file_systems[-1].ReadSingle(storage_html_path))

        # Likewise app.yaml.
        updates.append(app_yaml_update('2-1-0'))

        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-0-8'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('stuck here contents',
                         file_systems[-1].ReadSingle(storage_html_path))

        # And updates to other content won't happen either.
        updates.append(static_txt_update('important content!'))

        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-0-8'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('stuck here contents',
                         file_systems[-1].ReadSingle(storage_html_path))
        self.assertEqual('static.txt contents',
                         file_systems[-1].ReadSingle(static_txt_path))

        # Lastly - when the app version changes, everything should no longer be
        # pinned.
        delegate.SetAppVersion('2-1-0')
        CronServlet(Request.ForTest('trunk'), delegate_for_test=delegate).Get()
        self.assertEqual(AppYamlHelper.GenerateAppYaml('2-1-0'),
                         file_systems[-1].ReadSingle(app_yaml_path))
        self.assertEqual('y u not update!',
                         file_systems[-1].ReadSingle(storage_html_path))
        self.assertEqual('important content!',
                         file_systems[-1].ReadSingle(static_txt_path))
示例#29
0
 def _Render(self, path):
     return RenderServlet(Request.ForTest(path),
                          _RenderServletDelegate()).Get()
示例#30
0
 def testFilterSamples(self):
     sds = SamplesDataSource({}, {}, '.', Request.ForTest('/'))
     sds.get = self._FakeGet
     self.assertEquals(json.loads(self._ReadLocalFile('expected.json')),
                       sds.FilterSamples('samples.json', 'bobaloo'))