Best Python code snippet using lisa_python
__init__.py
Source:__init__.py  
...21        # Data initialization22        self.templates = {}23        if template_list is not None:24            self.templates.update(template_list)25    def _load_template(self, tpl_key, tpl_data=None):26        """ Instantiate a preloaded template27        Parameters:28            tpl_key:29            tpl_data:30        Returns:31        """32        add_context = {}33        context = RequestContext(HttpRequest())34        if tpl_data is not None:35            add_context.update(tpl_data)36            context.update(add_context)37        return self.templates[tpl_key].render(context)38class HtmlRenderer(BaseRenderer):39    """ Renderer for HTML forms40    """41    def __init__(self, template_list=None):42        """ Init function43        Parameters:44            template_list:45        """46        # Parameters test47        # if template_list is not None:48        #     if type(template_list) != dict:49        #         raise TypeError("template_list type is wrong (" + str(type(template_list)) + " received, dict needed")50        #51        #     for template in template_list.values():52        #         if not isinstance(template, Template):53        #             template_type = str(type(template_list))54        #             raise TypeError("template value type is wrong (" + template_type + " received, dict needed")55        # Data initialization56        html_renderer_templates_path = join('renderer', 'default')57        html_templates = {58            'form_error': loader.get_template(join(html_renderer_templates_path, 'form-error.html')),59            'warning': loader.get_template(join(html_renderer_templates_path, 'warning.html')),60            'input': loader.get_template(join(html_renderer_templates_path, 'inputs', 'input.html')),61            'select': loader.get_template(join(html_renderer_templates_path, 'inputs', 'select.html')),62            'btn_add': loader.get_template(join(html_renderer_templates_path, 'buttons', 'add.html')),63            'btn_del': loader.get_template(join(html_renderer_templates_path, 'buttons', 'delete.html')),64            'btn_collapse': loader.get_template(join(html_renderer_templates_path, 'buttons', 'collapse.html'))65        }66        if template_list is not None:67            html_templates.update(template_list)68        super(HtmlRenderer, self).__init__(html_templates)69    def _render_form_error(self, err_message):70        context = RequestContext(HttpRequest())71        data = {72            'message': err_message73        }74        context.update(data)75        return self.templates['form_error'].render(context)76    def _render_warnings(self, warnings):77        html_content = ''78        for warning in warnings:79            data = {80                'message': warning81            }82            html_content += self._load_template('warning', data)83        return html_content84    # def _render_input(self, input_id, value, placeholder, title):85    def _render_input(self, element):86        """87        :param element88        :return:89        """90        if not isinstance(element, SchemaElement):91            raise TypeError('element should be SchemaElement (' + str(type(element)) + ' given)')92        placeholder = ''93        tooltip = ''94        use = ''95        if 'placeholder' in element.options:96            placeholder = element.options['placeholder']97        if 'tooltip' in element.options:98            tooltip = element.options['tooltip']99        if 'use' in element.options:100            use = element.options['use']101        data = {102            'id': element.pk,103            'value': element.value,104            'placeholder': placeholder,105            'tooltip': tooltip,106            'use': use,107        }108        return self._load_template('input', data)109    def _render_select(self, select, select_class, option_list):110        # if type(select_id) not in [str, unicode, NoneType]:111        #     raise TypeError('First param (select_id) should be a str or None (' + str(type(select_id)) + ' given)')112        #113        # if not isinstance(option_list, types.ListType):114        #     raise TypeError('First param (option_list) should be a list (' + str(type(option_list)) + ' given)')115        #116        # for option in option_list:117        #     if not isinstance(option, types.TupleType):118        #         raise TypeError('Malformed param (option_list): type of item not good')119        #120        #     if len(option) != 3:121        #         raise TypeError('Malformed param (option_list): Length of item not good')122        #123        #     if type(option[0]) not in [str, unicode]:124        #         raise TypeError('Malformed param (option_list): item[0] should be a str')125        #126        #     if type(option[1]) not in [str, unicode]:127        #         raise TypeError('Malformed param (option_list): item[1] should be a str')128        #129        #     if type(option[2]) != bool:130        #         raise TypeError('Malformed param (option_list): item[2] should be a bool')131        data = {132            'select_id': select.pk,133            'select_class': select_class,134            'option_list': option_list135        }136        return self._load_template('select', data)137    # def _render_buttons(self, min_occurs, max_occurs, occurence_count):138    def _render_buttons(self, add_button, delete_button):139        """140        :param min_occurs:141        :param max_occurs:142        :param occurence_count:143        :return:144        """145        # add_button = False146        # del_button = False147        #148        # if occurence_count < max_occurs or max_occurs == -1:149        #     add_button = True150        #151        # if occurence_count > min_occurs:152        #     del_button = True153        #154        # if occurence_count < min_occurs:155        #     pass156        #157        # add_button_type = type(add_button)158        # del_button_type = type(del_button)159        #160        # if add_button_type is not bool:161        #     raise TypeError('add_button type is wrong (' + str(add_button_type) + 'received, bool needed')162        #163        # if del_button_type is not bool:164        #     raise TypeError('add_button type is wrong (' + str(del_button_type) + 'received, bool needed')165        #166        # form_string = ""167        #168        # # Fixed number of occurences, don't need buttons169        # if add_button or del_button:170        #     if add_button:171        #         form_string += self._load_template('btn_add', {'is_hidden': False})172        #     else:173        #         form_string += self._load_template('btn_add', {'is_hidden': True})174        #175        #     if del_button:176        #         form_string += self._load_template('btn_del', {'is_hidden': False})177        #     else:178        #         form_string += self._load_template('btn_del', {'is_hidden': True})179        #180        # return form_string181        # FIXME Remove type checking182        add_button_type = type(add_button)183        del_button_type = type(delete_button)184        if add_button_type is not bool:185            raise TypeError('add_button type is wrong (' + str(add_button_type) + 'received, bool needed')186        if del_button_type is not bool:187            raise TypeError('add_button type is wrong (' + str(del_button_type) + 'received, bool needed')188        form_string = ""189        # Fixed number of occurences, don't need buttons190        if not (add_button or delete_button):191            pass192        else:193            if add_button:194                form_string += self._load_template('btn_add', {'is_hidden': False})195            else:196                form_string += self._load_template('btn_add', {'is_hidden': True})197            if delete_button:198                form_string += self._load_template('btn_del', {'is_hidden': False})199            else:200                form_string += self._load_template('btn_del', {'is_hidden': True})201        return form_string202    def _render_collapse_button(self):203        return self._load_template('btn_collapse')204class DefaultRenderer(object):205    def __init__(self, xsd_data, template_list=None):206        """ Default renderer for the HTML form207        Parameters:208            - xsd_data:209            - template_list:210        """211        if not isinstance(xsd_data, SchemaElement):212            raise TypeError("xsd_data type should be a SchemaElement")213        if template_list is not None:214            if type(template_list) != dict:215                raise TypeError("template_list type is wrong (" + str(type(template_list)) + " received, dict needed")216            for template in template_list.values():217                if not isinstance(template, Template):218                    template_type = str(type(template_list))219                    raise TypeError("template value type is wrong (" + template_type + " received, dict needed")220        self.data = xsd_data221        self.warnings = []222        default_renderer_path = join('renderer', 'default')223        self.templates = {224            'form_error': loader.get_template(join(default_renderer_path, 'form-error.html')),225            'warning': loader.get_template(join(default_renderer_path, 'warning.html')),226            'input': loader.get_template(join(default_renderer_path, 'inputs', 'input.html')),227            'select': loader.get_template(join(default_renderer_path, 'inputs', 'select.html')),228            'checkbox': loader.get_template(join(default_renderer_path, 'inputs', 'checkbox.html')),229            'btn_add': loader.get_template(join(default_renderer_path, 'buttons', 'add.html')),230            'btn_del': loader.get_template(join(default_renderer_path, 'buttons', 'delete.html')),231            'btn_collapse': loader.get_template(join(default_renderer_path, 'buttons', 'collapse.html'))232        }233        if template_list is not None:234            self.templates.update(template_list)235    def _load_template(self, tpl_key, tpl_data=None):236        context = RequestContext(HttpRequest())237        if tpl_key not in self.templates.keys():238            raise IndexError('Template "' + tpl_key + '" not found in registered templates ' +239                             str(self.templates.keys()))240        if tpl_data is not None and type(tpl_data) != dict:241            raise TypeError('Data parameter should be a dict (' + str(type(tpl_data)) + ' given)')242        if tpl_data is not None:243            context.update(tpl_data)244        return self.templates[tpl_key].render(context)245    def _render_form_error(self, err_message):246        if type(err_message) not in [str, unicode]:247            raise TypeError('Error message should be string or unicode (' + str(type(err_message)) + ' given)')248        context = RequestContext(HttpRequest())249        data = {250            'message': err_message251        }252        context.update(data)253        return self.templates['form_error'].render(context)254    def _render_warnings(self):255        html_content = ''256        for warning in self.warnings:257            data = {258                'message': warning259            }260            html_content += self._load_template('warning', data)261        return html_content262    def _render_input(self, element):263        """264        :param element265        :return:266        """267        placeholder = ''268        tooltip = ''269        use = ''270        fixed = ''271        if 'placeholder' in element.options:272            placeholder = element.options['placeholder']273        if 'tooltip' in element.options:274            tooltip = element.options['tooltip']275        if 'use' in element.options:276            use = element.options['use']277        if 'fixed' in element.options:278            fixed = element.options['fixed']279        data = {280            'id': element.pk,281            'value': element.value,282            'placeholder': placeholder,283            'tooltip': tooltip,284            'use': use,285            'fixed': fixed,286        }287        return self._load_template('input', data)288    def _render_select(self, select, select_class, option_list):289        if select is None:290            select_id = ''291            fixed = False292        else:293            select_id = select.pk294            fixed = select.options['is_fixed'] if 'is_fixed' in select.options else False295        if not isinstance(option_list, types.ListType):296            raise TypeError('First param (option_list) should be a list (' + str(type(option_list)) + ' given)')297        for option in option_list:298            if not isinstance(option, types.TupleType):299                raise TypeError('Malformed param (option_list): type of item not good')300            if len(option) != 3:301                raise TypeError('Malformed param (option_list): Length of item not good')302            if type(option[0]) not in [str, unicode]:303                raise TypeError('Malformed param (option_list): item[0] should be a str')304            if type(option[1]) not in [str, unicode]:305                raise TypeError('Malformed param (option_list): item[1] should be a str')306            if type(option[2]) != bool:307                raise TypeError('Malformed param (option_list): item[2] should be a bool')308        data = {309            'select_id': select_id,310            'select_class': select_class,311            'option_list': option_list,312            'fixed': fixed,313        }314        return self._load_template('select', data)315    # def _render_buttons(self, min_occurs, max_occurs, occurence_count):316    def _render_buttons(self, add_button, delete_button):317        """Displays buttons for a duplicable/removable element318        Parameters:319            add_button: boolean320            delete_button: boolean321        Returns:322            JSON data323        """324        add_button_type = type(add_button)325        del_button_type = type(delete_button)326        if add_button_type is not bool:327            raise TypeError('add_button type is wrong (' + str(add_button_type) + 'received, bool needed')328        if del_button_type is not bool:329            raise TypeError('add_button type is wrong (' + str(del_button_type) + 'received, bool needed')330        form_string = ""331        # Fixed number of occurences, don't need buttons332        if not add_button and not delete_button:333            pass334        else:335            if add_button:336                form_string += self._load_template('btn_add', {'is_hidden': False})337            else:338                form_string += self._load_template('btn_add', {'is_hidden': True})339            if delete_button:340                form_string += self._load_template('btn_del', {'is_hidden': False})341            else:342                form_string += self._load_template('btn_del', {'is_hidden': True})343        return form_string344    def _render_collapse_button(self):...tests.py
Source:tests.py  
...16        Tests that 1 + 1 always equals 2.17        """18        self.assertEqual(1 + 1, 2)19class TestTemplates(TestCase):20    def _load_template(self, templateName, context):21        response = render_to_response(templateName, context)22        #document, errors = tidy_document(response.content)23        #self.assertEqual(len(errors),0,"%s\n================\n%s\n=================================\n" % (errors, response.content))24    def test_chapter(self):25        self._load_template("chapter.djt.html", dict())26    def test_country(self):27        self._load_template("country.djt.html", dict())28    def test_edit_event(self):29        self._load_template("edit-event.djt.html", dict())30    def test_event(self):31        self._load_template("event.djt.html", dict())32    def test_frame(self):33        self._load_template("frame.djt.html", dict())34    def test_front(self):35        self._load_template("front.djt.html", dict())36    def test_illustration(self):37        self._load_template("illustration.djt.html", dict())38    def test_image_upload(self):39        self._load_template("image-upload.djt.html", dict())40    def test_image_framed(self):41        self._load_template("img-framed.djt.html", dict())42    def test_location(self):43        self._load_template("location.djt.html", dict())44    def test_manuscript(self):45        self._load_template("manuscript.djt.html", dict())46    def test_msgallery(self):47        self._load_template("msgallery.djt.html", dict())48    def test_msgrid(self):49        self._load_template("msgrid.djt.html", dict())50    def test_mslist(self):51        self._load_template("mslist.djt.html", dict())52    def test_pagelist(self):53        self._load_template("pagelist.djt.html", dict())54    def test_scene(self):55        self._load_template("scene.djt.html", dict())56class TestStringBuilderTemplates(TestCase):57    def test_stringbuilder(self):58        requestFactory = RequestFactory()59        get = requestFactory.get("/country/1")60        for t in ['ms-state.stb','ms-text.stb','ms-origin.stb','ms-pages.stb',61                  'ill-form.stb','ill-painter.stb','ill-folio.stb','loc-contact.stb',62                  'loc-address.stb']:63            template = StringPattern(t)64            self.assertIsNotNone(template.apply(get, dict()),"Template %s fails" % (t))65            66class PageIntegrationTest(TestCase):67    ## recordtest.json can be created by populating a DB and then dumping it to json using the manage command68    fixtures = ['recordstest.json']69    ...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
