Exemple #1
0
    def setUp(self):
        super(ComponentTestCase, self).setUp()
        self.builder = Builder(self.builder_json)
        self.form = Form(self.form_json, self.builder)

        i18n = {
            'nl': {
                'First Name': 'Voornaam',
                'Last Name': 'Achternaam',
                'Survey': 'Enquête',
                'excellent': 'uitstekend',
                'great': 'supergoed',
                'My Favourites': 'Mijn favorieten',
                'Favourite Season': 'Favoriete seizoen',
                'Autumn': 'Herfst',
                'Favourite Food': 'Lievelingseten',
                'Cardinal Direction': 'Kardinale richting',
                'North': 'Noord',
                'East': 'Oost',
                'South': 'Zuid',
                'West': 'West',
                'Upload Base64': 'Upload binair naar ASCII',
                'Upload Url': 'Upload naar locatie'
            }
        }
        self.builder_i18n_nl = Builder(self.builder_json, language='nl', i18n=i18n)
        self.form_i18n_nl = Form(self.form_json, self.builder_i18n_nl)
Exemple #2
0
    def __getattr__(self, name):
        if name == '_formio' and self._name == 'formio.builder':
            # TODO implement caching on the model object
            # self._cache or self.env.cache API only works for model fields, not Python attr.

            # if '_formio' not in self.__dict__:
            no_cache = True
            if no_cache:
                context = self._context
                if 'lang' in context:
                    lang = context['lang']
                elif 'lang' not in context and 'uid' in context:
                    lang = self.env['res.users'].browse(context['uid']).lang
                elif 'lang' not in context and 'uid' not in context:
                    lang = self.write_uid.lang
                else:
                    raise UserError("The form builder can't be loaded. No (user) language was set.")

                res_lang = self.env['res.lang'].search([('code', '=', lang)], limit=1)

            if self.schema is False:
                # HACK masquerade empty Builder object
                builder_obj = Builder('{}')
            else:
                builder_obj = Builder(
                    self.schema,
                    language=res_lang.iso_code,
                    i18n=self.i18n_translations()
                )
            return builder_obj
        else:
            return self.__getattribute__(name)
    def test_schema_dict(self):
        builder_json = json.loads(self.builder_json)
        form_json = json.loads(self.form_json)
        self.builder = Builder(builder_json)
        self.form = Form(form_json, self.builder)

        self.builder_i18n_nl = Builder(builder_json,
                                       language='nl',
                                       i18n=self._i18n())
        self.form_i18n_nl = Form(form_json, self.builder_i18n_nl)
    def setUp(self):
        super(ComponentTestCase, self).setUp()
        self.builder = Builder(self.builder_json)
        self.form = Form(self.form_json, self.builder)
        self.form_empty = Form(self.form_empty_json, self.builder)

        self.builder_i18n_nl = Builder(self.builder_json,
                                       language='nl',
                                       i18n=self._i18n())
        self.form_i18n_nl = Form(self.form_json, self.builder_i18n_nl)
Exemple #5
0
    def __getattr__(self, name):
        if name == '_formio':
            if '_formio' not in self.__dict__:
                context = self._context
                if 'lang' in context:
                    lang = context['lang']
                elif 'lang' not in context and 'uid' in context:
                    lang = self.env['res.users'].browse(context['uid']).lang
                elif 'lang' not in context and 'uid' not in context:
                    lang = self.env['res.users'].browse(self.write_uid).lang
                else:
                    raise UserError(
                        "The form can't be loaded. No (user) language was set."
                    )

                res_lang = self.env['res.lang'].search([('code', '=', lang)],
                                                       limit=1)

                # TODO remove unicode?
                schema_json = u'%s' % self.builder_id.schema
                builder_obj = Builder(self.builder_id.schema,
                                      language=res_lang.iso_code,
                                      i18n=self.i18n_translations())

                if self.submission_data is False:
                    # HACK masquerade empty Form object
                    self._formio = Form('{}', builder_obj)
                else:
                    self._formio = Form(self.submission_data, builder_obj)
                return self._formio
        else:
            return self.__getattribute__(name)
    def test_Form_input_components_not_datagrid(self):
        """ Form: basic (not datagrid) input components """

        builder = Builder(self.builder_json)
        form = Form(self.form_json, builder)

        # firstName in columnsComponent
        firstName = form.input_components['firstName']
        self.assertIsInstance(firstName, textfieldComponent)
        self.assertEqual(firstName.label, 'First Name')
        self.assertEqual(firstName.value, 'Bob')
        self.assertEqual(firstName.type, 'textfield')

        # birthdate in columnsComponent
        birthdate = form.input_components['birthdate']
        self.assertIsInstance(birthdate, datetimeComponent)
        self.assertEqual(birthdate.label, 'Birthdate')
        self.assertEqual(birthdate.value, '1999-12-31')
        self.assertEqual(birthdate.type, 'datetime')
        self.assertIsInstance(birthdate.to_datetime().date(), date)

        # favouriteSeason in panelComponent
        season = form.input_components['favouriteSeason']
        self.assertEqual(season.label, 'Favourite Season')
        self.assertEqual(season.value, 'autumn')
        self.assertEqual(season.value_label, 'Autumn')
        self.assertEqual(season.type, 'select')
    def test_conditionally_shown_form_elements_do_not_render_when_hidden(self):
        builder = Builder(self.builder_json)

        hide_password_form = Form(self.hide_password_form_json, builder)
        hide_password_form.render_components()
        self.assertEqual(
            '<p>hide!</p>',
            hide_password_form.input_components['textField'].html_component)
        self.assertEqual(
            '', hide_password_form.input_components['maybeTextField'].
            html_component)
        self.assertEqual(
            '', hide_password_form.input_components['maybePassword'].
            html_component)

        show_textfield_form = Form(self.show_textfield_form_json, builder)
        show_textfield_form.render_components()
        self.assertEqual(
            '<p>show!</p>',
            show_textfield_form.input_components['textField'].html_component)
        self.assertEqual(
            '<p>maybe yes</p>', show_textfield_form.
            input_components['maybeTextField'].html_component)
        self.assertEqual(
            '<p>hunter2</p>', show_textfield_form.
            input_components['maybePassword'].html_component)
    def test_Form_input_components_datagrid_simple(self):
        """ Form: simple datagrid without nested (layout) components """

        builder = Builder(self.builder_json)
        form = Form(self.form_json, builder)

        self.assertIn('dataGrid', builder.input_components.keys())

        datagrid = form.input_components['dataGrid']

        self.assertEqual(len(datagrid.rows), 2)

        emails = ['*****@*****.**', '*****@*****.**']
        tz = timezone(timedelta(hours=2))
        registrationDateTimes = [
            datetime(2021, 4, 5, 12, tzinfo=tz),
            datetime(2021, 4, 6, 22, tzinfo=tz)
        ]

        for index, row in enumerate(datagrid.rows):
            # component object
            self.assertIsInstance(row.input_components['email'],
                                  emailComponent)
            self.assertIsInstance(row.input_components['registrationDateTime'],
                                  datetimeComponent)
            # value
            self.assertIn(row.input_components['email'].value, emails)
            self.assertEqual(
                row.input_components['registrationDateTime'].to_datetime(),
                registrationDateTimes[index])
    def _validate_component_api_properties(self):
        builder = Builder(self.schema)

        for comp_name, component in builder.input_components.items():
            properties = component.properties or {}
            found_prefix_keys = {
                prefix: False
                for prefix in self._component_api_keys()
            }
            keys = self._component_api_keys()

            for prop_key, prop_val in properties.items():
                if any([
                        prop_key == prefix
                        for prefix in self._component_api_keys()
                ]):
                    found_prefix_keys[prop_key] = True

            # TODO check all components and collect errors (log/raise only once)
            if sum([
                    1 for check in found_prefix_keys.values() if check == True
            ]) > 1:
                msg = _('Incorrect or conflicting "API Custom Properties" for Form Component, with:\n'
                        '- Label: %s\n'
                        '- Key: %s\n\n' \
                        'Custom Properties:\n' \
                        '%s')

                display_error = _(msg) % (component.label, component.key,
                                          properties)
                raise ValidationError(display_error)
    def test_conditionally_shown_form_elements_in_panel_toggle_on_condition_being_met(
            self):
        builder = Builder(self.builder_json)

        hide_secret_form = Form(self.hide_secret_form_json, builder)
        self.assertTrue(hide_secret_form.input_components['username1'].
                        conditionally_visible)
        self.assertTrue(hide_secret_form.input_components['password1'].
                        conditionally_visible)
        self.assertFalse(
            hide_secret_form.input_components['secret1'].conditionally_visible)

        self.assertTrue(hide_secret_form.input_components['username2'].
                        conditionally_visible)
        self.assertTrue(hide_secret_form.input_components['password2'].
                        conditionally_visible)
        self.assertFalse(
            hide_secret_form.input_components['secret2'].conditionally_visible)

        show_secret_form = Form(self.show_secret_form_json, builder)
        self.assertTrue(show_secret_form.input_components['username1'].
                        conditionally_visible)
        self.assertTrue(show_secret_form.input_components['password1'].
                        conditionally_visible)
        self.assertTrue(
            show_secret_form.input_components['secret1'].conditionally_visible)

        self.assertTrue(show_secret_form.input_components['username2'].
                        conditionally_visible)
        self.assertTrue(show_secret_form.input_components['password2'].
                        conditionally_visible)
        self.assertTrue(
            show_secret_form.input_components['secret2'].conditionally_visible)
    def test_conditionally_shown_top_level_form_elements_do_not_render_when_hidden(
            self):
        builder = Builder(self.builder_json)

        hide_secret_form = Form(self.hide_secret_form_json, builder)
        hide_secret_form.render_components()
        self.assertEqual(
            '<p>wrong</p>',
            hide_secret_form.input_components['username'].html_component)
        self.assertEqual(
            '<p>incorrect</p>',
            hide_secret_form.input_components['password'].html_component)
        self.assertEqual(
            '', hide_secret_form.input_components['secret'].html_component)

        show_secret_form = Form(self.show_secret_form_json, builder)
        show_secret_form.render_components()
        self.assertEqual(
            '<p>user</p>',
            show_secret_form.input_components['username'].html_component)
        self.assertEqual(
            '<p>secret</p>',
            show_secret_form.input_components['password'].html_component)
        self.assertEqual(
            '<p>Secret message</p>',
            show_secret_form.input_components['secret'].html_component)
    def test_conditionally_shown_form_elements_in_data_grid_toggle_on_global_data_condition_met(
            self):
        builder = Builder(self.builder_json)

        show_global_secret_only_form = Form(
            self.show_global_secret_only_form_json, builder)
        show_global_secret_only_datagrid = show_global_secret_only_form.input_components[
            'dataGrid']

        show_global_secret_only_first_row = show_global_secret_only_datagrid.rows[
            0]
        self.assertTrue(show_global_secret_only_first_row.
                        input_components['username3'].conditionally_visible)
        self.assertTrue(show_global_secret_only_first_row.
                        input_components['password3'].conditionally_visible)
        self.assertFalse(show_global_secret_only_first_row.
                         input_components['secret3'].conditionally_visible)
        self.assertTrue(show_global_secret_only_first_row.
                        input_components['globalSecret'].conditionally_visible)

        show_global_secret_only_second_row = show_global_secret_only_datagrid.rows[
            1]
        self.assertTrue(show_global_secret_only_second_row.
                        input_components['username3'].conditionally_visible)
        self.assertTrue(show_global_secret_only_second_row.
                        input_components['password3'].conditionally_visible)
        self.assertFalse(show_global_secret_only_second_row.
                         input_components['secret3'].conditionally_visible)
        self.assertTrue(show_global_secret_only_second_row.
                        input_components['globalSecret'].conditionally_visible)

        hide_global_secret_only_form = Form(
            self.hide_global_secret_only_form_json, builder)
        hide_global_secret_only_datagrid = hide_global_secret_only_form.input_components[
            'dataGrid']

        hide_global_secret_only_first_row = hide_global_secret_only_datagrid.rows[
            0]
        self.assertTrue(hide_global_secret_only_first_row.
                        input_components['username3'].conditionally_visible)
        self.assertTrue(hide_global_secret_only_first_row.
                        input_components['password3'].conditionally_visible)
        self.assertTrue(hide_global_secret_only_first_row.
                        input_components['secret3'].conditionally_visible)
        self.assertFalse(
            hide_global_secret_only_first_row.input_components['globalSecret'].
            conditionally_visible)

        hide_global_secret_only_second_row = hide_global_secret_only_datagrid.rows[
            0]
        self.assertTrue(hide_global_secret_only_second_row.
                        input_components['username3'].conditionally_visible)
        self.assertTrue(hide_global_secret_only_second_row.
                        input_components['password3'].conditionally_visible)
        self.assertTrue(hide_global_secret_only_second_row.
                        input_components['secret3'].conditionally_visible)
        self.assertFalse(
            hide_global_secret_only_second_row.
            input_components['globalSecret'].conditionally_visible)
    def test_conditionally_shown_top_level_form_elements_have_default_state_in_builder(
            self):
        builder = Builder(self.builder_json)

        self.assertTrue(
            builder.input_components['username'].conditionally_visible)
        self.assertTrue(
            builder.input_components['password'].conditionally_visible)
        self.assertFalse(
            builder.input_components['secret'].conditionally_visible)
    def test_conditionally_shown_form_elements_have_default_state_in_builder(
            self):
        builder = Builder(self.builder_json)

        self.assertTrue(
            builder.input_components['textField'].conditionally_visible)
        self.assertFalse(
            builder.input_components['maybeTextField'].conditionally_visible)
        self.assertTrue(
            builder.input_components['maybePassword'].conditionally_visible)
    def test_Builder_component_ids(self):
        """ Builder: component_ids (Dict) for direct mapping """

        builder = Builder(self.builder_json)

        # for key, comp in builder.component_ids.items():
        #     if comp.parent:
        #         print((comp.id, comp.key, comp.type, comp.parent, comp.parent.id))
        #     else:
        #         print((comp.id, comp.key, comp))

        self.assertEqual(len(builder.component_ids.keys()), 32)
Exemple #16
0
    def test_form_with_one_row_has_the_one_row_created_by_submission(self):
        builder = Builder(self.builder_json)

        form = Form(self.one_row_form_json, builder)
        self.assertEqual({'panel', 'submit'}, set(form.components.keys()))

        panel = form.components['panel']
        self.assertEqual({'dataGrid'}, set(panel.components.keys()))

        datagrid = form.components['panel'].components['dataGrid']
        self.assertEqual({'textField'}, set(datagrid.components.keys()))
        self.assertEqual(len(datagrid.rows), 1)
Exemple #17
0
    def test_default_state_in_builder_has_one_row(self):
        builder = Builder(self.builder_json)
        self.assertEqual({'panel', 'submit'}, set(builder.components.keys()))

        panel = builder.components['panel']
        self.assertEqual({'dataGrid'}, set(panel.components.keys()))

        datagrid = builder.components['panel'].components['dataGrid']
        self.assertEqual({'textField'}, set(datagrid.components.keys()))

        # datagrid will have no visible rows when initialized
        self.assertTrue(datagrid.initEmpty)
        self.assertEqual(len(datagrid.rows), 0)
Exemple #18
0
    def __getattr__(self, name):
        if name == '_formio':
            # TODO implement caching on the model object
            # self._cache or self.env.cache API only works for model fields, not Python attr.

            # if '_formio' not in self.__dict__:
            no_cache = True
            if no_cache:
                context = self._context
                if 'lang' in context:
                    lang = context['lang']
                elif 'lang' not in context and 'uid' in context:
                    lang = self.env['res.users'].browse(context['uid']).lang
                elif 'lang' not in context and 'uid' not in context:
                    lang = self.write_uid.lang
                else:
                    raise UserError("The form can't be loaded. No (user) language was set.")

                res_lang = self.env['res.lang'].search([('code', '=', lang)], limit=1)
                builder_obj = Builder(
                    self.builder_id.schema,
                    language=res_lang.iso_code,
                    i18n=self.builder_id.i18n_translations())

                if self.submission_data is False:
                    # HACK masquerade empty Form object
                    # TODO implement caching on the model object
                    # self._formio = Form('{}', builder_obj)
                    form = Form(
                        "{}",
                        builder_obj,
                        date_format=res_lang.date_format,
                        time_format=res_lang.time_format,
                    )
                else:
                    # TODO implement caching on the model object
                    # self._formio = Form(self.submission_data, builder_obj)
                    form = Form(
                        self.submission_data,
                        builder_obj,
                        date_format=res_lang.date_format,
                        time_format=res_lang.time_format,
                    )
                return form
        else:
            return self.__getattribute__(name)
    def test_Form_components_row_1_simple(self):
        """ Form: nested components SIMPLE """

        #############################
        # columns1 // row_1 // SIMPLE
        #############################

        builder = Builder(self.builder_json)
        form = Form(self.form_json, builder)

        columns1 = form.components['columns1']
        self.assertIsInstance(columns1, columnsComponent)
        self.assertEqual(columns1.key, 'columns1')
        self.assertEqual(len(columns1.rows), 2)

        # row_1 has 2 columns
        row_1 = columns1.rows[0]

        # row_1: col_1
        row_1_col_1 = row_1[0]

        ## keys
        keys = ['actionType']
        for comp in row_1_col_1['components']:
            self.assertIn(comp.key, keys)

        ## values
        for comp in row_1_col_1['components']:
            if comp.key == 'actionType':
                self.assertEqual(comp.value, 'check')

        # row_1: col_2
        row_1_col_2 = row_1[1]

        ## keys
        keys = ['startDateTime']
        for comp in row_1_col_2['components']:
            self.assertIn(comp.key, keys)

        ## values
        for comp in row_1_col_2['components']:
            if comp.key == 'startDateTime':
                self.assertEqual(comp.to_date(), date(2021, 4, 9))
    def test_conditionally_shown_form_elements_toggle_on_condition_being_met(
            self):
        builder = Builder(self.builder_json)

        hide_password_form = Form(self.hide_password_form_json, builder)
        self.assertTrue(hide_password_form.input_components['textField'].
                        conditionally_visible)
        self.assertFalse(hide_password_form.input_components['maybeTextField'].
                         conditionally_visible)
        self.assertFalse(hide_password_form.input_components['maybePassword'].
                         conditionally_visible)

        show_textfield_form = Form(self.show_textfield_form_json, builder)
        self.assertTrue(show_textfield_form.input_components['textField'].
                        conditionally_visible)
        self.assertTrue(show_textfield_form.input_components['maybeTextField'].
                        conditionally_visible)
        self.assertTrue(show_textfield_form.input_components['maybePassword'].
                        conditionally_visible)
    def test_Form_input_components_datagrid_nested(self):
        """ Form: complex datagrid with nested (layout) components """

        builder = Builder(self.builder_json)
        form = Form(self.form_json, builder)

        self.assertIn('dataGrid1', builder.input_components.keys())

        datagrid = form.input_components['dataGrid1']

        self.assertEqual(len(datagrid.rows), 3)

        # components
        deviceType = ['pumpB', 'pumpA', 'pumpC']
        tempCelcius = [65, 78, 55]
        escalate = [False, True]
        measurement_date = date(2021, 4, 9)

        for row in datagrid.rows:
            # TODO in Form components the datagrid.rows should only
            # have input components (not layout)

            # component object
            self.assertIsInstance(row.input_components['deviceType'],
                                  selectComponent)
            self.assertIsInstance(row.input_components['measurementTime'],
                                  datetimeComponent)
            self.assertIsInstance(row.input_components['temperatureCelsius'],
                                  numberComponent)
            self.assertIsInstance(row.input_components['escalate'],
                                  checkboxComponent)
            # value
            self.assertIn(row.input_components['deviceType'].value, deviceType)
            self.assertEqual(row.input_components['measurementTime'].to_date(),
                             measurement_date)
            self.assertIn(row.input_components['temperatureCelsius'].value,
                          tempCelcius)
            self.assertIn(row.input_components['escalate'].value, escalate)
 def setUp(self):
     super(resourceComponentTestCase, self).setUp()
     self.builder_res = Builder(self.builder_with_resource,
                                resources=self.builder_json_resource)
     self.form_res = Form(self.form_with_resource, self.builder_res)
    def test_Builder_components(self):
        """ Builder: components (OrderedDict) hierarchy, from toplevel and traverse
        nested components """
        """
        Top level components:
        - columns
        - content
        - radio
        - panel
        - survey
        - datagrid
        - html
        - columns (deep nested components)
        - signature
        - file (storage; Base64)
        - file (storage: Url)
        - button (submit)
        """

        builder = Builder(self.builder_json)

        ## debug
        # for key, comp in builder.components.items():
        #     print((comp.id, comp.key, comp.type, comp.parent))

        self.assertEqual(len(builder.components.keys()), 12)

        #################################
        # (top) columnsComponent: columns
        #################################
        # parent: None
        # components: firstName, lastName etc

        columns = builder.component_ids['ez2p9i']

        self.assertIsInstance(columns, columnsComponent)
        self.assertEqual(columns.key, 'columns')
        self.assertIsNone(columns.parent)

        # print('\n# (top) columnsComponent')
        # for key, comp in columns.components.items():
        #     print((comp.id, comp.key, comp))

        self.assertEqual(len(columns.components), 6)
        self.assertEqual(len(builder.components['columns'].components), 6)

        #############################
        # (top) panelComponent: panel
        #############################
        # parent: None
        # components: favouriteSeason, favouriteFood

        panel = builder.component_ids['em39da']

        self.assertIsInstance(panel, panelComponent)
        self.assertEqual(panel.key, 'panel')

        # parent
        self.assertIsNone(panel.parent)

        # print('\n# (top) panelsComponent')
        # for key, comp in panel.components.items():
        #     print((comp.id, comp.key, comp))

        # components
        self.assertEqual(len(panel.components), 2)
        self.assertEqual(len(builder.components['panel'].components), 2)

        ##################################
        # (top) columnsComponent: columns1
        ##################################
        # parent: None
        # components: actionType, startDateTime, dataGrid1 (deviceType, measurementTime, temperatureCelsius)

        columns = builder.component_ids['ejghurn']

        self.assertIsInstance(columns, columnsComponent)
        self.assertEqual(columns.key, 'columns1')

        # parent
        self.assertIsNone(columns.parent)

        # components

        # print('\n# (top) columnsComponent (columns1)')
        # for key, comp in columns.components.items():
        #     print((comp.id, comp.key, comp))

        self.assertEqual(len(columns.components), 3)
        self.assertEqual(len(builder.components['columns1'].components), 3)

        keys = ['actionType', 'startDateTime', 'dataGrid1']
        for key, comp in builder.components['columns1'].components.items():
            self.assertIn(comp.key, keys)

        ###################################
        # (top) datagridComponent: dataGrid
        ###################################
        # parent: None
        # components: name, email

        datagrid = builder.component_ids['ecw3wx']

        self.assertIsInstance(datagrid, datagridComponent)
        self.assertEqual(datagrid.key, 'dataGrid')

        # parent
        self.assertIsNone(columns.parent)

        # components

        # print('\n# (top) datagridComponent')
        # for key, comp in columns.components.items():
        #     print((comp.id, comp.key, comp))

        self.assertEqual(len(datagrid.components), 2)
        self.assertEqual(len(builder.components['dataGrid'].components), 2)

        keys = ['email', 'registrationDateTime']
        for key, comp in builder.components['dataGrid'].components.items():
            self.assertIn(comp.key, keys)

        ##########################################
        # datagridComponent: columns1 => dataGrid1
        ##########################################
        # parent: columns1
        # components: columns (which contains: panel, escalate checkbox)

        datagrid = builder.component_ids['eea699r']

        self.assertIsInstance(datagrid, datagridComponent)
        self.assertEqual(datagrid.key, 'dataGrid1')

        # parent
        self.assertIsInstance(datagrid.parent, columnsComponent)
        self.assertEqual(datagrid.parent.key, 'columns1')

        # components

        # print('\n# Component: columns1 => dataGrid')
        # for key, comp in datagrid.components.items():
        #     print((comp.id, comp.key, comp))

        # dataGrid1.components: columns
        self.assertEqual(len(datagrid.components), 1)
        self.assertEqual(
            builder.component_ids['eea699r'].components['columns'].id,
            'eleoxql00')

        #################################################################
        # columnsComponent: columns1 => dataGrid1 => <gridRow> => columns
        #################################################################
        # parent: dataGrid1
        # components: panel, escalate (checkbox)

        columns = builder.component_ids['eleoxql00']

        self.assertIsInstance(columns, columnsComponent)
        self.assertEqual(len(columns.components), 2)

        # parent
        self.assertIsInstance(columns.parent, datagridComponent.gridRow)
        self.assertEqual(columns.parent.datagrid.key, 'dataGrid1')

        # components

        keys = ['panel', 'escalate']
        for key, comp in columns.components.items():
            self.assertIn(comp.key, keys)

        ########################################################################
        # panelComponent: columns1 => dataGrid1 => <gridRow> => columns => panel
        ########################################################################
        # parent: columns
        # components: columns

        panel = builder.component_ids['ek5p7n6']

        self.assertIsInstance(panel, panelComponent)
        self.assertEqual(len(panel.components), 1)

        # parent
        self.assertIsInstance(panel.parent, columnsComponent)
        self.assertEqual(panel.parent.key, 'columns')

        ###################################################################################
        # columnsComponent: columns1 => dataGrid1 => <gridRow> columns => panel => columns1
        ###################################################################################
        # parent: panel
        # components: col (select) | col (datetime) | col (number)

        columns = builder.component_ids['ep08ekn']

        self.assertIsInstance(columns, columnsComponent)
        self.assertEqual(columns.key, 'columns1')

        # parent
        self.assertIsInstance(columns.parent, panelComponent)
        self.assertEqual(columns.parent.key, 'panel')

        # components
        self.assertEqual(len(columns.components), 3)

        keys = ['deviceType', 'measurementTime', 'temperatureCelsius']
        for key, comp in builder.component_ids['ep08ekn'].components.items():
            self.assertIn(comp.key, keys)

        for key, comp in columns.components.items():
            # parent
            self.assertIsInstance(comp.parent, columnsComponent)
            self.assertEqual(comp.parent.key, 'columns1')

            if key == 'deviceType':
                self.assertIsInstance(comp, selectComponent)
                self.assertEqual(comp.label, 'Device Type')
                # setter
                comp.label = 'Machine Type'
                self.assertEqual(comp.label, 'Machine Type')
            if key == 'measurementTime':
                self.assertIsInstance(comp, datetimeComponent)
                self.assertEqual(comp.label, 'Measurement Time')
                # setter
                comp.label = 'Measurement Date / Time'
                self.assertEqual(comp.label, 'Measurement Date / Time')
            if key == 'temperatureCelsius':
                self.assertIsInstance(comp, numberComponent)
                self.assertEqual(comp.label, 'Temperature Celsius')
                # setter
                comp.label = 'Temperature Fahrenheit'
                self.assertEqual(comp.label, 'Temperature Fahrenheit')
    def test_conditionally_shown_form_elements_for_global_data_condition_in_data_grid_do_not_render_when_hidden(
            self):
        builder = Builder(self.builder_json)

        show_global_secret_only_form = Form(
            self.show_global_secret_only_form_json, builder)
        show_global_secret_only_form.render_components()
        show_global_secret_only_datagrid = show_global_secret_only_form.input_components[
            'dataGrid']

        show_global_secret_only_first_row = show_global_secret_only_datagrid.rows[
            0]
        self.assertEqual(
            '<tr><td><table><tr><td><p>wrong</p></td><td><p>incorrect</p></td><td></td><td><p>Another secret message</p></td></tr></table></td></tr>',
            show_global_secret_only_first_row.html_component)
        self.assertEqual(
            '<p>wrong</p>', show_global_secret_only_first_row.
            input_components['username3'].html_component)
        self.assertEqual(
            '<p>incorrect</p>', show_global_secret_only_first_row.
            input_components['password3'].html_component)
        self.assertEqual(
            '', show_global_secret_only_first_row.input_components['secret3'].
            html_component)
        self.assertEqual(
            '<p>Another secret message</p>', show_global_secret_only_first_row.
            input_components['globalSecret'].html_component)

        show_global_secret_only_second_row = show_global_secret_only_datagrid.rows[
            1]
        self.assertEqual(
            '<tr><td><table><tr><td><p>wrong</p></td><td><p>incorrect</p></td><td></td><td><p>Another secret message</p></td></tr></table></td></tr>',
            show_global_secret_only_second_row.html_component)
        self.assertEqual(
            '<p>wrong</p>', show_global_secret_only_second_row.
            input_components['username3'].html_component)
        self.assertEqual(
            '<p>incorrect</p>', show_global_secret_only_second_row.
            input_components['password3'].html_component)
        self.assertEqual(
            '', show_global_secret_only_second_row.input_components['secret3'].
            html_component)
        self.assertEqual(
            '<p>Another secret message</p>',
            show_global_secret_only_second_row.
            input_components['globalSecret'].html_component)

        # Tying it all together
        self.assertEqual(
            f'<table>{show_global_secret_only_first_row.html_component}{show_global_secret_only_second_row.html_component}</table>',
            show_global_secret_only_datagrid.html_component)

        hide_global_secret_only_form = Form(
            self.hide_global_secret_only_form_json, builder)
        hide_global_secret_only_form.render_components()
        hide_global_secret_only_datagrid = hide_global_secret_only_form.input_components[
            'dataGrid']

        hide_global_secret_only_first_row = hide_global_secret_only_datagrid.rows[
            0]
        self.assertEqual(
            '<tr><td><table><tr><td><p>user</p></td><td><p>secret</p></td><td><p>Secret message</p></td><td></td></tr></table></td></tr>',
            hide_global_secret_only_first_row.html_component)
        self.assertEqual(
            '<p>user</p>', hide_global_secret_only_first_row.
            input_components['username3'].html_component)
        self.assertEqual(
            '<p>secret</p>', hide_global_secret_only_first_row.
            input_components['password3'].html_component)
        self.assertEqual(
            '<p>Secret message</p>', hide_global_secret_only_first_row.
            input_components['secret3'].html_component)
        self.assertEqual(
            '', hide_global_secret_only_first_row.
            input_components['globalSecret'].html_component)

        hide_global_secret_only_second_row = hide_global_secret_only_datagrid.rows[
            0]
        self.assertEqual(
            '<tr><td><table><tr><td><p>user</p></td><td><p>secret</p></td><td><p>Secret message</p></td><td></td></tr></table></td></tr>',
            hide_global_secret_only_second_row.html_component)
        self.assertEqual(
            '<p>user</p>', hide_global_secret_only_second_row.
            input_components['username3'].html_component)
        self.assertEqual(
            '<p>secret</p>', hide_global_secret_only_second_row.
            input_components['password3'].html_component)
        self.assertEqual(
            '<p>Secret message</p>', hide_global_secret_only_second_row.
            input_components['secret3'].html_component)
        self.assertEqual(
            '', hide_global_secret_only_second_row.
            input_components['globalSecret'].html_component)

        # Tying it all together
        self.assertEqual(
            f'<table>{hide_global_secret_only_first_row.html_component}{hide_global_secret_only_second_row.html_component}</table>',
            hide_global_secret_only_datagrid.html_component)
    def test_Form_components_simple(self):
        """ Form: simple components """

        builder = Builder(self.builder_json)
        form = Form(self.form_json, builder)

        #################################
        # (top) columnsComponent: columns
        #################################

        columns = form.components['columns']
        self.assertIsInstance(columns, columnsComponent)
        self.assertEqual(columns.key, 'columns')

        # row (only 1 row here)
        row = columns.rows[0]

        # col_1
        col_1 = row[0]
        col_1_keys = ['firstName', 'email', 'birthdate', 'appointmentDateTime']

        ## keys
        for comp in col_1['components']:
            self.assertIn(comp.key, col_1_keys)

        ## component objects
        for comp in col_1['components']:
            if comp.key == 'firstName':
                self.assertIsInstance(comp, textfieldComponent)
            elif comp.key == 'email':
                self.assertIsInstance(comp, emailComponent)
            elif comp.key == 'birthdate':
                self.assertIsInstance(comp, datetimeComponent)
            elif comp.key == 'appointmentDateTime':
                self.assertIsInstance(comp, datetimeComponent)

        ## values
        for comp in col_1['components']:
            if comp.key == 'firstName':
                self.assertEqual(comp.value, 'Bob')
            elif comp.key == 'email':
                self.assertEqual(comp.value, '*****@*****.**')
            elif comp.key == 'birthdate':
                self.assertEqual(comp.to_date(), date(1999, 12, 31))
            elif comp.key == 'appointmentDateTime':
                self.assertEqual(comp.to_date(), date(2021, 2, 26))

        # col_2
        col_2 = row[1]
        col_2_keys = ['lastName', 'phoneNumber']

        ## keys
        for comp in col_2['components']:
            self.assertIn(comp.key, col_2_keys)

        ## values
        for comp in col_2['components']:
            if comp.key == 'lastName':
                self.assertEqual(comp.value, 'Leers')
            elif comp.key == 'phoneNumber':
                self.assertEqual(comp.value, '(069) 999-9999')
Exemple #26
0
class Form:
    def __init__(self,
                 form_json,
                 builder=None,
                 builder_schema_json=None,
                 lang='en',
                 **kwargs):
        """
        @param form_json
        @param builder Builder
        @param builder_schema
        @param lang
        """
        if isinstance(form_json, dict):
            self.form = form_json
        else:
            self.form = json.loads(form_json)

        self.builder = builder
        self.builder_schema_json = builder_schema_json
        self.lang = lang

        if self.builder and self.builder_schema_json:
            raise Exception(
                "Constructor accepts either builder or builder_schema_json.")

        if self.builder:
            assert isinstance(self.builder, Builder)
        elif self.builder_schema_json:
            assert isinstance(self.builder_schema_json, str)
        else:
            raise Exception(
                "Provide either the argument: builder or builder_schema_json.")

        if self.builder is None and self.builder_schema_json:
            self.set_builder_by_builder_schema_json()

        # defaults to English (en) date/time format
        self.date_format = kwargs.get('date_format', '%m/%d/%Y')
        self.time_format = kwargs.get('time_format', '%H:%M:%S')

        self.input_components = {}

        self.components = OrderedDict()
        self.component_ids = {}

        self.load_components()
        self._input = self._data = FormInput(self)

    def set_builder_by_builder_schema_json(self):
        self.builder = Builder(self.builder_schema_json, self.lang)

    def load_components(self):
        for key, component in self.builder.components.items():
            # New object, don't affect the Builder component
            component_obj = self.builder.get_component_object(component.raw)
            component_obj.load(component_owner=self,
                               parent=None,
                               data=self.form,
                               all_data=self.form)
            self.components[key] = component_obj
            self.component_ids[component_obj.id] = component_obj

    @property
    def input(self):
        return self._input

    @property
    def data(self):
        logging.warning(
            'DEPRECATION WARNING: data attr/property shall be deleted in a future version.'
        )
        return self._data

    def render_components(self, force=False):
        for key, component in self.input_components.items():
            if force or component.html_component == "":
                if component.is_visible:
                    component.render()
                else:
                    component.html_component = ""
Exemple #27
0
 def test_builder(self):
     Builder(self.builder_json)
Exemple #28
0
 def set_builder_by_builder_schema_json(self):
     self.builder = Builder(self.builder_schema_json, self.lang)
Exemple #29
0
 def _builder(self):
     return Builder(self.builder_json)
    def test_Form_components_row_1_complex(self):
        """ Form: nested components COMPLEX """

        ##########################################
        # columns1 // row_2 // columns1 // COMPLEX
        ##########################################

        builder = Builder(self.builder_json)
        form = Form(self.form_json, builder)

        columns1 = form.components['columns1']
        self.assertIsInstance(columns1, columnsComponent)
        self.assertEqual(columns1.key, 'columns1')
        self.assertEqual(len(columns1.rows), 2)

        # row_2 has 1 column
        row_2 = columns1.rows[1]
        row_2_col_1 = row_2[0]

        ## keys
        keys = ['dataGrid1']
        dataGrid1 = None
        for comp in row_2_col_1['components']:
            self.assertIn(comp.key, keys)

            if comp.key == 'dataGrid1':
                dataGrid1 = comp

        # dataGrid1
        self.assertEqual(len(dataGrid1.rows), 3)
        for row in dataGrid1.rows:
            # row has only 1 component
            self.assertEqual(1, len(row.components.keys()))
            comp = row.components['columns']
            self.assertIsInstance(comp, columnsComponent)
            self.assertEqual(comp.key, 'columns')

        ## dataGrid1 // row 1
        columns_row = dataGrid1.rows[0]

        # XXX panel.components is OrderedDict()
        columns_in_panel = columns_row.components['columns'].components[
            'panel'].components['columns1']

        # only 1 row
        self.assertEqual(len(columns_in_panel.rows), 1)
        row_columns_in_panel = columns_in_panel.rows[0]

        ## keys
        keys = ['deviceType', 'measurementTime', 'temperatureCelsius']
        for comp in row_columns_in_panel[0]['components']:
            self.assertIn(comp.key, keys)

        ## component objects
        for comp in row_columns_in_panel[0]['components']:
            if comp.key == 'deviceType':
                self.assertIsInstance(comp, selectComponent)
            elif comp.key == 'measurementTime':
                self.assertIsInstance(comp, datetimeComponent)
            elif comp.key == 'temperatureCelsius':
                self.assertIsInstance(comp, integerComponent)

        ## values
        measurementTime = datetime(2021, 4, 9, 9, 00)
        for comp in row_columns_in_panel[0]['components']:
            if comp.key == 'deviceType':
                self.assertEqual(comp.value, 'pumpB')
            elif comp.key == 'measurementTime':
                self.assertEqual(comp.to_datetime(), measurementTime)
            elif comp.key == 'temperatureCelsius':
                self.assertEqual(comp.value, 65)