Source

fanstatic / fanstatic / test_compiler.py

  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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# -*- coding: utf-8 -*-
import os
import webob
import subprocess 
import time
import pytest
from fanstatic import Library, Resource, NeededResources, LibraryRegistry, Publisher
from fanstatic import MINIFIED, DEBUG
from fanstatic import Minifier, Compiler
from fanstatic.core import UnknownResourceExtensionError, ConfigurationError
from fanstatic.core import ProcessorNotFoundError
from fanstatic.compiler import CoffeeScript, SASS, LessCSS
from fanstatic.compiler import CompilerException
import fanstatic.registry


def test_compile_resource(monkeypatch, tmpdir):
    """
    The target of compilation of a resource is found on resource instantiation.
    """
    class AAACompiler(Compiler):
        source_extension = 'aaa'
        target_extension = 'js'
        
    # make sure it is loaded...
    fanstatic.registry.get_compiler_registry()
    # ...before doing the monkeypatch
    monkeypatch.setattr(fanstatic.registry, '_compiler_registry',
        fanstatic.registry.CompilerRegistry(aaa=AAACompiler))

    foo = Library('foo', tmpdir.strpath, devmode=True)

    # For resources that do not need to be compiled, the source is the source.
    tmpdir.join('a.js').write('a')
    a = Resource(foo, 'a.js')
    assert a.relpath == a.source

    # For resources that need compilation, the source is defined on
    # instantiation.
    tmpdir.join('b.aaa').write('b')
    b = Resource(foo, 'b.aaa')
    assert b.relpath == 'b.js'

    # Should also work for sub directories.
    subsub = tmpdir.join('sub/sub').ensure(dir=True)
    subsub.join('c.aaa').write('c')
    c = Resource(foo, 'sub/sub/c.aaa')
    assert c.relpath == 'sub/sub/c.js'

    # compiler is found based on the extension of the resource.
    assert c.compiler == AAACompiler

    # An error is raised when no compiler could be found for an extension
    with pytest.raises(UnknownResourceExtensionError):
        Resource(foo, 'f.foo')

def test_compiler_available(tmpdir):
    """The compiler associated to a Resource should be available during devmode."""
    class AAACompiler(Compiler):
        target_extension = 'js'

        @classmethod
        def available(cls):
            return False

    foo = Library('foo', str(tmpdir), devmode=True)
    with pytest.raises(ProcessorNotFoundError):
        Resource(foo, 'r1.aaa', compiler=AAACompiler)

    # In non-devmode, the compiler need not be available.
    foo.devmode = False
    tmpdir.join('r1.js').ensure()
    r1 = Resource(foo, 'r1.aaa', compiler=AAACompiler)

def test_custom_resource():

    class TestCompiler(Compiler):
        target_extension = 'js'

    class CustomResource(Resource):
        compiler = TestCompiler

    foo = Library('foo', '', devmode=True)
    r1 = CustomResource(foo, 'frop.baz')
    assert r1.compiler == TestCompiler
    assert r1.relpath == 'frop.js'


def test_configuration_error_mode(monkeypatch):
    """Can not set minified or debug for a compile Resource."""

    class FropCompiler(Compiler):
        source_extension = 'frop'
        target_extension = 'js'
        
    # make sure it is loaded...
    fanstatic.registry.get_compiler_registry()
    # ...before doing the monkeypatch
    monkeypatch.setattr(fanstatic.registry, '_compiler_registry',
        fanstatic.registry.CompilerRegistry(frop=FropCompiler))
    foo = Library('foo', '')
    with pytest.raises(ConfigurationError):
        Resource(foo, 'baz.frop', minified='baz-minified.js')
    with pytest.raises(ConfigurationError):
        Resource(foo, 'baz.frop', debug='baz-debug.js')


def test_compiler(tmpdir):
    # Set up a mock/test compiler. The compile action adds a trivial string to the file.
    class TestCompiler(Compiler):
        source_extension = 'test'
        target_extension = 'tst'

        @classmethod
        def __call__(cls, path, mode=None):
            open(cls.target_path(path), 'wb').write('# test:' + open(path).read())

    a = tmpdir.join('a.test')
    a.write('a')

    compiler = TestCompiler()
    # The target file name reflects the name of the compiler that was used.
    assert compiler.target_path(a.strpath) == a.strpath.rstrip('.test') + '.tst'
    # When the target file does not exist, we should compile it.
    assert compiler.should_process(a.strpath) == True
    compiler.__call__(a.strpath)
    target_path = compiler.target_path(a.strpath)
    # The file has been compiled.
    assert open(target_path).read() == '# test:a'
    # And therefore should not be compiled when the source file does not change.
    assert compiler.should_process(a.strpath) == False
    mtime1 = os.path.getmtime(target_path)
    # The time is not changed, because the `process` method does not re-compile the file.
    compiler.process(a.strpath)
    assert mtime1 == os.path.getmtime(target_path)
    # After changing the file, the compiler does it's work.
    time.sleep(0.02)
    a.write('b')
    compiler.process(a.strpath)
    assert mtime1 != os.path.getmtime(target_path)


def test_minified_for_compile_resource(tmpdir):
    foo = Library('foo', str(tmpdir), devmode=True)

    class Comp(Compiler):
        target_extension = 'js'

        minified = True
        debug = True

        @classmethod
        def __call__(cls, path, mode=None):
            # Make mode a part of the compilation:
            mode_ = {DEBUG: 'ddeebbuugg', MINIFIED: 'mmiinniiffiieedd'}.get(mode, '')
            open(cls.target_path(path, mode=mode), 'wb').write('#  compile  %s  :' % mode_ + open(path).read())

    tmpdir.join('r1.comp').write('frop')
    r1 = Resource(foo, 'r1.comp', compiler=Comp)

    needed = NeededResources(resources=[r1])
    assert needed.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r1.js"></script>'''
    assert tmpdir.join('r1.js').read() == '''\
#  compile    :frop'''

    needed_minified = NeededResources(resources=[r1], minified=True)
    assert needed_minified.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r1-min.js"></script>'''
    assert tmpdir.join('r1-min.js').read() == '''\
#  compile  mmiinniiffiieedd  :frop'''

    needed_debug = NeededResources(resources=[r1], debug=True)
    assert needed_debug.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r1-debug.js"></script>'''
    assert tmpdir.join('r1-debug.js').read() == '''\
#  compile  ddeebbuugg  :frop'''

    class DebugCompiler(Compiler):
        target_extension = 'js'

        minified = False
        debug = True

        @classmethod
        def __call__(cls, path, mode=None):
            # Make mode a part of the compilation:
            open(cls.target_path(path, mode=mode), 'wb').write('# compiler:' + open(path).read())

    # A resource with a compiler that only supplies a debug mode:
    tmpdir.join('r2.comp').write('frop2')
    r2 = Resource(foo, 'r2.comp', compiler=DebugCompiler)

    needed = NeededResources(resources=[r2])
    assert needed.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r2.js"></script>'''

    needed_debug = NeededResources(resources=[r2], debug=True)
    assert needed_debug.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r2-debug.js"></script>'''

    needed_minified = NeededResources(resources=[r2], minified=True)
    assert needed_minified.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r2.js"></script>'''

    class Mini(Minifier):

        @classmethod
        def __call__(cls, path, mode=None):
            input = open(path).read()
            while '  ' in input:
                input = input.replace('  ', ' ')
            open(cls.target_path(path), 'w').write(input.strip())

    tmpdir.join('r3.comp').write('    frop3      ')
    r3 = Resource(foo, 'r3.comp', compiler=DebugCompiler, minifier=Mini)
    needed_minified = NeededResources(resources=[r3], minified=True)
    assert needed_minified.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/r3-min.js"></script>'''
    # The minification step is applied by the minifier, not by the compiler.
    assert tmpdir.join('r3-min.js').read() == '''\
# compiler: frop3'''


def test_compiler_bundle_interaction(tmpdir, monkeypatch):
    class Foo(Compiler):
        source_extension = 'foo'
        target_extension = 'js'

        @classmethod
        def __call__(cls, path, mode=None):
            open(cls.target_path(path), 'w').write(open(path).read() + 'foo')

    # make sure it is loaded...
    fanstatic.registry.get_compiler_registry()
    # ...before doing the monkeypatch
    monkeypatch.setattr(fanstatic.registry, '_compiler_registry',
        fanstatic.registry.CompilerRegistry(foo=Foo()))

    foo = Library('foo', str(tmpdir), devmode=True)
    tmpdir.join('r1.foo').write('a')
    r1 = Resource(foo, 'r1.foo')
    tmpdir.join('r2.foo').write('b')
    r2 = Resource(foo, 'r2.foo')

    needed = NeededResources(bundle=True, resources=[r1, r2])
    assert needed.render() == '''\
<script type="text/javascript" src="/fanstatic/foo/:bundle:r1.js;r2.js"></script>'''

    # Run the compilation step before testing publishing the resources.
    r1.prepare()
    r2.prepare()

    # publish the resource.
    app = Publisher(LibraryRegistry([foo]))
    request = webob.Request.blank('/foo/:bundle:r1.js;r2.js')
    response = request.get_response(app)
    assert response.body == '''\
afoo
bfoo'''
    # The source file is available through the publisher:
    request = webob.Request.blank('/foo/r1.foo')
    response = request.get_response(app)
    assert response.body == 'a'
    # But not available through the bundle publisher, as the bundle publisher knows about the resources:
    request = webob.Request.blank('/foo/:bundle:r1.foo;r2.foo')
    response = request.get_response(app)
    assert response.status_int == 404

    # You can set 'ignores' on the Library instance in order to not publish the
    # source files.
    bar = Library('bar', str(tmpdir), ignores=['*foo'])
    app = Publisher(LibraryRegistry([bar]))
    request = webob.Request.blank('/bar/r1.foo')
    response = request.get_response(app)
    assert response.status_int == 404



def test_compiler_available_commandline(tmpdir, monkeypatch):
    """
    Test availability check for compilers depending on a executable
    available on the command line.
    """
    class NullCompiler(Compiler):
        @staticmethod
        def available():
            try:
                check = subprocess.check_call('which fropfrop', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            except subprocess.CalledProcessError:
                return False
            return not bool(check)

    assert NullCompiler.available() == False

    # Create a temporary executable script.
    script = tmpdir.join('fropfrop')
    script.write('echo hello')
    script.chmod(0770)

    # XXX Will this work on windoze?
    monkeypatch.setitem(os.environ, 'PATH', os.environ['PATH'] + ':%s' % tmpdir)
    assert NullCompiler.available() == True


def test_compilerexception_when_injecting(tmpdir):

    class ErrorCompiler(Compiler):
        source_extension = 'error'
        target_extension = 'js'

        @classmethod
        def __call__(cls, path, mode=None): 
            # lame reference to 1990's pop culture.
            raise CompilerException('Nothing compiles to you')

    tmpdir.join('a.error').ensure()
    foo = Library('foo', str(tmpdir), devmode=True)
    r1 = Resource(foo, 'a.error', compiler=ErrorCompiler())
    
    with pytest.raises(CompilerException):
        NeededResources(resources=[r1]).render()

@pytest.mark.skipif('not CoffeeScript.available()')
def test_coffeescriptcompiler(tmpdir):
    script = tmpdir.join('script.coffee')
    # from http://coffeescript.org :
    script.write('''\
square = (x) -> x * x
cube   = (x) -> square(x) * x

''')

    compiler = CoffeeScript()
    compiler(str(script))
    assert open(compiler.target_path(str(script))).read() == '''\
var cube, square;
square = function(x) {
  return x * x;
};
cube = function(x) {
  return square(x) * x;
};
'''

    with_syntax_error = tmpdir.join('error.coffee')
    with_syntax_error.write('a =')
    # If the input is invalid, should raise a compiler error.
    with pytest.raises(CompilerException):
        compiler(str(with_syntax_error))

    # Test handling files with non-ascii characters. 
    with_special_chars = tmpdir.join('with_special_chars.coffee')
    open(str(with_special_chars), 'w').write(u"a = 'Ṱ'".encode('utf-8'))
    compiler(str(with_special_chars))
    assert open(compiler.target_path(str(with_special_chars))).read() == '''\
var a;
a = 'Ṱ';
'''

@pytest.mark.skipif('not LessCSS.available()')
def test_lesscsscompiler(tmpdir):
    style = tmpdir.join('style.less')
    # from http://lesscss.org :
    style.write('''\
@color: #4D926F;

#header {
  color: @color;
}
h2 {
  color: @color;
}''')

    compiler = LessCSS()
    compiler(str(style))
    assert tmpdir.join('style.css').read() == '''\
#header {
  color: #4d926f;
}
h2 {
  color: #4d926f;
}
'''
    compiler(str(style), mode=MINIFIED)
    assert tmpdir.join('style-min.css').read() == '''\
#header{color:#4d926f;}
h2{color:#4d926f;}
'''

    with_syntax_error = tmpdir.join('error.less')
    with_syntax_error.write('.frop {')
    # If the input is invalid, should raise a compiler error.
    with pytest.raises(CompilerException):
        compiler(str(with_syntax_error))


@pytest.mark.skipif('not SASS.available()')
def test_scsscompiler(tmpdir):
    # from http://sass-lang.com/tutorial.html :
    style = tmpdir.join('style.scss')
    style.write('''\
#navbar {
  width: 80%;
  height: 23px;

  ul { list-style-type: none; }
  li {
    float: left;
    a { font-weight: bold; }
  }
}''')

    compiler = SASS()
    compiler(str(style))
    assert tmpdir.join('style.css').read() == '''\
#navbar {
  width: 80%;
  height: 23px; }
  #navbar ul {
    list-style-type: none; }
  #navbar li {
    float: left; }
    #navbar li a {
      font-weight: bold; }
'''

    compiler(str(style), mode=MINIFIED)
    assert tmpdir.join('style-min.css').read() == '''\
#navbar{width:80%;height:23px}#navbar ul{list-style-type:none}#navbar li{float:left}#navbar li a{font-weight:bold}
'''

    compiler(str(style), mode=DEBUG)
    assert tmpdir.join('style-debug.css').read() == '''\
#navbar {
  width: 80%;
  height: 23px;
}
#navbar ul {
  list-style-type: none;
}
#navbar li {
  float: left;
}
#navbar li a {
  font-weight: bold;
}
'''
    
    with_syntax_error = tmpdir.join('error.scss')
    with_syntax_error.write('#navbar {')
    # If the input is invalid, should raise a compiler error.
    with pytest.raises(CompilerException):
        compiler(str(with_syntax_error))