Esempio n. 1
0
def test_rendering_base_url():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed(resources=[y1])
    incl = Inclusion(needed)
    assert incl.render() == '''\
<link rel="stylesheet" type="text/css" href="/fanstatic/foo/b.css" />
<script type="text/javascript" src="/fanstatic/foo/a.js"></script>
<script type="text/javascript" src="/fanstatic/foo/c.js"></script>'''

    needed = init_needed(base_url='http://localhost/static', resources=[y1])
    incl = Inclusion(needed)
    assert incl.render() == '''\
<link rel="stylesheet" type="text/css" href="http://localhost/static/fanstatic/foo/b.css" />
<script type="text/javascript" src="http://localhost/static/fanstatic/foo/a.js"></script>
<script type="text/javascript" src="http://localhost/static/fanstatic/foo/c.js"></script>'''
    # The base_url has been set.
    assert needed.has_base_url()

    needed.set_base_url('foo')
    # The base_url can only be set once.
    assert needed._base_url == 'http://localhost/static'
Esempio n. 2
0
def test_mode_fully_specified():
    foo = Library('foo', '')
    k_debug = Resource(foo, 'k-debug.js')
    k = Resource(foo, 'k.js', debug=k_debug)
    x = Resource(foo, 'x.js', minified='x-min.js')

    needed = init_needed()
    needed.need(k)
    incl = Inclusion(needed)
    assert incl.resources == [k]

    incl = Inclusion(needed, mode='debug')
    assert incl.resources == [k_debug]

    # If no minified can be found, the 'raw' resource is taken.
    incl = Inclusion(needed, mode='minified')
    assert incl.resources == [k]

    # If only a minified resource is defined, debug returns the raw version.
    needed = init_needed()
    needed.need(x)

    incl = Inclusion(needed, mode='debug')
    assert incl.resources == [x]
    incl = Inclusion(needed, mode='minified')
    assert incl.resources == [x.modes['minified']]
Esempio n. 3
0
 def setUp(self):
     fanstatic.init_needed()
     self.context = object()
     self.request = TestRequest()
     self.resource_namespace = getMultiAdapter((self.context, self.request),
                                               ITraversable,
                                               name='resource')
 def test_include_needed(self):
     init_needed()
     obj = self._cut()
     obj.add('true', self._js_resource, discriminator_true)
     obj.add('false', self._js_resource, discriminator_false)
     obj.add('none', self._js_resource)
     self.assertEqual(obj.include_needed(None, None, None), ['true', 'none'])
     needed = get_needed().resources()
     self.assertIn(self._js_resource, needed)
 def test_include_needed(self):
     init_needed()
     obj = self._cut()
     obj.add('true', self._js_resource, discriminator_true)
     obj.add('false', self._js_resource, discriminator_false)
     obj.add('none', self._js_resource)
     self.assertEqual(obj.include_needed(None, None, None),
                      ['true', 'none'])
     needed = get_needed().resources()
     self.assertIn(self._js_resource, needed)
 def test_rendered_on_event(self):
     from arche.events import ViewInitializedEvent
     self.config.registry.settings['arche_ga.key'] = 'a_very_secret_code'
     self.config.include('arche_google_analytics')
     init_needed()
     request = testing.DummyRequest()
     view = self._mk_view(None, request)
     objectEventNotify(ViewInitializedEvent(view))
     needed = get_needed()
     self.assertTrue(needed.resources())
     self.assertIn('a_very_secret_code', needed.render())
Esempio n. 7
0
def test_convenience_clear_not_initialized():
    # This test is put near the top of this module, or at least before
    # the very first time ``init_needed()`` is called.
    dummy = get_needed()
    with pytest.raises(NotImplementedError):
        dummy.clear()
    with pytest.raises(NotImplementedError):
        clear_needed()

    # Initialize a needed resources object.
    needed = init_needed()
    assert get_needed() == needed
    assert thread_local_needed_data.__dict__[NEEDED] == needed

    # Clear it.
    del_needed()

    # It is gone, really.
    with pytest.raises(KeyError):
        thread_local_needed_data.__dict__[NEEDED]

    # Clearing it again is OK.
    del_needed()

    # get_needed still work, dummy-style.
    dummy2 = get_needed()
    assert dummy2 != needed
    with pytest.raises(NotImplementedError):
        dummy.clear()
    with pytest.raises(NotImplementedError):
        clear_needed()
Esempio n. 8
0
def test_library_url_base_url():
    foo = Library('foo', '')

    needed = init_needed(base_url="http://example.com/something")

    assert (needed.library_url(foo) ==
            'http://example.com/something/fanstatic/foo')
Esempio n. 9
0
def test_convenience_clear_not_initialized():
    # This test is put near the top of this module, or at least before
    # the very first time ``init_needed()`` is called.
    dummy = get_needed()
    with pytest.raises(NotImplementedError):
        dummy.clear()
    with pytest.raises(NotImplementedError):
        clear_needed()

    # Initialize a needed resources object.
    needed = init_needed()
    assert get_needed() == needed
    assert thread_local_needed_data.__dict__[NEEDED] == needed

    # Clear it.
    del_needed()

    # It is gone, really.
    with pytest.raises(KeyError):
        thread_local_needed_data.__dict__[NEEDED]

    # Clearing it again is OK.
    del_needed()

    # get_needed still work, dummy-style.
    dummy2 = get_needed()
    assert dummy2 != needed
    with pytest.raises(NotImplementedError):
        dummy.clear()
    with pytest.raises(NotImplementedError):
        clear_needed()
Esempio n. 10
0
def test_library_ordering_bug():
    jquery_lib = Library('jquery', '')
    jqueryui_lib = Library('jqueryui', '')
    obviel_lib = Library('obviel', '')
    bread_lib = Library('bread', '')
    app_lib = Library('app', '')

    jquery = Resource(jquery_lib, 'jquery.js')
    jqueryui = Resource(jqueryui_lib, 'jqueryui.js', depends=[jquery])

    obviel = Resource(obviel_lib, 'obviel.js', depends=[jquery])
    obviel_forms = Resource(obviel_lib, 'obviel_forms.js', depends=[obviel])
    obviel_datepicker = Resource(obviel_lib,
                                 'obviel_datepicker.js',
                                 depends=[obviel_forms, jqueryui])

    vtab = Resource(bread_lib, 'vtab.js', depends=[jqueryui])

    tabview = Resource(bread_lib, 'tabview.js', depends=[obviel, vtab])

    bread = Resource(bread_lib, 'bread.js', depends=[tabview, obviel_forms])

    app = Resource(app_lib, 'app.js', depends=[bread, obviel_datepicker])

    needed = init_needed(resources=[app])
    resources = sort_resources(needed.resources())
    for resource in resources:
        print((resource, resource.library.library_nr))
    assert resources == [
        jquery, jqueryui, obviel, obviel_forms, obviel_datepicker, vtab,
        tabview, bread, app
    ]
Esempio n. 11
0
def test_library_url_version_hashing(tmpdir):
    foo = Library('foo', tmpdir.strpath)
    # If the Library defines a version, the version is used.
    bar = Library('bar', '', version='1')

    needed = init_needed(versioning=True)
    url = needed.library_url(foo)
    assert re.match('/fanstatic/foo/:version:[0-9T:.-]*$', url)

    # The md5 based version URL is available through the
    # `versioning_use_md5` parameter:
    needed = init_needed(versioning=True, versioning_use_md5=True)
    md5_url = needed.library_url(foo)
    assert url != md5_url

    assert needed.library_url(bar) == '/fanstatic/bar/:version:1'
Esempio n. 12
0
def test_html_bottom_safe():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])
    y2 = Resource(foo, 'y2.js', bottom=True)

    needed = init_needed(resources=[y1, y2])
    injector = TopBottomInjector({})
    top, bottom = injector.group(needed)
    assert len(top) == 4
    assert len(bottom) == 0

    injector = TopBottomInjector(dict(bottom=True))
    top, bottom = injector.group(needed)
    assert len(top) == 3
    assert len(bottom) == 1
    # The bottom resource is y2.
    assert bottom.resources[0] == y2

    injector = TopBottomInjector(dict(bottom=True, force_bottom=True))
    top, bottom = injector.group(needed)
    assert len(top) == 1
    assert len(bottom) == 3

    top, bottom = injector.group(needed)
    assert len(top) == 1
    assert top.resources[0] == x2
    assert len(bottom) == 3
Esempio n. 13
0
def test_no_need_to_fill_in_not_required():
    lib = Library('lib', '')
    slot = Slot(lib, '.js', required=False)
    a = Resource(lib, 'a.js', depends=[slot])

    needed = init_needed(resources=[a])
    # slot wasn't required and not filled in, so filled slot doesn't show up
    assert needed.resources() == set([a])
Esempio n. 14
0
def test_slot_with_default_uses_default_if_nothing_given_in_need():
    lib = Library('lib', '')
    default_resource_for_slot = Resource(lib, 'b.js')
    slot = Slot(lib, '.js', default=default_resource_for_slot)
    a = Resource(lib, 'a.js', depends=[slot])
    needed = init_needed(resources=[a])
    relpaths = [r.relpath for r in sort_resources(needed.resources())]
    assert relpaths == ['b.js', 'a.js']
Esempio n. 15
0
def test_empty_base_url_and_publisher_signature():
    ''' When the base_url is not set and the publisher_signature is an empty string,
    render a URL without them. '''
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    needed = init_needed(publisher_signature='', resources=[x1])
    incl = Inclusion(needed)
    assert incl.render() == '''\
 def before_request(self):
     g.fanstatic = _FanstaticContext(
         init_needed(
             # TODO set base_url for this app if needed
             **current_app.config.get("FANSTATIC_OPTIONS", {})
         ),
         self,
     )
Esempio n. 17
0
def test_library_url_script_name_base_url():
    foo = Library('foo', '')
    needed = init_needed(script_name='/root',
                         base_url="http://example.com/something")

    # base_url is set so script_name should be ignored
    assert (needed.library_url(foo) ==
            'http://example.com/something/fanstatic/foo')
Esempio n. 18
0
def test_html_insert_head_with_attributes():
    # ticket 72: .need() broken when <head> tag has attributes
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    needed = init_needed(resources=[x1])

    injector = TopBottomInjector({})
    html = b'<html><head profile="http://example.org">something</head></html>'
    assert injector(html, needed) == b'''\
Esempio n. 19
0
def test_resource():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed()
    needed.need(y1)

    assert needed.resources() == set([x2, x1, y1])
Esempio n. 20
0
def test_rendering():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed(resources=[y1])
    incl = Inclusion(needed)

    assert incl.render() == '''\
Esempio n. 21
0
def test_inclusion_rollup_and_debug_missing():
    foo = Library('foo', '')
    h1 = Resource(foo, 'h1.js', debug='h1-debug.js')
    h2 = Resource(foo, 'h2.js', debug='h2-debug.js')
    gianth = Resource(foo, 'gianth.js', supersedes=[h1, h2])

    needed = init_needed(resources=[h1, h2])
    incl = Inclusion(needed, rollup=True, mode='debug')
    # No mode debug version of the rollup use it instead
    assert incl.resources == [gianth]
Esempio n. 22
0
def test_rendering_base_url_assign():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed(resources=[y1])
    needed.set_base_url('http://localhost/static')
    incl = Inclusion(needed)
    assert incl.render() == '''\
Esempio n. 23
0
    def test_register_form_resources(self):
        import colander
        import deform
        class DummySchema(colander.Schema):
            dummy = colander.SchemaNode(colander.String())
        dummy_form = deform.Form(DummySchema())

        from fanstatic import get_needed
        from fanstatic import init_needed
        from fanstatic import NeededResources
        init_needed() #Otherwise fanstatic won't get a proper needed resrouces object.
        context = testing.DummyResource()
        request = testing.DummyRequest()
        obj = self._cut(context, request)
        obj.register_form_resources(dummy_form)
        needed_resources = get_needed()
        self.assertIsInstance(needed_resources, NeededResources)
        filenames = [x.filename for x in needed_resources.resources()]
        #Note: Can be any filename registered by VoteIT. Just change it if this test fails :)
        self.assertIn('deform.css', filenames)
Esempio n. 24
0
def test_html_insert():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed(resources=[y1])

    injector = TopBottomInjector({})
    html = b"<html><head>something more</head></html>"
    assert injector(html, needed) == b'''\
def test_minified_mode_relpath_respect_subdir(compilers):
    compilers.add_compiler(MockCompiler())
    compilers.add_minifier(MockMinifier())
    lib = Library('lib', '')
    a = Resource(lib, 'foo/bar/a.js', compiler='mock', minifier='mock')

    needed = init_needed(resources=[a])
    incl = Inclusion(needed, compile=True, mode=MINIFIED)
    assert len(incl.resources) == 1
    assert incl.resources[0].relpath == 'foo/bar/a.min.js'
    assert incl.resources[0] != a
def test_bundle_resources():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.css')
    x2 = Resource(foo, 'b.css')
    x3 = Resource(foo, 'c.css', dont_bundle=True)

    bar = Library('bar', '')
    y1 = Resource(bar, 'y1.css')
    y2 = Resource(bar, 'y2.css')
    y3 = Resource(bar, 'subdir/y3.css')
    y4 = Resource(bar, 'subdir/y4.css')
    init_needed()

    bundle = bundle_resources([x1, x2])
    assert len(bundle) == 1
    assert isinstance(bundle[0], Bundle)

    # x3 is not bundle safe.
    bundle = bundle_resources([x1, x3])
    assert len(bundle) == 2
    # We don't create bundles of one element.
    assert bundle[0] == x1
    assert bundle[1] == x3

    # x2 and x1 are not bundled because x3 is in the way.
    # (sort_resources in NeededResources fixes the sorting)
    bundle = bundle_resources([x1, x3, x2])
    assert bundle == [x1, x3, x2]

    # The resources are sorted by renderer order, library dependencies
    # and resource dependencies.
    bundle = bundle_resources(sort_resources([x1, x3, x2]))
    assert len(bundle) == 2
    assert isinstance(bundle[0], Bundle)
    assert bundle[1] == x3

    bundle = bundle_resources([x1, x2, y1, y2])
    assert len(bundle) == 2

    bundle = bundle_resources([y1, y2, y3, y4])
    assert len(bundle) == 2
Esempio n. 27
0
def test_fill_slot_wrong_extension():
    lib = Library('lib', '')

    slot = Slot(lib, '.js')
    a = Resource(lib, 'a.js', depends=[slot])
    b = Resource(lib, 'b.css')

    needed = init_needed()
    needed.need(a, {slot: b})

    with pytest.raises(SlotError):
        needed.resources()
Esempio n. 28
0
def test_redundant_resource_reorder():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed()
    needed.need(x1)
    needed.need(x2)
    needed.need(y1)
    incl = Inclusion(needed)
    assert incl.resources == [x2, x1, y1]
Esempio n. 29
0
def test_sort_library_by_name():
    b_lib = Library('b_lib', '')
    a_lib = Library('a_lib', '')

    a_a = Resource(a_lib, 'a.js')
    a_b = Resource(b_lib, 'a.js')

    needed = init_needed()
    needed.need(a_b)
    needed.need(a_a)

    assert sort_resources(needed.resources()) == [a_a, a_b]
Esempio n. 30
0
def test_resource_subclass_render():
    foo = Library('foo', '')

    class MyResource(Resource):
        def render(self, library_url):
            return '<myresource reference="%s/%s"/>' % (library_url,
                                                        self.relpath)

    a = MyResource(foo, 'printstylesheet.css')
    needed = init_needed(resources=[a])
    incl = Inclusion(needed)
    assert incl.render() == """\
Esempio n. 31
0
def test_library_url_hashing_recompute(tmpdir):
    foo = Library('foo', tmpdir.strpath)

    needed = init_needed(versioning=True, recompute_hashes=True)

    url = needed.library_url(foo)

    # now create a file
    resource = tmpdir.join('test.js')

    time.sleep(0.5)
    # Sleep extra long on filesystems that report in seconds
    # instead of milliseconds.
    if os.path.getmtime(os.curdir).is_integer():
        time.sleep(1)
    resource.write('/* test */')

    # For a new request, the url is recomputed.
    new_needed = init_needed(versioning=True, recompute_hashes=True)
    # the hash is recalculated now, so it changes
    assert new_needed.library_url(foo) != url
Esempio n. 32
0
def test_html_top_bottom_force_bottom():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed(resources=[y1])
    injector = TopBottomInjector(dict(bottom=True, force_bottom=True))

    top, bottom = injector.group(needed)
    assert top.resources == [x2]
    assert bottom.resources == [x1, y1]
Esempio n. 33
0
def test_default_can_be_overridden():
    lib = Library('lib', '')
    default_resource_for_slot = Resource(lib, 'b.js')
    slot = Slot(lib, '.js', default=default_resource_for_slot)
    a = Resource(lib, 'a.js', depends=[slot])
    custom_resource_for_slot = Resource(lib, 'c.js')

    needed = init_needed()
    needed.need(a, {slot: custom_resource_for_slot})

    relpaths = [r.relpath for r in sort_resources(needed.resources())]
    assert relpaths == ['c.js', 'a.js']
Esempio n. 34
0
def test_top_bottom_insert():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    html = b"<html><head>start of head</head><body>rest of body</body></html>"

    needed = init_needed(resources=[y1])

    injector = TopBottomInjector(dict(bottom=True, force_bottom=True))
    assert injector(html, needed) == b'''\
Esempio n. 35
0
def test_redundant_more_complicated_depends_on_all():
    foo = Library('foo', '')
    a1 = Resource(foo, 'a1.js')
    a2 = Resource(foo, 'a2.js', depends=[a1])
    a3 = Resource(foo, 'a3.js', depends=[a2])
    a4 = Resource(foo, 'a4.js', depends=[a1])
    a5 = Resource(foo, 'a5.js', depends=[a4, a3])

    needed = init_needed()
    needed.need(a5)
    incl = Inclusion(needed)
    assert incl.resources == [a1, a2, a4, a3, a5]
Esempio n. 36
0
def test_convenience_need():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    needed = init_needed()
    assert get_needed() == needed
    assert get_needed().resources() == []

    y1.need()

    assert get_needed().resources() == [x2, x1, y1]
Esempio n. 37
0
def test_convenience_group_resource_need():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js')
    group = Group([x1, x2, y1])

    needed = init_needed()
    assert get_needed() == needed
    assert get_needed().resources() == []

    group.need()

    assert get_needed().resources() == [x2, x1, y1]
Esempio n. 38
0
def test_resource_need_should_pass_slots_to_needed():
    import fanstatic

    lib = Library("lib", "")
    c = Resource(lib, "c.js")
    slot = Slot(lib, ".js", depends=[c])
    a = Resource(lib, "a.js", depends=[slot])
    b = Resource(lib, "b.js", depends=[c])
    needed = fanstatic.init_needed()
    try:
        a.need({slot: c})
    finally:
        fanstatic.del_needed()
    assert slot in needed._slots
Esempio n. 39
0
    def __call__(self, request):

        # publisher
        if len(request.path_info.split(self.trigger)) > 1:
            path_info = request.path_info
            ignored = request.path_info_pop()
            while ignored != self.publisher_signature:
                ignored = request.path_info_pop()
            response = request.get_response(self.publisher)
            # forward to handler if the resource could not be found
            if response.status_int == 404:
                request.path_info = path_info
                return self.handler(request)
            return response

        # injector
        needed = fanstatic.init_needed(**self.config)
        if self.use_application_uri and not needed.has_base_url():
            base_url = wsgiref.util.application_uri(request.environ)
            # remove trailing slash for fanstatic
            needed.set_base_url(base_url.rstrip('/'))
        request.environ[fanstatic.NEEDED] = needed

        response = self.handler(request)

        if not (response.content_type and
                response.content_type.lower() in ['text/html',
                                                  'text/xml']):
            fanstatic.del_needed()
            return response

        if needed.has_resources():
            # Using response.body may cause a UnicodeDecodeError if some of
            # the libraries contain unicode strings. So it's best to pass
            # unicode_body directly, so the regexps won't fail.
            if self.injector is not None:
                result = self.injector(response.unicode_body,
                                       needed, request, response)
            else:
                result = needed.render_topbottom_into_html(
                    response.unicode_body)
            response.body = ''
            response.write(result)
        fanstatic.del_needed()
        return response
Esempio n. 40
0
def test_convenience_clear():
    foo = Library('foo', '')
    x1 = Resource(foo, 'a.js')
    x2 = Resource(foo, 'b.css')
    y1 = Resource(foo, 'c.js', depends=[x1, x2])

    z1 = Resource(foo, 'd.js')
    z2 = Resource(foo, 'e.js', depends=[z1, x1])

    needed = init_needed(resources=[y1])

    assert sort_resources(needed.resources()) == [x2, x1, y1]
    # For some reason,for example an error page needs to be rendered,
    # the currently needed resources need to be cleared.
    clear_needed()
    assert len(needed.resources()) == 0
    z2.need()
    assert sort_resources(needed.resources()) == [x1, z1, z2]
Esempio n. 41
0
    def __call__(self, environ, start_response):
        request = webob.Request(environ)
        # We only continue if the request method is appropriate.
        if not request.method in ['GET', 'POST']:
            return self.app(environ, start_response)

        # Initialize a needed resources object.
        # XXX this will set the needed on the thread local data, even
        # if the wrapped framework only gets the needed from the WSGI
        # environ.
        needed = fanstatic.init_needed(
            script_name=request.environ.get('SCRIPT_NAME'), **self.config)

        # Make sure the needed resource object is put in the WSGI
        # environment as well, for frameworks that choose to use it
        # from there.
        request.environ[fanstatic.NEEDED] = needed

        # Get the response from the wrapped application:
        response = request.get_response(self.app)

        # We only continue if the content-type is appropriate.
        if not (response.content_type and
                response.content_type.lower() in CONTENT_TYPES):
            # Clean up after our behinds.
            fanstatic.del_needed()
            return response(environ, start_response)

        # The wrapped application may have `needed` resources.
        if needed.has_resources():
            # Can't use response.text because there might not be any
            # charset. body is not unicode.
            result = needed.render_topbottom_into_html(response.body)
            # Reset the body...
            response.body = b''
            # Write will propely unfolder the previous application and
            # call close. Setting response.text or response.body won't do it.
            response.write(result)

        # Clean up after our behinds.
        fanstatic.del_needed()

        return response(environ, start_response)
Esempio n. 42
0
            def decorated(request):
                # injector
                needed = fanstatic.init_needed(**self.config)
                request.environ[fanstatic.NEEDED] = needed

                self.need_fanstatic()
                response =  view(request)
                if not (response.content_type and
                        response.content_type.lower() in ['text/html',
                                                          'text/xml']):
                    fanstatic.del_needed()
                    return response

                if needed.has_resources():
                    result = needed.render_topbottom_into_html(response.body)
                    response.body = ''
                    response.write(result)
                fanstatic.del_needed()
                return response
Esempio n. 43
0
    def __call__(self, request):

        # publisher
        if len(request.path_info.split(self.trigger)) > 1:
            path_info = request.path_info
            ignored = request.path_info_pop()
            while ignored != self.publisher_signature:
                ignored = request.path_info_pop()
            response = request.get_response(self.publisher)
            # forward to handler if the resource could not be found
            if response.status_int == 404:
                request.path_info = path_info
                return self.handler(request)
            return response

        # injector
        needed = fanstatic.init_needed(**self.config)
        if self.use_application_uri and not needed.has_base_url():
            base_url = wsgiref.util.application_uri(request.environ)
            # remove trailing slash for fanstatic
            needed.set_base_url(base_url.rstrip("/"))
        request.environ[fanstatic.NEEDED] = needed

        response = self.handler(request)

        if not (response.content_type and response.content_type.lower() in ["text/html", "text/xml"]):
            fanstatic.del_needed()
            return response

        if needed.has_resources():
            if self.injector is not None:
                result = self.injector(response.body, needed, request, response)
            else:
                result = needed.render_topbottom_into_html(response.body)
            try:
                response.text = ""
            except TypeError:
                response.body = ""
            response.write(result)
        fanstatic.del_needed()
        return response
Esempio n. 44
0
    def __call__(self, request):
        needed = fanstatic.init_needed(**self.config)
        if self.use_application_uri and not needed.has_base_url():
            base_url = wsgiref.util.application_uri(request.environ)
            # remove trailing slash for fanstatic
            needed.set_base_url(base_url.rstrip('/'))
        request.environ[fanstatic.NEEDED] = needed

        try:
            response = self.handler(request)

            if response.content_type \
                   and response.content_type.lower() in CONTENT_TYPES \
                   and needed.has_resources():

                result = self.injector(response.body, needed, request, response)
                response.body = ''
                response.write(result)

            return response
        finally:
            fanstatic.del_needed()
Esempio n. 45
0
    def __call__(self, request):
        # We only continue if the request method is appropriate.
        if not request.method in ['GET', 'POST']:
            return request.get_response(self.app)

        # Initialize a needed resources object.
        # XXX this will set the needed on the thread local data, even
        # if the wrapped framework only gets the needed from the WSGI
        # environ.
        needed = fanstatic.init_needed(**self.config)

        # Make sure the needed resource object is put in the WSGI
        # environment as well, for frameworks that choose to use it
        # from there.
        request.environ[fanstatic.NEEDED] = needed

        # Get the response from the wrapped application:
        response = request.get_response(self.app)

        # We only continue if the content-type is appropriate.
        if not (response.content_type and
                response.content_type.lower() in ['text/html', 'text/xml']):
            # Clean up after our behinds.
            fanstatic.del_needed()
            return response

        # The wrapped application may have `needed` resources.
        if needed.has_resources():
            result = needed.render_topbottom_into_html(response.body)
            # Reset the body...
            response.body = ''
            # And write the result. The `write` method handles unicode results.
            response.write(result)

        # Clean up after our behinds.
        fanstatic.del_needed()

        return response
Esempio n. 46
0
    def transformIterable(self, result, encoding):
        if not isinstance(result, XMLSerializer):
            getHeader = self.request.response.getHeader

            content_type = getHeader('Content-Type')
            if content_type is None or \
                    not content_type.startswith('text/html'):
                return None

            contentEncoding = getHeader('Content-Encoding')
            if contentEncoding and \
                    contentEncoding in ('zip', 'deflate', 'compress',):
                return None

            try:
                result = getHTMLSerializer(result, encoding=encoding,
                        pretty_print=self.pretty_print)
            except (TypeError, etree.ParseError):
                return None

        resources = fanstatic.init_needed(
                base_url=self.request.getURL(),
                publisher_signature='/++fanstatic++/',
                )

        from plone.fanstatic import groups
        for group in groups:
            group.need()

        resources = etree.HTML(resources.render()).find('head').getchildren()
        head = resources and result.tree.getroot().find('head') or None
        # Ajax are without head...
        if head:
            for item in resources:
                head.append(item)

        return result
Esempio n. 47
0
 def setUp(self):
     fanstatic.init_needed()
     self.context = object()
     self.request = TestRequest()
     self.resource_namespace  = getMultiAdapter(
         (self.context, self.request), ITraversable, name='resource')
Esempio n. 48
0
 def setUp(self):
     self.config = testing.setUp()
     init_needed()
Esempio n. 49
0
def initalize_fanstatic(context, event):
        base_url = IBaseUrl(event.request).url()
        base_url = base_url[:-1]  # just remove the slash (IBaseUrl always return a slash at the end)
        needed = fanstatic.init_needed(base_url=base_url, debug=False)
        context.resources.need()
Esempio n. 50
0
def _clearFLib(*args):
    from deform_autoneed import deform_autoneed_lib
    #To clear any old registered resources - needs to be done on test start too for some reason.
    deform_autoneed_lib.known_resources = {}
    init_needed()
Esempio n. 51
0
 def __init__(self, manager, **config):
   # call this first, to pop some items from the config
   self._injector = _make_injector(config)
   self._needed = init_needed(**config)
   self._manager = manager
   self._rendered = False
Esempio n. 52
0
 def test_start_raiting_included(self):
     from voteit.core.fanstaticlib import _star_rating_css
     init_needed()
     obj = self._cut()
     needed = get_needed().resources()
     self.assertIn(_star_rating_css, needed)