Fixed flake8 warnings.

This commit is contained in:
Tim Graham
2016-05-28 11:31:18 -04:00
parent 46b6839fb0
commit e0244cff08
9 changed files with 179 additions and 181 deletions

View File

@@ -20,7 +20,7 @@ docs:
$(MAKE) -C docs clean html $(MAKE) -C docs clean html
test: test:
@flake8 --ignore=W801,E128,E501,W402 formtools @flake8
@ coverage run `which django-admin.py` test tests @ coverage run `which django-admin.py` test tests
@coverage report @coverage report

View File

@@ -25,7 +25,7 @@ sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ----------------------------------------------------- # -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here. # If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0' # needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions # Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
@@ -40,7 +40,7 @@ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
source_suffix = '.rst' source_suffix = '.rst'
# The encoding of source files. # The encoding of source files.
#source_encoding = 'utf-8-sig' # source_encoding = 'utf-8-sig'
# The master toctree document. # The master toctree document.
master_doc = 'index' master_doc = 'index'
@@ -65,40 +65,40 @@ except ImportError:
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
#language = None # language = None
# There are two options for replacing |today|: either, you set today to some # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used: # non-false value, then it is used:
#today = '' # today = ''
# Else, today_fmt is used as the format for a strftime call. # Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y' # today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
exclude_patterns = ['_build'] exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents. # The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None # default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text. # If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True # add_function_parentheses = True
# If true, the current module name will be prepended to all description # If true, the current module name will be prepended to all description
# unit titles (such as .. function::). # unit titles (such as .. function::).
#add_module_names = True # add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the # If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default. # output. They are ignored by default.
#show_authors = False # show_authors = False
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting. # A list of ignored prefixes for module index sorting.
#modindex_common_prefix = [] # modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents. # If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False # keep_warnings = False
# -- Options for HTML output --------------------------------------------------- # -- Options for HTML output ---------------------------------------------------
@@ -110,26 +110,26 @@ html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme # Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the # further. For a list of options available for each theme, see the
# documentation. # documentation.
#html_theme_options = {} # html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory. # Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = ['_theme'] # html_theme_path = ['_theme']
# The name for this set of Sphinx documents. If None, it defaults to # The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation". # "<project> v<release> documentation".
#html_title = None # html_title = None
# A shorter title for the navigation bar. Default is the same as html_title. # A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None # html_short_title = None
# The name of an image file (relative to this directory) to place at the top # The name of an image file (relative to this directory) to place at the top
# of the sidebar. # of the sidebar.
#html_logo = None # html_logo = None
# The name of an image file (within the static path) to use as favicon of the # The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
#html_favicon = None # html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,
@@ -138,44 +138,44 @@ html_theme = 'default'
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format. # using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y' # html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to # If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities. # typographically correct entities.
#html_use_smartypants = True # html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. # Custom sidebar templates, maps document names to template names.
#html_sidebars = {} # html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to # Additional templates that should be rendered to pages, maps page names to
# template names. # template names.
#html_additional_pages = {} # html_additional_pages = {}
# If false, no module index is generated. # If false, no module index is generated.
#html_domain_indices = True # html_domain_indices = True
# If false, no index is generated. # If false, no index is generated.
#html_use_index = True # html_use_index = True
# If true, the index is split into individual pages for each letter. # If true, the index is split into individual pages for each letter.
#html_split_index = False # html_split_index = False
# If true, links to the reST sources are added to the pages. # If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True # html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True # html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True # html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will # If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the # contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served. # base URL from which the finished HTML is served.
#html_use_opensearch = '' # html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml"). # This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None # html_file_suffix = None
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'django-formtoolsdoc' htmlhelp_basename = 'django-formtoolsdoc'
@@ -184,14 +184,14 @@ htmlhelp_basename = 'django-formtoolsdoc'
# -- Options for LaTeX output -------------------------------------------------- # -- Options for LaTeX output --------------------------------------------------
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt', # 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
#'preamble': '', # 'preamble': '',
} }
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
@@ -203,23 +203,23 @@ latex_documents = [
# The name of an image file (relative to this directory) to place at the top of # The name of an image file (relative to this directory) to place at the top of
# the title page. # the title page.
#latex_logo = None # latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts, # For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters. # not chapters.
#latex_use_parts = False # latex_use_parts = False
# If true, show page references after internal links. # If true, show page references after internal links.
#latex_show_pagerefs = False # latex_show_pagerefs = False
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
#latex_show_urls = False # latex_show_urls = False
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
#latex_appendices = [] # latex_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
#latex_domain_indices = True # latex_domain_indices = True
# -- Options for manual page output -------------------------------------------- # -- Options for manual page output --------------------------------------------
@@ -232,7 +232,7 @@ man_pages = [
] ]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
#man_show_urls = False # man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------ # -- Options for Texinfo output ------------------------------------------------
@@ -247,16 +247,16 @@ texinfo_documents = [
] ]
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
#texinfo_appendices = [] # texinfo_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
#texinfo_domain_indices = True # texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'. # How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote' # texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu. # If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False # texinfo_no_detailmenu = False
# -- Options for Epub output --------------------------------------------------- # -- Options for Epub output ---------------------------------------------------
@@ -269,52 +269,52 @@ epub_copyright = u'2014, Django Software Foundation and individual contributors'
# The language of the text. It defaults to the language option # The language of the text. It defaults to the language option
# or en if the language is not set. # or en if the language is not set.
#epub_language = '' # epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL. # The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = '' # epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number # The unique identifier of the text. This can be a ISBN number
# or the project homepage. # or the project homepage.
#epub_identifier = '' # epub_identifier = ''
# A unique identification for the text. # A unique identification for the text.
#epub_uid = '' # epub_uid = ''
# A tuple containing the cover image and cover page html template filenames. # A tuple containing the cover image and cover page html template filenames.
#epub_cover = () # epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf. # A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = () # epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx. # HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title. # The format is a list of tuples containing the path and title.
#epub_pre_files = [] # epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx. # HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title. # The format is a list of tuples containing the path and title.
#epub_post_files = [] # epub_post_files = []
# A list of files that should not be packed into the epub file. # A list of files that should not be packed into the epub file.
#epub_exclude_files = [] # epub_exclude_files = []
# The depth of the table of contents in toc.ncx. # The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3 # epub_tocdepth = 3
# Allow duplicate toc entries. # Allow duplicate toc entries.
#epub_tocdup = True # epub_tocdup = True
# Fix unsupported image types using the PIL. # Fix unsupported image types using the PIL.
#epub_fix_images = False # epub_fix_images = False
# Scale large images. # Scale large images.
#epub_max_image_width = 0 # epub_max_image_width = 0
# If 'no', URL addresses will not be shown. # If 'no', URL addresses will not be shown.
#epub_show_urls = 'inline' # epub_show_urls = 'inline'
# If false, no index is generated. # If false, no index is generated.
#epub_use_index = True # epub_use_index = True
# Example configuration for intersphinx: refer to the Python standard library. # Example configuration for intersphinx: refer to the Python standard library.

View File

@@ -122,8 +122,8 @@ class WizardView(TemplateView):
return super(WizardView, cls).as_view(**initkwargs) return super(WizardView, cls).as_view(**initkwargs)
@classmethod @classmethod
def get_initkwargs(cls, form_list=None, initial_dict=None, def get_initkwargs(cls, form_list=None, initial_dict=None, instance_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs): condition_dict=None, *args, **kwargs):
""" """
Creates a dict with all needed parameters for the form wizard instances Creates a dict with all needed parameters for the form wizard instances
@@ -146,18 +146,22 @@ class WizardView(TemplateView):
will be called with the wizardview instance as the only argument. will be called with the wizardview instance as the only argument.
If the return value is true, the step's form will be used. If the return value is true, the step's form will be used.
""" """
kwargs.update({ kwargs.update({
'initial_dict': initial_dict or kwargs.pop('initial_dict', 'initial_dict': (
getattr(cls, 'initial_dict', None)) or {}, initial_dict or
'instance_dict': instance_dict or kwargs.pop('instance_dict', kwargs.pop('initial_dict', getattr(cls, 'initial_dict', None)) or {}
getattr(cls, 'instance_dict', None)) or {}, ),
'condition_dict': condition_dict or kwargs.pop('condition_dict', 'instance_dict': (
getattr(cls, 'condition_dict', None)) or {} instance_dict or
kwargs.pop('instance_dict', getattr(cls, 'instance_dict', None)) or {}
),
'condition_dict': (
condition_dict or
kwargs.pop('condition_dict', getattr(cls, 'condition_dict', None)) or {}
)
}) })
form_list = form_list or kwargs.pop('form_list', form_list = form_list or kwargs.pop('form_list', getattr(cls, 'form_list', None)) or []
getattr(cls, 'form_list', None)) or []
computed_form_list = OrderedDict() computed_form_list = OrderedDict()
@@ -186,7 +190,8 @@ class WizardView(TemplateView):
not hasattr(cls, 'file_storage')): not hasattr(cls, 'file_storage')):
raise NoFileStorageConfigured( raise NoFileStorageConfigured(
"You need to define 'file_storage' in your " "You need to define 'file_storage' in your "
"wizard view in order to handle file uploads.") "wizard view in order to handle file uploads."
)
# build the kwargs for the wizardview instances # build the kwargs for the wizardview instances
kwargs['form_list'] = computed_form_list kwargs['form_list'] = computed_form_list
@@ -231,8 +236,10 @@ class WizardView(TemplateView):
""" """
# add the storage engine to the current wizardview instance # add the storage engine to the current wizardview instance
self.prefix = self.get_prefix(request, *args, **kwargs) self.prefix = self.get_prefix(request, *args, **kwargs)
self.storage = get_storage(self.storage_name, self.prefix, request, self.storage = get_storage(
getattr(self, 'file_storage', None)) self.storage_name, self.prefix, request,
getattr(self, 'file_storage', None),
)
self.steps = StepsHelper(self) self.steps = StepsHelper(self)
response = super(WizardView, self).dispatch(request, *args, **kwargs) response = super(WizardView, self).dispatch(request, *args, **kwargs)
@@ -289,10 +296,8 @@ class WizardView(TemplateView):
# and try to validate # and try to validate
if form.is_valid(): if form.is_valid():
# if the form is valid, store the cleaned data and files. # if the form is valid, store the cleaned data and files.
self.storage.set_step_data(self.steps.current, self.storage.set_step_data(self.steps.current, self.process_step(form))
self.process_step(form)) self.storage.set_step_files(self.steps.current, self.process_step_files(form))
self.storage.set_step_files(self.steps.current,
self.process_step_files(form))
# check if the current step is the last step # check if the current step is the last step
if self.steps.current == self.steps.last: if self.steps.current == self.steps.last:
@@ -311,10 +316,11 @@ class WizardView(TemplateView):
# get the form instance based on the data from the storage backend # get the form instance based on the data from the storage backend
# (if available). # (if available).
next_step = self.steps.next next_step = self.steps.next
new_form = self.get_form(next_step, new_form = self.get_form(
next_step,
data=self.storage.get_step_data(next_step), data=self.storage.get_step_data(next_step),
files=self.storage.get_step_files(next_step)) files=self.storage.get_step_files(next_step),
)
# change the stored current step # change the stored current step
self.storage.current_step = next_step self.storage.current_step = next_step
return self.render(new_form, **kwargs) return self.render(new_form, **kwargs)
@@ -340,21 +346,19 @@ class WizardView(TemplateView):
final_forms = OrderedDict() final_forms = OrderedDict()
# walk through the form list and try to validate the data again. # walk through the form list and try to validate the data again.
for form_key in self.get_form_list(): for form_key in self.get_form_list():
form_obj = self.get_form(step=form_key, form_obj = self.get_form(
step=form_key,
data=self.storage.get_step_data(form_key), data=self.storage.get_step_data(form_key),
files=self.storage.get_step_files(form_key)) files=self.storage.get_step_files(form_key)
)
if not form_obj.is_valid(): if not form_obj.is_valid():
return self.render_revalidation_failure(form_key, return self.render_revalidation_failure(form_key, form_obj, **kwargs)
form_obj,
**kwargs)
final_forms[form_key] = form_obj final_forms[form_key] = form_obj
# render the done view and reset the wizard before returning the # render the done view and reset the wizard before returning the
# response. This is needed to prevent from rendering done with the # response. This is needed to prevent from rendering done with the
# same data twice. # same data twice.
done_response = self.done(final_forms.values(), done_response = self.done(final_forms.values(), form_dict=final_forms, **kwargs)
form_dict=final_forms,
**kwargs)
self.storage.reset() self.storage.reset()
return done_response return done_response
@@ -414,8 +418,7 @@ class WizardView(TemplateView):
'prefix': self.get_form_prefix(step, form_class), 'prefix': self.get_form_prefix(step, form_class),
'initial': self.get_form_initial(step), 'initial': self.get_form_initial(step),
}) })
if issubclass(form_class, (forms.ModelForm, if issubclass(form_class, (forms.ModelForm, forms.models.BaseInlineFormSet)):
forms.models.BaseInlineFormSet)):
# If the form is based on ModelForm or InlineFormSet, # If the form is based on ModelForm or InlineFormSet,
# add instance if available and not previously set. # add instance if available and not previously set.
kwargs.setdefault('instance', self.get_form_instance(step)) kwargs.setdefault('instance', self.get_form_instance(step))
@@ -491,9 +494,11 @@ class WizardView(TemplateView):
If the data doesn't validate, None will be returned. If the data doesn't validate, None will be returned.
""" """
if step in self.form_list: if step in self.form_list:
form_obj = self.get_form(step=step, form_obj = self.get_form(
step=step,
data=self.storage.get_step_data(step), data=self.storage.get_step_data(step),
files=self.storage.get_step_files(step)) files=self.storage.get_step_files(step),
)
if form_obj.is_valid(): if form_obj.is_valid():
return form_obj.cleaned_data return form_obj.cleaned_data
return None return None
@@ -581,8 +586,10 @@ class WizardView(TemplateView):
This method must be overridden by a subclass to process to form data This method must be overridden by a subclass to process to form data
after processing all steps. after processing all steps.
""" """
raise NotImplementedError("Your %s class has not defined a done() " raise NotImplementedError(
"method, which is required." % self.__class__.__name__) "Your %s class has not defined a done() method, which is required."
% self.__class__.__name__
)
class SessionWizardView(WizardView): class SessionWizardView(WizardView):
@@ -612,19 +619,16 @@ class NamedUrlWizardView(WizardView):
We require a url_name to reverse URLs later. Additionally users can We require a url_name to reverse URLs later. Additionally users can
pass a done_step_name to change the URL name of the "done" view. pass a done_step_name to change the URL name of the "done" view.
""" """
assert 'url_name' in kwargs, \ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs'
'URL name is needed to resolve correct wizard URLs'
extra_kwargs = { extra_kwargs = {
'done_step_name': kwargs.pop('done_step_name', 'done'), 'done_step_name': kwargs.pop('done_step_name', 'done'),
'url_name': kwargs.pop('url_name'), 'url_name': kwargs.pop('url_name'),
} }
initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, initkwargs = super(NamedUrlWizardView, cls).get_initkwargs(*args, **kwargs)
**kwargs)
initkwargs.update(extra_kwargs) initkwargs.update(extra_kwargs)
assert initkwargs['done_step_name'] not in initkwargs['form_list'], \ assert initkwargs['done_step_name'] not in initkwargs['form_list'], \
'step name "%s" is reserved for "done" view' % \ 'step name "%s" is reserved for "done" view' % initkwargs['done_step_name']
initkwargs['done_step_name']
return initkwargs return initkwargs
def get_step_url(self, step): def get_step_url(self, step):
@@ -643,32 +647,37 @@ class NamedUrlWizardView(WizardView):
query_string = "?%s" % self.request.GET.urlencode() query_string = "?%s" % self.request.GET.urlencode()
else: else:
query_string = "" query_string = ""
return redirect(self.get_step_url(self.steps.current) + return redirect(self.get_step_url(self.steps.current) + query_string)
query_string)
# is the current step the "done" name/view? # is the current step the "done" name/view?
elif step_url == self.done_step_name: elif step_url == self.done_step_name:
last_step = self.steps.last last_step = self.steps.last
return self.render_done(self.get_form(step=last_step, form = self.get_form(
step=last_step,
data=self.storage.get_step_data(last_step), data=self.storage.get_step_data(last_step),
files=self.storage.get_step_files(last_step) files=self.storage.get_step_files(last_step),
), **kwargs) )
return self.render_done(form, **kwargs)
# is the url step name not equal to the step in the storage? # is the url step name not equal to the step in the storage?
# if yes, change the step in the storage (if name exists) # if yes, change the step in the storage (if name exists)
elif step_url == self.steps.current: elif step_url == self.steps.current:
# URL step name and storage step name are equal, render! # URL step name and storage step name are equal, render!
return self.render(self.get_form( form = self.get_form(
data=self.storage.current_step_data, data=self.storage.current_step_data,
files=self.storage.current_step_files, files=self.storage.current_step_files,
), **kwargs) )
return self.render(form, **kwargs)
elif step_url in self.get_form_list(): elif step_url in self.get_form_list():
self.storage.current_step = step_url self.storage.current_step = step_url
return self.render(self.get_form( return self.render(
data=self.storage.current_step_data, self.get_form(
files=self.storage.current_step_files, data=self.storage.current_step_data,
), **kwargs) files=self.storage.current_step_files,
),
**kwargs
)
# invalid step name, reset to first and redirect. # invalid step name, reset to first and redirect.
else: else:
@@ -690,8 +699,7 @@ class NamedUrlWizardView(WizardView):
NamedUrlWizardView provides the url_name of this wizard in the context NamedUrlWizardView provides the url_name of this wizard in the context
dict `wizard`. dict `wizard`.
""" """
context = super(NamedUrlWizardView, self).get_context_data(form=form, context = super(NamedUrlWizardView, self).get_context_data(form=form, **kwargs)
**kwargs)
context['wizard']['url_name'] = self.url_name context['wizard']['url_name'] = self.url_name
return context return context

View File

@@ -1,3 +1,6 @@
[flake8]
max-line-length = 119
[metadata] [metadata]
license-file = LICENSE license-file = LICENSE

View File

@@ -54,11 +54,9 @@ class PreviewTests(TestCase):
""" """
FormPreview.parse_params takes a request object as the first argument. FormPreview.parse_params takes a request object as the first argument.
""" """
preview = TestFormPreview(TestForm)
response = self.client.get('/preview/') response = self.client.get('/preview/')
state = response.context['state'] state = response.context['state']
self.assertTrue(state.get('user') is not None, "Expected to find a " self.assertIsNotNone(state.get('user') is not None)
"user key in response.context['state']")
def test_unused_name(self): def test_unused_name(self):
""" """

View File

@@ -18,7 +18,8 @@ class TestCookieStorage(TestStorage, TestCase):
cookie_signer = signing.get_cookie_signer(storage.prefix) cookie_signer = signing.get_cookie_signer(storage.prefix)
storage.request.COOKIES[storage.prefix] = cookie_signer.sign( storage.request.COOKIES[storage.prefix] = cookie_signer.sign(
storage.encoder.encode({'key1': 'value1'})) storage.encoder.encode({'key1': 'value1'})
)
self.assertEqual(storage.load_data(), {'key1': 'value1'}) self.assertEqual(storage.load_data(), {'key1': 'value1'})
@@ -41,5 +42,7 @@ class TestCookieStorage(TestStorage, TestCase):
storage.init_data() storage.init_data()
storage.update_response(response) storage.update_response(response)
unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value) unsigned_cookie_data = cookie_signer.unsign(response.cookies[storage.prefix].value)
self.assertJSONEqual(unsigned_cookie_data, self.assertJSONEqual(
{"step_files": {}, "step": None, "extra_data": {}, "step_data": {}}) unsigned_cookie_data,
{"step_files": {}, "step": None, "extra_data": {}, "step_data": {}}
)

View File

@@ -64,8 +64,7 @@ class TestModelForm(forms.ModelForm):
fields = '__all__' fields = '__all__'
TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2, TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2, fields='__all__')
fields='__all__')
class TestWizard(WizardView): class TestWizard(WizardView):
@@ -95,32 +94,27 @@ class FormTests(TestCase):
self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2})
testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)]) testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)])
self.assertEqual( self.assertEqual(testform['form_list'], {'start': Step1, 'step2': Step2})
testform['form_list'], {'start': Step1, 'step2': Step2})
testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)]) testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)])
self.assertEqual( self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3})
testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3})
testform = TestWizardWithInitAttrs.get_initkwargs() testform = TestWizardWithInitAttrs.get_initkwargs()
self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2})
def test_first_step(self): def test_first_step(self):
request = get_request() request = get_request()
testform = TestWizard.as_view([Step1, Step2]) testform = TestWizard.as_view([Step1, Step2])
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.steps.current, '0') self.assertEqual(instance.steps.current, '0')
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.steps.current, 'start') self.assertEqual(instance.steps.current, 'start')
def test_persistence(self): def test_persistence(self):
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
request = get_request({'test_wizard-current_step': 'start', request = get_request({'test_wizard-current_step': 'start', 'name': 'data1'})
'name': 'data1'})
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.steps.current, 'start') self.assertEqual(instance.steps.current, 'start')
@@ -133,56 +127,57 @@ class FormTests(TestCase):
def test_form_condition(self): def test_form_condition(self):
request = get_request() request = get_request()
testform = TestWizard.as_view( testform = TestWizard.as_view(
[('start', Step1), ('step2', Step2), ('step3', Step3)], [('start', Step1), ('step2', Step2), ('step3', Step3)],
condition_dict={'step2': True}) condition_dict={'step2': True}
)
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_next_step(), 'step2') self.assertEqual(instance.get_next_step(), 'step2')
testform = TestWizard.as_view( testform = TestWizard.as_view(
[('start', Step1), ('step2', Step2), ('step3', Step3)], [('start', Step1), ('step2', Step2), ('step3', Step3)],
condition_dict={'step2': False}) condition_dict={'step2': False}
)
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_next_step(), 'step3') self.assertEqual(instance.get_next_step(), 'step3')
testform = TestWizardWithInitAttrs.as_view( testform = TestWizardWithInitAttrs.as_view(
[('start', Step1), ('step2', Step2), ('step3', Step3)]) [('start', Step1), ('step2', Step2), ('step3', Step3)]
)
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_next_step(), 'step2') self.assertEqual(instance.get_next_step(), 'step2')
def test_form_kwargs(self): def test_form_kwargs(self):
request = get_request() request = get_request()
testform = TestWizard.as_view([
testform = TestWizard.as_view([('start', Step1), ('start', Step1),
('kwargs_test', CustomKwargsStep1)]) ('kwargs_test', CustomKwargsStep1),
])
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_form_kwargs('start'), {}) self.assertEqual(instance.get_form_kwargs('start'), {})
self.assertEqual(instance.get_form_kwargs('kwargs_test'), {'test': True}) self.assertEqual(instance.get_form_kwargs('kwargs_test'), {'test': True})
self.assertEqual(instance.get_form('kwargs_test').test, True) self.assertEqual(instance.get_form('kwargs_test').test, True)
def test_form_prefix(self): def test_form_prefix(self):
request = get_request() request = get_request()
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_form_prefix(), 'start') self.assertEqual(instance.get_form_prefix(), 'start')
self.assertEqual(instance.get_form_prefix('another'), 'another') self.assertEqual(instance.get_form_prefix('another'), 'another')
def test_form_initial(self): def test_form_initial(self):
request = get_request() request = get_request()
testform = TestWizard.as_view(
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)], [('start', Step1), ('step2', Step2)],
initial_dict={'start': {'name': 'value1'}}) initial_dict={'start': {'name': 'value1'}}
)
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'})
self.assertEqual(instance.get_form_initial('step2'), {}) self.assertEqual(instance.get_form_initial('step2'), {})
testform = TestWizardWithInitAttrs.as_view( testform = TestWizardWithInitAttrs.as_view(
[('start', Step1), ('step2', Step2)]) [('start', Step1), ('step2', Step2)]
)
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'})
@@ -191,51 +186,42 @@ class FormTests(TestCase):
def test_form_instance(self): def test_form_instance(self):
request = get_request() request = get_request()
the_instance = TestModel() the_instance = TestModel()
testform = TestWizard.as_view([('start', TestModelForm), ('step2', Step2)], testform = TestWizard.as_view(
instance_dict={'start': the_instance}) [('start', TestModelForm), ('step2', Step2)],
instance_dict={'start': the_instance}
)
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(instance.get_form_instance('start'), the_instance)
self.assertIsNone(instance.get_form_instance('non_exist_instance'))
testform = TestWizardWithInitAttrs.as_view([('start', TestModelForm), ('step2', Step2)])
response, instance = testform(request)
self.assertEqual( self.assertEqual(
instance.get_form_instance('start'), instance.get_form_instance('start'),
the_instance) TestWizardWithInitAttrs.instance_dict['start']
self.assertEqual( )
instance.get_form_instance('non_exist_instance'),
None)
testform = TestWizardWithInitAttrs.as_view(
[('start', TestModelForm), ('step2', Step2)])
response, instance = testform(request)
self.assertEqual(
instance.get_form_instance('start'),
TestWizardWithInitAttrs.instance_dict['start'])
def test_formset_instance(self): def test_formset_instance(self):
request = get_request() request = get_request()
the_instance1, created = TestModel.objects.get_or_create( the_instance1, created = TestModel.objects.get_or_create(name='test object 1')
name='test object 1') the_instance2, created = TestModel.objects.get_or_create(name='test object 2')
the_instance2, created = TestModel.objects.get_or_create( testform = TestWizard.as_view(
name='test object 2') [('start', TestModelFormSet), ('step2', Step2)],
testform = TestWizard.as_view([('start', TestModelFormSet), ('step2', Step2)], instance_dict={'start': TestModel.objects.filter(name='test object 1')}
instance_dict={'start': TestModel.objects.filter(name='test object 1')}) )
response, instance = testform(request) response, instance = testform(request)
self.assertEqual(list(instance.get_form_instance('start')), [the_instance1]) self.assertEqual(list(instance.get_form_instance('start')), [the_instance1])
self.assertEqual(instance.get_form_instance('non_exist_instance'), None) self.assertEqual(instance.get_form_instance('non_exist_instance'), None)
self.assertEqual(instance.get_form().initial_form_count(), 1) self.assertEqual(instance.get_form().initial_form_count(), 1)
def test_done(self): def test_done(self):
request = get_request() request = get_request()
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
response, instance = testform(request) response, instance = testform(request)
self.assertRaises(NotImplementedError, instance.done, None) self.assertRaises(NotImplementedError, instance.done, None)
def test_revalidation(self): def test_revalidation(self):
request = get_request() request = get_request()
testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])
response, instance = testform(request) response, instance = testform(request)
instance.render_done(None) instance.render_done(None)

View File

@@ -6,12 +6,13 @@ from formtools.wizard.storage.base import BaseStorage
class TestLoadStorage(TestCase): class TestLoadStorage(TestCase):
def test_load_storage(self): def test_load_storage(self):
self.assertEqual( self.assertIsInstance(
type(get_storage('formtools.wizard.storage.base.BaseStorage', 'wizard1')), get_storage('formtools.wizard.storage.base.BaseStorage', 'wizard1'),
BaseStorage) BaseStorage
)
def test_missing_storage(self): def test_missing_storage(self):
self.assertRaises(MissingStorage, get_storage, with self.assertRaises(MissingStorage):
'formtools.wizard.storage.idontexist.IDontExistStorage', 'wizard1') get_storage('formtools.wizard.storage.idontexist.IDontExistStorage', 'wizard1')
self.assertRaises(MissingStorage, get_storage, with self.assertRaises(MissingStorage):
'formtools.wizard.storage.base.IDontExistStorage', 'wizard1') get_storage('formtools.wizard.storage.base.IDontExistStorage', 'wizard1')

View File

@@ -457,8 +457,7 @@ class WizardFormKwargsOverrideTests(TestCase):
self.assertNotEqual(formset.queryset, None) self.assertNotEqual(formset.queryset, None)
self.assertEqual(formset.initial_form_count(), 1) self.assertEqual(formset.initial_form_count(), 1)
self.assertEqual(['staff@example.com'], self.assertEqual(['staff@example.com'], list(formset.queryset.values_list('email', flat=True)))
list(formset.queryset.values_list('email', flat=True)))
class WizardInlineFormSetTests(TestCase): class WizardInlineFormSetTests(TestCase):