Skip to content

Commit

Permalink
Merge e7c5b72 into 5001033
Browse files Browse the repository at this point in the history
  • Loading branch information
jace committed Sep 22, 2020
2 parents 5001033 + e7c5b72 commit dce730a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
11 changes: 9 additions & 2 deletions baseframe/forms/form.py
Expand Up @@ -138,13 +138,13 @@ def __init_subclass__(cls, **kwargs):
)

def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
for attr in self.__expects__:
if attr not in kwargs:
raise TypeError("Expected parameter %s was not supplied" % attr)
setattr(self, attr, kwargs.pop(attr))

# Make editing objects easier
# TODO: These fields predate the `__expects__` protocol and are pending
# deprecation.
self.edit_obj = kwargs.get('obj')
self.edit_model = kwargs.get('model')
self.edit_parent = kwargs.get('parent')
Expand All @@ -159,6 +159,13 @@ def __init__(self, *args, **kwargs):
self.edit_parent = self.edit_obj.parent
else:
self.edit_id = None

# Call baseclass after expected parameters have been set. `__init__` will call
# `process`, which will in turn call the ``get_<fieldname>`` methods, and they
# will need proper context
super(Form, self).__init__(*args, **kwargs)

# Finally, populate the ``choices`` attr of selection fields
self.set_queries()

def populate_obj(self, obj):
Expand Down
25 changes: 25 additions & 0 deletions tests/test_form.py
Expand Up @@ -67,6 +67,15 @@ def set_confirm_password(self, obj):
pass


class InitOrderForm(forms.Form):
__expects__ = ('expected_item',)

has_context = forms.StringField("Has context")

def get_has_context(self, obj):
return self.expected_item


@pytest.fixture
def user():
return SimpleUser(fullname="Test user", company="Test company", password="test")
Expand Down Expand Up @@ -148,3 +157,19 @@ def test_set(test_client, user):
assert not user.password_is("test")
assert user.password_is("Test123")
assert not hasattr(user, 'confirm_password')


def test_init_order(test_client):
"""Test that get_<fieldname> methods have proper context."""

with pytest.raises(TypeError):
# A parameter named `expected_item` is expected
InitOrderForm(meta={'csrf': False})

# get_<fieldname> is only called when there is an object
form = InitOrderForm(expected_item='probe', meta={'csrf': False})
assert form.has_context.data is None

# get_<fieldname> has context when it is called
form = InitOrderForm(expected_item='probe', obj=object(), meta={'csrf': False})
assert form.has_context.data == 'probe'

0 comments on commit dce730a

Please sign in to comment.