def testUnmatchedEndIfBlock(self):
        '''Tests that an unmatched </if> raises an exception.'''

        files = {
            'index.html':
            '''
      <!DOCTYPE HTML>
      <html>
        <if expr="lang == 'fr'">
          bonjour
        </if>
        <if expr='lang == "de"'>
          hallo
        </if>
        </if>
      </html>
      ''',
        }

        tmp_dir = util.TempDir(files)

        with self.assertRaises(Exception) as cm:
            html_inline.GetResourceFilenames(tmp_dir.GetPath('index.html'),
                                             None)
        self.failUnlessEqual(str(cm.exception), 'Unmatched </if>')
        tmp_dir.CleanUp()
示例#2
0
    def testFileResourcesMultipleBackgroundsWithNewline2(self):
        '''Tests inlined image file resources with line break before first url()
    and before second url().'''

        tmp_dir = util.TempDir({
            'test.css': '''
      .image {
        background:
          url(test.png),
          url(test.png);
      }
      ''',
            'test.png': 'PNG DATA',
            '2x/test.png': '2x PNG DATA',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('test.css'))
        html.SetDefines({'scale_factors': '2x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      .image {
        background: -webkit-image-set(url(data:image/png;base64,UE5HIERBVEE=) 1x, url(data:image/png;base64,MnggUE5HIERBVEE=) 2x),
          -webkit-image-set(url(data:image/png;base64,UE5HIERBVEE=) 1x, url(data:image/png;base64,MnggUE5HIERBVEE=) 2x);
      }
      '''))
        tmp_dir.CleanUp()
示例#3
0
    def testGenerateDepFile(self):
        output_dir = util.TempDir({})
        builder = build.RcBuilder()

        class DummyOpts(object):
            def __init__(self):
                self.input = util.PathFromRoot('grit/testdata/depfile.grd')
                self.verbose = False
                self.extra_verbose = False

        expected_dep_file = output_dir.GetPath('substitute.grd.d')
        builder.Run(DummyOpts(), [
            '-o',
            output_dir.GetPath(), '--depdir',
            output_dir.GetPath(), '--depfile', expected_dep_file
        ])

        self.failUnless(os.path.isfile(expected_dep_file))
        with open(expected_dep_file) as f:
            line = f.readline()
            (dep_output_file, deps_string) = line.split(': ')
            deps = deps_string.split(' ')

            self.failUnlessEqual("default_100_percent.pak", dep_output_file)
            self.failUnlessEqual(deps, [
                util.PathFromRoot('grit/testdata/default_100_percent/a.png'),
                util.PathFromRoot('grit/testdata/grit_part.grdp'),
                util.PathFromRoot('grit/testdata/special_100_percent/a.png'),
            ])
        output_dir.CleanUp()
示例#4
0
    def testFileResourcesImageTag(self):
        '''Tests inlined image file resources with available high DPI assets on
    an image tag.'''

        tmp_dir = util.TempDir({
            'index.html': '''
      <!DOCTYPE HTML>
      <html>
        <body>
          <img id="foo" src="test.png">
        </body>
      </html>
      ''',
            'test.png': 'PNG DATA',
            '2x/test.png': '2x PNG DATA',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('index.html'))
        html.SetDefines({'scale_factors': '2x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      <!DOCTYPE HTML>
      <html>
        <body>
          <img id="foo" src="data:image/png;base64,UE5HIERBVEE=" style="content: -webkit-image-set(url('data:image/png;base64,UE5HIERBVEE=') 1x, url('data:image/png;base64,MnggUE5HIERBVEE=') 2x);">
        </body>
      </html>
      '''))
        tmp_dir.CleanUp()
  def testFilenameVariableExpansion(self):
    '''Tests that variables are expanded in filenames before inlining.'''

    files = {
      'index.html': '''
      <html>
      <head>
      <link rel="stylesheet" href="style[WHICH].css">
      <script src="script[WHICH].js"></script>
      </head>
      <include src="tmpl[WHICH].html">
      <img src="img[WHICH].png">
      </html>
      ''',
      'style1.css': '''h1 {}''',
      'tmpl1.html': '''<h1></h1>''',
      'script1.js': '''console.log('hello');''',
      'img1.png': '''abc''',
    }

    expected_inlined = '''
      <html>
      <head>
      <style>h1 {}</style>
      <script>console.log('hello');</script>
      </head>
      <h1></h1>
      <img src="data:image/png;base64,YWJj">
      </html>
      '''

    source_resources = set()
    tmp_dir = util.TempDir(files)
    for filename in files:
      source_resources.add(tmp_dir.GetPath(filename))

    def replacer(var, repl):
      return lambda filename: filename.replace('[%s]' % var, repl)

    # Test normal inlining.
    result = html_inline.DoInline(
        tmp_dir.GetPath('index.html'),
        None,
        filename_expansion_function=replacer('WHICH', '1'))
    resources = result.inlined_files
    resources.add(tmp_dir.GetPath('index.html'))
    self.failUnlessEqual(resources, source_resources)
    self.failUnlessEqual(expected_inlined,
                         util.FixLineEnd(result.inlined_data, '\n'))

    # Test names-only inlining.
    result = html_inline.DoInline(
        tmp_dir.GetPath('index.html'),
        None,
        names_only=True,
        filename_expansion_function=replacer('WHICH', '1'))
    resources = result.inlined_files
    resources.add(tmp_dir.GetPath('index.html'))
    self.failUnlessEqual(resources, source_resources)
    tmp_dir.CleanUp()
示例#6
0
    def testAllowlistStrings(self):
        output_dir = util.TempDir({})
        builder = build.RcBuilder()

        class DummyOpts(object):
            def __init__(self):
                self.input = util.PathFromRoot(
                    'grit/testdata/allowlist_strings.grd')
                self.verbose = False
                self.extra_verbose = False

        allowlist_file = util.PathFromRoot('grit/testdata/allowlist.txt')
        builder.Run(DummyOpts(),
                    ['-o', output_dir.GetPath(), '-w', allowlist_file])
        header = output_dir.GetPath('allowlist_test_resources.h')
        rc = output_dir.GetPath('en_allowlist_test_strings.rc')

        allowlisted_ids = ['IDS_MESSAGE_ALLOWLISTED']
        non_allowlisted_ids = ['IDS_MESSAGE_NOT_ALLOWLISTED']
        self._verifyAllowlistedOutput(
            header,
            allowlisted_ids,
            non_allowlisted_ids,
        )
        self._verifyAllowlistedOutput(rc,
                                      allowlisted_ids,
                                      non_allowlisted_ids,
                                      encoding='utf16')
        output_dir.CleanUp()
示例#7
0
    def testWriteOnlyNew(self):
        output_dir = util.TempDir({})
        builder = build.RcBuilder()

        class DummyOpts(object):
            def __init__(self):
                self.input = util.PathFromRoot('grit/testdata/substitute.grd')
                self.verbose = False
                self.extra_verbose = False

        UNCHANGED = 10
        header = output_dir.GetPath('resource.h')

        builder.Run(DummyOpts(), ['-o', output_dir.GetPath()])
        self.failUnless(os.path.exists(header))
        first_mtime = os.stat(header).st_mtime

        os.utime(header, (UNCHANGED, UNCHANGED))
        builder.Run(DummyOpts(),
                    ['-o', output_dir.GetPath(), '--write-only-new', '0'])
        self.failUnless(os.path.exists(header))
        second_mtime = os.stat(header).st_mtime

        os.utime(header, (UNCHANGED, UNCHANGED))
        builder.Run(DummyOpts(),
                    ['-o', output_dir.GetPath(), '--write-only-new', '1'])
        self.failUnless(os.path.exists(header))
        third_mtime = os.stat(header).st_mtime

        self.assertTrue(abs(second_mtime - UNCHANGED) > 5)
        self.assertTrue(abs(third_mtime - UNCHANGED) < 5)
        output_dir.CleanUp()
  def testImgSrcsetIgnoresI18n(self):
    '''Tests that $i18n{...} strings are ignored when inlining.
    '''

    src_html = '''
      <html>
      <head></head>
      <body>
        <img srcset="$i18n{foo}">
      </body>
      </html>
      '''

    files = {
      'index.html': src_html,
    }

    expected_inlined = src_html

    source_resources = set()
    tmp_dir = util.TempDir(files)
    for filename in files:
      source_resources.add(tmp_dir.GetPath(util.normpath(filename)))

    result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None)
    resources = result.inlined_files
    resources.add(tmp_dir.GetPath('index.html'))
    self.failUnlessEqual(resources, source_resources)
    self.failUnlessEqual(expected_inlined,
                         util.FixLineEnd(result.inlined_data, '\n'))
    tmp_dir.CleanUp()
示例#9
0
    def testAssertTemplateOutputs(self):
        output_dir = util.TempDir({})

        class DummyOpts(object):
            def __init__(self):
                self.input = util.PathFromRoot(
                    'grit/testdata/substitute_tmpl.grd')
                self.verbose = False
                self.extra_verbose = False

        # Incomplete output file list should fail.
        builder_fail = build.RcBuilder()
        self.failUnlessEqual(
            2,
            builder_fail.Run(DummyOpts(), [
                '-o',
                output_dir.GetPath(), '-E', 'name=foo', '-a',
                os.path.abspath(output_dir.GetPath('en_foo_resources.rc'))
            ]))

        # Complete output file list should succeed.
        builder_ok = build.RcBuilder()
        self.failUnlessEqual(
            0,
            builder_ok.Run(DummyOpts(), [
                '-o',
                output_dir.GetPath(), '-E', 'name=foo', '-a',
                os.path.abspath(
                    output_dir.GetPath('en_foo_resources.rc')), '-a',
                os.path.abspath(output_dir.GetPath('sv_foo_resources.rc')),
                '-a',
                os.path.abspath(output_dir.GetPath('resource.h'))
            ]))
        output_dir.CleanUp()
示例#10
0
    def testPartInclusionFailure(self):
        template = u'''
      <grit latest_public_release="2" current_release="3">
        <outputs>
          %s
        </outputs>
      </grit>'''

        part_failures = [
            (exception.UnexpectedContent, u'<part file="x">fnord</part>'),
            (exception.UnexpectedChild,
             u'<part file="x"><output filename="x" type="y" /></part>'),
        ]
        for raises, data in part_failures:
            data = StringIO.StringIO(template % data)
            self.assertRaises(raises, grd_reader.Parse, data, '.')

        gritpart_failures = [
            (exception.UnexpectedAttribute,
             u'<grit-part file="xyz"></grit-part>'),
            (exception.MissingElement, u'<output filename="x" type="y" />'),
        ]
        for raises, data in gritpart_failures:
            top_grd = StringIO.StringIO(template % u'<part file="bad.grp" />')
            with util.TempDir({'bad.grp': data}) as temp_dir:
                self.assertRaises(raises, grd_reader.Parse, top_grd,
                                  temp_dir.GetPath())
    def testImgSrcset(self):
        '''Tests that img srcset="" attributes are converted.'''

        # Note that there is no space before "img10.png" and that
        # "img11.png" has no descriptor.
        files = {
          'index.html': '''
      <html>
      <img src="img1.png" srcset="img2.png 1x, img3.png 2x">
      <img src="img4.png" srcset=" img5.png   1x , img6.png 2x ">
      <img src="chrome://theme/img11.png" srcset="img7.png 1x, '''\
              '''chrome://theme/img13.png 2x">
      <img srcset="img8.png 300w, img9.png 11E-2w,img10.png -1e2w">
      <img srcset="img11.png">
      <img srcset="img11.png, img2.png 1x">
      <img srcset="img2.png 1x, img11.png">
      </html>
      ''',
          'img1.png': '''a1''',
          'img2.png': '''a2''',
          'img3.png': '''a3''',
          'img4.png': '''a4''',
          'img5.png': '''a5''',
          'img6.png': '''a6''',
          'img7.png': '''a7''',
          'img8.png': '''a8''',
          'img9.png': '''a9''',
          'img10.png': '''a10''',
          'img11.png': '''a11''',
        }

        expected_inlined = '''
      <html>
      <img src="data:image/png;base64,YTE=" srcset="data:image/png;base64,'''\
              '''YTI= 1x,data:image/png;base64,YTM= 2x">
      <img src="data:image/png;base64,YTQ=" srcset="data:image/png;base64,'''\
              '''YTU= 1x,data:image/png;base64,YTY= 2x">
      <img src="chrome://theme/img11.png" srcset="data:image/png;base64,'''\
              '''YTc= 1x,chrome://theme/img13.png 2x">
      <img srcset="data:image/png;base64,YTg= 300w,data:image/png;base64,'''\
              '''YTk= 11E-2w,data:image/png;base64,YTEw -1e2w">
      <img srcset="data:image/png;base64,YTEx">
      <img srcset="data:image/png;base64,YTEx,data:image/png;base64,YTI= 1x">
      <img srcset="data:image/png;base64,YTI= 1x,data:image/png;base64,YTEx">
      </html>
      '''

        source_resources = set()
        tmp_dir = util.TempDir(files)
        for filename in files:
            source_resources.add(tmp_dir.GetPath(filename))

        # Test normal inlining.
        result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None)
        resources = result.inlined_files
        resources.add(tmp_dir.GetPath('index.html'))
        self.failUnlessEqual(resources, source_resources)
        self.failUnlessEqual(expected_inlined,
                             util.FixLineEnd(result.inlined_data, '\n'))
        tmp_dir.CleanUp()
示例#12
0
    def testGenerateDepFileWithResourceIds(self):
        output_dir = util.TempDir({})
        builder = build.RcBuilder()

        class DummyOpts(object):
            def __init__(self):
                self.input = util.PathFromRoot(
                    'grit/testdata/substitute_no_ids.grd')
                self.verbose = False
                self.extra_verbose = False

        expected_dep_file = output_dir.GetPath('substitute_no_ids.grd.d')
        builder.Run(DummyOpts(), [
            '-f',
            util.PathFromRoot('grit/testdata/resource_ids'), '-o',
            output_dir.GetPath(), '--depdir',
            output_dir.GetPath(), '--depfile', expected_dep_file
        ])

        self.failUnless(os.path.isfile(expected_dep_file))
        with open(expected_dep_file) as f:
            line = f.readline()
            (dep_output_file, deps_string) = line.split(': ')
            deps = deps_string.split(' ')

            self.failUnlessEqual("resource.h", dep_output_file)
            self.failUnlessEqual(2, len(deps))
            self.failUnlessEqual(
                deps[0], util.PathFromRoot('grit/testdata/substitute.xmb'))
            self.failUnlessEqual(
                deps[1], util.PathFromRoot('grit/testdata/resource_ids'))
        output_dir.CleanUp()
    def testReadFile(self):
        def Test(data, encoding, expected_result):
            with open('testfile', 'wb') as f:
                f.write(data)
            if util.ReadFile('testfile', encoding) != expected_result:
                print(util.ReadFile('testfile', encoding), expected_result)
            self.failUnless(
                util.ReadFile('testfile', encoding) == expected_result)

        test_std_newline = '\xEF\xBB\xBFabc\ndef'  # EF BB BF is UTF-8 BOM
        newlines = ['\n', '\r\n', '\r']

        with util.TempDir({}) as tmp_dir:
            with tmp_dir.AsCurrentDir():
                for newline in newlines:
                    test = test_std_newline.replace('\n', newline)
                    Test(test, util.BINARY, test)
                    # RAW_TEXT uses universal newline mode
                    Test(test, util.RAW_TEXT, test_std_newline)
                    # utf-8 doesn't strip BOM
                    Test(test, 'utf-8', test_std_newline.decode('utf-8'))
                    # utf-8-sig strips BOM
                    Test(test, 'utf-8-sig',
                         test_std_newline.decode('utf-8')[1:])
                    # test another encoding
                    Test(test, 'cp1252', test_std_newline.decode('cp1252'))
                self.assertRaises(UnicodeDecodeError, Test, '\x80', 'utf-8',
                                  None)
示例#14
0
    def testFileResourcesCRLF(self):
        '''Tests inlined image file resource when url() is preceded by a Windows
    style line break.'''

        tmp_dir = util.TempDir({
            'test.css': '''
      .image {
        background:\r\nurl(test.png);
      }
      ''',
            'test.png': 'PNG DATA',
            '2x/test.png': '2x PNG DATA',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('test.css'))
        html.SetDefines({'scale_factors': '2x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      .image {
        background: -webkit-image-set(url(data:image/png;base64,UE5HIERBVEE=) 1x, url(data:image/png;base64,MnggUE5HIERBVEE=) 2x);
      }
      '''))
        tmp_dir.CleanUp()
示例#15
0
    def testFileResourcesSubdirs(self):
        '''Tests inlined image file resources if url() filename is in a subdir.'''

        tmp_dir = util.TempDir({
            'test.css': '''
      .image {
        background: url('some/sub/path/test.png');
      }
      ''',
            'some/sub/path/test.png': 'PNG DATA',
            'some/sub/path/2x/test.png': '2x PNG DATA',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('test.css'))
        html.SetDefines({'scale_factors': '2x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      .image {
        background: -webkit-image-set(url('data:image/png;base64,UE5HIERBVEE=') 1x, url('data:image/png;base64,MnggUE5HIERBVEE=') 2x);
      }
      '''))
        tmp_dir.CleanUp()
示例#16
0
    def testFileResourcesPreprocess(self):
        '''Tests preprocessed image file resources with available high DPI
    assets.'''

        tmp_dir = util.TempDir({
            'test.css': '''
      .image {
        background: url('test.png');
      }
      ''',
            'test.png': 'PNG DATA',
            '1.4x/test.png': '1.4x PNG DATA',
            '1.8x/test.png': '1.8x PNG DATA',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('test.css'))
        html.SetDefines({'scale_factors': '1.4x,1.8x'})
        html.SetAttributes({'flattenhtml': 'false', 'preprocess': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      .image {
        background: -webkit-image-set(url('test.png') 1x, url('1.4x/test.png') 1.4x, url('1.8x/test.png') 1.8x);
      }
      '''))
        tmp_dir.CleanUp()
示例#17
0
 def testNewFile(self):
     """Create a new file."""
     tool = newgrd.NewGrd()
     with util.TempDir({}) as output_dir:
         output_file = os.path.join(output_dir.GetPath(), 'new.grd')
         self.assertIsNone(tool.Run(DummyOpts(), [output_file]))
         self.assertTrue(os.path.exists(output_file))
示例#18
0
  def testGetResourceFilenames(self):
    '''Tests that all included files are returned by GetResourceFilenames.'''

    files = {
      'index.html': '''
      <!DOCTYPE HTML>
      <html>
        <head>
          <link rel="stylesheet" href="test.css">
          <link rel="stylesheet"
              href="really-long-long-long-long-long-test.css">
        </head>
        <body>
          <include src='test.html'>
          <include
              src="really-long-long-long-long-long-test-file-omg-so-long.html">
          <iron-icon src="[[icon]]"></iron-icon><!-- Should be ignored. -->
          <iron-icon src="{{src}}"></iron-icon><!-- Also ignored. -->
        </body>
      </html>
      ''',

      'test.html': '''
      <include src="test2.html">
      ''',

      'really-long-long-long-long-long-test-file-omg-so-long.html': '''
      <!-- This really long named resource should be included. -->
      ''',

      'test2.html': '''
      <!-- This second level resource should also be included. -->
      ''',

      'test.css': '''
      .image {
        background: url('test.png');
      }
      ''',

      'really-long-long-long-long-long-test.css': '''
      a:hover {
        font-weight: bold;  /* Awesome effect is awesome! */
      }
      ''',

      'test.png': 'PNG DATA',
    }

    source_resources = set()
    tmp_dir = util.TempDir(files)
    for filename in files:
      source_resources.add(tmp_dir.GetPath(filename))

    resources = html_inline.GetResourceFilenames(tmp_dir.GetPath('index.html'),
                                                 None)
    resources.add(tmp_dir.GetPath('index.html'))
    self.failUnlessEqual(resources, source_resources)
    tmp_dir.CleanUp()
示例#19
0
    def testWithCloseTags(self):
        '''Tests that close tags are removed.'''

        files = {
            'index.html': '''
      <html>
      <head>
      <link rel="stylesheet" href="style1.css"></link>
      <link rel="stylesheet" href="style2.css">
      </link>
      <link rel="stylesheet" href="style2.css"
      >
      </link>
      <script src="script1.js"></script>
      </head>
      <include src="tmpl1.html"></include>
      <include src="tmpl2.html">
      </include>
      <include src="tmpl2.html"
      >
      </include>
      <img src="img1.png">
      </html>
      ''',
            'style1.css': '''h1 {}''',
            'style2.css': '''h2 {}''',
            'tmpl1.html': '''<h1></h1>''',
            'tmpl2.html': '''<h2></h2>''',
            'script1.js': '''console.log('hello');''',
            'img1.png': '''abc''',
        }

        expected_inlined = '''
      <html>
      <head>
      <style>h1 {}</style>
      <style>h2 {}</style>
      <style>h2 {}</style>
      <script>console.log('hello');</script>
      </head>
      <h1></h1>
      <h2></h2>
      <h2></h2>
      <img src="data:image/png;base64,YWJj">
      </html>
      '''

        source_resources = set()
        tmp_dir = util.TempDir(files)
        for filename in files:
            source_resources.add(tmp_dir.GetPath(filename))

        # Test normal inlining.
        result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None)
        resources = result.inlined_files
        resources.add(tmp_dir.GetPath('index.html'))
        self.failUnlessEqual(resources, source_resources)
        self.failUnlessEqual(expected_inlined,
                             util.FixLineEnd(result.inlined_data, '\n'))
    def testInlineCSSImports(self):
        '''Tests that @import directives in inlined CSS files are inlined too.
    '''

        files = {
            'index.html':
            '''
      <html>
      <head>
      <link rel="stylesheet" href="css/test.css">
      </head>
      </html>
      ''',
            'css/test.css':
            '''
      @import url('test2.css');
      blink {
        display: none;
      }
      ''',
            'css/test2.css':
            '''
      .image {
        background: url('../images/test.png');
      }
      '''.strip(),
            'images/test.png':
            'PNG DATA'
        }

        expected_inlined = '''
      <html>
      <head>
      <style>
      .image {
        background: url('data:image/png;base64,UE5HIERBVEE=');
      }
      blink {
        display: none;
      }
      </style>
      </head>
      </html>
      '''

        source_resources = set()
        tmp_dir = util.TempDir(files)
        for filename in files:
            source_resources.add(tmp_dir.GetPath(util.normpath(filename)))

        result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None)
        resources = result.inlined_files
        resources.add(tmp_dir.GetPath('index.html'))
        self.failUnlessEqual(resources, source_resources)
        self.failUnlessEqual(expected_inlined,
                             util.FixLineEnd(result.inlined_data, '\n'))

        tmp_dir.CleanUp()
    def testPreprocessOnlyEvaluatesIncludeAndIf(self):
        '''Tests that preprocess_only=true evaluates <include> and <if> only.  '''

        files = {
            'index.html': '''
      <html>
        <head>
          <link rel="stylesheet" href="not_inlined.css">
          <script src="also_not_inlined.js">
        </head>
        <body>
          <include src="inline_this.html">
          <if expr="True">
            <p>'if' should be evaluated.</p>
          </if>
        </body>
      </html>
      ''',
            'not_inlined.css': ''' /* <link> should not be inlined. */ ''',
            'also_not_inlined.js': ''' // <script> should not be inlined. ''',
            'inline_this.html': ''' <p>'include' should be inlined.</p> '''
        }

        expected_inlined = '''
      <html>
        <head>
          <link rel="stylesheet" href="not_inlined.css">
          <script src="also_not_inlined.js">
        </head>
        <body>
          <p>'include' should be inlined.</p>
          <p>'if' should be evaluated.</p>
        </body>
      </html>
      '''

        source_resources = set()
        tmp_dir = util.TempDir(files)
        source_resources.add(tmp_dir.GetPath('index.html'))
        source_resources.add(tmp_dir.GetPath('inline_this.html'))

        result = html_inline.DoInline(tmp_dir.GetPath('index.html'),
                                      None,
                                      preprocess_only=True)
        resources = result.inlined_files
        resources.add(tmp_dir.GetPath('index.html'))
        self.failUnlessEqual(resources, source_resources)

        # Ignore whitespace
        expected_inlined = re.sub(r'\s+', ' ', expected_inlined)
        actually_inlined = re.sub(r'\s+', ' ',
                                  util.FixLineEnd(result.inlined_data, '\n'))
        self.failUnlessEqual(expected_inlined, actually_inlined)

        tmp_dir.CleanUp()
示例#22
0
    def testExpandVariablesInFilename(self):
        '''
    Tests variable substitution in filenames while flattening images
    with multiple scale factors.
    '''

        tmp_dir = util.TempDir({
            'index.html': '''
      <!DOCTYPE HTML>
      <html>
        <head>
          <link rel="stylesheet" href="test.css">
        </head>
        <body>
          <!-- Don't need a body. -->
        </body>
      </html>
      ''',
            'test.css': '''
      .image {
        background: url('test[WHICH].png');
      }
      ''',
            'test1.png': 'PNG DATA',
            '1.4x/test1.png': '1.4x PNG DATA',
            '1.8x/test1.png': '1.8x PNG DATA',
        })

        def replacer(var, repl):
            return lambda filename: filename.replace('[%s]' % var, repl)

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('index.html'))
        html.SetDefines({'scale_factors': '1.4x,1.8x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.SetFilenameExpansionFunction(replacer('WHICH', '1'))
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      <!DOCTYPE HTML>
      <html>
        <head>
          <style>
      .image {
        background: -webkit-image-set(url('data:image/png;base64,UE5HIERBVEE=') 1x, url('data:image/png;base64,MS40eCBQTkcgREFUQQ==') 1.4x, url('data:image/png;base64,MS44eCBQTkcgREFUQQ==') 1.8x);
      }
      </style>
        </head>
        <body>
          <!-- Don't need a body. -->
        </body>
      </html>
      '''))
        tmp_dir.CleanUp()
示例#23
0
    def testGenerateDepFileWithDependOnStamp(self):
        output_dir = util.TempDir({})
        builder = build.RcBuilder()

        class DummyOpts(object):
            def __init__(self):
                self.input = util.PathFromRoot('grit/testdata/substitute.grd')
                self.verbose = False
                self.extra_verbose = False

        expected_dep_file_name = 'substitute.grd.d'
        expected_stamp_file_name = expected_dep_file_name + '.stamp'
        expected_dep_file = output_dir.GetPath(expected_dep_file_name)
        expected_stamp_file = output_dir.GetPath(expected_stamp_file_name)
        if os.path.isfile(expected_stamp_file):
            os.remove(expected_stamp_file)
        builder.Run(DummyOpts(), [
            '-o',
            output_dir.GetPath(), '--depdir',
            output_dir.GetPath(), '--depfile', expected_dep_file,
            '--depend-on-stamp'
        ])
        self.failUnless(os.path.isfile(expected_stamp_file))
        first_mtime = os.stat(expected_stamp_file).st_mtime

        # Reset mtime to very old.
        OLDTIME = 10
        os.utime(expected_stamp_file, (OLDTIME, OLDTIME))

        builder.Run(DummyOpts(), [
            '-o',
            output_dir.GetPath(), '--depdir',
            output_dir.GetPath(), '--depfile', expected_dep_file,
            '--depend-on-stamp'
        ])
        self.failUnless(os.path.isfile(expected_stamp_file))
        second_mtime = os.stat(expected_stamp_file).st_mtime

        # Some OS have a 2s stat resolution window, so can't do a direct comparison.
        self.assertTrue((second_mtime - OLDTIME) > 5)
        self.assertTrue(abs(second_mtime - first_mtime) < 5)

        self.failUnless(os.path.isfile(expected_dep_file))
        with open(expected_dep_file) as f:
            line = f.readline()
            (dep_output_file, deps_string) = line.split(': ')
            deps = deps_string.split(' ')

            self.failUnlessEqual(expected_stamp_file_name, dep_output_file)
            self.failUnlessEqual(deps, [
                util.PathFromRoot('grit/testdata/substitute.xmb'),
            ])
        output_dir.CleanUp()
 def testPartInclusion(self):
     top_grd = u'''\
     <grit latest_public_release="2" current_release="3">
       <release seq="3">
         <messages>
           <message name="IDS_TEST" desc="test">
             test
           </message>
           <part file="sub.grp" />
         </messages>
       </release>
     </grit>'''
     sub_grd = u'''\
     <grit-part>
       <message name="IDS_TEST2" desc="test2">test2</message>
       <part file="subsub.grp" />
       <message name="IDS_TEST3" desc="test3">test3</message>
     </grit-part>'''
     subsub_grd = u'''\
     <grit-part>
       <message name="IDS_TEST4" desc="test4">test4</message>
     </grit-part>'''
     expected_output = u'''\
     <grit current_release="3" latest_public_release="2">
       <release seq="3">
         <messages>
           <message desc="test" name="IDS_TEST">
             test
           </message>
           <part file="sub.grp">
             <message desc="test2" name="IDS_TEST2">
               test2
             </message>
             <part file="subsub.grp">
               <message desc="test4" name="IDS_TEST4">
                 test4
               </message>
             </part>
             <message desc="test3" name="IDS_TEST3">
               test3
             </message>
           </part>
         </messages>
       </release>
     </grit>'''
     with util.TempDir({
             'sub.grp': sub_grd,
             'subsub.grp': subsub_grd
     }) as temp_dir:
         output = grd_reader.Parse(StringIO.StringIO(top_grd),
                                   temp_dir.GetPath())
     self.assertEqual(expected_output.split(), output.FormatXml().split())
示例#25
0
 def testFindTranslationsWithSubstitutions(self):
   # This is a regression test; we had a bug where GRIT would fail to find
   # messages with substitutions e.g. "Hello [IDS_USER]" where IDS_USER is
   # another <message>.
   output_dir = util.TempDir({})
   builder = build.RcBuilder()
   class DummyOpts(object):
     def __init__(self):
       self.input = util.PathFromRoot('grit/testdata/substitute.grd')
       self.verbose = False
       self.extra_verbose = False
   builder.Run(DummyOpts(), ['-o', output_dir.GetPath()])
   output_dir.CleanUp()
示例#26
0
  def testFileIsOutput(self):
    grd = self.MakeGrd()
    dirname = util.TempDir({})
    try:
      tool = build.RcBuilder()
      tool.o = grit_runner.Options()
      tool.output_directory = dirname.GetPath()
      tool.res = grd
      tool.Process()

      self.failUnless(os.path.isfile(dirname.GetPath('de_GoogleDesktop.adm')))
      self.failUnless(os.path.isfile(dirname.GetPath('de_README.txt')))
    finally:
      dirname.CleanUp()
示例#27
0
    def testRemoveUnsupportedScale(self):
        '''Tests removing an unsupported scale factor from an explicit image-set.'''

        tmp_dir = util.TempDir({
            'index.html': '''
      <!DOCTYPE HTML>
      <html>
        <head>
          <link rel="stylesheet" href="test.css">
        </head>
        <body>
          <!-- Don't need a body. -->
        </body>
      </html>
      ''',
            'test.css': '''
      .image {
        background: -webkit-image-set(url('test.png') 1x,
                                      url('test1.4.png') 1.4x,
                                      url('test1.8.png') 1.8x);
      }
      ''',
            'test.png': 'PNG DATA',
            'test1.4.png': '1.4x PNG DATA',
            'test1.8.png': '1.8x PNG DATA',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('index.html'))
        html.SetDefines({'scale_factors': '1.8x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      <!DOCTYPE HTML>
      <html>
        <head>
          <style>
      .image {
        background: -webkit-image-set(url('data:image/png;base64,UE5HIERBVEE=') 1x,
                                      url('data:image/png;base64,MS44eCBQTkcgREFUQQ==') 1.8x);
      }
      </style>
        </head>
        <body>
          <!-- Don't need a body. -->
        </body>
      </html>
      '''))
        tmp_dir.CleanUp()
示例#28
0
    def testRunOutput(self):
        """Verify basic correct Run behavior."""
        tool = rc2grd.Rc2Grd()

        class DummyOpts(object):
            verbose = False
            extra_verbose = False

        with util.TempDir({}) as output_dir:
            rcfile = os.path.join(output_dir.GetPath(), 'foo.rc')
            open(rcfile, 'w').close()
            self.assertIsNone(tool.Run(DummyOpts(), [rcfile]))
            self.assertTrue(
                os.path.exists(os.path.join(output_dir.GetPath(), 'foo.grd')))
示例#29
0
    def testThemeResources(self):
        '''Tests inserting high DPI aviator://theme references.'''

        tmp_dir = util.TempDir({
            'index.html':
            '''
      <!DOCTYPE HTML>
      <html>
        <head>
          <link rel="stylesheet" href="test.css">
        </head>
        <body>
          <!-- Don't need a body. -->
        </body>
      </html>
      ''',
            'test.css':
            '''
      .image {
        background: url('aviator://theme/IDR_RESOURCE_NAME');
        content: url('aviator://theme/IDR_RESOURCE_NAME_WITH_Q?$1');
      }
      ''',
        })

        html = chrome_html.ChromeHtml(tmp_dir.GetPath('index.html'))
        html.SetDefines({'scale_factors': '2x'})
        html.SetAttributes({'flattenhtml': 'true'})
        html.Parse()
        self.failUnlessEqual(
            StandardizeHtml(html.GetData('en', 'utf-8')),
            StandardizeHtml('''
      <!DOCTYPE HTML>
      <html>
        <head>
          <style>
      .image {
        background: -webkit-image-set(url('aviator://theme/IDR_RESOURCE_NAME') 1x, url('aviator://theme/IDR_RESOURCE_NAME@2x') 2x);
        content: -webkit-image-set(url('aviator://theme/IDR_RESOURCE_NAME_WITH_Q?$1') 1x, url('aviator://theme/IDR_RESOURCE_NAME_WITH_Q@2x?$1') 2x);
      }
      </style>
        </head>
        <body>
          <!-- Don't need a body. -->
        </body>
      </html>
      '''))
        tmp_dir.CleanUp()
    def testInlineCSSLinks(self):
        '''Tests that only CSS files referenced via relative URLs are inlined.'''

        files = {
            'index.html':
            '''
      <html>
      <head>
      <link rel="stylesheet" href="foo.css">
      <link rel="stylesheet" href="chrome://resources/bar.css">
      </head>
      </html>
      ''',
            'foo.css':
            '''
      @import url(chrome://resources/blurp.css);
      blink {
        display: none;
      }
      ''',
        }

        expected_inlined = '''
      <html>
      <head>
      <style>
      @import url(chrome://resources/blurp.css);
      blink {
        display: none;
      }
      </style>
      <link rel="stylesheet" href="chrome://resources/bar.css">
      </head>
      </html>
      '''

        source_resources = set()
        tmp_dir = util.TempDir(files)
        for filename in files:
            source_resources.add(tmp_dir.GetPath(filename))

        result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None)
        resources = result.inlined_files
        resources.add(tmp_dir.GetPath('index.html'))
        self.failUnlessEqual(resources, source_resources)
        self.failUnlessEqual(expected_inlined,
                             util.FixLineEnd(result.inlined_data, '\n'))
        tmp_dir.CleanUp()