formsetのテスト面倒。

formsetの取る引数の形式が独特なのでそれに合わせてデータを作るのが面倒。
こんな感じの関数を作っておくとテストのとき楽かもしれない。

def formset_to_params(formset):
    r = {}
    mform = formset.management_form
    for k, bf in zip(mform.fields.keys(), mform):
        r[bf.html_name] = mform.initial.get(k)

    for form in formset.forms:
        for k, bf in zip(form.fields.keys(), form):
            r[bf.html_name] = form.initial.get(k)
    return r

実行結果

sum_form = SumFormSet(initial=[{"x":10, "y":90}, {"x":20, "y":80}], extra_args=dict(sum=99))
import pprint
pprint.pprint(formset_to_params(sum_form))

# {'form-0-x': 10,
#  'form-0-y': 90,
#  'form-1-x': 20,
#  'form-1-y': 80,
#  'form-2-x': None,
#  'form-2-y': None,
#  'form-INITIAL_FORMS': 2,
#  'form-MAX_NUM_FORMS': None,
#  'form-TOTAL_FORMS': 3}

# print SumFormSet(formset_to_params(sum_form), extra_args=dict(sum=100)).is_valid()
# => True