Permalink
Browse files

Assorted bits of code cleanup; mainly better PEP8.

- Insert blank lines where missing
- Remove surplus blank lines
- Remove some unused imports
- Remove the use of the ``string`` module from lettuce.strings (work on the ``str`` objects directly which is just what ``string`` does - it's mostly obsolete now)
- Reshuffled a few bits of code to use ``all()`` or ``any()`` where appropriate and *not* use them where inappropriate

No functionality changes. (All tests still pass.)
  • Loading branch information...
chris-morgan committed Jul 30, 2011
1 parent 7436c4b commit 37d5a910755be0612b26e3cb62301d78201d4206
View
@@ -32,6 +32,7 @@
fs = FileSystem()
+
class HashList(list):
__base_msg = 'The step "%s" have no table defined, so ' \
'that you can\'t use step.hashes.%s'
@@ -64,6 +65,7 @@ def last(self):
raise AssertionError(self.__base_msg % (self.step.sentence, 'last'))
+
class Language(object):
code = 'en'
name = 'English'
@@ -73,6 +75,7 @@ class Language(object):
examples = 'Examples|Scenarios'
scenario_outline = 'Scenario Outline'
scenario_separator = 'Scenario( Outline)?'
+
def __init__(self, code=u'en'):
self.code = code
for attr, value in languages.LANGUAGES[code].items():
@@ -98,6 +101,7 @@ def guess_from_string(cls, string):
return instance
+
class StepDefinition(object):
"""A step definition is a wrapper for user-defined callbacks. It
gets a few metadata from file, such as filename and line number"""
@@ -122,6 +126,7 @@ def __call__(self, *args, **kw):
return ret
+
class StepDescription(object):
"""A simple object that holds filename and line number of a step
description (step within feature file)"""
@@ -132,6 +137,7 @@ def __init__(self, line, filename):
self.line = line
+
class ScenarioDescription(object):
"""A simple object that holds filename and line number of a scenario
description (scenario within feature file)"""
@@ -146,6 +152,7 @@ def __init__(self, scenario, filename, string, language):
self.line = pline + 1
break
+
class FeatureDescription(object):
"""A simple object that holds filename and line number of a feature
description"""
@@ -168,6 +175,7 @@ def __init__(self, feature, filename, string, language):
self.description_at = tuple(described_at)
+
class Step(object):
""" Object that represents each step on feature files."""
has_definition = False
@@ -198,8 +206,8 @@ def propose_definition(self):
method_name = sentence
groups = [
- ('"', re.compile(r'("[^"]+")')), # double quotes
- ("'", re.compile(r"('[^']+')")), # single quotes
+ ('"', re.compile(r'("[^"]+")')), # double quotes
+ ("'", re.compile(r"('[^']+')")), # single quotes
]
attribute_names = []
@@ -217,21 +225,19 @@ def propose_definition(self):
method_name = method_name.replace(match, group_name)
attribute_names.append(group_name)
-
-
method_name = unicodedata.normalize('NFKD', method_name) \
.encode('ascii', 'ignore')
method_name = '%s(step%s)' % (
"_".join(re.findall("\w+", method_name)).lower(),
- attribute_names and (", %s" % ", ".join(attribute_names)) or ""
- )
+ attribute_names and (", %s" % ", ".join(attribute_names)) or "")
return method_name, sentence
def solve_and_clone(self, data):
sentence = self.sentence
hashes = self.hashes[:] # deep copy
for k, v in data.items():
+
def evaluate(stuff):
return stuff.replace(u'<%s>' % unicode(k), unicode(v))
@@ -387,7 +393,7 @@ def run(self, ignore_case):
return True
@staticmethod
- def run_all(steps, outline = None, run_callbacks = False, ignore_case = True):
+ def run_all(steps, outline=None, run_callbacks=False, ignore_case=True):
"""Runs each step in the given list of steps.
Returns a tuple of five lists:
@@ -434,7 +440,7 @@ def run_all(steps, outline = None, run_callbacks = False, ignore_case = True):
return (all_steps, steps_passed, steps_failed, steps_undefined, reasons_to_fail)
@classmethod
- def many_from_lines(klass, lines, filename = None, original_string = None):
+ def many_from_lines(klass, lines, filename=None, original_string=None):
"""Parses a set of steps from lines of input.
This will correctly parse and produce a list of steps from lines without
@@ -652,18 +658,16 @@ def run_scenario(almost_self, order=-1, outline=None, run_callbacks=False):
steps_skipped = filter(skip, all_steps)
if outline:
- call_hook(
- 'outline', 'scenario', self, order, outline, reasons_to_fail
- )
+ call_hook('outline', 'scenario', self, order, outline,
+ reasons_to_fail)
return ScenarioResult(
self,
steps_passed,
steps_failed,
steps_skipped,
steps_undefined,
- True
- )
+ True)
if self.outlines:
first = True
@@ -757,14 +761,15 @@ def from_string(new_scenario, string, tags=None, with_file=None, original_string
with_file=with_file,
original_string=original_string,
language=language,
- tags=tags
- )
+ tags=tags)
return scenario
+
class Feature(object):
""" Object that represents a feature."""
described_at = None
+
def __init__(self, name, remaining_lines, with_file, original_string,
language=None, tags=None):
@@ -778,8 +783,7 @@ def __init__(self, name, remaining_lines, with_file, original_string,
self.scenarios, self.description = self._parse_remaining_lines(
remaining_lines,
original_string,
- with_file
- )
+ with_file)
self.original_string = original_string
@@ -841,17 +845,12 @@ def from_string(new_feature, string, with_file=None, language=None):
found = len(re.findall(r'%s:[ ]*\w+' % language.feature, "\n".join(lines), re.U))
if found > 1:
- raise LettuceSyntaxError(
- with_file,
- 'A feature file must contain ONLY ONE feature!'
- )
+ raise LettuceSyntaxError(with_file,
+ 'A feature file must contain ONLY ONE feature!')
elif found == 0:
- raise LettuceSyntaxError(
- with_file,
- 'Features must have a name. e.g: "Feature: This is my name"'
- )
-
+ raise LettuceSyntaxError(with_file,
+ 'Features must have a name. e.g: "Feature: This is my name"')
while lines:
matched = re.search(r'%s:(.*)' % language.feature, lines[0], re.I)
@@ -898,15 +897,12 @@ def _parse_remaining_lines(self, lines, original_string, with_file=None):
parts = strings.split_scenarios(lines, scenario_prefix)
- scenario_strings = [
- u"%s" % (s) for s in parts if s.strip()
- ]
+ scenario_strings = [u"%s" % (s) for s in parts if s.strip()]
kw = dict(
original_string=original_string,
with_file=with_file,
language=self.language,
- tags=self.tags
- )
+ tags=self.tags)
scenarios = [Scenario.from_string(s, **kw) for s in scenario_strings]
@@ -932,6 +928,7 @@ def run(self, scenarios=None, run_controller=None, ignore_case=True):
call_hook('after_each', 'feature', self)
return FeatureResult(self, *scenarios_ran)
+
class FeatureResult(object):
"""Object that holds results of each scenario ran from within a feature"""
def __init__(self, feature, *scenario_results):
@@ -942,6 +939,7 @@ def __init__(self, feature, *scenario_results):
def passed(self):
return all([result.passed for result in self.scenario_results])
+
class ScenarioResult(object):
"""Object that holds results of each step ran from within a scenario"""
def __init__(self, scenario, steps_passed, steps_failed, steps_skipped,
@@ -966,14 +964,15 @@ def passed(self):
def failed(self):
return len(self.steps_failed) > 0
+
class TotalResult(object):
def __init__(self, feature_results):
self.feature_results = feature_results
self.scenario_results = []
self.steps_passed = 0
self.steps_failed = 0
self.steps_skipped = 0
- self.steps_undefined= 0
+ self.steps_undefined = 0
self._proposed_definitions = []
self.steps = 0
for feature_result in self.feature_results:
@@ -986,7 +985,6 @@ def __init__(self, feature_results):
self.steps += scenario_result.total_steps
self._proposed_definitions.extend(scenario_result.steps_undefined)
-
def _filter_proposed_definitions(self):
sentences = []
for step in self._proposed_definitions:
View
@@ -18,6 +18,7 @@
from lettuce.core import STEP_REGISTRY
from lettuce.exceptions import StepLoadingError
+
def step(regex):
"""Decorates a function, so that it will become a new step
definition.
View
@@ -19,11 +19,13 @@
from django.utils.importlib import import_module
from django.conf import settings
+
def _filter_bultins(module):
"returns only those apps that are not builtin django.contrib"
name = module.__name__
return not name.startswith("django.contrib") and name != 'lettuce.django'
+
def _filter_configured_apps(module):
"returns only those apps that are in django.conf.settings.LETTUCE_APPS"
app_found = True
@@ -35,6 +37,7 @@ def _filter_configured_apps(module):
return app_found
+
def _filter_configured_avoids(module):
"returns apps that are not within django.conf.settings.LETTUCE_AVOID_APPS"
run_app = False
@@ -45,9 +48,11 @@ def _filter_configured_avoids(module):
return not run_app
+
def get_apps():
return map(import_module, settings.INSTALLED_APPS)
+
def harvest_lettuces(only_the_apps=None, avoid_apps=None, path="features"):
"""gets all installed apps that are not from django.contrib
returns a list of tuples with (path_to_app, app_module)
@@ -56,6 +61,7 @@ def harvest_lettuces(only_the_apps=None, avoid_apps=None, path="features"):
apps = get_apps()
if isinstance(only_the_apps, tuple) and any(only_the_apps):
+
def _filter_only_specified(module):
return module.__name__ in only_the_apps
apps = filter(_filter_only_specified, apps)
@@ -65,6 +71,7 @@ def _filter_only_specified(module):
apps = filter(_filter_configured_avoids, apps)
if isinstance(avoid_apps, tuple) and any(avoid_apps):
+
def _filter_avoid(module):
return module.__name__ not in avoid_apps
@@ -28,6 +28,7 @@
from lettuce.django import server
from lettuce.django import harvest_lettuces
+
class Command(BaseCommand):
help = u'Run lettuce tests all along installed apps'
args = '[PATH to feature file or folder]'
@@ -59,6 +60,7 @@ class Command(BaseCommand):
make_option('--xunit-file', action='store', dest='xunit_file', default=None,
help='Write JUnit XML to this file. Defaults to lettucetests.xml'),
)
+
def stopserver(self, failed=False):
raise SystemExit(int(failed))
@@ -71,7 +73,7 @@ def get_paths(self, args, apps_to_run, apps_to_avoid):
else:
paths = args
else:
- paths = harvest_lettuces(apps_to_run, apps_to_avoid) # list of tuples with (path, app_module)
+ paths = harvest_lettuces(apps_to_run, apps_to_avoid) # list of tuples with (path, app_module)
return paths
View
@@ -128,18 +128,12 @@ def wait(self):
self.lock.acquire()
def should_serve_static_files(self):
- conditions = [
- StaticFilesHandler is not None,
- getattr(settings, 'STATIC_URL', False),
- ]
- return all(conditions)
+ return (StaticFilesHandler is not None and
+ getattr(settings, 'STATIC_URL', False))
def should_serve_admin_media(self):
- conditions = [
- 'django.contrib.admin' in settings.INSTALLED_APPS,
- getattr(settings, 'LETTUCE_SERVE_ADMIN_MEDIA', False),
- ]
- return any(conditions)
+ return ('django.contrib.admin' in settings.INSTALLED_APPS or
+ getattr(settings, 'LETTUCE_SERVE_ADMIN_MEDIA', False))
def run(self):
self.lock.acquire()
View
@@ -16,6 +16,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import traceback
+
class NoDefinitionFound(Exception):
""" Exception raised by lettuce.core.Step, when trying to solve a
Step, but does not find a suitable step definition.
@@ -26,8 +27,8 @@ class NoDefinitionFound(Exception):
def __init__(self, step):
self.step = step
super(NoDefinitionFound, self).__init__(
- 'The step r"%s" is not defined' % self.step.sentence
- )
+ 'The step r"%s" is not defined' % self.step.sentence)
+
class ReasonToFail(object):
""" Exception that contains detailed information about a
@@ -39,6 +40,7 @@ def __init__(self, exc):
self.cause = unicode(exc)
self.traceback = traceback.format_exc(exc)
+
class LettuceSyntaxError(SyntaxError):
def __init__(self, filename, string):
self.filename = filename
Oops, something went wrong.

0 comments on commit 37d5a91

Please sign in to comment.