jeudi 26 septembre 2019

Testing checkbox in Django as field in form

I have a form with a single field which is a two level checkbox, if I select parent checkbox while no children selected, the parent with all children items will show in my json data after submit. I want to write a test to test this. I'm new to Django test, after reading Django documents, still struggle on manipulating the checkbox. My form looks like this:

class RerunForm(forms.Form):
    items = ItemStatus(
        queryset=models.Container.objects.none(),
        widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')),
        help_text="Select items that you want to rerun.",
    )

    def __init__(self, rerunqueryset, *args, **kwargs):
        super(RerunForm, self).__init__(*args, **kwargs)
        self.fields['items'].queryset = rerunqueryset

class ItemStatus(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.name, obj.state)

rerunqueryset is passed from view, which is like this

<QuerySet [<Container: AT1>, <Container: AT1_1>, <Container: AT1_2>, <Container: AT1_3>, <Container: AT1_4>, <Container: AT2>, <Container: AT2_1>

My page looks like this:

In my django test, I want test: 1. check parent level item while no children checked, parent and all children names will show in json after submit 2. check parent level item, and any children item, only checked children show in json data after submit.

Till now, I have codes like client and context to access my checkbox label, my question is how do I set certain checkbox to 'checked', and trigger submit button?

>>>response = client.get('/rerun/1')
>>>response.context['form']['items'][0].data
{u'index': '0', u'name': 'items', u'template_name': u'django/forms/widgets/checkbox_option.html', u'type': u'checkbox', u'selected': False, u'attrs': {'checked': '', u'id': u'id_items_0'}, u'value': 5742, u'label': 'AT1 (PASS)'}

Aucun commentaire:

Enregistrer un commentaire