summaryrefslogtreecommitdiff
path: root/systrace/catapult/common/py_vulcanize/py_vulcanize/html_module_unittest.py
blob: fb4af16c8d7a9f88cf5cb7cb84f0a84d93af9b26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import unittest
import StringIO

from py_vulcanize import fake_fs
from py_vulcanize import generate
from py_vulcanize import html_generation_controller
from py_vulcanize import html_module
from py_vulcanize import parse_html_deps
from py_vulcanize import project as project_module
from py_vulcanize import resource
from py_vulcanize import resource_loader as resource_loader


class ResourceWithFakeContents(resource.Resource):

  def __init__(self, toplevel_dir, absolute_path, fake_contents):
    """A resource with explicitly provided contents.

    If the resource does not exist, then pass fake_contents=None. This will
    cause accessing the resource contents to raise an exception mimicking the
    behavior of regular resources."""
    super(ResourceWithFakeContents, self).__init__(toplevel_dir, absolute_path)
    self._fake_contents = fake_contents

  @property
  def contents(self):
    if self._fake_contents is None:
      raise Exception('File not found')
    return self._fake_contents


class FakeLoader(object):

  def __init__(self, source_paths, initial_filenames_and_contents=None):
    self._source_paths = source_paths
    self._file_contents = {}
    if initial_filenames_and_contents:
      for k, v in initial_filenames_and_contents.iteritems():
        self._file_contents[k] = v

  def FindResourceGivenAbsolutePath(self, absolute_path):
    candidate_paths = []
    for source_path in self._source_paths:
      if absolute_path.startswith(source_path):
        candidate_paths.append(source_path)
    if len(candidate_paths) == 0:
      return None

    # Sort by length. Longest match wins.
    candidate_paths.sort(lambda x, y: len(x) - len(y))
    longest_candidate = candidate_paths[-1]

    return ResourceWithFakeContents(
        longest_candidate, absolute_path,
        self._file_contents.get(absolute_path, None))

  def FindResourceGivenRelativePath(self, relative_path):
    absolute_path = None
    for script_path in self._source_paths:
      absolute_path = os.path.join(script_path, relative_path)
      if absolute_path in self._file_contents:
        return ResourceWithFakeContents(script_path, absolute_path,
                                        self._file_contents[absolute_path])
    return None


class ParseTests(unittest.TestCase):

  def testValidExternalScriptReferenceToRawScript(self):
    parse_results = parse_html_deps.HTMLModuleParserResults("""<!DOCTYPE html>
      <script src="../foo.js">
      """)

    file_contents = {}
    file_contents[os.path.normpath('/tmp/a/foo.js')] = """
'i am just some raw script';
"""

    metadata = html_module.Parse(
        FakeLoader([os.path.normpath('/tmp')], file_contents),
        'a.b.start',
        '/tmp/a/b/',
        is_component=False,
        parser_results=parse_results)
    self.assertEquals([], metadata.dependent_module_names)
    self.assertEquals(
        ['a/foo.js'], metadata.dependent_raw_script_relative_paths)

  def testExternalScriptReferenceToModuleOutsideScriptPath(self):
    parse_results = parse_html_deps.HTMLModuleParserResults("""<!DOCTYPE html>
      <script src="/foo.js">
      """)

    file_contents = {}
    file_contents[os.path.normpath('/foo.js')] = ''

    def DoIt():
      html_module.Parse(FakeLoader([os.path.normpath('/tmp')], file_contents),
                        'a.b.start',
                        '/tmp/a/b/',
                        is_component=False,
                        parser_results=parse_results)
    self.assertRaises(Exception, DoIt)

  def testExternalScriptReferenceToFileThatDoesntExist(self):
    parse_results = parse_html_deps.HTMLModuleParserResults("""<!DOCTYPE html>
      <script src="/foo.js">
      """)

    file_contents = {}

    def DoIt():
      html_module.Parse(FakeLoader([os.path.normpath('/tmp')], file_contents),
                        'a.b.start',
                        '/tmp/a/b/',
                        is_component=False,
                        parser_results=parse_results)
    self.assertRaises(Exception, DoIt)

  def testValidImportOfModule(self):
    parse_results = parse_html_deps.HTMLModuleParserResults("""<!DOCTYPE html>
      <link rel="import" href="../foo.html">
      """)

    file_contents = {}
    file_contents[os.path.normpath('/tmp/a/foo.html')] = """
"""

    metadata = html_module.Parse(
        FakeLoader([os.path.normpath('/tmp')], file_contents),
        'a.b.start',
        '/tmp/a/b/',
        is_component=False,
        parser_results=parse_results)
    self.assertEquals(['a.foo'], metadata.dependent_module_names)

  def testStyleSheetImport(self):
    parse_results = parse_html_deps.HTMLModuleParserResults("""<!DOCTYPE html>
      <link rel="stylesheet" href="../foo.css">
      """)

    file_contents = {}
    file_contents[os.path.normpath('/tmp/a/foo.css')] = """
"""
    metadata = html_module.Parse(
        FakeLoader([os.path.normpath('/tmp')], file_contents),
        'a.b.start',
        '/tmp/a/b/',
        is_component=False,
        parser_results=parse_results)
    self.assertEquals([], metadata.dependent_module_names)
    self.assertEquals(['a.foo'], metadata.style_sheet_names)

  def testUsingAbsoluteHref(self):
    parse_results = parse_html_deps.HTMLModuleParserResults("""<!DOCTYPE html>
      <script src="/foo.js">
      """)

    file_contents = {}
    file_contents[os.path.normpath('/src/foo.js')] = ''

    metadata = html_module.Parse(
        FakeLoader([os.path.normpath("/tmp"), os.path.normpath("/src")],
                   file_contents),
        "a.b.start",
        "/tmp/a/b/",
        is_component=False,
        parser_results=parse_results)
    self.assertEquals(['foo.js'], metadata.dependent_raw_script_relative_paths)


class HTMLModuleTests(unittest.TestCase):

  def testBasicModuleGeneration(self):
    file_contents = {}
    file_contents[os.path.normpath('/tmp/a/b/start.html')] = """
<!DOCTYPE html>
<link rel="import" href="/widget.html">
<link rel="stylesheet" href="../common.css">
<script src="/raw_script.js"></script>
<script src="/excluded_script.js"></script>
<dom-module id="start">
  <template>
  </template>
  <script>
    'use strict';
    console.log('inline script for start.html got written');
  </script>
</dom-module>
"""
    file_contents[os.path.normpath('/py_vulcanize/py_vulcanize.html')] = """<!DOCTYPE html>
"""
    file_contents[os.path.normpath('/components/widget.html')] = """
<!DOCTYPE html>
<link rel="import" href="/py_vulcanize.html">
<widget name="widget.html"></widget>
<script>
'use strict';
console.log('inline script for widget.html');
</script>
"""
    file_contents[os.path.normpath('/tmp/a/common.css')] = """
/* /tmp/a/common.css was written */
"""
    file_contents[os.path.normpath('/raw/raw_script.js')] = """
console.log('/raw/raw_script.js was written');
"""
    file_contents[os.path.normpath(
        '/raw/components/polymer/polymer.min.js')] = """
"""

    with fake_fs.FakeFS(file_contents):
      project = project_module.Project(
          [os.path.normpath('/py_vulcanize/'),
           os.path.normpath('/tmp/'),
           os.path.normpath('/components/'),
           os.path.normpath('/raw/')])
      loader = resource_loader.ResourceLoader(project)
      a_b_start_module = loader.LoadModule(
          module_name='a.b.start', excluded_scripts=['\/excluded_script.js'])
      load_sequence = project.CalcLoadSequenceForModules([a_b_start_module])

      # Check load sequence names.
      load_sequence_names = [x.name for x in load_sequence]
      self.assertEquals(['py_vulcanize',
                         'widget',
                         'a.b.start'], load_sequence_names)

      # Check module_deps on a_b_start_module
      def HasDependentModule(module, name):
        return [x for x in module.dependent_modules
                if x.name == name]
      assert HasDependentModule(a_b_start_module, 'widget')

      # Check JS generation.
      js = generate.GenerateJS(load_sequence)
      assert 'inline script for start.html' in js
      assert 'inline script for widget.html' in js
      assert '/raw/raw_script.js' in js
      assert 'excluded_script.js' not in js

      # Check HTML generation.
      html = generate.GenerateStandaloneHTMLAsString(
          load_sequence, title='', flattened_js_url='/blah.js')
      assert '<dom-module id="start">' in html
      assert 'inline script for widget.html' not in html
      assert 'common.css' in html

  def testPolymerConversion(self):
    file_contents = {}
    file_contents[os.path.normpath('/tmp/a/b/my_component.html')] = """
<!DOCTYPE html>
<dom-module id="my-component">
  <template>
  </template>
  <script>
    'use strict';
    Polymer ( {
      is: "my-component"
    });
  </script>
</dom-module>
"""
    with fake_fs.FakeFS(file_contents):
      project = project_module.Project([
          os.path.normpath('/py_vulcanize/'), os.path.normpath('/tmp/')])
      loader = resource_loader.ResourceLoader(project)
      my_component = loader.LoadModule(module_name='a.b.my_component')

      f = StringIO.StringIO()
      my_component.AppendJSContentsToFile(
          f,
          use_include_tags_for_scripts=False,
          dir_for_include_tag_root=None)
      js = f.getvalue().rstrip()
      expected_js = """
    'use strict';
    Polymer ( {
      is: "my-component"
    });
""".rstrip()
      self.assertEquals(expected_js, js)

  def testInlineStylesheetURLs(self):
    file_contents = {}
    file_contents[os.path.normpath('/tmp/a/b/my_component.html')] = """
<!DOCTYPE html>
<style>
.some-rule {
    background-image: url('../something.jpg');
}
</style>
"""
    file_contents[os.path.normpath('/tmp/a/something.jpg')] = 'jpgdata'
    with fake_fs.FakeFS(file_contents):
      project = project_module.Project([
          os.path.normpath('/py_vulcanize/'), os.path.normpath('/tmp/')])
      loader = resource_loader.ResourceLoader(project)
      my_component = loader.LoadModule(module_name='a.b.my_component')

      computed_deps = []
      my_component.AppendDirectlyDependentFilenamesTo(computed_deps)
      self.assertEquals(set(computed_deps),
                        set([os.path.normpath('/tmp/a/b/my_component.html'),
                             os.path.normpath('/tmp/a/something.jpg')]))

      f = StringIO.StringIO()
      ctl = html_generation_controller.HTMLGenerationController()
      my_component.AppendHTMLContentsToFile(f, ctl)
      html = f.getvalue().rstrip()
      # FIXME: This is apparently not used.
      expected_html = """
.some-rule {
    background-image: url(data:image/jpg;base64,anBnZGF0YQ==);
}
""".rstrip()