Beispiel #1
0
    def test_pop(self):
        new = Div().append_to(self.page)
        self.page.pop(0)
        self.assertTrue(new not in self.page)
        new2 = Div().append_to(self.page)
        self.page.pop()
        self.assertTrue(new2 not in self.page)
        new3 = Div()
        self.page(child_foo=new3)
        self.page.pop('child_foo')
        self.assertTrue(new3 not in self.page)
        new4, new5 = Div(), Div()
        self.page(child_foo_1=new4)
        self.page(child_foo_2=new4)
        self.page.pop(['child_foo_1', 'child_foo_2'])
        self.assertTrue(new4 not in self.page and new5 not in self.page)

        with self.assertRaises(DOMModByKeyError):
            test = Div()(test_key=A())
            test.pop('nonexistentkey')

        with self.assertRaises(DOMModByIndexError):
            test = Div()(A(), P())
            test.pop(2)
Beispiel #2
0
 def init(self):
     self.body.main.container.attr(klass="album py-5 bg-light")
     self.body.main.container(
         Div(klass="container")(Div(klass='row')(persons=[
             Div(klass='col-md-4')(Div(klass='card mb-4 shadow-sm')(A(
                 href=f'person/{person.person_id}')(Div(
                     klass='card-body'
                 )(P(klass='card-text')
                   (f'{person.name.title()} {person.second_name.title()}'),
                   contacts=[
                       Div(klass='contactIcon')(I(klass=CONTACTS_ICONS.get(
                           contact.contact_type, 'noIcon')))
                       for contact in person.contacts
                   ])))) for person in self.content_data['people']
         ])))
Beispiel #3
0
    def test_root(self):
        class Obj:
            foo = 'foo'
            bar = 'bar'

            class Div(TempyREPR):
                def repr(self):
                    self(self.bar)

            class Pre(TempyREPR):
                def repr(self):
                    self(self.foo + 'test')

        inst = Obj()
        self.assertEqual(Pre()(Span()(A()(inst))).render(),
                         '<pre><span><a>footest</a></span></pre>')
Beispiel #4
0
    def test_after_places(self):
        class Obj:
            foo = 'foo'
            bar = 'bar'

            class TestA(AfterDiv):
                def repr(self):
                    self(self.bar)

            class A(AfterSpan):
                def repr(self):
                    self(self.foo + 'test')

        inst = Obj()
        self.assertEqual(Pre()(Span(), A()(inst)).render(),
                         '<pre><span></span><a>footest</a></pre>')
        self.assertEqual(Pre()(Div(), Div()(inst)).render(),
                         '<pre><div></div><div>bar</div></pre>')
Beispiel #5
0
    def test_near_places(self):
        class Obj:
            foo = 'foo'
            bar = 'bar'

            class TestA(NearDiv):
                def repr(self):
                    self(self.bar)

            class TestB(NearSpan):
                def repr(self):
                    self(self.foo + 'test')

        inst = Obj()
        self.assertEqual(Pre()(Span(), A()(inst)).render(),
                         '<pre><span></span><a>footest</a></pre>')
        self.assertEqual(Pre()(T.Custom()(inst), Div()).render(),
                         '<pre><custom>bar</custom><div></div></pre>')
Beispiel #6
0
    def init(self):
        self(Div(klass='pageTitle')('Rottura Del Silenzio'))
        self(
            Pre(klass='preText')("""
Dal 1998 Associazione Ekidna organizza la Rottura Del Silenzio, un festival diy (do it yourself).
Dopo 20 anni non sappiamo più cosa dire per raccontarla, quindi lo lasciamo fare agli altri:"""
            ),
            Blockquote()(Pre(klass='preText')("""Succede che in Emilia, qui dalle nostre parti, finita la primavera, ci viene una certa voglia di stare seduti su un prato tutti rivolti verso un palco, con uno sguazzone  in mano (acqua frizzante con vino bianco scadente), andando a tempo di musica con la testa. Il bello di queste cose è che iniziano al venerdì sera e vanno avanti fino alla domenica. Un’altra cosa bella è che solitamente si entra a offerta libera;: lasci quello che vuoi, se lo vuoi.

Entri in questi posti e sei circondato tutto il giorno dalla musica di gruppi di cui non conosci manco il nome ma dentro di te pensi: “Cazzo! Questi spaccano!” e avvicinandoti ad una tizia chiedi il nome di chi ha appena suonato così te li puoi andare a riascoltare su Spotify, scoprendo poi che sono meglio dal vivo. Ti chiedi anche se la conversazione con la tizia citata sopra avrà un epilogo felice, ma scopri con grosso dispiacere che è lesbica e che quindi, forse, è meglio tornare con i tuoi amici a fumare e a prendere l’ennesimo sguazzone. Girando scopri anche che ci sono un sacco di banchetti. Ce n’è uno di un’etichetta indipendente che crede ancora nel fare musica DOITYOURSELF, come dovrebbe essere. Poi ce n’è un altro di una rivista, che stampa giornaletti e li dà via a gratis! Cioè veramente, tu puoi prenderne quanti ne vuoi, per amici, parenti, morose, basta che si leggano. Guarda questi! Scrivono per il puro piacere di scrivere, per il puro piacere di raccontare. Sempre DOITYOURSELF, sia chiaro! Poi ce n’è un altro che vende braccialetti DOITYOURSELF di cui sicuramente la tua ex-morosa fricchettona-ma-anche-no, ne sarebbe stata entusiasta. Poi ragioni un po’ sul DOITYOURSELF, ma veramente questa gente si sbatte per fare qualcosa? Ti guardi intorno e vedi che sono tutti felici e sorridenti, come dovrebbe essere. Capisci che queste persone si sbattono perchè lo vogliono, per l’amore di fare, per lo stare insieme, per la musica e per divertirsi. E pensi che questo posto è proprio un bel posto.

Uno di questi si chiama Ekidna, un circolo alle porte di Carpi (San Martino Scuole), a cui piace molto fare le cose (e le fanno veramente bene). In estate organizza questo festival che si chiama ROTTURA DEL SILENZIO; ora mai sono arrivati alla diciannovesima edizione. Quest’anno si svolgerà il 17-18-19 giugno e noi di Mumble: siamo felicissimi di farne parte. Per tutti i tre giorni ci suoneranno un sacco di gruppi, banchetti, cibo e sguazzoni. Il tutto è ad offerta libera e consigliamo veramente la presenza, non per tutte le cose citate sopra, ma perchè, in realtà, questi ragazzi hanno un Idromele (DOITYOURSELF) che è la fine del mondo."""
            )),
            "Giacomo Malaguti - ", A(href="http://www.mumbleduepunti.it/")('MUMBLE:'), Br(), Br(),
            "Per proporvi con banchetti, per dare una mano, per seperne qualcosa di più o solo per dire che ti piace: ", A(href="https://www.facebook.com/rotturadelsilenzio/")('facebook.com/rotturadelsilenzio')
        )
        self(Br(), Br())
        self(Div(id='photos')(
                Img(src=url_for('static', filename='img/rottura/%s' % pic)) for pic in sorted(self._data.get('locandine',[]), reverse=True)
            )
        )
        self(self._get_analytics())
Beispiel #7
0
    def test_inside_places(self):
        class Obj:
            foo = 'foo'
            bar = 'bar'

            class TestA(InsideDiv):
                def repr(self):
                    self(self.bar)

            class A(InsideSpan):
                def repr(self):
                    self(self.foo + 'test')

            class Test2(InsideP):
                def repr(self):
                    self(self.bar + 'test')

        inst = Obj()
        self.assertEqual(Span()(A()(inst)).render(),
                         '<span><a>footest</a></span>')
        self.assertEqual(Div()(Div()(inst)).render(),
                         '<div><div>bar</div></div>')
        self.assertEqual(P()(T.CustomTag()(inst)).render(),
                         '<p><customtag>bartest</customtag></p>')
Beispiel #8
0
 def test_contents(self):
     test = [A(), Div(), P()]
     div = Div()(test)
     self.assertEqual(div.contents(), test)
Beispiel #9
0
 def test_reverse(self):
     div = Div()(A(), Div(), P())
     test = next(reversed(div))
     self.assertTrue(isinstance(test, P))
Beispiel #10
0
 def test_next_magic(self):
     div = Div()(A(), P(), Div())
     test = next(div)
     self.assertTrue(isinstance(test, A))
Beispiel #11
0
 def test_replace_with(self):
     old = Div().append_to(self.page)
     old.replace_with(A())
     self.assertTrue(isinstance(self.page[0], A))
Beispiel #12
0
 def test_next_childs(self):
     d = Div()
     childs = [A(), P(), P(), Div(), 'test', 1]
     d(childs)
     self.assertEqual(childs[0], next(d))
Beispiel #13
0
 def test_childs_index(self):
     div = Div()
     a = A()
     div(P(), P(), a)
     self.assertEqual(div[2], a)
Beispiel #14
0
 def test_fill_a(self):
     a = A(href='www.test.com')
     expected = '<a href="www.test.com">www.test.com</a>'
     self.assertEqual(a.render(), expected)
Beispiel #15
0
from tempy.tags import Html, Head, Body, Meta, Link, Div, P, A
my_text_list = ['This is foo', 'This is Bar', 'Have you met my friend Baz?']
another_list = ['Lorem ipsum ', 'dolor sit amet, ', 'consectetur adipiscing elit']

# make tags instantiating TemPy objects
page = Html()(  # add tags inside the one you created calling the parent
    Head()(  # add multiple tags in one call
        Meta(charset='utf-8'),  # add tag attributes using kwargs in tag initialization
        Link(href="my.css", typ="text/css", rel="stylesheet")
    ),
    body=Body()(  # give them a name so you can navigate the DOM with those names
        Div(klass='linkBox')(
            A(href='www.foo.com')
        ),
        (P()(text) for text in my_text_list),  # tag insertion accepts generators
        another_list  # add text from a list, str.join is used in rendering
    )
)

# add tags and content later
page[1][0](A(href='www.bar.com'))  # calling the tag
page(test=Div()) # WARNING! Correct ordering with named Tag insertion is ensured with Python >= 3.5 (because kwargs are ordered)
page[1][0].append(A(href='www.baz.com'))  # using the API
link = Link().append_to(page.body) # access the body as if it's a page attribute
link.attr(href='www.python.org')('This is a link to Python') # Add attributes and content to already placed tags

page.render() # does not return on Python shell

testfile = open("tempyTest.html", "w")
print(page.render(), file=testfile)
testfile.close()
Beispiel #16
0
 def test_children(self):
     test = [A(), Div(), P(), 'test']
     div = Div()(test)
     self.assertEqual(list(div.children()), test[:-1])
Beispiel #17
0
 def test_iadd(self):
     a = A()
     div = Div()
     div += a
     self.assertTrue(a in div)
     self.assertEqual(div[0], a)
Beispiel #18
0
from tempy.tags import Html, Head, Body, Meta, Link, Div, P, A
my_text_list = ['This is foo', 'This is Bar', 'Have you met my friend Baz?']
another_list = [
    'Lorem ipsum ', 'dolor sit amet, ', 'consectetur adipiscing elit'
]

# make tags instantiating TemPy objects
page = Html()(  # add tags inside the one you created calling the parent
    Head()(  # add multiple tags in one call
        Meta(charset='utf-8'
             ),  # add tag attributes using kwargs in tag initialization
        Link(href="my.css", typ="text/css", rel="stylesheet")),
    body=Body()
    (  # give them a name so you can navigate the DOM with those names
        Div(klass='linkBox')(A(href='www.foo.com')),
        (P()(text)
         for text in my_text_list),  # tag insertion accepts generators
        another_list  # add text from a list, str.join is used in rendering
    ))

# add tags and content later
page[1][0](A(href='www.bar.com'))  # calling the tag
page[1][0].append(A(href='www.baz.com'))  # using the API
link = A().append_to(
    page.body[0])  # access the body as if it's a page attribute
page.body(
    testDiv=Div()
)  # WARNING! Correct ordering with named Tag insertion is ensured with Python >= 3.5 (because kwargs are ordered)
link.attr(href='www.python.org')(
    'This is a link to Python.'
)  # Add attributes and content to already placed tags
Beispiel #19
0
 def test_iter_chidls(self):
     d = Div()
     childs = [A(), P(), P(), Div(), 'test', 1]
     d(childs)
     for i, child in enumerate(d):
         self.assertEqual(childs[i], child)
Beispiel #20
0
    def test_replace_element(self):
        link = A()
        css = Css({
            'html': {
                'body': {
                    'color': 'red',
                    Div: {
                        'color': 'green',
                        'border': '1px'
                    },
                    link: {
                        'color': 'purple'
                    },
                    A: {
                        'color': 'yellow'
                    }
                }
            },
            '#myid': {
                'color': 'blue'
            }
        })

        css_values = {
            'html': {
                'body': {
                    'color': 'red',
                    Div: {
                        'color': 'green',
                        'border': '1px'
                    },
                    link: {
                        'color': 'grey'
                    },
                    A: {
                        'color': 'yellow'
                    }
                }
            },
            '#myid': {
                'color': 'purple'
            }
        }

        css.replace_element(['#myid'], {'color': 'purple'})
        self.assertEqual({'color': 'purple'}, css.attrs['css_attrs']['#myid'])

        # nested example
        css.replace_element(['html', 'body', link], {'color': 'grey'})
        self.assertEqual({'color': 'grey'},
                         css.attrs['css_attrs']['html']['body'][link])

        # failed to find
        css.replace_element(['myid'], {'color': 'purple'})
        self.assertEqual({'color': 'purple'}, css.attrs['css_attrs']['#myid'])
        with self.assertRaises(AttrNotFoundError):
            css.replace_element(['myid'], {'color': 'purple'},
                                ignore_error=False)

        # wrong args type
        css.replace_element('', None)
        self.assertEqual(css_values, css.attrs['css_attrs'])
        with self.assertRaises(WrongArgsError):
            css.replace_element('', None, ignore_error=False)

        css.replace_element('', {'color': 'purple'})
        self.assertEqual(css_values, css.attrs['css_attrs'])
        with self.assertRaises(WrongArgsError):
            css.replace_element('', {'color': 'purple'}, ignore_error=False)

        css.replace_element(['html'], {'color': 'purple'})
        self.assertEqual({'color': 'purple'}, css.attrs['css_attrs']['html'])
Beispiel #21
0
 def test_iter_reversed(self):
     d = Div()
     childs = [A(), P(), P(), Div(), 'test', 1]
     d(childs)
     for t_child, child in zip(reversed(childs), reversed(d)):
         self.assertEqual(t_child, child)
Beispiel #22
0
 def init(self):
     from pprint import pprint
     pprint(self.__dict__)
     self.head(self.css())
     self.head(
         Meta(charset="utf-8"),
         Meta(
             name="viewport",
             content="width=device-width, initial-scale=1, shrink-to-fit=no"
         ),
         Title()(f'{self.app.config.project_name} - {self.page_title}'))
     self.content_title = Div(
         klass='d-flex justify-content-between flex-wrap '
         'flex-md-nowrap align-items-center pb-2 mb-3 border-bottom')(
             H1(klass='h2')(self.page_title), self.breadcrumb)
     self.content = Div(
         klass=
         'd-flex justify-content-between flex-wrap pb-2 mb-3 flex-md-nowrap'
     )
     self.body(
         Nav(klass='navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0'
             )(A(klass='navbar-brand col-sm-3 col-md-2 mr-0',
                 href='/app')(self.app.config.project_name),
               Input(klass='form-control form-control-dark w-100',
                     typ='text',
                     placeholder='Search',
                     **{'aria-label': 'Search'}),
               Ul(klass='navbar-nav px-3')(Li(klass='nav-item text-nowrap')(
                   A(klass='nav-link', href='/signout')('Sign out')))),
         Div(klass="container-fluid")(Div(klass='row')(Nav(
             klass='col-md-2 d-none d-md-block bg-light sidebar'
         )(Div(klass='sidebar-sticky')(
             Ul(klass='nav flex-column')
             (Li(klass='nav-item')(A(klass='nav-link active', href='/app')(
                 I(klass='fas fa-home'
                   ),
                 ' Dashboard',
                 Span(klass='sr-only')
                 ('(current)')
             )),
              Li(klass=
                 'nav-item sidebar-heading d-flex justify-content-between '
                 'align-items-center px-3 mt-4 mb-1 text-muted')
              (A(klass='nav-link', href='/app/processes')(
                  I(klass="fas fa-chalkboard-teacher"),
                  ' Processes ',
              ),
               A(klass='navbar-toggler collapsed',
                 **{
                     "data-toggle": "collapse",
                     "data-target": "#processesList",
                     "aria-expanded": "false"
                 })(I(klass="fas fa-plus-circle navbar-toggler-icon"))),
              Div(klass="collapse",
                  id="processesList")(Ul(klass="nav flex-column")(
                      Li(klass='nav-item')(A(
                          href=f'/app/processes/{process.name.lower()}',
                          klass='nav-link')(I(
                              klass=f'fas {process.icon}'), ' ' +
                                            process.name.title()))
                      for process in self.app.processes.values()))),
             H6(klass='sidebar-heading d-flex justify-content-between '
                'align-items-center px-3 mt-4 mb-1 text-muted')(
                    Span()('Saved Links')),
         )),
                                                       Main(
                                                           role='main',
                                                           klass=
                                                           'col-md-9 ml-sm-auto col-lg-10 pt-3 px-4'
                                                       )(self.content_title,
                                                         self.content))),
         self.js())